0% found this document useful (0 votes)
12 views53 pages

kavi report 2_merged

The document outlines a major project titled 'KS SMART ONLINE GROCERY SHOPPING WEB APPLICATION' submitted for a Master's degree in Computer Science at Periyar University. It describes the development of a web-based grocery e-commerce platform utilizing technologies such as React, Node.js, and MySQL, focusing on user-friendly features like product browsing, cart management, and order tracking. Future enhancements are suggested, including payment gateway integration and AI-driven recommendations, while the project aims to provide a scalable solution for online grocery shopping.

Uploaded by

kavi24042003
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)
12 views53 pages

kavi report 2_merged

The document outlines a major project titled 'KS SMART ONLINE GROCERY SHOPPING WEB APPLICATION' submitted for a Master's degree in Computer Science at Periyar University. It describes the development of a web-based grocery e-commerce platform utilizing technologies such as React, Node.js, and MySQL, focusing on user-friendly features like product browsing, cart management, and order tracking. Future enhancements are suggested, including payment gateway integration and AI-driven recommendations, while the project aims to provide a scalable solution for online grocery shopping.

Uploaded by

kavi24042003
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/ 53

KS SMART ONLINE GROCERY SHOPPING WEB

APPLICATION
A major project submitted in partial fulfillment of the requirements for the degree
of

MASTER OF SCIENCE

IN

COMPUTER SCIENCE
By
KAVIYARASAN S
[Reg. No: U23PG507CSC013]

DEPARTMENT OF COMPUTER SCIENCE

PERIYAR UNIVERSITY
NAAC 'A++' Grade with
CGPA3.61(Cycle-3)

State University – NIRF Rank 56–State Public University Rank 25


Salem–636011, Tamil Nadu ,India.
APRIL 2025
Dr.I LAURENCE AROQUIARAJ M.Sc., M.Phil., M.Tech., M.C.A., Ph.D.

Professor,

Department of Computer Science,

Periyar University,

Salem-636011.

CERTIFICATE
This is to certify that the report of major project entitled as

“KS SMART ONLINE GROCERY SHOPPING WEB APPLICATION”

submitted in partial fulfillment of the requirement for the award of degree of

MASTER OF SCIENCE IN COMPUTER SCIENCE to the Periyar

University, Salem is a record of bonafide work carried out by KAVIYARASAN


S (U23PG507CSC013) under my supervision and guidance.

Place: Salem

Date:

Signature of the Guide Signature of the HOD

Submitted of the Viva-Voice Examination held on .

Internal Examiner External Examiner


ACKNOWLEDGEMENT

First, I would think God Almighty for providing me with everything that
I required in completing this project.

I would like to extend my sincere thanks to Prof. Dr. JAGANNATHAN,


Vice Chancellor, Periyar University, Salem who has been an invaluable for
providing the facility to complete this mini project successfully.

I would like to extend my sincere thanks to.


Dr.C.CHANDRASEKAR,M.C.A,Ph.D, Senior Professor, Head of the
Department, Department of Computer Science, Periyar University, Salem. For
the support and encourage.

I acknowledge with thanks the kind patronage, loving inspiration and


timely guidance which I have received from my Dr. I. LAURENCE
AROQUIRAJ M.Sc., M.Phil., M.Tech., M.C.A, Professor, and Department of
Computer Science, Periyar University.

I extend my thanks to my parents and well-wishes for their constant support


and encouragement.

Place: Salem-636011 Signature of the student

Date: [KAVIYARASAN S]
DECLARATION

I hereby, declare that the major project report entitled as “KS SMART
ONLINE GROCERY SHOPPING WEB APPLICATION” submitted to
Periyar University in partial fulfillment of their requirements for the award of
Degree of MASTER OF SCIENCE IN COMPUTER SCIENCE in the record
work carried out by me, under the supervision of Dr.I LAURENCE AROQUIARAJ
M.Sc., M.Phil., M.Tech., M.C.A., Ph.D. Professor, Department of Computer
Science, Periyar University, Salem-11, during the year 2023-2025. To the best of
my Knowledge, the work reported here in not part of which a degree or award
was conferred on an earlier to one or any other candidate.

Place: Salem-636011 Signature of the student

Date: [KAVIYARASAN S]
CONTENTS

CHAPTER INDEX PAGE NO.


NO.
ABSTRACT 1

1 INTRODUCTION 2

SYSTEM CONFIGURATION
2 2.1 HARDWARE REQUIREMENTS 3

2.2 SOFTWARE REQUIREMENTS


6
3 SYSTEM STUDY

4 IMPLEMENTATION 8
5 DEPENDENCIES 11
6 USAGE AND LIMITATIONS OF THE SYSTEM 13

18
7 TESTING
21
8 CONCLUSION

9
FUTURE ENHANCEMENT 22

10
BIBLIOGRAPHY 24
APPENDIX
11 11.1 FLOWCHART AND CASE DIAGRAM 25
11.2 SOURCE CODE
11.3 RESULT
ABSTRACT

The grocery e-commerce system is a web-based platform designed to provide users with a
seamless online shopping experience for groceries and household essentials. Built using
modern technologies such as React, Vite, and TailwindCSS for the frontend, and Node.js
with Express for the backend, the system offers an intuitive interface for product browsing,
filtering, and purchasing.

The integration of Context API ensures efficient state management, particularly for the
shopping cart functionality. Secure authentication is implemented using JSON Web
Tokens (JWT) and password hashing with bcrypt. Users can add products to their cart,
update quantities, and proceed to checkout, with order details stored securely in a MySQL
database.

While the system currently lacks a payment gateway for online transactions, it supports
essential features for managing orders and tracking their status. Future enhancements may
include payment gateway integration, AI-powered product recommendations, real-time
notifications, and enhanced security features.

The grocery e-commerce system serves as a scalable and user-friendly solution, providing
a solid foundation for further development and expansion in the e-commerce sector.

1
CHAPTER - 1
INDRODUCTION

The grocery e-commerce system is a web-based platform designed to simplify the online
shopping experience for users by providing a convenient and efficient way to browse,
select, and purchase groceries. With the growing demand for online shopping, especially
in the grocery sector, this system addresses the need for a user-friendly platform that offers
seamless product discovery, secure transactions, and efficient order management.
The system consists of a frontend built using React and Vite, offering a responsive and
interactive user interface. TailwindCSS is used to ensure a clean and modern design. The
backend is powered by Node.js and Express, managing user authentication, product data,
and order processing. Secure authentication is achieved using JWT (JSON Web Tokens),
while bcrypt ensures password hashing for user data protection. Data management and
storage are handled using a MySQL database.
Key functionalities of the system include product listing, category filtering, and a shopping
cart feature using Context API for state management. Users can add products to their cart,
modify quantities, and proceed to checkout. Additionally, the system supports order
tracking, allowing users to monitor their purchases. Although a payment gateway is not
currently integrated, the architecture is designed to support future enhancements such as
payment processing, real-time notifications, and AI-driven product recommendations.
This project aims to provide a scalable and robust solution for grocery shopping, offering
both convenience to customers and operational ease for administrators. The grocery e-
commerce system serves as a foundation for further development, ensuring adaptability to
meet evolving user and business requirements.

2
CHAPTER - 2
SYSTEM CONFIGURATION

1. Hardware Requirements
• Processor: Intel Core i5 or equivalent (Minimum)
• RAM: 8 GB (Minimum), 16 GB (Recommended for smooth
development)
• Storage: 100 GB of free space for development and database storage
• Graphics: Integrated or dedicated GPU for UI testing (Optional)
• Network: Stable internet connection for API testing and package
management

🛠 2. Software Requirements
Frontend:
• Operating System: Windows, macOS, or Linux
• IDE/Code Editor: Visual Studio Code or any compatible editor
• Node.js: Version 18 or later
• Vite: Version 6 or later
• React: Version 19
• TailwindCSS: Latest version for UI styling
• Axios: For API integration
• NPM or Yarn: For package management

3
Backend:
• Node.js: Version 18 or later
• Express: Latest version for backend server management
• MySQL: Version 8.0 or later for database management
• Bcrypt: For password hashing
• JWT (JSON Web Tokens): For authentication
• Nodemon: For real-time server monitoring during development

3. Database Configuration
• Database Management System: MySQL
• Database Name: grocery_db
• User Management: Configured with secure credentials
• Tables: Users, Products, Orders, Cart, Categories
• Connection: Backend uses mysql2 library for database interaction

4. Development Tools
• Postman or Insomnia: For API testing
• Git: For version control and collaboration
• Docker (Optional): For containerized deployment
• Jest or Mocha: For unit and integration testing

4
5. Additional Configurations
• Environment Variables:
o .env file for storing sensitive data like database credentials and JWT
secret keys.
• API Base URL: Configured in the frontend for API requests.
• Port Configuration:
o Frontend: Typically runs on localhost:5173
o Backend: Typically runs on localhost:3000
• CORS: Enabled for cross-origin requests using Express middleware.

5
CHAPTER - 3
SYSTEM STUDY
The system study is a crucial phase in the development of any software application,
including the grocery e-commerce system. It involves understanding the existing
problems, analyzing user requirements, identifying system objectives, and proposing an
effective solution. Here's a breakdown of the system study for this project:

1. Existing System (Manual or Traditional Grocery Shopping)


• Customers visit physical stores to purchase groceries.
• No real-time stock visibility or product comparisons.
• Limited options for customers with disabilities or those in remote areas.
• Time-consuming and often inconvenient.
• No order tracking or personalized recommendations.

Limitations of the Existing System


• Inconvenient shopping experience, especially during peak hours or emergencies.
• Requires physical presence and manual effort.
• No digital record of past purchases or spending patterns.
• Lack of customization and filtering options.
• Inefficient for bulk or scheduled purchases.

Proposed System (Online Grocery E-Commerce)


• A user-friendly online platform to browse, search, and purchase grocery items.
• Real-time inventory management to avoid out-of-stock issues.
• Secure user registration and login using JWT authentication.
• Smart cart system using React Context API to handle cart operations.
6
• Order management and tracking system for a transparent experience.
• Scalable architecture to support future enhancements like online payments,
notifications, and recommendations.

Feasibility Study
• Technical Feasibility: Uses well-supported technologies (React, Node.js,
MySQL) ensuring a stable system.
• Economic Feasibility: Reduces overhead costs of physical operations and reaches
a wider market.
• Operational Feasibility: Easy to use and maintain, even for non-technical users
and admins.
• Schedule Feasibility: Modular development allows implementation within a
reasonable timeframe.

Objective of the System Study


• Understand user and business needs for a digital grocery platform.
• Identify gaps in the current process and solve them through automation.
• Develop a scalable, secure, and responsive e-commerce application.

7
CHAPTER - 4
IMPLEMENTATION

1. Frontend Implementation (React + Vite + TailwindCSS)


Key Technologies:
• React: For building reusable UI components.
• Vite: For fast development and bundling.
• TailwindCSS: For responsive and utility-first UI styling.
• Axios: For making HTTP requests to the backend.
• React Context API: For managing global cart state across components.
Features Implemented:
• Product Listing Page: Fetches and displays all products from the backend.
• Category Filtering: Users can filter products based on categories.
• Cart Page: Users can view, update, and remove products from their cart.
• Checkout Page: Collects user address and prepares order summary.
• User Authentication: Login and signup forms that communicate with the backend
API.

🛠 2. Backend Implementation (Node.js + Express)


Key Technologies:
• Node.js: JavaScript runtime for server-side development.
• Express.js: Lightweight web framework for building RESTful APIs.
• MySQL: Relational database to store users, products, and orders.
• bcrypt: For secure password hashing.
• jsonwebtoken (JWT): For secure user login and token-based authentication.
8
Features Implemented:
• User Routes:
o /register: Registers a new user with hashed password.
o /login: Authenticates user and returns a JWT token.
• Product Routes:
o /products: Fetches all products.
o /products/:category: Filters products by category.
• Cart & Order Routes:
o Cart operations are handled on the frontend using Context API.
o Orders are submitted to the backend and stored in the database.
• Middleware:
o Authentication middleware to protect private routes using JWT.

3. Database Design (MySQL)


Tables:
• Users: Stores user information (ID, name, email, password).
• Products: Stores product details (ID, name, category, price, image).
• Orders: Stores order data (order ID, user ID, product details, total amount, status).
• Categories: Stores available product categories.

4. API Communication
• Frontend uses Axios to communicate with the Express API.
• All user, product, and order actions are done through RESTful API endpoints.
• JWT token is stored in local storage and attached to requests that require
authentication.

9
5. Security Features
• Passwords are hashed before being stored using bcrypt.
• Protected routes (like order placement) require a valid JWT token.
• User input is validated on both frontend and backend to prevent SQL injection or
malformed data.

10
CHAPTER - 5
DEPENDENCIES
There are numerous package.json files, most of which are from
node_modules, which are not what we are looking for. However, it seems like
the main project directories are /grocery/grocery-ecommerce and
/grocery/server. I'll check the package.json in those locations to find the actual
dependencies.

I found both the frontend and backend package.json files. I'll extract and
display the dependencies from them now.

Frontend Dependencies

• @google/generative-ai: ^0.24.0

• autoprefixer: ^10.4.20

• axios: ^1.8.0

• postcss: ^8.5.3

• react: ^19.0.0

• react-dom: ^19.0.0

• react-router-dom: ^7.2.0

• tailwindcss: ^3.4.17

DevDependencies:

• @eslint/js: ^9.19.0

11
• @types/react: ^19.0.8

• @types/react-dom: ^19.0.3

• @vitejs/plugin-react: ^4.3.4

• eslint: ^9.19.0

• eslint-plugin-react: ^7.37.4

• eslint-plugin-react-hooks: ^5.0.0

• eslint-plugin-react-refresh: ^0.4.18

• globals: ^15.14.0

• vite: ^6.1.0

Backend Dependencies

• bcrypt: ^5.1.1

• cors: ^2.8.5

• express: ^4.21.2

• jsonwebtoken: ^9.0.2

• mysql2: ^3.12.0

• nodemon: ^3.1.9

DevDependencies:

• @types/bcrypt: ^5.0.2

• @types/express: ^5.0.0

• @types/jsonwebtoken: ^9.0.

12
CHAPTER - 6
USAGE

Frontend (React + Vite)


1. react, react-dom, react-router-dom
o For building the UI and creating components.
o react-router-dom handles client-side routing.
2. tailwindcss, autoprefixer, postcss
o tailwindcss for utility-first CSS.
o postcss and autoprefixer handle CSS transformations and
browser compatibility.
3. axios
o For making API requests (e.g., fetching product data or
submitting orders).
4. @google/generative-ai
o Possibly used for AI-driven features like product
recommendations or chatbots.

Development Tools
1. vite, @vitejs/plugin-react
o Vite is a fast build tool and development server.
o Plugin for supporting React in Vite.
2. eslint, eslint-plugin-react, eslint-plugin-react-hooks
o For code linting and maintaining code quality.
3. @eslint/js, globals

13
o Provides ESLint rules and configuration.
4. @types/react, @types/react-dom
o TypeScript type definitions for React and DOM.

Backend (Node.js + Express)


1. express
o Core web server framework to create API endpoints.
2. cors
o Enables Cross-Origin Resource Sharing for API requests
from the frontend.
3. bcrypt
o Used for password hashing and authentication.
4. jsonwebtoken
o For authentication using JSON Web Tokens (JWT).
5. mysql2
o Database driver to connect to a MySQL database.
6. nodemon
o For automatically restarting the server during development.

Backend Development Tools


1. @types/bcrypt, @types/express, @types/jsonwebtoken
o TypeScript definitions to enable type checking in the
backend.

14
LIMITATIONS OF THE SYSTEM

1. Functional Limitations
• Basic Cart Management:
o While the cart feature is implemented, it may lack advanced
functionalities like product recommendations, wishlists, or
abandoned cart recovery.
• No Payment Gateway Integration:
o If there's no payment gateway, it can’t process online payments,
limiting transactions to cash on delivery.
• Limited Product Customization:
o Users may not be able to customize orders (e.g., selecting product
variants or quantities easily).
• Lack of Real-Time Updates:
o Without WebSocket or polling, the cart or product availability might
not reflect real-time changes.

2. Technical Limitations
• Client-Side Heavy:
o Relying on React and Vite without server-side rendering (SSR) may
impact SEO and initial load time.
• API Dependency:
o If the backend APIs are down or fail, the frontend has no offline
mode or graceful error handling.
• Limited Scalability:
o Using a single MySQL database without sharding or load balancing
may lead to performance issues under high traffic.

15
• No Caching Mechanism:
o Without caching, frequent database queries may increase server load
and response time.

3. Security Limitations
• Weak Authentication:
o JWT-based authentication is useful but may lack features like multi-
factor authentication (MFA).
• Password Management:
o While bcrypt ensures password hashing, no additional security
measures like rate limiting or account lockout are mentioned.
• Data Exposure:
o Lack of encryption for sensitive data transmission can lead to
potential data leaks.

4. User Experience Limitations


• No Personalization:
o Without AI-driven recommendations or personalized content, users
may find it difficult to discover products.
• Limited Error Handling:
o If Axios requests fail, there may be no detailed error messages or
fallback behavior.
• Mobile Responsiveness:
o While Tailwind CSS ensures responsive design, further testing is
needed to optimize for different devices.

16
5. Future Expansion Limitations
• No Multi-Vendor Support:
o The system seems designed for a single vendor. Supporting multiple
vendors would require significant architectural changes.
• Lack of Analytics:
o No tools for tracking user behavior, product performance, or sales
analytics are integrated.
• No Notification System:
o Users may not receive order updates, promotions, or notifications
without a real-time notification feature.

17
CHAPTER - 7
TESTING
✅ 1. Unit Testing
• Purpose: Test individual components, functions, or modules.
• Tools:
o Frontend: Jest, React Testing Library
o Backend: Mocha, Chai, Supertest
• Examples:
o Test React components like ProductCard, Cart, or Filters.
o Verify API endpoints using mock requests.
o Test utility functions like price calculations.

🧪 2. Integration Testing
• Purpose: Test interactions between components and services.
• Tools:
o Jest with Mock Service Worker (MSW)
o Supertest for API testing
• Examples:
o Test the communication between the frontend and backend.
o Verify if product data is fetched and displayed correctly.
o Check if the cart updates correctly when items are added.

🖥️ 3. End-to-End (E2E) Testing


• Purpose: Test the entire user journey.
• Tools:
o Cypress, Playwright

18
• Examples:
o Simulate a user browsing products, adding items to the cart, and
completing a checkout.
o Verify error handling when APIs fail.

🔐 4. Security Testing
• Purpose: Identify vulnerabilities and ensure data protection.
• Tools:
o OWASP ZAP, Postman for API security testing
• Examples:
o Test JWT token validation for authentication.
o Perform SQL injection and XSS attack tests.

📊 5. Performance Testing
• Purpose: Ensure the system handles traffic efficiently.
• Tools:
o Apache JMeter, k6
• Examples:
o Simulate thousands of concurrent users to test backend API
performance.
o Monitor response time and server resource consumption.

🛡️ 6. User Acceptance Testing (UAT)


• Purpose: Validate if the application meets business requirements.
• Process:
o Provide a demo environment for stakeholders.
o Gather feedback through surveys or observation.

19
🧰 7. Recommended Tools for Your Tech Stack
• Frontend: Jest, React Testing Library, Cypress
• Backend: Mocha, Chai, Supertest
• API: Postman, Insomnia
• CI/CD: GitHub Actions, CircleCI for automated testing

20
CHAPTER - 8
CONCLUSION

The grocery e-commerce system is a well-structured application that uses


modern technologies such as React, Vite, and TailwindCSS for the frontend, and
Node.js with Express for the backend. It effectively manages product data and
cart functionality using Context API and Axios for API requests. The backend
ensures secure authentication with JWT tokens and bcrypt for password hashing.
While the system offers a solid foundation with responsive UI and basic cart
management, it has limitations, including the lack of advanced features like
product recommendations, personalized content, and real-time updates.
Additionally, the absence of a payment gateway restricts it to basic order
management. Enhancing the system with secure payment integration, improved
authentication mechanisms, and AI-driven recommendations would significantly
improve user experience. Implementing end-to-end and unit tests using Jest or
Cypress, alongside performance monitoring with tools like JMeter or k6, would
ensure the system's reliability and scalability. Overall, with further development
and testing, this grocery e-commerce system has the potential to become a robust
and user-friendly platform.

21
CHAPTER - 9

FUTURE ENHANCEMENT

Real-Time Updates:
Implement WebSocket or similar technologies for dynamic cart updates,
inventory tracking, and order status notifications.
AI-Driven Recommendations:
Provide personalized product suggestions based on user preferences and
shopping behavior.
Review and Rating System:
Allow users to rate and review products to enhance customer trust and
decision-making.
Multi-Vendor Support:
Expand the platform to support multiple sellers, increasing product variety
and competition.
Enhanced Security:
Implement multi-factor authentication (MFA), role-based access control
(RBAC), and improved API security.
Analytics and Reporting:
Integrate tools for real-time data analysis, generating insights into user
behavior and sales performance.
Microservices Architecture:
Improve scalability and maintainability by breaking the system into
smaller, independent services.
Caching Mechanisms:
Use solutions like Redis to reduce database load and improve response
times.

22
Progressive Web App (PWA):
Develop a PWA version to ensure a seamless, app-like experience on
mobile and desktop devices.
Order Tracking and Notifications:
Provide real-time order tracking with push notifications to keep users
informed.
Loyalty and Reward Programs:
Implement a point-based loyalty system to encourage repeat purchases and
customer retention.

23
CHAPTER - 10

BIBLIOGRAPHY

1. React Documentation - React: A JavaScript library for building user interfaces.


Available at: https://react.dev
2. Vite Documentation - Vite: A modern build tool and development server. Available
at: https://vitejs.dev
3. TailwindCSS Documentation - Tailwind CSS: A utility-first CSS framework.
Available at: https://tailwindcss.com
4. Node.js Documentation - Node.js: JavaScript runtime environment. Available at:
https://nodejs.org
5. Express Documentation - Express: A minimal Node.js web application framework.
Available at: https://expressjs.com
6. Axios Documentation - Axios: A promise-based HTTP client for making API
requests. Available at: https://axios-http.com
7. JWT Documentation - JSON Web Tokens (JWT) for secure authentication.
Available at: https://jwt.io
8. Bcrypt Documentation - Bcrypt: A library for hashing passwords. Available at:
https://www.npmjs.com/package/bcrypt
9. MySQL Documentation - MySQL: A relational database management system.
Available at: https://dev.mysql.com/doc
10.Nodemon Documentation - Nodemon: A tool for automatically restarting Node.js
applications. Available at: https://www.npmjs.com/package/nodemon

24
CHAPTER - 11
APPENDIX
11.1 FLOWCHART :

25
CASE DIAGRAM :

ARCHITECTURE :

26
11.2 SOURCE CODE :

Index.html:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css
" rel="stylesheet" integrity="sha384-
QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6h
W+ALEwIH" crossorigin="anonymous">
<link rel="icon" type="image/svg+xml" href="https://encrypted-
tbn0.gstatic.com/images?q=tbn:ANd9GcSjcCHQfg7G7N-
8mR_UGJqqnq0ebvLY9e_HhgNrOEBaebV8TZp2_BSBWXgHuyIrabSHEtI
&usqp=CAU" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery online shop</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

App.jsx:

import React, { useState } from 'react';


import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
// import DemoProduct from './components/DemoProduct';
import NavBar from './components/NavBar';
import './components/DemoProduct.css';
import './components/NavBar.css';
import ProductsPage from './components/ProductsPage';
import './components/ProductsPage.css';
27
import CartPage from './components/CartPage';
import './components/CartPage.css';
import AdminPage from './components/AdminPage';
import './components/AdminPage.css';
import HomePage from './components/HomePage';
import Footer from './components/Footer';
import Register from './components/Register';
import Login from './components/Login';
import ParentComponent from './components/ParentComponent';
import { ProductProvider } from './components/ProductContext';

const App = () => {


const [cart, setCart] = useState([]);
const [searchQuery, setSearchQuery] = useState('');
return (
<ProductProvider>
<Router>
<NavBar setSearchQuery={setSearchQuery} />
<Routes>
<Route path="/" element={<HomePage setCart={setCart} />} />
<Route path="/products" element={<ProductsPage
setCart={setCart} searchQuery={searchQuery} />} />
<Route path="/cart" element={<CartPage cart={cart} />} />
<Route path="/admin" element={<AdminPage />} />
<Route path="/register" element={<Register />} />
<Route path="/login" element={<Login />} />
<Route path="/demo-products" element={<ParentComponent />}
/>
</Routes>
<Footer />
</Router>
</ProductProvider>
);
};

export default App;


Home.jsx:
28
import React, { useState, useEffect, useRef } from 'react';
import DemoProduct from './DemoProduct';
import { useNavigate } from 'react-router-dom';
import './HomePage.css';
import { GoogleGenerativeAI } from "@google/generative-ai";

const HomePage = () => {


const [cart, setCart] = useState([]);
const [isResponseScreen, setisResponseScreen] = useState(false);
const [messages, setMessages] = useState([{ sender: "bot", text: "Hello! How
can I help you?" }]);
const [message, setMessage] = useState("");
const [isLoading, setIsLoading] = useState(false);

const navigate = useNavigate();


const scrollContainerRef = useRef(null);

const images = [
'https://t4.ftcdn.net/jpg/10/12/78/81/240_F_1012788183_sTeQ5erXIWN
djXCD9vxbOL6DD7VCIVi0.jpg',
'https://as2.ftcdn.net/v2/jpg/02/08/39/07/1000_F_208390795_ZJCAgG8i
Z02jp1PgN7oAHfiK76Qbmc9B.jpg',
'https://t3.ftcdn.net/jpg/06/94/61/54/240_F_694615457_lquEGMmKewy
MjAfoQKo5zsTMS92iW6U4.jpg',
'https://t3.ftcdn.net/jpg/00/81/83/04/240_F_81830420_ewjyAWnwt1XS
2dpiaMWW9KJwQ4KjsQkM.jpg',
'https://t3.ftcdn.net/jpg/09/49/50/86/240_F_949508651_9WrpT5CRmPx
J7DJH53i8MHjc6GVMb5WI.jpg'
];

const addToCart = (product) => {


setCart([...cart, product]);
navigate('/cart');
};

useEffect(() => {
29
const scrollContainer = scrollContainerRef.current;
let scrollAmount = 0;
const scrollStep = 500;

const intervalId = setInterval(() => {


if (scrollContainer) {
if (scrollAmount >= scrollContainer.scrollWidth / 2) {
scrollAmount = 0;
scrollContainer.scrollTo({ left: 0, behavior: 'smooth' });
}
scrollAmount += scrollStep;
scrollContainer.scrollLeft = scrollAmount;
}
}, 5000);

return () => clearInterval(intervalId);


}, []);

const hitRequest = () => {


if (message) {
generateResponse(message);
} else {
alert("You must write something.... !");
}
};

const generateResponse = async (msg) => {


if (!msg) return;

setIsLoading(true);
try {
const genAI = new
GoogleGenerativeAI(import.meta.env.VITE_GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"
});
const result = await model.generateContent(msg);
const newMessages = [
30
...messages,
{ sender: "user", text: msg },
{ sender: "bot", text: result.response.text() },
];
setMessages(newMessages);
setisResponseScreen(true);
setMessage("");
} catch (error) {
console.error("Gemini API Error:", error);
setMessages([...messages, { sender: "bot", text: "Oops! Something went
wrong. Please try again." }]);
} finally {
setIsLoading(false);
}
};

useEffect(() => {
const chatContainer = document.querySelector('.chatbot-messages');
if (chatContainer) {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
}, [messages, isLoading]);

useEffect(() => {
if (isResponseScreen) {
setTimeout(() => {
document.querySelector(".chatbot-input input")?.focus();
}, 0);
}
}, [isResponseScreen]);

return (
<>
<div>
<header className="header">
<h1 class="modern-heading">Welcome to Our Grocery Store!</h1>
<link
31
href="https://fonts.googleapis.com/css2?family=Poppins:wght@600&display
=swap" rel="stylesheet">
</link>
<div className='para'>

<p>Fresh and quality groceries delivered to your


doorstep.</p></div>
</header>

<main className="main-content">
<section className="horizontal-scroll">
<h2>Our Best Picks</h2>
<hr />
<div className="carousel-wrapper">
<div className="scroll-container" ref={scrollContainerRef}>
{images.concat(images).map((src, index) => (
<img key={index} src={src} alt={`Product ${index +
1}`} />
))}
</div>
<button className="shop-now-overlay" onClick={() =>
navigate('/products')}>
Shop Now
</button>
</div>
</section>
</main>
</div>

<DemoProduct setCart={setCart} />

{/* Chatbot Button */}


<div className="chatbot-container">
<button className="chatbot-toggle" onClick={() =>
setisResponseScreen(!isResponseScreen)}>
Chat with Us
32
</button>

{isResponseScreen && (
<div className="chatbot-popup">
<div className="chatbot-header">
<h4>Chatbot</h4>
<button onClick={() =>
setisResponseScreen(false)}>✖</button>
</div>
<div className="chatbot-messages">
{messages.map((msg, index) => (
<div key={index} className={`chat-message
${msg.sender}`}>
{msg.text}
</div>
))}
{isLoading && <div className="chat-message
bot">Typing...</div>}
</div>
<div className="chatbot-input">
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && hitRequest()}
placeholder="Type your message..."
/>
<button onClick={hitRequest}>Send</button>
</div>
</div>
)}
</div>
</>
);
};

33
export default HomePage;

Register.jsx:

import { useState } from 'react';


import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import './Register.css';

const Register = () => {


const [values, setValues] = useState({
username: '',
email: '',
password: '',
});

const [errorMsg, setErrorMsg] = useState('');


const navigate = useNavigate();

const handleChanges = (e) => {


setValues({ ...values, [e.target.name]: e.target.value });
};

const handleSubmit = async (e) => {


e.preventDefault();

if (!values.username || !values.email || !values.password) {


setErrorMsg('All fields are required.');
return;
}

try {
const response = await axios.post('http://localhost:3000/auth/register',
values);
if (response.status === 201) {
navigate('/login');
}
34
} catch (err) {
setErrorMsg('Registration failed. Try again.');
console.log(err.message);
}
};

return (
<div className="register-bg">
<div className="glass-card">
<h2 className="glass-title">Create Account</h2>
{errorMsg && <p className="glass-error">{errorMsg}</p>}
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
placeholder="Username"
className="glass-input"
onChange={handleChanges}
/>
<input
type="email"
name="email"
placeholder="Email"
className="glass-input"
onChange={handleChanges}
/>
<input
type="password"
name="password"
placeholder="Password"
className="glass-input"
onChange={handleChanges}
/>
<button type="submit" className="glass-button">
Register
</button>
</form>
35
<div className="glass-footer">
<span>Already have an account?</span>
<Link to="/login" className="glass-link">
Login
</Link>
</div>
</div>
</div>
);
};

export default Register;

Login.jsx:

import { useState } from 'react';


import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import './Login.css'; // Import the new CSS

const Login = () => {


const [values, setValues] = useState({ email: '', password: '' });
const [errorMsg, setErrorMsg] = useState('');
const navigate = useNavigate();

const handleChanges = (e) => {


setValues({ ...values, [e.target.name]: e.target.value });
};

const handleSubmit = async (e) => {


e.preventDefault();

if (!values.email || !values.password) {
setErrorMsg('All fields are required.');
return;
}
36
try {
const response = await axios.post('http://localhost:3000/auth/login', values);
if (response.status === 201) {
localStorage.setItem('user', JSON.stringify(response.data));
navigate('/');
}
} catch (err) {
setErrorMsg('Invalid email or password.');
console.log(err.message);
}
};

return (
<div className="login-bg">
<div className="glass-card">
<h2 className="glass-title">Welcome Back</h2>
{errorMsg && <p className="glass-error">{errorMsg}</p>}
<form onSubmit={handleSubmit}>
<input
type="email"
name="email"
placeholder="Email Address"
className="glass-input"
onChange={handleChanges}
/>
<input
type="password"
name="password"
placeholder="Password"
className="glass-input"
onChange={handleChanges}
/>
<button type="submit" className="glass-button">
Sign In
</button>
</form>
37
<div className="glass-footer">
<span>New here? </span>
<Link to="/register" className="glass-link">
Create an account
</Link>
</div>
</div>
</div>
);
};

export default Login;

AdminPage.jsx:

import React, { useState } from "react";


import axios from "axios";
import "./AdminPage.css";

const AdminPage = () => {


const [product, setProduct] = useState({
name: "",
category: "",
price: "",
image: "",
description: "",
});
const [searchName, setSearchName] = useState("");
const [orders, setOrders] = useState([]);

const handleChange = (e) => {


setProduct({ ...product, [e.target.name]: e.target.value });
};

const handleSubmit = async (e) => {


e.preventDefault();
38
if (!product.name || !product.category || !product.price || !product.image ||
!product.description) {
alert("Please fill all fields");
return;
}

try {
const response = await axios.post("http://localhost:3000/auth/add-product",
product);
alert(response.data.message);
setProduct({ name: "", category: "", price: "", image: "", description: "" });
} catch (error) {
console.error("Error adding product:", error);
alert("Failed to add product");
}
};

const handleSearch = async () => {


if (!searchName) {
alert("Please enter a user name to search.");
return;
}
try {
const response = await
axios.get(`http://localhost:3000/auth/orders?name=${searchName}`);
setOrders(response.data.orders);
} catch (error) {
console.error("Error fetching orders:", error);
alert(error.response?.data?.message || "Failed to fetch order details.");
}
};

return (
<div className="admin-bg">
<div className="admin-page">
<h2>Admin Page - Add Product</h2>
<form onSubmit={handleSubmit} className="admin-form">
39
<input type="text" name="name" placeholder="Product Name"
value={product.name} onChange={handleChange} />
<select name="category" value={product.category}
onChange={handleChange}>
<option value="">Select Category</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Dairy">Dairy</option>
<option value="Bread & Baked goods">Bread & Baked goods</option>
<option value="Meat & Fish">Meat & Fish</option>
<option value=" Cans & Jars">Cans & Jars</option>
<option value=" Pasta,rice & cereals">Pasta,rice & cereals</option>
<option value=" Sauces & Condiments">sauces & condiments</option>
<option value=" Herbs & Spices">Herbs & Spices</option>
<option value="Frozen Foods">Frozen Foods</option>
<option value=" Drinks">Drinks</option>
<option value="Household & Cleaning">Household &
Cleaning</option>
</select>
<input type="text" name="measurement"
placeholder="measurementPrice" value={product.measurement}
onChange={handleChange} />
<input type="number" name="price" placeholder="Price"
value={product.price} onChange={handleChange} />
<input type="text" name="image" placeholder="Image URL"
value={product.image} onChange={handleChange} />
<textarea name="description" placeholder="Product Description"
value={product.description} onChange={handleChange}></textarea>
<button type="submit">Add Product</button>
</form>
<br></br>
<h2>Search Orders by User Name</h2>
<input
type="text"
placeholder="Enter user name"
value={searchName}
onChange={(e) => setSearchName(e.target.value)}
40
/>

<button className="srb" onClick={handleSearch}>Search</button>


{orders.length > 0 && (
<table className="orders-table">
<thead>
<tr className="tab">
<th className="t">Customer Name</th>
<th>Contact Number</th>
<th>Address</th>
<th>Total Cost</th>
<th>Payment Method</th>
<th>Order Items</th>
<th>Date & Time </th>
</tr>
</thead>
<tbody>
{orders.map((order, index) => (
<tr key={index} className="tab">
<td className="ta">{order.customerName}</td>
<td>{order.contactNumber}</td>
<td>{order.address}</td>
<td>₹{order.totalCost}</td>
<td>{order.paymentMethod}</td>
<td>
<ul>
{order.cartItems.map((item, i) => (
<li key={i}>{item.name} (x{item.quantity})</li>
))}
</ul>
</td>
<td>
{new Intl.DateTimeFormat("en-GB", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
41
minute: "2-digit",
second: "2-digit",
hour12: false,
}).format(new Date(order.created_at))}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
};

export default AdminPage;

Server .env:

DB_HOST="localhost"
DB_USER="root"
DB_PASSWORD=""
DB_NAME="grocery"
PORT=3000
JWT_KEY="jwt-secret-key"
[email protected]
eMAIL_PASS=Pw-Kavi@2003

users Table:

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
42
11.3 RESULT :

1.Home page

2.Product Page

43
3.Cart Page

4.Register Page

44
5.Login Page

6.Order Summery

45
7.Place Order Successfully

8.Admin Page

46
9.Contact Page

47
10. Contact us Message Received For Admin

48

You might also like