0% found this document useful (0 votes)
20 views100 pages

ProShop 1

BCA project E commerce website for electronics items full project report thesis
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)
20 views100 pages

ProShop 1

BCA project E commerce website for electronics items full project report thesis
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
You are on page 1/ 100

ProShop – The Ultimate Electronics Shopping

Experience

Thesis Submitted for partial fulfillment of the requirement for


the award of the degree of

BACHELOR OF COMPUTER APPLICATION

By

Kamrujama Siddique

Under the supervision of

Dr. Abdul Majid Farooqi


Assistance Professor, CDOE

Center For Distance and Online Education(CDOE)


Jamia Hamdard

(Deemed to be University)

Hamdard Nagar New Delhi-11006

2025
CERTIFICATE

On the basis of the declaration submitted by Kamrujama Siddique, Enrollment No:-


JH/ODL/BCA/JULY-22/3239 a student of the Bachelor of Computer Applications (BCA)
program, I hereby certify that the dissertation entitled "ProShop – The Ultimate Electronics
Shopping Experience," submitted to the Center for Distance and Online Education (CDOE), Jamia
Hamdard, New Delhi, in partial fulfillment of the requirements for the award of the degree of
Bachelor of Computer Applications (BCA), has been carried out by him under my supervision

Dr. Abdul Majid Farooqi Dr Abdul Majid Farooqi

Program Coordinator BCA, (CDOE) Supervisor

i
DECLARATION

I, KAMRUJAMA SIDDIQUE a student of BACHELOR OF COMPUTER APPLICATION


(BCA), (Enrolment No:- ODL/BCA/JULY-22/3239) hereby declare that the dissertation
Entitled “ProShop – The Ultimate Electronics Shopping Experience" which is being submitted
by me to the Centre for Distance and Online Education, Jamia Hamdard, New Delhi in partial
fulfillment of the requirement for the award of the degree of Bachelor of Computer
Application (BCA) in OL mode is my original work and has not been submitted anywhere else
for the award of any Degree, Diploma, Associateship, Fellowship or other similar title or
recognition.

(Student’s Signature)

Date:

Place:

ii
ACKNOWLEDGEMENT

I would like to express my sincere gratitude to all those who supported me throughout the
development of this project, “ProShop – Electronics E-Commerce Website”. This project has
been a valuable learning experience and would not have been possible without the
encouragement, guidance, and support I received along the way.

First and foremost, I would like to thank my mentor and project guide, Dr. Abdul Majid
Farooqi, for their consistent support, insightful feedback, and technical guidance throughout the
duration of this project. Their expertise and encouragement played a vital role in shaping the
direction and quality of my work.

I am also extremely grateful to Jamia Hamdard University for providing the infrastructure,
resources, and a conducive learning environment that enabled the successful execution of this
project.
A special note of thanks to my classmates and friends for their constant motivation, constructive
suggestions, and help in testing the website and providing valuable feedback during different
stages of development.

I would also like to thank my family for their unwavering support, patience, and understanding
during the entire process. Their belief in me has always been a source of inspiration and strength.

Student’s Signature

Date:

iii
List of Abbreviation
______________________________________________________________________________

Abbreviation Full Form

1. UI User Interface

2. UX User Experience

3. HTML HyperText Markup Language

4. CSS Cascading Style Sheets

5. DB Database

6. API Application Programming Interface

7. IDE Integrated Development Environment

8. HTTP Hypertext Transfer Protocol

9. HTTPS Hypertext Transfer Protocol Secure

10. CRUD Create, Read, Update, Delete

11. CDN Content Delivery Network

12. OTP One-Time Password

13. SSL Secure Sockets Layer

14. SQL Structured Query Language

15. NoSQL Not Only Structured Query Language

16. PWA Progressive Web Application

17. ERP Enterprise Resource Planning

18. DBMS Database Management System

19. CMS Content Management System

iv
20. SEO Search Engine Optimization

21. 2FA Two-Factor Authentication

22. SKU Stock Keeping Unit

23. MVC Model-View-Controller

24. JSON JavaScript Object Notation

25. DOM Document Object Model

26. SRS Software Requirements Specification

27. RAM Random Access Memory

28. OS Operating System

29. IP Internet Protocol

30. AI Artificial Intelligence

31. UXD User Experience Design

32. VS Code Visual Studio Code

33. JS JavaScript

34. UI/UX User Interface / User Experience

35. DB Connect Database Connectivity

v
Table of Contents
______________________________________________________________________________

Approved Performa

Certificate of Originality ……………………………………………………………………….. i

Declaration ……………………………………………………………………………………... ii

Acknowledge …………………………………………………………………………………... iii

List of Abbreviation …………………………………………………………………………… iv

Table of Contents ……………………………………………………………………………… vi

List of figures ………………………………………………………………………………… viii


List of Tables ………………………………………………………………………………….. ix

Approved Synopsis

1. Introduction …………………………………………………………………………… .. 1

2. Objective ……………………………………………………………………………….. 2

3. Problem Statement ……………………………………………………………………… 3

4. Software Requirement Specification (SRS) ……………………………………………. 5

1. Hardware Requirements ………………………………………………………... 5


2. Software Requirements …………………………………………………………. 5

5. Context Flow Chart …………………………………………………………………….. 6

6. Data Flow Diagram ……………………………………………………………………... 7


➢ DFD Level 0 …………………………………………………………………….. 7

➢ DFD Level 1 …………………………………………………………………… 9

➢ DFD Level 2 …………………………………………………………………… 11

7. Entity Relationship Diagram (ER – Diagram) ………………………………………… 13


8. Appendix A: Source Code of the Project………………………………………………. 14

9. Conclusion …………………………………………………………………………….. 82

10. Limitation ……………………………………………………………………………. 84

vi
11. Future Scope …………………………………………………………………………. 86

12. Bibliography ………………………………………………………………………….. 89

vii
List Of Figures
______________________________________________________________________________

Context Flow Chart

➢ Figure no:-5.1 ………………………………………………………………………….. 6

Data Flow Diagram

➢ Figure no:-6.1 ………………………………………………………………………….. 7

➢ Figure no:-6.2 …………………………………………………………………………. 9

➢ Figure no:-6.3 …………………………………………………………………………. 11

Entity Relationship Diagram (ER – Diagram)


➢ Figure no:-7.1 …………………………………………………………………………. 13

Appendix A: Source code of the Project

➢ Figure no:-8.1 …………………………………………………………………………. 19

➢ Figure no:-8.2 …………………………………………………………………………. 22

➢ Figure no:-8.3 …………………………………………………………………………. 27

➢ Figure no:-8.4 …………………………………………………………………………. 33

➢ Figure no:-8.5 …………………………………………………………………………. 41


➢ Figure no:-8.6 …………………………………………………………………………. 54

➢ Figure no:-8,7 …………………………………………………………………………. 65

➢ Figure no:-8.8 ………………………………………………………………………… 81

viii
List of Tables
______________________________________________________________________________

Software Requirements Specification

➢ Table no:-4.1 …………………………………………………………………………….. 5

➢ Table no:-4.2 …………………………………………………………………………….. 5

Data Flow Diagram (DFD)

➢ Table no:-6.1 …………………………………………………………………………….. 8

➢ Table no:-6.2 ………………………………………………………………………….... 10


➢ Table no:-6.3 …………………………………………………………………………… 11

ix
1. Introduction
______________________________________________________________________________

In the era of rapid digital transformation, online shopping has become a fundamental part of
everyday life. Consumers now expect convenience, speed, and a seamless experience when
purchasing products—especially in the domain of electronics, where up-to-date information,
specifications, and pricing play a crucial role. The project titled "ProShop – The Ultimate
Electronics Shopping Experience" aims to provide users with a dynamic and user-friendly
platform dedicated to browsing, selecting, and purchasing a wide range of electronic products
online.

This e-commerce platform focuses on electronic gadgets such as smartphones, laptops,


headphones, smartwatches, and home appliances, offering a responsive and intuitive interface
that allows users to explore products in detail, compare features, manage their shopping carts,
and place secure orders. With the growing dependency on electronic devices, an organized and
efficient online store that caters to this specific niche ensures relevance and practical utility for
end-users.

The ProShop website is designed with a modern approach to UI/UX, enabling smooth
navigation, product filtering, detailed product views, customer reviews, and secure payment
functionality. It bridges the gap between consumers and top-notch electronics by offering an
accessible, virtual shopping space tailored to meet their technological needs. In addition, it
supports product categorization, promotional banners, featured product sections, and an admin
dashboard to manage product listings and customer orders effectively.

The core objective behind the development of this platform is not only to facilitate online sales
of electronic goods but also to empower users with knowledge and choices through transparent
information and ease of access. From small personal gadgets to large appliances, users can make
informed buying decisions from the comfort of their homes.
In conclusion, ProShop is more than just a website—it's an integrated solution that reflects the
current trends in e-commerce and digital shopping. The platform is developed to meet the
expectations of today’s tech-savvy consumers while ensuring performance, security, and
scalability for business growth.

1
2. Objective
______________________________________________________________________________

The primary objective of the ProShop e-commerce website project is to design and develop a
feature-rich, user-friendly, and responsive online platform for the sale and purchase of electronic
products. The platform aims to offer customers a convenient, efficient, and secure way to browse
and shop for a wide range of electronic items including smartphones, laptops, accessories, smart
devices, and home appliances.

Specific objectives include:

❖ To provide a centralized platform for showcasing and selling various electronic


products online with categorized listings and detailed product information.

❖ To ensure a seamless user experience through intuitive design, easy navigation, fast
loading speeds, and responsive layouts that work well on both desktop and mobile
devices.

❖ To implement core e-commerce functionalities such as user registration and login,


product search and filtering, shopping cart, order management, and checkout process.

❖ To integrate secure payment gateway functionality that allows users to make payments
safely and reliably.

❖ To allow product review and rating features that help users make informed purchasing
decisions based on other customers’ feedback.

❖ To develop an admin dashboard that allows administrators to manage inventory, update


product details, process orders, and view customer activities.
❖ To provide account management capabilities such as order history, user profile editing,
and password recovery options for better user control.

❖ To incorporate modern design principles for better visual appeal and brand trust, using
components such as promotional banners, featured products, and new arrival sections.
❖ To reduce physical dependency on offline shopping by offering a virtual store that is
accessible 24/7 from anywhere.
❖ To enable scalability so that more features, products, or categories can be added in the
future without major restructuring.

2
3. Problem Statements
______________________________________________________________________________

With the rapid evolution of digital technologies and the internet, consumer behavior has shifted
significantly from traditional in-store shopping to online platforms. Despite this shift, many
customers still face challenges when searching for reliable and user-friendly e-commerce
websites, especially in the niche of electronic products. Existing platforms often suffer from
issues like poor user experience, limited product information, slow load times, lack of
responsiveness, and security concerns during transactions.

In many developing areas, small and medium-sized electronics retailers are unable to offer their
products online due to high development costs, lack of technical knowledge, or dependency on
third-party marketplaces. As a result, they miss out on the growing segment of digital consumers,
and customers, in turn, are limited to a few large players with limited variety or inflated prices.
Additionally, some e-commerce websites lack transparency in pricing, clear product
specifications, or user reviews, which affects consumer trust. Others are not optimized for mobile
users, making it difficult for a majority of users who shop using smartphones. A lack of
personalized shopping experience, limited filtering options, and poor backend management also
create friction in both the user and admin experience.

From a business perspective, the absence of an integrated admin system for managing inventory,
tracking orders, and processing sales can slow down operations, increase human errors, and
reduce customer satisfaction.
Hence, the key problems to address are:

1. Lack of a dedicated and streamlined platform focused solely on electronics products.


2. Inadequate user interfaces and shopping experiences across many existing e-commerce
websites.

3. Limited accessibility on mobile devices and other responsive layouts.

4. Difficulty in managing inventory and orders effectively from the admin side.

5. Security and trust issues related to online transactions.

6. Unavailability of product reviews, filters, and technical specifications for user assistance.

7. Lack of an affordable, scalable solution for smaller electronics businesses to sell online.

3
This project aims to solve these problems by building ProShop, a modern, responsive, and user-
centric electronic e-commerce website that delivers seamless shopping, efficient product
management, and a secure transaction environment.

4
4. Software Requirements Specification (SRS)
______________________________________________________________________________

1. Hardware Requirements

Component Specification

Processor Intel Core i5 or higher / Apple M1 or equivalent

RAM Minimum 4 GB (8 GB recommended)

Hard Disk Minimum 500 MB of free disk space

Display Minimum 1366×768 resolution

Internet Connection Required for live server testing and deployment

Device PC / Laptop / Smartphone / Tablet

Table no:-4.1

2. Software Requirements

Component Specification

Operating System Windows 10/11, macOS, Linux (Ubuntu)

Web Browser Google Chrome, Mozilla Firefox, Microsoft Edge (latest versions)

Code Editor / IDE Visual Studio Code, Sublime Text, Atom, etc.

Runtime Node.js (for backend/server-side logic if applicable)


Environment

Package Manager npm or yarn

Database MongoDB (NoSQL) / MySQL (Relational DB)

Server Framework Express.js (optional for backend)

Version Control Tool Git and GitHub

Table no:-4.2

5
5. Context Flow Chart
______________________________________________________________________________

Figure no:-5.1

6
6. Data Flow Diagram (DFD)
______________________________________________________________________________

Data Flow Level 0

Figure no:-6.1

7
Component Description / Role

User Management Handles user authentication, registration, and profile data. Connects
with the User Database.

User Database Stores all user-related data such as credentials, profiles, and order
history.

Admin Manages the platform including products, orders, users, and system
configurations.

Product Catalog Displays all available products. Admin uses this module to
add/update product listings.

Product Database Stores detailed product information like name, description, price,
inventory levels, and images.

Order Database Contains order records including product ID, user ID, quantity,
price, order status, etc.

Payment Gateway Facilitates secure transaction processing for customer payments.

Order Gateway Handles requests between frontend, order database, and


payment/shipping modules.

Order Processing Validates and prepares orders for shipping. Links with the Order
Gateway and Shipping Provider.

Shipping & Manages packaging, tracking, and delivery process. Works with the
Fulfillment Shipping Provider and Inventory Sync.

Shipping Provider Third-party logistics service that delivers orders to the customer.

Shipping Data Ensures data integrity between order processing, shipping, and
Consistency inventory systems.

Supplier API Interface to third-party suppliers for inventory and stock updates.

Inventory Sync Syncs inventory levels between database, shipping, and supplier
systems.

Analytics Service Collects performance and user data for reporting and system
optimization.

Analytics & Visualizes collected data like sales trends, user behavior, and stock
Reporting analytics.

8
Logs & Analytics DB Stores system logs and analytics data used by reporting tools and
admin monitoring.

Uststom Likely a custom/internal system or typo for “Customer System” –


assumed to interact with user management.

Table no:-6.1

Data Flow Diagram Level 1

Figure no:-6.2

9
Component Function / Role

Customer End-user who browses products and places orders.

User Management Handles login, registration, and customer data.

Product Catalog Displays available electronic items for purchase.

Order Processing Manages the order workflow from placement to shipping.

Inventory Sync Keeps product stock updated across systems.

Shipping & Fulfillment Handles order packaging, tracking, and dispatch.

Supplier API Connects with external suppliers for restocking items.

Shipping Provider Third-party service delivering products to customers.

Analytics & Reporting Tracks performance, sales, and user behavior.

Shipping Logs shipping details and fulfillment status.

External Analytics Integrates external tools for advanced analytics.

Table no:-6.2

10
Data Flow Diagram Level 2

Figure no:-6.3

Component Role / Description

User Management Handles user login, password reset, authentication, and audit
logging.

11
Order Section Manages order creation, validation, and processing.

Product Catalog Displays products with recommendations; linked to product


database.

Inventory Sync Real-time inventory updates; issues low-stock alerts.

Checkout & Processes final purchase and generates order confirmation.


Confirmation

Shipping Provider Handles shipping label generation and product delivery.

Payment Manages order payment and stores confirmation.

Supplier API Restocks inventory based on low-stock alerts.

Analytics & Reporting Tracks behavior, sales, and detects fraud.

External Analytics Integrates external tools for deep analysis and fraud detection.

Table no:-6.3

12
7. Entity Relationship Diagram (ER – Diagram)
______________________________________________________________________________

Figure no:-7.1

13
8. Appendix A:-Source Code of the Project
______________________________________________________________________________

A.1 Index.js

import React from 'react';

import ReactDOM from 'react-dom/client';

import './assets/styles/bootstrap.custom.css';

import './assets/styles/index.css';

// import 'bootstrap/dist/css/bootstrap.min.css';

import App from './App';

import reportWebVitals from './reportWebVitals';

import {

createBrowserRouter,

createRoutesFromElements,

Route,

RouterProvider,

} from 'react-router-dom';

import { HelmetProvider } from 'react-helmet-async';

import PrivateRoute from './components/PrivateRoute';

import AdminRoute from './components/AdminRoute';

import HomeScreen from './screens/HomeScreen';

import ProductScreen from './screens/ProductScreen';

import CartScreen from './screens/CartScreen';

import LoginScreen from './screens/LoginScreen';

import RegisterScreen from './screens/RegisterScreen';

14
import ShippingScreen from './screens/ShippingScreen';

import PaymentScreen from './screens/PaymentScreen';

import PlaceOrderScreen from './screens/PlaceOrderScreen';

import OrderScreen from './screens/OrderScreen';

import ProfileScreen from './screens/ProfileScreen';

import OrderListScreen from './screens/admin/OrderListScreen';

import ProductListScreen from './screens/admin/ProductListScreen';

import ProductEditScreen from './screens/admin/ProductEditScreen';

import UserListScreen from './screens/admin/UserListScreen';

import UserEditScreen from './screens/admin/UserEditScreen';

import store from './store';

import { Provider } from 'react-redux';

import { PayPalScriptProvider } from '@paypal/react-paypal-js';

const router = createBrowserRouter(

createRoutesFromElements(

<Route path='/' element={<App />}>

<Route index={true} path='/' element={<HomeScreen />} />

<Route path='/search/:keyword' element={<HomeScreen />} />

<Route path='/page/:pageNumber' element={<HomeScreen />} />

<Route

path='/search/:keyword/page/:pageNumber'

element={<HomeScreen />}

/>

<Route path='/product/:id' element={<ProductScreen />} />

<Route path='/cart' element={<CartScreen />} />

15
<Route path='/login' element={<LoginScreen />} />

<Route path='/register' element={<RegisterScreen />} />

{/* Registered users */}

<Route path='' element={<PrivateRoute />}>

<Route path='/shipping' element={<ShippingScreen />} />

<Route path='/payment' element={<PaymentScreen />} />

<Route path='/placeorder' element={<PlaceOrderScreen />} />

<Route path='/order/:id' element={<OrderScreen />} />

<Route path='/profile' element={<ProfileScreen />} />

</Route>

{/* Admin users */}

<Route path='' element={<AdminRoute />}>

<Route path='/admin/orderlist' element={<OrderListScreen />}


/>

<Route path='/admin/productlist' element={<ProductListScreen


/>} />

<Route

path='/admin/productlist/:pageNumber'

element={<ProductListScreen />}

/>

<Route path='/admin/userlist' element={<UserListScreen />} />

<Route path='/admin/product/:id/edit'
element={<ProductEditScreen />} />

<Route path='/admin/user/:id/edit' element={<UserEditScreen


/>} />

</Route>

</Route>

16
);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(

<React.StrictMode>

<HelmetProvider>

<Provider store={store}>

<PayPalScriptProvider deferLoading={true}>

<RouterProvider router={router} />

</PayPalScriptProvider>

</Provider>

</HelmetProvider>

</React.StrictMode>

);

reportWebVitals();

A.2 Store,js

import { configureStore } from '@reduxjs/toolkit';

import { apiSlice } from './slices/apiSlice';

import cartSliceReducer from './slices/cartSlice';

import authReducer from './slices/authSlice';

17
const store = configureStore({

reducer: {

[apiSlice.reducerPath]: apiSlice.reducer,

cart: cartSliceReducer,

auth: authReducer,

},

middleware: (getDefaultMiddleware) =>

getDefaultMiddleware().concat(apiSlice.middleware),

devTools: true,

});

export default store;

Figure no:-8.1
A.3 App.js

18
import { useEffect } from 'react';

import { useDispatch } from 'react-redux';

import { Container } from 'react-bootstrap';

import { Outlet } from 'react-router-dom';

import Header from './components/Header';

import Footer from './components/Footer';

import { logout } from './slices/authSlice';

import { ToastContainer } from 'react-toastify';

import 'react-toastify/dist/ReactToastify.css';

const App = () => {

const dispatch = useDispatch();

useEffect(() => {

const expirationTime = localStorage.getItem('expirationTime');

if (expirationTime) {

const currentTime = new Date().getTime();

if (currentTime > expirationTime) {

dispatch(logout());

}, [dispatch]);

19
return (

<>

<ToastContainer />

<Header />

<main className='py-3'>

<Container>

<Outlet />

</Container>

</main>

<Footer />

</>

);

};

export default App;

A.4 Cartutilis.js

export const addDecimals = (num) => {

return (Math.round(num * 100) / 100).toFixed(2);

};

// NOTE: the code below has been changed from the course code to fix
an issue

// with type coercion of strings to numbers.

20
// Our addDecimals function expects a number and returns a string, so
it is not

// correct to call it passing a string as the argument.

export const updateCart = (state) => {

// Calculate the items price in whole number (pennies) to avoid


issues with

// floating point number calculations

const itemsPrice = state.cartItems.reduce(

(acc, item) => acc + (item.price * 100 * item.qty) / 100,

);

state.itemsPrice = addDecimals(itemsPrice);

// Calculate the shipping price

const shippingPrice = itemsPrice > 100 ? 0 : 10;

state.shippingPrice = addDecimals(shippingPrice);

// Calculate the tax price

const taxPrice = 0.15 * itemsPrice;

state.taxPrice = addDecimals(taxPrice);

const totalPrice = itemsPrice + shippingPrice + taxPrice;

// Calculate the total price

state.totalPrice = addDecimals(totalPrice);

// Save the cart to localStorage

21
localStorage.setItem('cart', JSON.stringify(state));

return state;

};

Figure no:-8.2

A.5 cartslice.js

export const addDecimals = (num) => {

return (Math.round(num * 100) / 100).toFixed(2);

};

// NOTE: the code below has been changed from the course code to fix
an issue

// with type coercion of strings to numbers.

// Our addDecimals function expects a number and returns a string, so


it is not

22
// correct to call it passing a string as the argument.

export const updateCart = (state) => {

// Calculate the items price in whole number (pennies) to avoid


issues with

// floating point number calculations

const itemsPrice = state.cartItems.reduce(

(acc, item) => acc + (item.price * 100 * item.qty) / 100,

);

state.itemsPrice = addDecimals(itemsPrice);

// Calculate the shipping price

const shippingPrice = itemsPrice > 100 ? 0 : 10;

state.shippingPrice = addDecimals(shippingPrice);

// Calculate the tax price

const taxPrice = 0.15 * itemsPrice;

state.taxPrice = addDecimals(taxPrice);

const totalPrice = itemsPrice + shippingPrice + taxPrice;

// Calculate the total price

state.totalPrice = addDecimals(totalPrice);

// Save the cart to localStorage

localStorage.setItem('cart', JSON.stringify(state));

23
return state;

};

A.6 Productapi.js

import { PRODUCTS_URL } from '../constants';

import { apiSlice } from './apiSlice';

export const productsApiSlice = apiSlice.injectEndpoints({

endpoints: (builder) => ({

getProducts: builder.query({

query: ({ keyword, pageNumber }) => ({

url: PRODUCTS_URL,

params: { keyword, pageNumber },

}),

keepUnusedDataFor: 5,

providesTags: ['Products'],

}),

getProductDetails: builder.query({

query: (productId) => ({

url: `${PRODUCTS_URL}/${productId}`,

}),

keepUnusedDataFor: 5,

}),

createProduct: builder.mutation({

24
query: () => ({

url: `${PRODUCTS_URL}`,

method: 'POST',

}),

invalidatesTags: ['Product'],

}),

updateProduct: builder.mutation({

query: (data) => ({

url: `${PRODUCTS_URL}/${data.productId}`,

method: 'PUT',

body: data,

}),

invalidatesTags: ['Products'],

}),

uploadProductImage: builder.mutation({

query: (data) => ({

url: `/api/upload`,

method: 'POST',

body: data,

}),

}),

deleteProduct: builder.mutation({

query: (productId) => ({

url: `${PRODUCTS_URL}/${productId}`,

method: 'DELETE',

}),

25
providesTags: ['Product'],

}),

createReview: builder.mutation({

query: (data) => ({

url: `${PRODUCTS_URL}/${data.productId}/reviews`,

method: 'POST',

body: data,

}),

invalidatesTags: ['Product'],

}),

getTopProducts: builder.query({

query: () => `${PRODUCTS_URL}/top`,

keepUnusedDataFor: 5,

}),

}),

});

export const {

useGetProductsQuery,

useGetProductDetailsQuery,

useCreateProductMutation,

useUpdateProductMutation,

useUploadProductImageMutation,

useDeleteProductMutation,

useCreateReviewMutation,

useGetTopProductsQuery,

26
} = productsApiSlice;

Figure no:-8.3

A.7 Oderssliceapi.js

import { apiSlice } from './apiSlice';

import { ORDERS_URL, PAYPAL_URL } from '../constants';

export const orderApiSlice = apiSlice.injectEndpoints({

endpoints: (builder) => ({

createOrder: builder.mutation({

query: (order) => ({

url: ORDERS_URL,

method: 'POST',

body: order,

27
}),

}),

getOrderDetails: builder.query({

query: (id) => ({

url: `${ORDERS_URL}/${id}`,

}),

keepUnusedDataFor: 5,

}),

payOrder: builder.mutation({

query: ({ orderId, details }) => ({

url: `${ORDERS_URL}/${orderId}/pay`,

method: 'PUT',

body: details,

}),

}),

getPaypalClientId: builder.query({

query: () => ({

url: PAYPAL_URL,

}),

keepUnusedDataFor: 5,

}),

getMyOrders: builder.query({

query: () => ({

url: `${ORDERS_URL}/mine`,

}),

keepUnusedDataFor: 5,

28
}),

getOrders: builder.query({

query: () => ({

url: ORDERS_URL,

}),

keepUnusedDataFor: 5,

}),

deliverOrder: builder.mutation({

query: (orderId) => ({

url: `${ORDERS_URL}/${orderId}/deliver`,

method: 'PUT',

}),

}),

}),

});

export const {

useCreateOrderMutation,

useGetOrderDetailsQuery,

usePayOrderMutation,

useGetPaypalClientIdQuery,

useGetMyOrdersQuery,

useGetOrdersQuery,

useDeliverOrderMutation,

} = orderApiSlice;

29
A.8 Userapislice.js
import { apiSlice } from './apiSlice';

import { USERS_URL } from '../constants';

export const userApiSlice = apiSlice.injectEndpoints({

endpoints: (builder) => ({

login: builder.mutation({

query: (data) => ({

url: `${USERS_URL}/auth`,

method: 'POST',

body: data,

}),

}),

register: builder.mutation({

query: (data) => ({

url: `${USERS_URL}`,

method: 'POST',

body: data,

}),

}),

logout: builder.mutation({

query: () => ({

url: `${USERS_URL}/logout`,

method: 'POST',

30
}),

}),

profile: builder.mutation({

query: (data) => ({

url: `${USERS_URL}/profile`,

method: 'PUT',

body: data,

}),

}),

getUsers: builder.query({

query: () => ({

url: USERS_URL,

}),

providesTags: ['User'],

keepUnusedDataFor: 5,

}),

deleteUser: builder.mutation({

query: (userId) => ({

url: `${USERS_URL}/${userId}`,

method: 'DELETE',

}),

}),

getUserDetails: builder.query({

query: (id) => ({

url: `${USERS_URL}/${id}`,

}),

31
keepUnusedDataFor: 5,

}),

updateUser: builder.mutation({

query: (data) => ({

url: `${USERS_URL}/${data.userId}`,

method: 'PUT',

body: data,

}),

invalidatesTags: ['User'],

}),

}),

});

export const {

useLoginMutation,

useLogoutMutation,

useRegisterMutation,

useProfileMutation,

useGetUsersQuery,

useDeleteUserMutation,

useUpdateUserMutation,

useGetUserDetailsQuery,

} = userApiSlice;

32
Figure no:-8.4

A.9 Usercontroller.js

import asyncHandler from '../middleware/asyncHandler.js';

import generateToken from '../utils/generateToken.js';

import User from '../models/userModel.js';

// @desc Auth user & get token

// @route POST /api/users/auth

// @access Public

const authUser = asyncHandler(async (req, res) => {

const { email, password } = req.body;

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

33
if (user && (await user.matchPassword(password))) {

generateToken(res, user._id);

res.json({

_id: user._id,

name: user.name,

email: user.email,

isAdmin: user.isAdmin,

});

} else {

res.status(401);

throw new Error('Invalid email or password');

});

// @desc Register a new user

// @route POST /api/users

// @access Public

const registerUser = asyncHandler(async (req, res) => {

const { name, email, password } = req.body;

const userExists = await User.findOne({ email });

if (userExists) {

res.status(400);

throw new Error('User already exists');

34
}

const user = await User.create({

name,

email,

password,

});

if (user) {

generateToken(res, user._id);

res.status(201).json({

_id: user._id,

name: user.name,

email: user.email,

isAdmin: user.isAdmin,

});

} else {

res.status(400);

throw new Error('Invalid user data');

});

// @desc Logout user / clear cookie

// @route POST /api/users/logout

// @access Public

35
const logoutUser = (req, res) => {

res.clearCookie('jwt');

res.status(200).json({ message: 'Logged out successfully' });

};

// @desc Get user profile

// @route GET /api/users/profile

// @access Private

const getUserProfile = asyncHandler(async (req, res) => {

const user = await User.findById(req.user._id);

if (user) {

res.json({

_id: user._id,

name: user.name,

email: user.email,

isAdmin: user.isAdmin,

});

} else {

res.status(404);

throw new Error('User not found');

});

// @desc Update user profile

// @route PUT /api/users/profile

36
// @access Private

const updateUserProfile = asyncHandler(async (req, res) => {

const user = await User.findById(req.user._id);

if (user) {

user.name = req.body.name || user.name;

user.email = req.body.email || user.email;

if (req.body.password) {

user.password = req.body.password;

const updatedUser = await user.save();

res.json({

_id: updatedUser._id,

name: updatedUser.name,

email: updatedUser.email,

isAdmin: updatedUser.isAdmin,

});

} else {

res.status(404);

throw new Error('User not found');

});

37
// @desc Get all users

// @route GET /api/users

// @access Private/Admin

const getUsers = asyncHandler(async (req, res) => {

const users = await User.find({});

res.json(users);

});

// @desc Delete user

// @route DELETE /api/users/:id

// @access Private/Admin

const deleteUser = asyncHandler(async (req, res) => {

const user = await User.findById(req.params.id);

if (user) {

if (user.isAdmin) {

res.status(400);

throw new Error('Can not delete admin user');

await User.deleteOne({ _id: user._id });

res.json({ message: 'User removed' });

} else {

res.status(404);

throw new Error('User not found');

});

38
// @desc Get user by ID

// @route GET /api/users/:id

// @access Private/Admin

const getUserById = asyncHandler(async (req, res) => {

const user = await User.findById(req.params.id).select('-password');

if (user) {

res.json(user);

} else {

res.status(404);

throw new Error('User not found');

});

// @desc Update user

// @route PUT /api/users/:id

// @access Private/Admin

const updateUser = asyncHandler(async (req, res) => {

const user = await User.findById(req.params.id);

if (user) {

user.name = req.body.name || user.name;

user.email = req.body.email || user.email;

user.isAdmin = Boolean(req.body.isAdmin);

const updatedUser = await user.save();

39
res.json({

_id: updatedUser._id,

name: updatedUser.name,

email: updatedUser.email,

isAdmin: updatedUser.isAdmin,

});

} else {

res.status(404);

throw new Error('User not found');

});

export {

authUser,

registerUser,

logoutUser,

getUserProfile,

updateUserProfile,

getUsers,

deleteUser,

getUserById,

updateUser,

};

40
Figure no:-8.5

A.10 Productcontroller.js

import asyncHandler from '../middleware/asyncHandler.js';

import Product from '../models/productModel.js';

// @desc Fetch all products

// @route GET /api/products

// @access Public

const getProducts = asyncHandler(async (req, res) => {

const pageSize = process.env.PAGINATION_LIMIT;

const page = Number(req.query.pageNumber) || 1;

const keyword = req.query.keyword

? {

41
name: {

$regex: req.query.keyword,

$options: 'i',

},

: {};

const count = await Product.countDocuments({ ...keyword });

const products = await Product.find({ ...keyword })

.limit(pageSize)

.skip(pageSize * (page - 1));

res.json({ products, page, pages: Math.ceil(count / pageSize) });

});

// @desc Fetch single product

// @route GET /api/products/:id

// @access Public

const getProductById = asyncHandler(async (req, res) => {

// NOTE: checking for valid ObjectId to prevent CastError moved to


separate

// middleware. See README for more info.

const product = await Product.findById(req.params.id);

if (product) {

return res.json(product);

} else {

42
// NOTE: this will run if a valid ObjectId but no product was
found

// i.e. product may be null

res.status(404);

throw new Error('Product not found');

});

// @desc Create a product

// @route POST /api/products

// @access Private/Admin

const createProduct = asyncHandler(async (req, res) => {

const product = new Product({

name: 'Sample name',

price: 0,

user: req.user._id,

image: '/images/sample.jpg',

brand: 'Sample brand',

category: 'Sample category',

countInStock: 0,

numReviews: 0,

description: 'Sample description',

});

const createdProduct = await product.save();

res.status(201).json(createdProduct);

});

43
// @desc Update a product

// @route PUT /api/products/:id

// @access Private/Admin

const updateProduct = asyncHandler(async (req, res) => {

const { name, price, description, image, brand, category,


countInStock } =

req.body;

const product = await Product.findById(req.params.id);

if (product) {

product.name = name;

product.price = price;

product.description = description;

product.image = image;

product.brand = brand;

product.category = category;

product.countInStock = countInStock;

const updatedProduct = await product.save();

res.json(updatedProduct);

} else {

res.status(404);

throw new Error('Product not found');

});

44
// @desc Delete a product

// @route DELETE /api/products/:id

// @access Private/Admin

const deleteProduct = asyncHandler(async (req, res) => {

const product = await Product.findById(req.params.id);

if (product) {

await Product.deleteOne({ _id: product._id });

res.json({ message: 'Product removed' });

} else {

res.status(404);

throw new Error('Product not found');

});

// @desc Create new review

// @route POST /api/products/:id/reviews

// @access Private

const createProductReview = asyncHandler(async (req, res) => {

const { rating, comment } = req.body;

const product = await Product.findById(req.params.id);

if (product) {

const alreadyReviewed = product.reviews.find(

45
(r) => r.user.toString() === req.user._id.toString()

);

if (alreadyReviewed) {

res.status(400);

throw new Error('Product already reviewed');

const review = {

name: req.user.name,

rating: Number(rating),

comment,

user: req.user._id,

};

product.reviews.push(review);

product.numReviews = product.reviews.length;

product.rating =

product.reviews.reduce((acc, item) => item.rating + acc, 0) /

product.reviews.length;

await product.save();

res.status(201).json({ message: 'Review added' });

} else {

46
res.status(404);

throw new Error('Product not found');

});

// @desc Get top rated products

// @route GET /api/products/top

// @access Public

const getTopProducts = asyncHandler(async (req, res) => {

const products = await Product.find({}).sort({ rating: -1


}).limit(3);

res.json(products);

});

export {

getProducts,

getProductById,

createProduct,

updateProduct,

deleteProduct,

createProductReview,

getTopProducts,

};

A.11 Ordercontroller.js

47
import asyncHandler from '../middleware/asyncHandler.js';

import Order from '../models/orderModel.js';

import Product from '../models/productModel.js';

import { calcPrices } from '../utils/calcPrices.js';

import { verifyPayPalPayment, checkIfNewTransaction } from


'../utils/paypal.js';

// @desc Create new order

// @route POST /api/orders

// @access Private

const addOrderItems = asyncHandler(async (req, res) => {

const { orderItems, shippingAddress, paymentMethod } = req.body;

if (orderItems && orderItems.length === 0) {

res.status(400);

throw new Error('No order items');

} else {

// NOTE: here we must assume that the prices from our client are
incorrect.

// We must only trust the price of the item as it exists in

// our DB. This prevents a user paying whatever they want by


hacking our client

// side code -
https://gist.github.com/bushblade/725780e6043eaf59415fbaf6ca7376ff

// get the ordered items from our database

const itemsFromDB = await Product.find({

_id: { $in: orderItems.map((x) => x._id) },

48
});

// map over the order items and use the price from our items from
database

const dbOrderItems = orderItems.map((itemFromClient) => {

const matchingItemFromDB = itemsFromDB.find(

(itemFromDB) => itemFromDB._id.toString() ===


itemFromClient._id

);

return {

...itemFromClient,

product: itemFromClient._id,

price: matchingItemFromDB.price,

_id: undefined,

};

});

// calculate prices

const { itemsPrice, taxPrice, shippingPrice, totalPrice } =

calcPrices(dbOrderItems);

const order = new Order({

orderItems: dbOrderItems,

user: req.user._id,

shippingAddress,

paymentMethod,

itemsPrice,

49
taxPrice,

shippingPrice,

totalPrice,

});

const createdOrder = await order.save();

res.status(201).json(createdOrder);

});

// @desc Get logged in user orders

// @route GET /api/orders/myorders

// @access Private

const getMyOrders = asyncHandler(async (req, res) => {

const orders = await Order.find({ user: req.user._id });

res.json(orders);

});

// @desc Get order by ID

// @route GET /api/orders/:id

// @access Private

const getOrderById = asyncHandler(async (req, res) => {

const order = await Order.findById(req.params.id).populate(

'user',

'name email'

50
);

if (order) {

res.json(order);

} else {

res.status(404);

throw new Error('Order not found');

});

// @desc Update order to paid

// @route PUT /api/orders/:id/pay

// @access Private

const updateOrderToPaid = asyncHandler(async (req, res) => {

// NOTE: here we need to verify the payment was made to PayPal


before marking

// the order as paid

const { verified, value } = await verifyPayPalPayment(req.body.id);

if (!verified) throw new Error('Payment not verified');

// check if this transaction has been used before

const isNewTransaction = await checkIfNewTransaction(Order,


req.body.id);

if (!isNewTransaction) throw new Error('Transaction has been used


before');

const order = await Order.findById(req.params.id);

51
if (order) {

// check the correct amount was paid

const paidCorrectAmount = order.totalPrice.toString() === value;

if (!paidCorrectAmount) throw new Error('Incorrect amount paid');

order.isPaid = true;

order.paidAt = Date.now();

order.paymentResult = {

id: req.body.id,

status: req.body.status,

update_time: req.body.update_time,

email_address: req.body.payer.email_address,

};

const updatedOrder = await order.save();

res.json(updatedOrder);

} else {

res.status(404);

throw new Error('Order not found');

});

// @desc Update order to delivered

// @route GET /api/orders/:id/deliver

52
// @access Private/Admin

const updateOrderToDelivered = asyncHandler(async (req, res) => {

const order = await Order.findById(req.params.id);

if (order) {

order.isDelivered = true;

order.deliveredAt = Date.now();

const updatedOrder = await order.save();

res.json(updatedOrder);

} else {

res.status(404);

throw new Error('Order not found');

});

// @desc Get all orders

// @route GET /api/orders

// @access Private/Admin

const getOrders = asyncHandler(async (req, res) => {

const orders = await Order.find({}).populate('user', 'id name');

res.json(orders);

});

export {

53
addOrderItems,

getMyOrders,

getOrderById,

updateOrderToPaid,

updateOrderToDelivered,

getOrders,

};

Figure no:-8.6

B.1 Home Screen.jsx

import { Row, Col } from 'react-bootstrap';

import { useParams } from 'react-router-dom';

import { useGetProductsQuery } from '../slices/productsApiSlice';

import { Link } from 'react-router-dom';

import Product from '../components/Product';

54
import Loader from '../components/Loader';

import Message from '../components/Message';

import Paginate from '../components/Paginate';

import ProductCarousel from '../components/ProductCarousel';

import Meta from '../components/Meta';

const HomeScreen = () => {

const { pageNumber, keyword } = useParams();

const { data, isLoading, error } = useGetProductsQuery({

keyword,

pageNumber,

});

return (

<>

{!keyword ? (

<ProductCarousel />

) : (

<Link to='/' className='btn btn-light mb-4'>

Go Back

</Link>

)}

{isLoading ? (

<Loader />

) : error ? (

55
<Message variant='danger'>

{error?.data?.message || error.error}

</Message>

) : (

<>

<Meta />

<h1>Latest Products</h1>

<Row>

{data.products.map((product) => (

<Col key={product._id} sm={12} md={6} lg={4} xl={3}>

<Product product={product} />

</Col>

))}

</Row>

<Paginate

pages={data.pages}

page={data.page}

keyword={keyword ? keyword : ''}

/>

</>

)}

</>

);

};

export default HomeScreen;

56
B.2 Login.jsx

import { useState, useEffect } from 'react';

import { Link, useLocation, useNavigate } from 'react-router-dom';

import { Form, Button, Row, Col } from 'react-bootstrap';

import { useDispatch, useSelector } from 'react-redux';

import Loader from '../components/Loader';

import FormContainer from '../components/FormContainer';

import { useLoginMutation } from '../slices/usersApiSlice';

import { setCredentials } from '../slices/authSlice';

import { toast } from 'react-toastify';

const LoginScreen = () => {

const [email, setEmail] = useState('');

const [password, setPassword] = useState('');

const dispatch = useDispatch();

const navigate = useNavigate();

const [login, { isLoading }] = useLoginMutation();

const { userInfo } = useSelector((state) => state.auth);

57
const { search } = useLocation();

const sp = new URLSearchParams(search);

const redirect = sp.get('redirect') || '/';

useEffect(() => {

if (userInfo) {

navigate(redirect);

}, [navigate, redirect, userInfo]);

const submitHandler = async (e) => {

e.preventDefault();

try {

const res = await login({ email, password }).unwrap();

dispatch(setCredentials({ ...res }));

navigate(redirect);

} catch (err) {

toast.error(err?.data?.message || err.error);

};

return (

<FormContainer>

<h1>Sign In</h1>

<Form onSubmit={submitHandler}>

58
<Form.Group className='my-2' controlId='email'>

<Form.Label>Email Address</Form.Label>

<Form.Control

type='email'

placeholder='Enter email'

value={email}

onChange={(e) => setEmail(e.target.value)}

></Form.Control>

</Form.Group>

<Form.Group className='my-2' controlId='password'>

<Form.Label>Password</Form.Label>

<Form.Control

type='password'

placeholder='Enter password'

value={password}

onChange={(e) => setPassword(e.target.value)}

></Form.Control>

</Form.Group>

<Button disabled={isLoading} type='submit' variant='primary'>

Sign In

</Button>

{isLoading && <Loader />}

</Form>

59
<Row className='py-3'>

<Col>

New Customer?{' '}

<Link to={redirect ? `/register?redirect=${redirect}` :


'/register'}>

Register

</Link>

</Col>

</Row>

</FormContainer>

);

};

export default LoginScreen;

B.3 Registerscreen.jsx

import { useState, useEffect } from 'react';

import { Link, useLocation, useNavigate } from 'react-router-dom';

import { Form, Button, Row, Col } from 'react-bootstrap';

import { useDispatch, useSelector } from 'react-redux';

import Loader from '../components/Loader';

import FormContainer from '../components/FormContainer';

import { useRegisterMutation } from '../slices/usersApiSlice';

import { setCredentials } from '../slices/authSlice';

60
import { toast } from 'react-toastify';

const RegisterScreen = () => {

const [name, setName] = useState('');

const [email, setEmail] = useState('');

const [password, setPassword] = useState('');

const [confirmPassword, setConfirmPassword] = useState('');

const dispatch = useDispatch();

const navigate = useNavigate();

const [register, { isLoading }] = useRegisterMutation();

const { userInfo } = useSelector((state) => state.auth);

const { search } = useLocation();

const sp = new URLSearchParams(search);

const redirect = sp.get('redirect') || '/';

useEffect(() => {

if (userInfo) {

navigate(redirect);

}, [navigate, redirect, userInfo]);

const submitHandler = async (e) => {

61
e.preventDefault();

if (password !== confirmPassword) {

toast.error('Passwords do not match');

} else {

try {

const res = await register({ name, email, password


}).unwrap();

dispatch(setCredentials({ ...res }));

navigate(redirect);

} catch (err) {

toast.error(err?.data?.message || err.error);

};

return (

<FormContainer>

<h1>Register</h1>

<Form onSubmit={submitHandler}>

<Form.Group className='my-2' controlId='name'>

<Form.Label>Name</Form.Label>

<Form.Control

type='name'

placeholder='Enter name'

value={name}

onChange={(e) => setName(e.target.value)}

62
></Form.Control>

</Form.Group>

<Form.Group className='my-2' controlId='email'>

<Form.Label>Email Address</Form.Label>

<Form.Control

type='email'

placeholder='Enter email'

value={email}

onChange={(e) => setEmail(e.target.value)}

></Form.Control>

</Form.Group>

<Form.Group className='my-2' controlId='password'>

<Form.Label>Password</Form.Label>

<Form.Control

type='password'

placeholder='Enter password'

value={password}

onChange={(e) => setPassword(e.target.value)}

></Form.Control>

</Form.Group>

<Form.Group className='my-2' controlId='confirmPassword'>

<Form.Label>Confirm Password</Form.Label>

<Form.Control

type='password'

63
placeholder='Confirm password'

value={confirmPassword}

onChange={(e) => setConfirmPassword(e.target.value)}

></Form.Control>

</Form.Group>

<Button disabled={isLoading} type='submit' variant='primary'>

Register

</Button>

{isLoading && <Loader />}

</Form>

<Row className='py-3'>

<Col>

Already have an account?{' '}

<Link to={redirect ? `/login?redirect=${redirect}` :


'/login'}>

Login

</Link>

</Col>

</Row>

</FormContainer>

);

};

export default RegisterScreen;

64
Figure no:-8.7

B.4 Productscreen.jsx

import { useState } from 'react';

import { useNavigate, useParams } from 'react-router-dom';

import { Link } from 'react-router-dom';

import { useDispatch, useSelector } from 'react-redux';

import {

Row,

Col,

Image,

ListGroup,

Card,

Button,

Form,

65
} from 'react-bootstrap';

import { toast } from 'react-toastify';

import {

useGetProductDetailsQuery,

useCreateReviewMutation,

} from '../slices/productsApiSlice';

import Rating from '../components/Rating';

import Loader from '../components/Loader';

import Message from '../components/Message';

import Meta from '../components/Meta';

import { addToCart } from '../slices/cartSlice';

const ProductScreen = () => {

const { id: productId } = useParams();

const dispatch = useDispatch();

const navigate = useNavigate();

const [qty, setQty] = useState(1);

const [rating, setRating] = useState(0);

const [comment, setComment] = useState('');

const addToCartHandler = () => {

dispatch(addToCart({ ...product, qty }));

navigate('/cart');

};

66
const {

data: product,

isLoading,

refetch,

error,

} = useGetProductDetailsQuery(productId);

const { userInfo } = useSelector((state) => state.auth);

const [createReview, { isLoading: loadingProductReview }] =

useCreateReviewMutation();

const submitHandler = async (e) => {

e.preventDefault();

try {

await createReview({

productId,

rating,

comment,

}).unwrap();

refetch();

toast.success('Review created successfully');

} catch (err) {

toast.error(err?.data?.message || err.error);

67
}

};

return (

<>

<Link className='btn btn-light my-3' to='/'>

Go Back

</Link>

{isLoading ? (

<Loader />

) : error ? (

<Message variant='danger'>

{error?.data?.message || error.error}

</Message>

) : (

<>

<Meta title={product.name} description={product.description}


/>

<Row>

<Col md={6}>

<Image src={product.image} alt={product.name} fluid />

</Col>

<Col md={3}>

<ListGroup variant='flush'>

<ListGroup.Item>

<h3>{product.name}</h3>

</ListGroup.Item>

68
<ListGroup.Item>

<Rating

value={product.rating}

text={`${product.numReviews} reviews`}

/>

</ListGroup.Item>

<ListGroup.Item>Price:
${product.price}</ListGroup.Item>

<ListGroup.Item>

Description: {product.description}

</ListGroup.Item>

</ListGroup>

</Col>

<Col md={3}>

<Card>

<ListGroup variant='flush'>

<ListGroup.Item>

<Row>

<Col>Price:</Col>

<Col>

<strong>${product.price}</strong>

</Col>

</Row>

</ListGroup.Item>

<ListGroup.Item>

<Row>

<Col>Status:</Col>

69
<Col>

{product.countInStock > 0 ? 'In Stock' : 'Out


Of Stock'}

</Col>

</Row>

</ListGroup.Item>

{/* Qty Select */}

{product.countInStock > 0 && (

<ListGroup.Item>

<Row>

<Col>Qty</Col>

<Col>

<Form.Control

as='select'

value={qty}

onChange={(e) =>
setQty(Number(e.target.value))}

>

{[...Array(product.countInStock).keys()].m
ap(

(x) => (

<option key={x + 1} value={x + 1}>

{x + 1}

</option>

)}

70
</Form.Control>

</Col>

</Row>

</ListGroup.Item>

)}

<ListGroup.Item>

<Button

className='btn-block'

type='button'

disabled={product.countInStock === 0}

onClick={addToCartHandler}

>

Add To Cart

</Button>

</ListGroup.Item>

</ListGroup>

</Card>

</Col>

</Row>

<Row className='review'>

<Col md={6}>

<h2>Reviews</h2>

{product.reviews.length === 0 && <Message>No


Reviews</Message>}

<ListGroup variant='flush'>

{product.reviews.map((review) => (

71
<ListGroup.Item key={review._id}>

<strong>{review.name}</strong>

<Rating value={review.rating} />

<p>{review.createdAt.substring(0, 10)}</p>

<p>{review.comment}</p>

</ListGroup.Item>

))}

<ListGroup.Item>

<h2>Write a Customer Review</h2>

{loadingProductReview && <Loader />}

{userInfo ? (

<Form onSubmit={submitHandler}>

<Form.Group className='my-2' controlId='rating'>

<Form.Label>Rating</Form.Label>

<Form.Control

as='select'

required

value={rating}

onChange={(e) => setRating(e.target.value)}

>

<option value=''>Select...</option>

<option value='1'>1 - Poor</option>

<option value='2'>2 - Fair</option>

<option value='3'>3 - Good</option>

72
<option value='4'>4 - Very Good</option>

<option value='5'>5 - Excellent</option>

</Form.Control>

</Form.Group>

<Form.Group className='my-2'
controlId='comment'>

<Form.Label>Comment</Form.Label>

<Form.Control

as='textarea'

row='3'

required

value={comment}

onChange={(e) => setComment(e.target.value)}

></Form.Control>

</Form.Group>

<Button

disabled={loadingProductReview}

type='submit'

variant='primary'

>

Submit

</Button>

</Form>

) : (

<Message>

Please <Link to='/login'>sign in</Link> to write


a review

73
</Message>

)}

</ListGroup.Item>

</ListGroup>

</Col>

</Row>

</>

)}

</>

);

};

export default ProductScreen;

B.5 Placeorderscreen.jsx

import React, { useEffect } from 'react';

import { Link, useNavigate } from 'react-router-dom';

import { toast } from 'react-toastify';

import { Button, Row, Col, ListGroup, Image, Card } from 'react-


bootstrap';

import { useDispatch, useSelector } from 'react-redux';

import Message from '../components/Message';

import CheckoutSteps from '../components/CheckoutSteps';

import Loader from '../components/Loader';

import { useCreateOrderMutation } from '../slices/ordersApiSlice';

74
import { clearCartItems } from '../slices/cartSlice';

const PlaceOrderScreen = () => {

const navigate = useNavigate();

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

const [createOrder, { isLoading, error }] =


useCreateOrderMutation();

useEffect(() => {

if (!cart.shippingAddress.address) {

navigate('/shipping');

} else if (!cart.paymentMethod) {

navigate('/payment');

}, [cart.paymentMethod, cart.shippingAddress.address, navigate]);

const dispatch = useDispatch();

const placeOrderHandler = async () => {

try {

const res = await createOrder({

orderItems: cart.cartItems,

shippingAddress: cart.shippingAddress,

paymentMethod: cart.paymentMethod,

itemsPrice: cart.itemsPrice,

shippingPrice: cart.shippingPrice,

75
taxPrice: cart.taxPrice,

totalPrice: cart.totalPrice,

}).unwrap();

dispatch(clearCartItems());

navigate(`/order/${res._id}`);

} catch (err) {

toast.error(err);

};

return (

<>

<CheckoutSteps step1 step2 step3 step4 />

<Row>

<Col md={8}>

<ListGroup variant='flush'>

<ListGroup.Item>

<h2>Shipping</h2>

<p>

<strong>Address:</strong>

{cart.shippingAddress.address},
{cart.shippingAddress.city}{' '}

{cart.shippingAddress.postalCode},{' '}

{cart.shippingAddress.country}

</p>

</ListGroup.Item>

76
<ListGroup.Item>

<h2>Payment Method</h2>

<strong>Method: </strong>

{cart.paymentMethod}

</ListGroup.Item>

<ListGroup.Item>

<h2>Order Items</h2>

{cart.cartItems.length === 0 ? (

<Message>Your cart is empty</Message>

) : (

<ListGroup variant='flush'>

{cart.cartItems.map((item, index) => (

<ListGroup.Item key={index}>

<Row>

<Col md={1}>

<Image

src={item.image}

alt={item.name}

fluid

rounded

/>

</Col>

<Col>

<Link to={`/product/${item.product}`}>

{item.name}

77
</Link>

</Col>

<Col md={4}>

{item.qty} x ${item.price} = $

{(item.qty * (item.price * 100)) / 100}

</Col>

</Row>

</ListGroup.Item>

))}

</ListGroup>

)}

</ListGroup.Item>

</ListGroup>

</Col>

<Col md={4}>

<Card>

<ListGroup variant='flush'>

<ListGroup.Item>

<h2>Order Summary</h2>

</ListGroup.Item>

<ListGroup.Item>

<Row>

<Col>Items</Col>

<Col>${cart.itemsPrice}</Col>

</Row>

</ListGroup.Item>

78
<ListGroup.Item>

<Row>

<Col>Shipping</Col>

<Col>${cart.shippingPrice}</Col>

</Row>

</ListGroup.Item>

<ListGroup.Item>

<Row>

<Col>Tax</Col>

<Col>${cart.taxPrice}</Col>

</Row>

</ListGroup.Item>

<ListGroup.Item>

<Row>

<Col>Total</Col>

<Col>${cart.totalPrice}</Col>

</Row>

</ListGroup.Item>

<ListGroup.Item>

{error && (

<Message
variant='danger'>{error.data.message}</Message>

)}

</ListGroup.Item>

<ListGroup.Item>

<Button

type='button'

79
className='btn-block'

disabled={cart.cartItems === 0}

onClick={placeOrderHandler}

>

Place Order

</Button>

{isLoading && <Loader />}

</ListGroup.Item>

</ListGroup>

</Card>

</Col>

</Row>

</>

);

};

export default PlaceOrderScreen;

80
Figure no:-8.7

81
9. Conclusion
______________________________________________________________________________

The development of the ProShop e-commerce website signifies a comprehensive and modern
approach to the digital retail experience for electronic products. In a time where convenience,
accessibility, and speed are crucial for consumer satisfaction, ProShop is designed to bridge the
gap between customers and a wide range of electronics—offering them an intuitive, user-centric
platform to explore, compare, and purchase devices from the comfort of their homes.

This project demonstrates the successful integration of multiple e-commerce functionalities


into a single, seamless web application. Core features such as product listing, user registration,
login authentication, product filtering, shopping cart management, secure payment processing,
and order tracking have been implemented to deliver an optimal shopping journey. Additionally,
the admin panel enables backend operations like inventory management, order processing, and
product updates, ensuring efficient workflow and business control.

The architecture of ProShop is built using web technologies that are scalable and
responsive. The design prioritizes mobile accessibility and fast performance, ensuring a
consistent and pleasant user experience across devices. The separation of user roles (customer
and admin), modular backend services (inventory, shipping, and analytics), and external
integrations (payment gateway, shipping providers, and analytics tools) illustrates the project’s
adaptability for real-world deployment and future expansion.

Throughout the system’s design, special attention has been paid to data integrity, security,
and performance. With secure authentication, real-time inventory sync, and transaction
validation, ProShop addresses the most critical concerns in online shopping—building user trust
and reliability. Features such as low-stock alerts, customer reviews, fraud detection, and analytics
reporting allow both users and administrators to benefit from a smarter, more intelligent system.

Moreover, ProShop supports business scalability. The system’s structure makes it easy to
incorporate additional product categories, enhance user features (like wishlists, coupons, and
chatbots), and expand to mobile or PWA versions. This flexibility ensures the website’s long-
term viability and adaptability in a competitive market.

From a development standpoint, this project enabled the practical application of theoretical
knowledge in web development, database management, UI/UX design, and system architecture.
It served as a hands-on experience in translating customer needs into functional software
modules, managing dynamic data flows, and ensuring cross-module integration.

In conclusion, ProShop is not just an academic exercise or prototype—it is a foundation for


a fully scalable, market-ready electronics e-commerce platform. It solves real-world problems

82
for both consumers and sellers, enhances the shopping experience through speed and simplicity,
and meets today’s expectations for online electronic retail platforms. With future enhancements
and feature additions, ProShop has the potential to become a competitive player in the digital
electronics marketplace.

83
10. Limitations
______________________________________________________________________________

Despite being a well-structured and functional e-commerce website for electronics, the ProShop
platform does have certain limitations. These are areas that either restrict the system's current
capabilities or require further development to reach full commercial standards.

1. No Native Mobile Application

• The platform is responsive on mobile browsers but lacks a dedicated mobile app.
• This may affect user retention and push notification capabilities compared to native apps.

2. Limited Payment Integration

• Currently, only one or two payment gateways (e.g., Razorpay or Stripe) are integrated.
• There’s no support for UPI, net banking, EMI options, or wallet-based payments (like
Paytm, PhonePe, etc.).

3. Absence of Real-Time Chat Support

• No built-in live chat or chatbot system for customer service is included.

• Users must rely on email/contact forms for support, which may slow down query
resolution.

4. No AI-Based Personalization

• Product recommendations are static and not AI-driven.

• The system does not personalize search results, home page, or product suggestions based
on user behavior.

5. Basic Inventory Management


• Inventory updates are not yet automated via external systems.

84
• Real-time inventory sync with third-party vendors or ERP systems is limited or manual.

6. Limited Scalability for Large Enterprise Use

• While the current system works well for medium-sized inventory, it may face
performance issues with extremely large-scale datasets (thousands of SKUs).

• Database optimization and cloud hosting are required for scaling to enterprise levels.

7. Security Features are Basic

• The current system has basic security (authentication, HTTPS), but lacks advanced
measures like 2FA (Two-Factor Authentication), data encryption at rest, and advanced
fraud detection systems.

8. No Multi-Vendor Support

• Only a single admin manages product listings.

• The platform does not support multiple sellers or vendor accounts (like Amazon or
Flipkart).

9. Order Cancellation & Return Module is Limited

• There is no automated return/refund workflow.

• Users cannot self-initiate returns or cancellations from the frontend.

10. Analytics Dashboard is Simple

• While the system logs user activity and sales, analytics reporting is limited and does not
support visualizations, export options, or detailed business insights.

85
11. Future Scope
______________________________________________________________________________

While the current implementation of the ProShop e-commerce platform successfully delivers
core functionalities for browsing and purchasing electronic items, there are multiple
opportunities for further enhancement and expansion. These improvements can help the system
evolve into a fully scalable, intelligent, and competitive commercial-grade platform.

1. Development of a Mobile Application


• Building native Android and iOS apps for ProShop will significantly enhance
accessibility, user retention, and engagement.
• Mobile apps can support push notifications, in-app messaging, and offline browsing
modes.

2. Multi-Vendor Marketplace Integration

• Transforming ProShop into a multi-vendor platform will allow multiple sellers to list
their products.

• This expands the product catalog, increases competition, and boosts customer satisfaction
through varied options.

3. AI-Based Personalization

• Implementing artificial intelligence to provide smart product recommendations,


personalized homepages, and behavior-based search results.

• Machine learning can be used to improve customer engagement, repeat visits, and
conversions.

4. Enhanced Security Features

• Future updates can include two-factor authentication (2FA), data encryption at rest,
fraud detection systems, and activity monitoring.
• Ensures compliance with data protection regulations like GDPR and PCI-DSS.

86
5. Automated Return and Refund System

• Develop a user-initiated return module with automatic refund processing, tracking, and
approval workflows.

• Adds convenience and improves trust in the platform.

6. Loyalty Program & Wallet System


• Introduce loyalty points, discount coupons, referral programs, and digital wallet options
to reward repeat customers.
• Encourages customer retention and increased cart values.

7. Chatbot and Live Support

• Integrate a chatbot for automated query handling and a live chat system for real-time
support.

• Enhances user experience and reduces customer service costs.

8. Advanced Analytics Dashboard

• A full-featured admin analytics dashboard with charts, graphs, reports, and data
exports.

• Helps admins monitor sales, traffic, product performance, and customer behavior in real-
time.

9. Internationalization (i18n) & Multi-Currency Support

• Extend the platform to support multiple languages and currencies, making it suitable
for international customers.

• Currency conversion, tax calculation, and language localization can be managed via
APIs.

10. Integration with Logistics & ERP Systems

87
• Seamless integration with third-party logistics providers (BlueDart, Delhivery, etc.)
and ERP systems (Tally, SAP) for automatic shipping and inventory updates.

11. Progressive Web App (PWA) Upgrade

• Convert the website into a Progressive Web App to provide app-like functionality
through the browser with offline capabilities.

12. Voice Search & Smart Assistant Integration


• Integration with voice-based search tools (Google Assistant, Alexa) to make the
platform more accessible and future-ready.

88
12. Bibliography
______________________________________________________________________________

Web Development References

1. MDN Web Docs – https://developer.mozilla.org/


For HTML, CSS, JavaScript syntax, functions, and browser APIs.

2. W3Schools – https://www.w3schools.com/
For frontend design references, web structure, and sample codes.

3. Stack Overflow – https://stackoverflow.com/


For troubleshooting, logic correction, and real-time coding solutions.

4. GeeksforGeeks – https://www.geeksforgeeks.org/
For backend logic explanation and JS concepts.

5. freeCodeCamp – https://www.freecodecamp.org/
For tutorials on responsive web design and JavaScript-based development.

Technology & Tools Documentation

6. Node.js Documentation – https://nodejs.org/en/docs/


For backend development, server creation, and package usage.

7. MongoDB Documentation – https://www.mongodb.com/docs/


For data modeling, queries, and database integration.

8. GitHub – https://github.com/
For version control, code storage, and project management.
9. Visual Studio Code – https://code.visualstudio.com/
As the primary IDE used in project development.
E-Commerce & UX/UI Design Resources

10. Figma – https://www.figma.com/


Used for designing user interface mockups and wireframes.
11. Canva – https://www.canva.com/
Used for project visuals and banners.
12. Bootstrap Documentation – https://getbootstrap.com/docs/
For responsive design and layout support.

89
AI-Assisted Tools

13. ChatGPT by OpenAI – https://chat.openai.com/


For generating project documentation, requirements, diagrams, and system planning.

General Knowledge & Research

14. Wikipedia – https://www.wikipedia.org/


For theoretical concepts such as e-commerce models, system architecture, and workflow
diagrams.

15. YouTube Tutorials (Traversy Media, Codevolution, Programming with Mosh)


For step-by-step video guides on frontend and backend integration.

90

You might also like