You are on page 1of 77

ONLINE BAKERY STORE

By

Muhammad Shoaib Aslam

Roll No: 17113

2019-GCUF-08753

Muhammad Arslan Shah

Roll No: 17036

2019-GCUF-07330
Thesis submitted in partial fulfillment

Of the requirements for the degree of

Bachelor OF SCIENCE

IN

INFORMATION TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY

GC UNIVERSITY, FAISALABAD

August 2023

i
DECLARATION

I carry the work reported in this project under the supervision of Dr, Muhammad Younas,
Lecturer, Department of Information Technology, Government College University, and Faisalabad
Pakistan. I hereby declare that my project, “Online Bakery Store” and all its contents that
include Software are the product of my research. I further declare that this work has not been
submitted for the award of any other degree diploma. The University has all rights to take into
action if the information provided is found inaccurate at any stage.

Signature of the Students:

Muhammad Shoaib Aslam

Roll No: 17113

2019-GCUF-08753

Muhammad Arslan Shah

Roll No: 17036

2019-GCUF-07330

ii
CERTIFICATE BY THE PROJECT SUPERVISOR

It is to certify that Muhammad Shoaib Aslam , Muhammad Arslan Shah under Roll
no. 17113,17036 and Registration No. 2019-GCUF-08753 , 2019-GCUF-07330 has completed
his Final Year Project named as “Online Bakery Store” for Government College University,
Faisalabad, at the Department of Information Technology to fulfill the partial requirement of the
degree of Bachelorof Science in Information Technology, BS(IT).

Supervisor

Name:
Signature:
Designation with Stamp:

Member of Supervisory Committee

Name:
Signature:
Designation with Stamp:

Member of Supervisory Committee

Name:
Signature:
Designation with Stamp:

Chairperson

Name:
Signature:
Designation with Stamp:

iii
DEDICATED

TO

My Graceful and Polite PARENTS

&

All Family Members

Who live in my mind and soul

whose love is more precious than

pearls and diamonds?

Who are those whom I say my own whose

love will never change whose prayers

will never die

iv
ACKNOWLEDGEMENT

First and foremost, all prayers go to ALLAH, I find no words to define my heartiest
sense of gratitude to the Almighty ALLAH, the Most Generous Compassionate, and
Beneficent, and to Prophet MUHAMMAD (SAW), Who is the best light of guidance
for whole humanity from dawn to dusk. I am so much thankful to ALLAH by whom
Grace and Blessings I completed my project on time.
I am also grateful to my loving parents for their encouragement and all sort of
moral, social, and financial support not only in my academic career but also in all other
aspects of life. Their prayers were incessant and enabled me to reach this stage. I am
also thankful to all my family and my grandparents for their kindness, love and
eversupporting prayers.
I truly acknowledge the cooperation and help of my Supervisor Mr. Afzal
Hussain Lecturer, Department of Information Technology, and Government College
University Faisalabad. He has been of consistent help, motivation, and guidance
throughout this project. He has been a great source of guidelines throughout this project.
I also feel great honor to express my sincere and cordial thanks to Dr. Maryam
Rehman (Head of the Department) for her invaluable inspiration and healthy
criticism towards handling the project effectively and comprehensively.
I express my gratitude towards Dr. Sheraz Malik, Professor of Government
College University Faisalabad, under whose kind and scholastic guidance, keen interest
and constant encouragement.
At last, but not least, special thanks to all the developer's communities
throughout the entire Internet for tirelessly resolving the issues and helping and
providing guidance to my queries and problems in the development of the software and
resolving issues in the hardware.
Words are very important to convey thoughts and thanks; the words are
impossible to find to thanks my father and whole family for their prayers and
encouragement for us and for our work.

v
Contents
CHAPTER-1.................................................................................................................................................1
Introduction................................................................................................................................................1
Stakeholders...............................................................................................................................................1
System Model............................................................................................................................................2
Functional Requirments.............................................................................................................................3
Non-functional Requirements..................................................................................................................14
CHAPTER-2 ANALYSIS...........................................................................................................15
Use case model....................................................................................................................................15
System Sequence Diagram (SSD) of each use case............................................................................17
Domain class diagram..........................................................................................................................18
CHAPTER-3 DESIGN..............................................................................................................................19
Design class diagram...........................................................................................................................19
Sequence Diagrams of each SSD.......................................................................................................20
Description of Bakery Use Case in Fully Dressed Format..................................................................15
Bakery login.........................................................................................................................................15
Add a new/update/delete product............................................................
Customer login.......................................................................................
Select getagory...................................................................................................................................21
CHAPTER-4 IMPLEMENTATION.......................................................................................................23
Coding/Algorithm..............................................................................................................................26
Navbar...............................................................................................................................................26
Home code.........................................................................................................................................29
Registration.........................................................................................................................................33
Login...................................................................................................................................................41
Cards code..........................................................................................................................................57
Cart code.............................................................................................................................................59
Item code............................................................................................................................................62
Items code...........................................................................................................................................65
Category filter code..............................................................................................................................68
CHAPTER-5 TESTING...........................................................................................................................70
Test Case..............................................................................................................................................70
Test Case: Login case..........................................................................................................................70
Test Case: Registration case.................................................................................................71

Test Case: Categories filter case.............................................................................................73

Test Case: Add to Cart...........................................................................................................75


v
CHAPTER-1

SOFTWARE REQUIREMENT SPECIFICATION

Introduction
Creating a website you stop being invisible to the people trying to find you online. More
and more studies are telling us about the ROBO effect where customers are learning to
research online before buying offline. They are typing their problems or needs into the
search engine of their choice and are researching the organization that appear for those
queries. If you do not have a Web presence, there is no chance of you showing up and you
never even enter into their thought process. In 2016, you cannot afford to be invisible.

Stakeholders

Manufacturers

Make products and do not sell most directly to the public. Instead, they sell in bulk to
wholesalers and retailers. Buying directly from the manufacturer is the cheapest way to
buy products for resale, but most have minimum purchase requirements that you will
need to meet. You will also need to stock and reship products when selling to customers.
For these reasons, it is often easier to buy directly from a wholesaler.

Wholesalers

Wholesalers buy products in bulk from manufacturers, mark them up slightly and then
sell them to retailers for resale to the public. If they have minimal purchases, they are
usually much less than a manufacturer needs. Wholesalers typically stock products from
dozens - if not hundreds - of manufacturers and tend to operate in a specific industry or
niche. Most are strictly wholesale operators, meaning they only sell to retailers and not
directly to the public.

Retailer

A retailer is someone who sells products directly to the public at a markup. If you run an
e- commerce business, simply put, you are a retailer. Customer - A customer is your
customer! They are the people who browse your store, and buy your stuff! Treat them like
royalty.

System Model

1. Users
2. Admin

1
1. Users
In this module:

• Users can see products without registration


• User can see product description and price of the product
• User Registration required when user want to buy the product
• User can see filter the products
• User’s registration must required

2. Admin

In this module:

• Login/Logout
• Admin will add/delete/update the products

Functional Requirement
Various functional modules can be implemented by the system. It provides an overview of
the system requirement.

Maintenance:

It is the system, which maintains the description of the products and their classification
characteristics (size, weight, cost etc.) Following are the two main components of
Maintenance.

Product:

It contains product information, item number, size, categories etc. It is also the vendor or
seller's admin where they can add product information to websites.

Price:

Only for product prices and applicable discounts on products.

Transaction:

2
A transaction is a payment method in which money is transferred for the purchase of
products. This process is secure and password protected. The three steps involved in an
online transaction are registration, ordering, and payment.

Stock Report:

Generate available product quantity and product status.

Order Report:

List of products that the customer can purchase. Who can buy?

Delivery Report:

List of products that can be delivered to the customer.

Registration:

User must be registered if he wants to buy the product, unregistered user cannot go to
shopping cart.

Login:

User login to the system by entering valid user id and password for purchase.

Cart Changes:

Cart changes means after login or registration the user can order or cancel the product
from the shopping cart.

Logout:

User has to logout after ordering or surfing the product.

3
Requirement Name: Maintenance

Requirement #: Req01 Requirement Type: Functional

Description: This requirement maintains the description of the


products and their classification characteristics (size,
weight, cost etc.)

Rationale: Typically involves routine inspections, upgrades, proper


lubrication (where applicable), adjustments.

Originator: Admin

Fit Criterion:

Customer 8 Customer 2
Satisfaction: Dissatisfaction:

Priority: 2 Conflicts: Nil

Supporting
Materials:

History:

Table1.2: Maintenance

Requirement Name: Product


Requirement #: Req06 Requirement Type: Functional

Description: This requirement product information, item number, size,


categories etc. It is also the vendor or seller's admin where
they can add product information to websites.

Rationale: Reasons for buying that are based on logic or judgement


rather than on emotion.

4
Originator: Admin

Fit Criterion: price, speed of delivery, availability of service, where it's made

Customer Customer 3
Satisfaction: Dissatisfaction:

Priority: Conflicts:

3 Nil

Supporting NA
Materials:

History:

Table1.3: Product
Requirement Name: Price
Requirement #: Req06 Requirement Type: Functional

Description: Only for product prices and applicable discounts on products.

Rationale:

Originator: Admin

Fit Criterion:

5
Customer Customer
Satisfaction: Dissatisfaction:

7 3

Priority: 3 Conflicts: Nil

Supporting
Materials:

NA

History: NILL

Table1.4: Price

Requirement Name: Transaction


Requirement #: Req06 Requirement Type: Functional

Description: This requirement is a payment method in which money is


transferred for the purchase of products. This process is
secure and password protected. The three steps involved in

an online transaction are registration, ordering, and payment.

Rationale: Can see the details of specific brand

Originator: User

Fit Criterion: When requested

Customer Customer
Satisfaction: Dissatisfaction:

7 3

6
Priority: Conflicts:

3 Nil
Supporting
Materials:

NA
History:

NILL
Table1.5: Transaction

Requirement Name: Stock Report


Requirement #: Req06 Requirement Type: Functional

Description: This requirement is Generate available product quantity and product


status.

Rationale:

Originator: User

Fit Criterion: When requested

Customer Customer
Satisfaction: Dissatisfaction:

7 3
Priority: Conflicts:

3 Nil
Supporting
Materials:

NA

7
History:

NILL
Table1.6: Stock Report

Requirement Name: Order Report


Requirement #: Req01 Requirement Type: Functional

Description: This requirement List of products that the customer can


purchase. Who can buy?

Rationale: To login in website system

Originator:

Fit Criterion: Hospital is login in system.

Customer 9 Customer 1
Satisfaction: Dissatisfaction:

Priority: 1 Conflicts: Nil

Supporting NA
Materials:

History: NA

Table1.7: Order Report

8
Requirement Name: Delivery Report
Requirement #: Req06 Requirement Type: Functional

Description: This requirement List of products that can be delivered to the


customer.

Rationale:

Originator: Admin

Fit Criterion: When requested

Customer Customer
Satisfaction: Dissatisfaction:

7 3

Priority: Conflicts:

3 Nil

Supporting

Materials: NA

History:

NILL

Table1.8: Delivery Report

Requirement Name: Registration

9
Requirement #: Req06 Requirement Type: Functional

Description: The requirement User must be registered if he wants to buy


the product, unregistered user cannot go to shopping cart.

Rationale:

Originator: Admin

Fit Criterion: Must required

Customer Customer
Satisfaction: Dissatisfaction:

7 3

Priority: 3 Conflicts: NIL

Supporting NA
Materials:

History:

Table1.9: Registration

Requirement Name: Login


Requirement #: Req06 Requirement Type: Functional

1
Description: This requirement User login to the system by entering valid
user id and password for purchase.

Rationale:

Originator: Admin

Fit Criterion: When requested

Customer Customer
Satisfaction: Dissatisfaction:

7 3

Priority: Conflicts:

3 Nil

Supporting
Materials:

NA

History:

NILL

Table1.10: Login

Requirement Name: Cart changes


Requirement #: Req06 Requirement Type: Functional

1
Description: Cart changes means after login or registration the user can
order or cancel the product from the shopping cart.

Rationale: User can cancel the order

Originator: Admin

Fit Criterion: When requested

Customer Customer
Satisfaction: Dissatisfaction:

7 3
Priority: Conflicts:

3 Nil
Supporting
Materials:

NA
History:

NILL
Table1.11: Cart changes

Requirement Name: Logout


Requirement #: Req06 Requirement Type: Functional

Description: User has to logout after ordering or surfing the product.

Rationale: Account logout

Originator: Admin

1
Fit Criterion: When requested

Customer Customer
Satisfaction: Dissatisfaction:

7 3

Priority: Conflicts:

3 Nil

Supporting
Materials:

NA

History:

NILL

Table1.12: Logout

Nonfunctional Requirement
There are many other types of NFRs, all of which can have a significant impact on the
performance, scalability, and usability of your e-commerce platform. These include:

Security – defining the level of security that must be met such as the OWASP Top 10
Privacy – meeting the basic requirements for GDPR Scalability

Performance – ensuring that the system can handle expected traffic and Able to meet
order volume during normal and peak hours. Key User Journey

Velocity – Defining how long each step along the key user journey will take.

1
Web Services Speed – Specifying how long web services will take to respond.
Accessibility – Ensuring that the platform meets basic accessibility standards.
Documentation – Ensuring that the platform is well documented.

Quality – Even the best e-commerce platforms can be misused so you must insist that
the code is developed to a good standard.

Extensibility – Ensuring that the platform can be extended in a way that allows for
future growth. Data integrity.

Retention – specifying how long data must be stored and how data integrity is
maintained.

Testing – Defining how unit testing will be built into the solution.

Compatibility – Ensuring that the platform can easily integrate with third-party
systems.

Search - Specifying how quickly the system will return search results.

Availability - defining the agreed uptime of the platform under normal conditions
Infrastructure - defining the performance limits of the infrastructure (CPU and
memory usage

1
CHAPTER-2 ANALYSIS

Use Case Model

Web Customer actor uses some web site to make purchases online. Top-level use
cases are View Items, Make Purchase and Client Register. View Items use case could
use by customer as top-level use case if customer only wants to find and see some
products. This use case could also use as a part of Make Purchase use case. Client
Register use case allows customer to register on the web site, for example to get some
coupons or be invited to private sales. Note, that Checkout use case is included use
case not available by itself - checkout is part of making purchase

Except for the Web Customer actor, several other actors will described below with
detailed use cases.

Use case diagram example - top-level use cases

View Items use case is extended by several optional use cases - customer may search for
items, browse catalog, view items recommended for him/her, add items to shopping cart

1
or wish list. All these use cases are extending use cases because they provide some
optional functions allowing customer to find item.

Customer Authentication use case is included in View Recommended Items and Add
to Wish List because both require the customer to authenticate. At the same time, item
could added to the shopping cart without user authentication.
System Sequence Diagram (SSD) of each use case

1
Domain class diagram

Each customer has unique id and linked to exactly one account. Account owns shopping
cart and orders. Customer could register as a web user to be able to buy items online.
Customer is not required to be a web user because purchases could also made by phone or
by ordering from catalogues. Web user has login name, which also serves as unique id.
Web user could be in several states - new, active, temporary blocked, or banned, and
linked to a shopping cart. Shopping cart belongs to account.

Domain class diagram example.

Account owns customer orders. Customer may have no orders. Customer orders are
sorted and unique. Each order could refer to several payments, possibly none. Every
payment has unique id and related to exactly one account.
Each order has current order status. Both order and shopping cart have line items linked
to a specific product. Each line item related to exactly one product. A product could be
associated to many line items or no item at all.

1
CHAPTER-3 DESIGN

Design Class Diagram

1
Sequence Diagrams of each SSD

Description of Bakery Use Case in Fully Dressed Format

Use Case Name: Bakery Login


UC # 1 Ref: Req. #1

1
UC Name User Login

Level (Abstract or Detailed)

Description This requirement enables bakery to login in system.

Actor (s)

Stakeholders

Preconditions Customer must know his/her email and Password before login to
the system.

Success Guarantee User is successfully login.

Main Success Action Response


Scenario
Entered email and
password in form and
press login button or
Enter button

2. User is successfully logged


in.

3. System shows the contents to


be changed.

Extensions If the email and password is wrong than show error message
according to error.

Special requirements User remember his/her email and Password for login.

2
Frequency of Login to the Bakery Multiple times in a day.
Occurrence

Table 2.1: Bakery Login

Use Case Name: Add a new/update/delete product


UC # 2 Ref: Req. #2

UC Name Admin can Add a new/update/ elete variants

Level (Abstract or Detailed)

Description The owner can Add a new/upd te/delete product

Actor (s) Owner

Stakeholders

Preconditions Owner is login.

Success Guarantee Add successfully, update or delete.

Main Success Action Response


Scenario
1. Click and login
admin account.

2
2-add, update and delete
records

Extensions If not add, update or delete records .No error massage will
appear.

Special requirements Admin must be login before this.

Frequency of Update any time


Occurrence

Table: Add a new/update/delete Blood

Description Customer, Use Case in Fully Dressed Format

Use Case Name: Customer Login


UC # 1 Ref: Req. #1

UC Name Citizen Login

Level (Abstract or Detailed)

Description This requirement enables customer to login in system.

Actor (s) user

Stakeholders customer

Preconditions user must remember his/her email and Password which provide
in registration form

Success Guarantee User is successfully logged in.

2
Main Success Action Response
Scenario
2. Entered email and
password in form and
press login button

2.User is successfully logged


in welcome page

3-System shows the


information about store.

Extensions If the email and password is wrong than return into login page,
and show error message.

Special requirements User remembers his/her email and Password.

Frequency of User can login Multiple times in a day.


Occurrence

Table 2.4: User Login

Use Case Name: Select Category


UC # 2 Ref: Req. #2

UC Name Select category

Level (Abstract or Detailed)

Description This requirement about selection of product

2
Actor (s) Customer

Stakeholders Admin/Customer

Preconditions User must Log In

Success Guarantee If login successful

Main Success Scenario Action Response

1. Logged in to the citizen

panel successfully

2. System show the


status to User.

3-

Extensions If something went wrong, system respond accordingly.

Special requirements Log in

Frequency of User can login multiple times in a day and can check his fee
Occurrence status.

Table: select category

2
CHAPTER-4 Implementation
Navbar Coding

import React, { useEffect, useState } from "react"; import "./header.css";

import { FiShoppingCart } from "react-icons/fi"; import axios from

"axios"; import Categoryfilter from

"../../components/categoryfilter/Categoryfilter";

import { useSelector } from "react-redux"; import { toast }

from "react-hot-toast"; import { setUser } from "../../redux-

toolkit/slices/authSlice"; import { dispatch } from

"../../redux-toolkit/store"; import { Link } from "react-

router-dom"; const Header = () => {

const token = useSelector((state) => state.login.token); const user =

useSelector((state) => state.login.user); const total_quantity =

useSelector((state) => state.cart.total_quantity); useEffect(() =>

{ axios

.get("http://localhost:5000/api/v1/auth/me", {

headers: {

Authorization: `Bearer ${token}`,

},

2
})

.then((response) =>

{ dispatch(setUser(response?.data?.data

));

})

.catch((error) =>

{ toast.error(error.message);

});

}, []);

return (

<>

<nav className="navbar navbar-expand-lg navbar-dark">

<div className="container-fluid">

<a className="navbar-brand " href="#">

<div className="text-dark"> BAKERY</div>

</a>

<div className="collapse navbar-collapse" id="navbarSupportedContent">

<ul className="navbar-nav me-auto mb-2 mb-lg-0">

<li className="nav-item">

<a className="nav-link active" aria-current="page" href="#">

<Link to="/home" className="text-white text-decoration-none">

Home

</Link>

2
</a>

</li>

<Categoryfilter />

<li className="nav-item">

<a className="nav-link" href="#">

About

</a>

</li>

<li className="nav-item">

<a className="nav-link" href="#">

Contact Us

</a>

</li>

</ul>

<div className="user-name">

{user?.first_name} {user?.city} {user?.email}

</div>

<form className="d-flex"></form>

<Link

to="/cart"

className="cart-count d-flex align-items-center ms-3 text-warning"

>

<FiShoppingCart size={30} />

2
<div className="count ms-2">{total_quantity ?? 0}</div>

</Link>

</div>

</div>

</nav>

</>

); }; export default

Header;

Home Code

import React, { useEffect } from "react";

import { useSelector } from "react-redux";

import Card from "../../components/card/Card"; import Header

from "../../components/header/Header"; import { getCategories }

from "../../redux-toolkit/actions/categories"; import "./home.css";

2
const Home = () => {

const user = useSelector((state) => state.login.user);

const filteredCategories = useSelector(

(state) => state.home.filteredCategories

);

useEffect(() =>

{ getCategories();

}, []);

return (

<div className="home-page">

<Header />

<div className="banner-page">

<div className=" mt-1">

<div className="">

<img

src="../assests/images/bannerr.jpg"

alt="" width="auto" height="auto"

className="banner-page"

/>

</div>

</div>

</div>

2
{filteredCategories?.map((category) => {

return (

<div className="collection px-3 mt-3">

{category?.variants?.length > 0 && (

<>

<h2 className="collection-header1 s">{category?.title}</h2>

<div className="collection-row d-flex">

{category?.variants?.map((variant) => {

return <Card variant={variant} />;

})}

</div>

</>

)}

</div>

);

})}

</div>

);

};

export default Home;

3
Registration Code

import React, { useState } from "react"; import { Link,

useNavigate } from "react-router-dom"; import

"./registration.css";

3
import { setLoggedIn, setToken } from "../../redux-toolkit/slices/authSlice";

import { dispatch } from "../../redux-toolkit/store"; import { toast } from

"react-hot-toast"; import { register } from "../../redux-toolkit/actions/auth";

const Registration = () => { const

[state, setState] =

useState({ first_name: "",

last_name: "", email: "", city:

"", password: "", cpassword: "",

}); const [loading, setLoading] =

useState(false); const history =

useNavigate(); const changeState = (e) => {

const target = e.target; const name =

target.name; let value = target.value; if

(name === "age") { value = Number(value

?? 0);

} setState((prev)

=> { return {

...prev,

[name]: value,

};

});

};

const submitHandler = (e) => {

3
register(state, setLoading)

.then((res) =>

{ dispatch(setLoggedIn(true));

dispatch(setToken(res?.data?.token));

toast.success("Registered Successfully!");

history("/home");

})

.catch((error) => {

console.log(error);

toast.error(error.message);

setLoading(false);

});

e.preventDefault();

}; return (

<div className="register-page pt-3 mt-4">

<h2 className="text-center">Register</h2>

<form className="register-form p-0 ">

<div className="form-group mt-2">

<label htmlFor="firstname">First Name</label>

<input type="text"

id="first_name"

name="first_name"

3
className="form-control"

value={state.first_name}

onChange={changeState}

/>

</div>

<div className="form-group mt-2">

<label htmlFor="lastname">Last Name</label>

<input type="text"

id="last_name"

name="last_name"

className="form-control"

value={state.last_name}

onChange={changeState}

/>

</div>

<div className="form-group mt-2">

<label htmlFor="email">Email</label>

<input type="email"

id="email" name="email"

className="form-control"

value={state.email}

onChange={changeState}

/>

</div>

<div className="form-group mt-2">

3
<label htmlFor="city">City</label>

<input type="text"

id="city" name="city"

className="form-control"

value={state.city}

onChange={changeState}

/>

</div>

<div className="form-group mt-2"> <label htmlFor="password">Password</label>

<input type="password"

id="password"

name="password"

className="form-control"

value={state.password}

onChange={changeState}

/>

</div>

<div className="form-group mt-2">

<label htmlFor="cpassword">Confirm Password</label>

<input type="password"

id="cpassword"

name="cpassword"

className="form-control"

value={state.cpassword}

onChange={changeState}

3
/>

<div className="mt-4 ">

Already have account? <Link to="/login">Login</Link>

</div>

</div>

<button className="btn btn-primary w-100 mt-3" onClick={submitHandler}>

Register

</button>

</form>

</div>

); }; export default

Registration;

Server

Register User api

const crypto = require("crypto"); const ErrorResponse =

require("../utils/errorResponse"); const asyncHandler =

require("../middleware/async"); const sendEmail =

require("../utils/sendEmail"); const User =

require("../models/User");

// @desc Register user

// @route POST /api/v1/auth/register

3
// @access Public

exports.register = asyncHandler(async (req, res, next) => { const

{ first_name, last_name, email, city, password, role } = req.body; //

Create user const user = await User.create({ first_name, last_name,

email, city,

password,

role,

});

sendTokenResponse(user, 200, res);

});

3
Login

import React, { useState } from "react"; import { Link, useNavigate } from

"react-router-dom"; import { login } from "../../redux-toolkit/actions/auth";

import { setLoggedIn, setToken } from "../../redux-toolkit/slices/authSlice";

import { dispatch } from "../../redux-toolkit/store"; import { toast } from

"react-hot-toast";

import "./login.css";

3
const Login = () => { const [state, setState] =

useState({ email: "", password: "" }); const history =

useNavigate(); const [loading, setLoading] =

useState(false); const changeState = (e) => { const target =

e.target; const name = target.name; const value =

target.value; setState((prev) => { return {

...prev,

[name]: value,

};

});

};

const submitHandler = (e) => {

login(state, setLoading)

.then((res) =>

{ dispatch(setLoggedIn(true));

dispatch(setToken(res?.data?.token));

toast.success("Logged In Successfully!");

history("/home");

})

.catch((error) => { console.log(error);

toast.error("Incorrect email or password");

setLoading(false);

});

3
e.preventDefault();

};

return (

<div className="login-page mt-5">

<h2 className="text-center text-dark">Login</h2>

<form className="login-form ">

<div className="form-group ">

<label htmlFor="email">Email</label>

<input type="email"

id="email" name="email"

className="form-control"

value={state.email}

onChange={changeState}

/>

</div>

<div className="form-group mt-3">

<label htmlFor="password">Password</label>

<input type="password"

id="password"

name="password"

className="form-control mb-

2" value={state.password}

onChange={changeState}

4
/>

<a href="#" className="mt-2 float-end ">

Forget password

</a>

</div>

<button className="btn btn-success w-100 login-

btn mt-5" onClick={submitHandler}

>

Sign in

</button>

<div className="mt-4 ">

Don't have an account? <Link to="/register">Create</Link>

</div>

</form>

</div>

); }; export default

Login;

Login User api

// @desc Login user

// @route POST /api/v1/auth/login

4
// @access Public

exports.login = asyncHandler(async (req, res, next) => {

const { email, password } = req.body;

// Validate emil & password

if (!email || !password) { return next(new ErrorResponse("Please provide an

email and password", 400));

// Check for user const user = await User.findOne({ email

}).select("+password"); if (!user) { return next(new

ErrorResponse("Invalid credentials", 401));

// Check if password matches const isMatch = await

user.matchPassword(password);

if (!isMatch) { return next(new ErrorResponse("Invalid

credentials", 401));

sendTokenResponse(user, 200, res);

});

4
// @desc Update user details

// @route PUT /api/v1/auth/updatedetails

// @access Private

exports.updateDetails = asyncHandler(async (req, res, next) => {

const fieldsToUpdate = { first_name: req.body.first_name,

last_name: req.body.last_name, email: req.body.email,

};

const user = await User.findByIdAndUpdate(req.user.id, fieldsToUpdate,

{ new: true, runValidators: true,

});

res.status(200).json({

success: true, data:

user,

});

});

// @desc Update password

// @route PUT /api/v1/auth/updatepassword

// @access Private

exports.updatePassword = asyncHandler(async (req, res, next) =>

{ const user = await

User.findById(req.user.id).select("+password");

4
// Check current password if (!(await

user.matchPassword(req.body.currentPassword))) { return

next(new ErrorResponse("Password is incorrect", 401));

user.password = req.body.newPassword;

await user.save();

sendTokenResponse(user, 200, res);

});

// @desc Forgot password

// @route POST /api/v1/auth/forgotpassword

// @access Public

exports.forgotPassword = asyncHandler(async (req, res, next) => {

const user = await User.findOne({ email: req.body.email });

if (!user) { return next(new ErrorResponse("There is no user with that

email", 404));

// Get reset token const resetToken =

user.getResetPasswordToken();

4
await user.save({ validateBeforeSave: false });

// Create reset url const resetUrl =

`${req.protocol}://${req.get(

"host"

)}/api/v1/auth/resetpassword/${resetToken}`;

const message = `You are receiving this email because you (or someone else) has
requested the reset of a password. Please make a PUT request to: \n\n ${resetUrl}`;

try { await sendEmail({ email:

user.email, subject: "Password

reset token", message,

});

res.status(200).json({ success: true, data: "Email sent" });

} catch (err) { console.log(err);

user.resetPasswordToken = undefined;

user.resetPasswordExpire = undefined;

await user.save({ validateBeforeSave: false });

return next(new ErrorResponse("Email could not be sent", 500));

4
res.status(200).json({

success: true,

data: user,

});

});

// @desc Reset password

// @route PUT /api/v1/auth/resetpassword/:resettoken

// @access Public

exports.resetPassword = asyncHandler(async (req, res, next) => {

// Get hashed token const

resetPasswordToken = crypto

.createHash("sha256")

.update(req.params.resettoken)

.digest("hex");

const user = await

User.findOne({ resetPasswordToken,

resetPasswordExpire: { $gt: Date.now() },

});

if (!user) { return next(new ErrorResponse("Invalid

token", 400));

4
// Set new password

user.password = req.body.password;

user.resetPasswordToken = undefined;

user.resetPasswordExpire = undefined;

await user.save();

sendTokenResponse(user, 200, res);

});

// Get token from model, create cookie and send response

const sendTokenResponse = (user, statusCode, res) => {

// Create token const token =

user.getSignedJwtToken();

const options =

{ expires: new

Date(

Date.now() + process.env.JWT_COOKIE_EXPIRE * 24 * 60 * 60 * 1000

),

httpOnly: true,

};

if (process.env.NODE_ENV === "production")

{ options.secure = true;

}
4
res.status(statusCode).cookie("token", token, options).json({

success: true, token,

});

};

Variants api for Updating


const ErrorResponse =

require("../utils/errorResponse"); const asyncHandler =

require("../middleware/async"); const Variant =

require("../models/Variant"); const Category =

require("../models/Category");

// @desc Get variants

// @route GET /api/v1/variants

// @route GET /api/v1/categories/:categoryId/variants

// @access Public

exports.getVariants = asyncHandler(async (req, res, next) => { if

(req.params.categoryId) { const variants = await Variant.find({ category:

req.params.categoryId });

return

res.status(200).json({

success: true, count:

variants.length,

4
data: variants,

});

} else

{ res.status(200).json(res.advancedResult

s);

});

// @desc Get single variant

// @route GET /api/v1/variants/:id

// @access Public

exports.getVariant = asyncHandler(async (req, res, next) =>

{ const variant = await

Variant.findById(req.params.id).populate({ path: "category",

select: "title description",

});

if (!variant) { return next( new ErrorResponse(`No variant with the

id of ${req.params.id}`),

404

);

res.status(200).json({

success: true,
4
data: course,

4
});

});

// @desc Add variant

// @route POST /api/v1/categories/:categoryId/variants

// @access Private

exports.addVariant = asyncHandler(async (req, res, next) =>

{ req.body.category = req.params.categoryId;

const category = await Category.findById(req.params.categoryId);

if (!category) { return next( new ErrorResponse(`No category with the id of

${req.params.bootcampId}`),

404

);

const variant = await Variant.create(req.body);

res.status(200).json({ suc

cess: true,

data: variant,

});

5
});

// @desc Update variant

// @route PUT /api/v1/variants/:id

// @access Private

exports.updateVariant = asyncHandler(async (req, res, next) =>

{ let variant = await Variant.findById(req.params.id);

if (!variant) { return next( new ErrorResponse(`No variant with the

id of ${req.params.id}`),

404

);

variant = await Variant.findByIdAndUpdate(req.params.id, req.body,

{ new: true, runValidators: true,

});

res.status(200).json({ suc

cess: true,

data: variant,

});

});

5
// @desc Delete variant

// @route DELETE /api/v1/variants/:id

// @access Private

exports.deleteVariant = asyncHandler(async (req, res, next) =>

{ const variant = await Variant.findById(req.params.id);

if (!variant) { return next( new ErrorResponse(`No variant with the

id of ${req.params.id}`),

404

);

await variant.remove();

res.status(200).json({

success: true, data:

{},

});

});

5
Cards Code

import React from 'react'; import { useNavigate } from 'react-

router-dom'; import { setsingleItem } from '../../redux-

toolkit/slices/itemsSlice'; import { dispatch } from '../../redux-

toolkit/store'; import './card.css';

const Card = ({ variant }) =>

{ const history = useNavigate();

const handleClick = (variant) => {

dispatch(setsingleItem(variant));

history(`/items/${variant._id}`);

5
};

return (

<div className="card-box" onClick={() => handleClick(variant)}>

<div className="image-container">

{variant?.image == 'no-photo.jpg' ? (

<img

src="./assests/images/cake.jpg

" alt="" width="280px"

height="150px"

className="card-image"

/>

):(

<img

src={variant?.image}

alt="" width="280px"

height="150px"

className="card-

image"

/>

)}

</div>

<div className="title-row d-flex justify-content-between mt-2">

<div className="title">{variant?.title}</div>

<div className="price">PKR {variant?.price}</div>

</div>

5
<div className="description-row mt-2">{variant?.description}</div>

</div>

);

};

export default Card;

Cart Code

import React, { useState } from "react";

import { decreaseQuantity,

increaseQuantity,

} from "../../redux-toolkit/slices/cartSlice"; import

{ dispatch } from "../../redux-toolkit/store";

import "./cart.css";

5
const Cart = ({ item }) => {

return (

<div className="cart d-flex mt-5" key={item?._id}>

<div className="cart-image-container me-3">

{item?.image == "no-photo.jpg" ? (

<img

src="../assests/images/cake.jpg

" alt="" width="auto"

height="auto"

className="cart-image"

/>

):(

<img

src={item?.image}

alt="" width="auto"

height="auto"

className="cart-

image"

/>

)}

</div>

<div className="cart-detail d-flex flex-column w-50 ms-3">

<div className="cart-title">{item?.title}</div>

<div className="cart-price">Rs: {item?.price}</div>

<div className="cart-description mt-3">{item?.description}</div>

5
<div className="quantity-row w-100 d-flex align-items-center justify-
contentend">

<button className="decrease-btn" onClick={() =>

dispatch(decreaseQuantity(item?._id))}

>

</button>

<div className="quantity">{item?.quantity}</div>

<button className="increase-btn" onClick={() =>

dispatch(increaseQuantity(item?._id))}

>

</button>

</div>

</div>

</div>

);

};

export default Cart;

5
Item Code

import React from "react";

import { useSelector } from "react-redux"; import Header

from "../../components/header/Header"; import { addItem }

from "../../redux-toolkit/slices/cartSlice"; import { dispatch

} from "../../redux-toolkit/store"; import "./item.css";

const Item = () => {

const variant = useSelector((state) => state.items.singleItem);

const handleAddToCart = (variant) =>

{ dispatch(addItem(variant));

};

return (

<div className="item-page">

5
<Header />

<div className="item-main-page d-flex mt-5">

<div className="item-image-container me-3">

{variant?.image == "no-photo.jpg" ? (

<img

src="../assests/images/cake6.jpg"

alt="" width="auto"

height="auto"

className="item-image"

/>

):(

<img

src={variant?.image}

alt="" width="auto"

height="auto"

className="item-

image"

/>

)}

</div>

<div className="item-detail d-flex flex-column w-50 ms-3 ">

<div className="item-title">{variant?.title}</div>

<div className="item-price">PKR {variant?.price}</div>

<div className="item-description">{variant?.description}</div>

<div className=" w-100 d-flex justify-content-between mt-3">

5
<button className="btn btn-primary add-to-

cart mt-5 " onClick={() =>

handleAddToCart(variant)}

>

Add to Cart

</button>

</div>

</div>

</div>

</div>

);

};

export default Item;

Items Code

import React from "react";

import "./items.css";

import Card from "./card/Card";

const Item = () => {

return (

6
<div className="home-page">

<div className="collection px-3 mt-3">

<h2 className="collection-header1 s">CAKES</h2>

<div className="collection-row d-flex">

<Card />

<Card />

<Card />

<Card />

<Card />

<Card />

<Card />

</div>

</div>

</div>

); }; export

default Item;

Cart Page Code

import React, { useState } from "react"; import { useSelector

} from "react-redux"; import { Navigate, useNavigate } from

"react-router-dom"; import Cart from

"../../components/cart/Cart"; import Header from

"../../components/header/Header"; import { placeOrders }

from "../../redux-toolkit/actions/order"; import { dispatch }

from "../../redux-toolkit/store"; import "./cart.css";

6
const CartPage = () => { const navigate = useNavigate();

const [orderPlaced, setOrderPlaced] = useState(false); const

cartItems = useSelector((state) => state.cart.cartItems); const

total_bill = useSelector((state) => state.cart.total_bill); const

orderHandler = (body) => {

placeOrders(body, setOrderPlaced);

};

return (

<div className="cart-page">

<Header />

<div className="item-collection d-flex flex-column">

{cartItems?.map((item) => { return <Cart

item={item} key={item?._id} />;

})}

<div className="button-container d-flex align-items-center justify-content-end mt-


5">

<button className="place-order btn btn-primary" onClick={() =>

orderHandler({ total_bill, line_items: cartItems })}

>

Place Order

</button>

</div>

</div>

{orderPlaced && <Navigate to="/orders" />}

6
</div>

);

};

Category Filter Code

import React, { useEffect, useMemo, useState } from "react"; import

{ useSelector } from "react-redux"; import { Link } from "react-router-

dom"; import { setFilterCatgories } from "../../redux-

toolkit/slices/categoriesSlice"; import { dispatch } from "../../redux-

toolkit/store"; import "./categoryfilter.css";

//Filter list by category in React JS export default function App()

{ const allCategories = useSelector((state) =>

state.home.categories); const handleCategoryChange = (id) => {

let filteredCategories = allCategories?.filter(

(category) => category?._id == id

);

dispatch(setFilterCatgories(filteredCategories));

};

return (

6
<div className="dropdown">

<button type="button" className="btn

dropdown-toggle m-1" data-bs-

toggle="dropdown"

>

Category

</button>

<ul className="dropdown-menu">

{allCategories?.map((category) => {

return (

<li onClick={() =>

handleCategoryChange(category?._id)}

key={category?._id} >

{category?.title}

</li>

);

})}

</ul>

</div>

);

6
CHAPTER-5 TESTING

Test Case

Test Cases
Test Case: User Login
Test Case #: 1 Test Case Name: User login

System: Login Sub System: Login

Designed By: Design Date:

Executed By: Execution Date:

Short Enter User email and password in the login form and press login
Description: button.

Pre-Condition: User email and Password

Operating System: Windows 10 Professional Environment: Node.js

Software Tools & Visual Studio Community version, Bootstrap5 react.js


Technologies with environment, Mongoose Database and Windows Operating

version System

Steps Strate gy Action Input Actual Expected Stat Remarks


(Testto Result / Result/ us
Pass System Expected (Pas
/ Response System s/Fai
(TesttoFail) Response l)

6
1 T-T-P User email Khannasee Successfully Successfu Pass Test is
and mabbas59 login lly login pass
password
0@gmail.c
om

123456

2 T-T-F User email Khannasee Not login Not login Pass Test is
and mabbas59 pass
password 0@gmail.c
om 123

Table: Login

Comments

Test Case: User Registration


Test Case #: 2 Test Case Name: Registration

System: Sub System: Registration

Designed By: Design Date:

Executed By: Execution Date:

Short Description: Check all the text boxes, radio buttons, buttons, etc.

Pre-Condition: 1. Fill all fields with the necessary


data;

2. Click on register now

6
Operating System: Windows 10 Professional Environment: React

Software Tools & Visual Studio Code Bootstrap5 react environment,


Technologies with Mongoose

version Database and Windows Operating System

Steps Strategy Action Input Actual Expected Status Remark


(Test-to Result / Result/ (Pass/Fail) s
Pass / System Expected
(Testto- System
Response
Fail)
Response

1 T-T-P First Registered Registered Pass Test is


name, last Successfully Successfully pass
name,ema
il,city,pass
word and
confirm
password

2 T-T-F First Invalid Invalid Pass Test is


name, inputs inputs pass
email, and
password

Test Case: Categories filter


Test Case #: 3 Test Case Name: Categories filter

System: Sub System:

Designed By: Design Date:

Executed By: Execution Date:

6
Short Description: User can filter the categories

Pre-Condition:

Operating Windows 10 pro Environment: Node.js


System:

Software Tools Visual Studio Code Bootstrap5 node.js environment, Mongoose


& Technologies Database and Windows Operating System
with version

Steps Strategy Action Input Actual Expected Stat Rema


(Test-to- Result / Result/ us rks
Pass) / System Expected (Pas
(Test-to- Response System s/
Fail) Response Fail)

1 T-T-P Click Select any System Successfull Pass Test is


on category filtered the y pass
catego category
ries Successfully

2 T-T-F Click If user Show error Error shown Pass Test is


on does not pass
catego Please select
ry select the category
category

Table: Categories filter

Comments

6
Test Case: Add to cart
Test Case #: 4 Test Case Name: Items add to cart

System: Sub System:

Designed By: Design Date:

Executed By: Execution Date:

Short Description: User can add items to cart

Pre-Condition:

Table: Add to cart

Operating Windows 10 pro Environment: React and


System: node.js

Software Tools Visual Studio Code, Bootstrap5 React.js,node.js, Mongoose Database


and Windows Operating System
&
Technologies
with version

Step Strateg Action Input Actual Result Expected Status Rema


s y / System Result/ (Pass/Fai rks
(Testto-
Pass) / Response Expected l)
(Testto- System
Fail)
Response

1 T-T-P Click item Click Successful Successful Pass Test


which is
user want
add to pass
cart

6
2 T-T-F Place Detail Error Error Pass Test
post Message Message is
Pass

Comments

You might also like