Homespun

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

1

ONLINE HOMEMADE FOOD ORDERING PORTAL


A Project Report Submitted to the Government Arts College (Autonomous),
Coimbatore

In Fulfilments of the requirement

For the Award of Degree of

MASTER OF COMPUTER APPLICATIONS


Submitted by

MAREESWARI J
REG. NO :22MCA503

Under the Guidance of

Dr. R.A. ROSELINE M.Sc., M.Phil., Ph.D.,.

Associate Professor & Head

POST GRADUATE AND RESEARCH DEPARTMENT OF COMPUTER APPLICATIONS

GOVERNMENT ARTS COLLEGE (AUTONOMOUS), COIMBATORE-641 018

Re-accredited wit "B++" Grade by NACC. Affiliated to Bharathiar University.


1

DECLARATION

I here declare that this project, entitled with "BAKERY MANAGEMENT


SYSTEM" Submitted to the Government Arts College (Autonomous),
Coimbatore in fulfillment of the requirements for the award of the Degree of
Master of Computer Applications is a bonafide record of the original project
work done by under the Supervision and guidance of Dr. R.A. Roseline, M.Sc.
,M.Phil., Ph .d., Associate Professor, Post Graduate and Research Department
of Computer Applications , Government Arts College (Autonomous),
Coimbatore641 018.

PLACE : Coimbatore Signature of the Candidate

DATE : (MAREESWARI J)

22MCA503
2

CERTIFICATE

This is to certify that the project entitled "BAKERY MANAGEMENT SYSTEM" is a


record of an original project work done by MAREESWARI J (22MCA503)
Submitted to Bharathiyar University in a fulfillment of the requirement for the
award of the Degree of MASTER OF COMPUTER APPLICATIONS.

Head of the Department Signature of the


Guide

Submitted for the project viva-voice examination held on

Internal Examiner External


Examiner
3

ACKNOWLEDGEMENT

I hereby this opportunity to acknowledge my deep sense of gratitude and


heartfelt thanks to our beloved Principal Dr. R. ULAGI M.Sc., M.Phil., Ph.D.,.
Government Arts College (Autonomous), Coimbatore, who has given permission
to carry out the project by providing necessary facilities and permitting me with
all facilities to complete it successfully.

I also express my sincere and profound thanks to the Head of the


Department, Dr. R. A. ROSELINE M.Sc., M. Phil., Ph .D., Associate Professor and
Head, Post Graduate and Research Department of Computer Applications,
Government Arts College (Autonomous), Coimbatore, for her valuable support
and suggestions in my project work.

I would also express my sincere gratitude to my internal guide, Dr. R. A.


ROSELINE M.Sc., M.Phil., Ph. D., Associate Professor and Head, Post Graduate
and Research Department of Computer Applications, Government Arts College
(Autonomous), Coimbatore, for who wrought shaped my project into better one
with her valuable guidance for completion of this project.

Finally, I also express my sincere gratitude to all of my parents and friends


who helped for my career without whose sustained support, I could not have
made my debut in Computer Applications.
4

TABLE OF CONTENT
TITLE PAGE NO.

DECLARATION II

ACKNOWLEDGEMENT IV

ABSTRACT 6

CHAPTER-1: INTRODUCTION

1.1 Overview of the project 8

1.2 Objective of the project 9

CHAPTER-2: SYSTEM STUDY

2.1 Existing System 11

2.2 Proposed System 11

CHAPTER-3: SYSTEM REQUIREMENTS

3.1 System Requirement Specification 13

3.2 Functional Requirements 13

3.3 Non-Functional Requirements 14

CHAPTER-4: SYSTEM ANALYSIS

4.1 Data Flow Diagrams 15

4.2 UML Diagrams 18

4.3 Sequences Diagram 20

4.4 Class Diagrams 24

4.5 E-R Diagram 26

CHAPTER-5: SOFTWARE DEVELOPMENT

5.1 Benefits 26
5

5.2 Software Requirements 26

CHAPTER-6: SYSTEM TESTING AND IMPLEMENTATION 29

CHAPTER-7: CONCLUSION

6.1 Conclusion 30

APPENDIX-A:

1.Source Code 31
2.Enclousers 43

APPENDIX-B:

BIBLIOGRAPHY 48
6

ABSTRACT

The proliferation of online food ordering platforms (HOMESPUN) has


transformed the way consumers access and enjoy homemade cuisine. This
paper presents the development and implementation of an intuitive and
efficient online homemade food ordering portal, leveraging modern web
technologies such as React, MongoDB, Express, and Node.js (MERN stack).

The proposed portal provides a user-friendly interface for customers to


browse through a diverse array of homemade food options and place orders.
Utilizing React, the frontend of the portal offers an interactive and responsive
design, enhancing user engagement and satisfaction. Meanwhile, MongoDB
serves as the backend database, facilitating seamless data storage and retrieval,
ensuring scalability and performance. Express.js, a robust web application
framework, is employed to handle server-side operations, enabling efficient
request handling and routing. Node.js forms the backbone of the application,
facilitating real-time communication between the client and server, ensuring
smooth and uninterrupted user experience.
Key features of the portal include user authentication and authorization
mechanisms, allowing registered users to manage their profiles, track order
history, and receive personalized recommendations based on past orders.
Additionally, the portal incorporates a secure payment gateway, enabling users
to make hassle-free transactions while ensuring the safety of their sensitive
information.
Moreover, the portal integrates advanced search and filtering
functionalities, enabling users to easily discover homemade dishes based on
their preferences, dietary restrictions, and location. Furthermore, the platform
supports seamless communication between customers and homemade food
providers, fostering a sense of community and trust within the online
marketplace.
7

Overall, the proposed online homemade food ordering portal


(HOMESPUN) offers a comprehensive solution for both customers seeking
homemade culinary experiences and food providers looking to showcase their
talents and reach a wider audience. By leveraging the power of React,
MongoDB, Express, and Node.js, the portal delivers a seamless and delightful
user experience, thereby revolutionizing the way homemade food is accessed
and enjoyed in the digital age.
8

CHAPTER-1 INTRODUCTION
1.1 Overview of the project
The Online Homemade Food Ordering Portal is a digital platform designed
to connect home-based cooks with consumers seeking freshly prepared
homemade meals. It serves as a marketplace where individuals can discover,
order, and enjoy a wide variety of homemade dishes conveniently from their
own homes. The portal caters to both food providers, who are typically
passionate home cooks or smallscale culinary entrepreneurs, and consumers
looking for authentic, homemade cuisine.

1.1.1 Key Features

 User Authentication and Profiles: The portal allows users to create


accounts, log in securely, and manage their profiles. Registered users can
save their preferences, view order history, and receive personalized
recommendations based on their past interactions with the platform.

 Product Catalogue Management: Centralized database for garments with


categorization, tagging, and efficient search functionality.

 Shopping Cart and Checkout: Seamless addition/removal of items


to/from the cart with smooth checkout process and multiple payment
options.

 Inventory Management: Real-time tracking of stock levels with


automated alerts for low stock or out-of-stock items.

 Order Processing and Fulfilment: Efficient order confirmation, processing,


and integration with logistics for timely order fulfilment.

 Responsive Design and Cross-Platform Compatibility: Consistent user


experience across devices with responsive design for optimal viewing.

 Security Features: Encryption for secure transactions, SSL protocols, and


multi-factor authentication for data privacy.
9

❖ Reporting and Analytics: Generation of reports on sales, user behaviour,


and inventory status for data-driven decision-making.

❖ System Scalability: Designing the system to handle a growing product


range and user base with future enhancements and integrations in mind.

Overall, the Online Homemade Food Ordering Portal provides a convenient


and reliable platform for individuals to explore, order, and enjoy homemade
culinary experiences, while also empowering home-based cooks to showcase
their talents and reach a wider audience.

1.2 Objective of the project:

 The primary aim is to create a digital platform that enables users to easily
discover and order freshly prepared homemade meals from a diverse
range of home-based cooks.

 The project seeks to provide users with a convenient and hassle-free way
to access homemade food, eliminating the need for extensive meal
preparation and cooking time.

 By connecting consumers with home cooks and small-scale culinary


entrepreneurs, the project aims to support local food businesses and
empower individuals to showcase their culinary talents and share their
homemade dishes with a broader audience.

 A key objective is to maintain the quality and authenticity of homemade


cuisine, ensuring that users receive delicious, homemade meals made
with fresh ingredients and personalized care.
10

 The project aims to foster a sense of community and connection between


food providers and consumers, facilitating communication, feedback, and
interaction within the platform.

 Through intuitive design, efficient functionality, and responsive customer


service, the project seeks to deliver a seamless and enjoyable user
experience that encourages repeat usage and positive word-of-mouth
referrals.

 Another objective is to prioritize user safety and data security by


implementing robust authentication mechanisms, secure payment
processing, and adherence to food safety regulations and guidelines.

 Overall, the objective of the project is to create a comprehensive online


platform that revolutionizes the way homemade food is accessed,
enjoyed, and shared, while also fostering community engagement and
supporting local food businesses.
11

CHAPTER-2 SYSTEM STUDY

2.1 Existing System:

 In the existing system, consumers typically rely on traditional methods for


procuring homemade food, such as cooking at home or purchasing from
local markets, friends, or family members.

 Consumers may face limitations in terms of variety, convenience, and


accessibility when seeking homemade meals, as options are often limited
to personal networks or local community connections.

 The existing system lacks standardized processes and quality control


measures for homemade food procurement.

 Communication channels between buyers and sellers may be limited,


hindering the establishment of trust and rapport within the homemade
food marketplace.

2.2 Proposed System

 The proposed system involves the development of a


comprehensive online platform dedicated to homemade food ordering
and delivery.

 The proposed system offers users unparalleled accessibility and


convenience by providing a user-friendly interface for browsing, ordering,
and tracking homemade meals.
12

 Users can access a wide selection of homemade dishes from the comfort
of their homes, eliminating the need for extensive meal preparation.

 The proposed system incorporates robust features and functionality,


including advanced secure payment processing, user authentication,
order tracking, and communication tools. These features enhance the
overall user experience and ensure seamless transactions between food
providers and consumers.

 The proposed system implements quality assurance measures to uphold


the authenticity, freshness, and safety of homemade meals.

 Food providers may undergo verification processes, and the platform may
enforce food safety standards and guidelines to maintain quality and
hygiene standards.

 The proposed system is designed for scalability and expansion, allowing


for the inclusion of additional features, integration with third-party
services, and expansion into new markets or regions over time.

The proposed system represents a significant advancement over the existing


system, offering users a comprehensive and streamlined solution for accessing
homemade cuisine while fostering community engagement and promoting
quality, safety, and convenience within the homemade
13

CHAPTER-3 SYSTEM REQUIREMENTS

3.1 System Requirement Specification

3.1.1 Software Requirements:


• Operating System: Windows 8 or Linux-based operating system (e.g.,
Ubuntu Server) for hosting backend services, offering stability and
security.
• Database Management System: MongoDB for storing product data, user
information, and session management.
• Backend Framework: Node.js with Express.js for building RESTful APIs and
handling server-side logic.
• Frontend Framework: React.js for building interactive and responsive user
interfaces.
• Package Manager: npm (Node Package Manager) for managing project
dependencies and packages.
• Other Tools: Git for version control, Docker for containerization, and PM2
for process management.
3.1.2 Hardware Requirements
• Servers: Adequate servers or cloud instances to host the backend and
frontend components of the system.
• Storage: Sufficient storage space for storing application code, media files
(images of garments), user data, and backups.
• Networking: Reliable network infrastructure with high-speed internet
connectivity to ensure smooth communication between servers,
databases, and client devices.

3.2 Functional Requirements


14

• User Authentication: Implement user authentication functionalities such


as registration, login, logout, password reset, and session management.
• Product Management: Develop CRUD (Create, Read, Update, Delete)
operations for managing products, categories, and attributes.
• Shopping Cart: Implement functionalities for adding/removing items
to/from the cart, updating quantities, and calculating total prices.
• Order Management: Create APIs for handling order creation, processing,
status updates, and email notifications to users.
• Inventory Management: Develop logic to track inventory levels, update
stock quantities, and send notifications for low stock items.
• User Profiles: Develop APIs to manage user profiles, including viewing
order history, updating personal information
• Payment Integration: Integrate with payment gateways (Stripe) to
facilitate secure online transactions.
• Responsive Design: Design user interfaces to be responsive and
mobilefriendly, ensuring optimal viewing experience across various
devices and screen sizes.

3.3 Non-Functional Requirements:


• Performance: Optimize application performance by minimizing response
times, caching frequently accessed data, and optimizing database queries.
• Security: Implement security measures such as data encryption, input
validation, authentication, authorization, and protection against common
web vulnerabilities.
• Usability: Design intuitive user interfaces with clear navigation,
informative feedback, and accessibility features to enhance user
experience.
• Reliability: Ensure high availability, fault tolerance, and data integrity by
deploying the application on reliable hosting platforms and implementing
backup and recovery mechanisms.
15

These system requirements provide a comprehensive foundation for the


development and deployment of the Online Homemade Food ordering Portal
(Homespun),ensuring that it meets the needs of users, administrators, and
stakeholders while adhering to industry standards and best practices.

CHAPTER-4
SYSTEM ANALYSIS
16

4.1 Data Flow Diagrams

Registration Login
Login Add Products
Profile View Products
View data -COMMERCE
E View
Orders
User Search Update
Orders Admin
Search result SYSTEM
Update Products
Order Request Remove Products
Order Response Inventory
Logout Log out
17

Detailed Level DFD


In detailed level DFDs the main process is divided into sub processes and we
try to find out the flow from one process to another process. We find the
interaction among External entities, processes, sub processes and database.
Use Case Diagrams
A use case diagrams describes a sequence of actions that provide something of
measurable value to an actor and is drawn as a horizontal ellipse an actor is a
person, organization, or external system that plays a role in one or more
interactions with your system.

Home
User Validator

Login

Payment

Order
Admin

Search
Registered Unregistered

Figure 4.3 Overall use case

Un Registered Use Case

Home page

Search

Filters
18

Figure 4.4 Un Registered Use Case


Registered Use Case

Register

Login

Home

Profile

Create Order Payment


Registered

Search

Logout

Figure 4.5 Un Registered Use Case


Administrator Use Case

Home

Login

Create User

Profile

View Order Payment


Administrator

Search

Logout
19

Figure 4.6 Administrator Use Case


4.2 UML ACTIVITY DIAGRAM

Providing
Credentials

No
Validation

Yes

Services Figure 4.7 Administrator Use Case


20

Figure 4.8 Registration Process


21

Administrator Process

Figure 4.8 Administrator Process


22

4.2 SEQUENCE DIAGRAM


23

Figure 4.11 Registration Sequence


24

4.3 CLASS DIAGRAM

Figure 4.12 Class Diagram


25

4.5 E-R DIAGRAM

Figure 4.13 E-R Diagram


26

CHAPTER-5
SOFTWARE DEVELOPMENT
5.1 Benefits:
Benefits for Consumers:

o Users can easily access a wide variety of homemade meals from


the comfort of their homes, eliminating the need for meal
preparation and cooking time.

o The portal provides users with access to a diverse range of


homemade cuisines, catering to different tastes, dietary
preferences, and cultural backgrounds.

o Homemade meals are typically prepared with fresh ingredients


and personalized care, ensuring high-quality, flavorful dishes
that meet consumers' expectations.

o Users have access to detailed information about food providers,


including profiles, menus, pricing, and customer reviews,
enabling informed decisionmaking.

o The platform fosters a sense of community and connection


among users, facilitating communication, feedback exchange,
and cultural exchange within the homemade food ecosystem.

Benefits for Food Providers:

 Home cooks and small-scale culinary entrepreneurs can reach a wider


audience and expand their customer base beyond traditional networks
and geographic limitations.

 The portal provides a centralized platform for food providers to showcase


their culinary talents and promote their homemade dishes to a larger
audience.
27

 Access to an online marketplace can lead to increased sales, revenue, and


business opportunities for food providers, enabling them to grow and
sustain their homemade food businesses.
 By participating in the platform, food providers receive support and
recognition from the community, fostering a sense of pride and belonging
within the local food ecosystem.
Overall, Online Homemade Food Ordering Portal(Homespun)offers a range of
benefits to consumers, food providers, and society at large, including convenience,
quality, community engagement, and economic support for local food businesses.

5.2 Software Requirements

1. Development Tools:
• Integrated Development Environment (IDE): Visual Studio Code for
writing and debugging code.
• Git: Version control system for tracking changes in codebase,
collaboration, and managing source code.
• Node.js: JavaScript runtime environment for executing server-side
code.
• npm (Node Package Manager): Package manager for installing and
managing project dependencies.
• MongoDB Compass: GUI tool for interacting with MongoDB
databases during development.

2. Backend Requirements:
• Node.js: JavaScript runtime environment for building the backend
server.
• Express.js: Web application framework for Node.js to create
RESTful APIs and handle HTTP requests.
• MongoDB: NoSQL database for storing product data, user
information, and session management.
• Mongoose: MongoDB object modeling tool for Node.js to interact
with MongoDB databases.
28

3. Frontend Requirements:
• React.js: JavaScript library for building user interfaces and frontend
components.
• React Router: Library for handling client-side routing in React
applications.
• Axios: HTTP client for making API requests from the frontend to the
backend server.
• Redux (optional): State management library for managing
application state in large-scale React applications.

4. Authentication and Authorization:


• JSON Web Tokens (JWT): Secure token-based authentication
mechanism for verifying user identity and authorizing access to
protected resources.

5. Payment Integration:
• Stripe.js: JavaScript library for integrating Stripe payment gateway
into the application for processing online payments securely.

6. Deployment Tools:
• AWS: Cloud hosting platforms for deploying and scaling the
application in production environments.

7. Testing and Quality Assurance:


• React Testing Library or Enzyme: Libraries for testing React
components and user interfaces.

8. Other Tools and Libraries:


• dotenv: Library for loading environment variables from .env files
into Node.js applications.
• bcrypt: Library for hashing passwords securely before storing them
in the database.
29

• nodemon: Utility for automatically restarting the Node.js server


when changes are detected in the codebase during development.

These software requirements provide the necessary tools and libraries for
developing the System, covering both backend and frontend development,
authentication, payment integration, deployment, testing, and quality
assurance.
30

CHAPTER-6
SYSTEM TESTING AND IMPLEMENTATION SYSTEM TESTING

1. Requirements Verification: Ensure that all functional and non-functional


requirements specified for the system are met.

2. Unit Testing: Test individual components of the system, including


backend APIs, frontend components, and database interactions, using
tools like Jest, Mocha, or React Testing Library.

3. Integration Testing: Test the integration between different modules and


components of the system to ensure they work together as expected.

4. End-to-End Testing: Perform end-to-end tests to simulate real user


scenarios and verify that all system components function correctly
together. Tools like Cypress or Selenium can be used for automated end-
to-end testing.
SYSTEM IMPLEMENTATION
 Deployment Planning: Plan the deployment strategy, including server
setup, database configuration, and environment variables.
 Environment Setup: Set up production and staging environments for
deploying and testing the system.
 Database Migration: Migrate the database schema and seed initial data if
necessary.
 Backend Deployment: Deploy backend services, including Node.js server
and Express.js APIs, on the selected hosting platform (AWS) using Docker
containers or traditional server setup.
 Frontend Deployment: Build the frontend React.js application and deploy
static files to a web server or CDN (Content Delivery Network) for serving
to users.
 Configuration: Configure environment variables, API endpoints, and other
settings for the deployed environments.
31

CHAPTER-7 CONCLUSION

In conclusion, the development of Online Homemade Food Ordering Portal


presents a promising opportunity to create a comprehensive and user-centric
platform for purchasing homemade food online. By leveraging the MERN stack
(MongoDB, Express.js, React.js, Node.js) and integrating essential features such
as product management, user authentication, shopping cart functionality, and
payment integration, this project aims to deliver a seamless and enjoyable
shopping experience for users while providing valuable insights and growth
opportunities for administrators and businesses.
Through the implementation of modern technologies, best practices in
software development, and adherence to industry standards and security
protocols, the online homemade food ordering portal is poised to address the
evolving needs of online shoppers. By focusing on usability, performance,
security, and scalability, the project aims to deliver a robust and reliable
solution that meets the demands of today's competitive e-commerce
landscape.
In summary, the Online homemade food ordering portal represents more than
just an online food ordering platform—it's a testament to innovation,
collaboration, and the relentless pursuit of excellence in software
development. With a focus on user experience, technical excellence, and
business value, this project aims to make a significant impact in the world of e-
commerce and contribute to the success and growth of homemade food in the
digital age.
32

APPENDIX-A 1.Source Code

1.1 Homespun/src/App.js

import './App.css';
import Navbar from './Components/Navbar/Navbar'; import {
BrowserRouter,Routes,Route } from 'react-router-dom';
import Home from './Pages/Home';
import ProductsDiplay from
'./Pages/ProductsDiplay'; import Product from
'./Pages/Product'; import Cart from './Pages/Cart';
import LoginSignup from './Pages/LoginSignup';
import Footer from './Components/Footer/Footer'
; function App() { return (
<div >
<BrowserRouter>
<Navbar/>
<Routes>
<Route path='/' element={<Home/>}/>
<Route path='/breakfast' element={< ProductsDiplay banner={null}
category="breakfast" />} />
<Route path='/lunch' element={<
ProductsDiplay banner={null} category="lunch" />} />
<Route path='/dinner' element={<
ProductsDiplay banner={null} category="dinner" />} />
<Route path='/product' element={<Product />}>
<Route path=':productId' element={<Product/>}/>
</Route>
<Route path='/cart' element={<Cart />} />
<Route path='/login' element={<LoginSignup />} />
</Routes>
<Footer/>
</BrowserRouter>
</div>
);
33

export default App;

1.2 Homespun/src/Components/CartItem.js

import React, {useContext} from 'react' import


'./CartItems.css' import remove_icon from
'../Assets/cart_cross_icon.png' import {ShopContext}
from '../../Context/ShopContext';

const CartItems = () => {


const {getTotalCartAmount, all_product, cartItems, removeFromCart } =
useContext(ShopContext);
// console.log(all_product)
return (
<div className='cartitems'>
<div className="cartitems-main">
<p>Products</p>
<p>Title</p>
<p>Price</p>
<p>Quantity</p>
<p>Total</p>
<p>Remove</p>
</div>
<hr />

{all_product.map((e)=>{ if(cart
Items[e.id]>0)
{
return (
<div className="cartitems-format cartitems-main">
<img src={e.image} alt="" className='carticon-producticon' />
<p>{e.name}</p>
<p> ₹{e.new_price} </p>
<button
className='cartitemsquantity'>{cartItems[e.id]}</button>
<p> ₹{e.new_price * cartItems[e.id]} </p>
<img style={{width: '30px', height: '30px'}}
className='remove' src={remove_icon} onClick={()=>{removeFromCart(e.id)}}
alt="" />
<hr />

</div>)
}
return null;
})}
34

<div className="cartitems-down">
<div className="cartitems-total">
<h1>cart totals</h1>
<div>
<div className="cartitems-total-item">
<p>subtotal</p>
<p> ₹{getTotalCartAmount()}</p>
{/* <p> {total} </p> */}
</div>
<hr />
<div className="cartitems-total-item">
<p>shipping fee</p>
<p>free</p>
</div>
<hr />
<div className="cartitems-total-item">
<h3>total</h3>
<h3> ₹{getTotalCartAmount()} </h3>
</div>
</div>
<button>proceed to checkout</button>
</div>
</div>
</div>
)
}

export default CartItems;

1.3 Homespun/src/Components/Display.js

import React, { useContext } from 'react' import


'./Display.css' import star_icon from
'../Assets/star_icon.png'; import stardull_icon from
'../Assets/star_dull_icon.png' import { ShopContext }
from '../../Context/ShopContext'; const Display =
(props) => { const {product} = props; const
{addToCart} = useContext(ShopContext); return (
<div className='display'>
<div className="display-left">
<div className="display-img">
<img src={product.image} alt="" />
</div>
</div>
<div className="display-right">
<h1>{product.name}</h1>
35

<div className="display-star">
<img src={star_icon} alt="" />
<img src={star_icon} alt="" />
<img src={star_icon} alt="" />
<img src={star_icon} alt="" />
<img src={stardull_icon} alt="" />
<p>(47)</p>
</div>
<div className="display-prices">
<div className="display-oldprice">
₹{product.old_price}
</div>
<div className="display-newprice">
₹{product.new_price}
</div>
</div>
<div className="display-discription">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur,
error eius, neque unde accusantium impedit ratione aspernatur reiciendis
necessitatibus eum quaerat! Culpa incidunt iure consequatur similique itaque
repudiandae amet odit!
</div>
<button onClick={()=> {addToCart(product.id)}} > ADD TO CART</button>
</div>
</div>
)
}

export default Display

1.4 Homespun/src/Components/Navbar.js

import React, { useContext, useState } from 'react';


import './Navbar.css'; import logo_big from
'../Assets/logo_big.png'; import cart_icon from
'../Assets/cart_icon.png'; import { Link } from
'react-router-dom'; import { ShopContext } from
'../../Context/ShopContext'; const Navbar = () => {
const [menu,setMenu] = useState('shop');
const {getTotalCartItems} = useContext(ShopContext);

return (
<div className='navbar'>
<div className='nav-left'>
<img src={logo_big} alt=''/>
<p>HomeSpun</p>
36

</div>
<ul>
<li onClick={()=>{setMenu('home')}} > <Link className='link'
style={{textDecoration: 'none' }} to='/'>Home</Link>{menu===
'home'?<hr/>:<></>} </li>
<li onClick={()=>{setMenu('break-fast')}}><Link className='link'
style={{textDecoration: 'none' }} to='/breakfast'>Break-Fast</Link> {menu===
'break-fast'?<hr/>:<></>}</li>
<li onClick={()=>{setMenu('lunch')}} > <Link
className='link' style={{textDecoration: 'none' }} to='/lunch'>Lunch</Link>
{menu=== 'lunch'?<hr/>:<></>}</li>
<li onClick={()=>{setMenu('dinner')}} > <Link className='link'
style={{textDecoration: 'none' }} to='/dinner'>Dinner</Link> {menu===
'dinner'?<hr/>:<></>}</li>
</ul>
<div className='nav-right'>
{localStorage.getItem('auth-token')
?<button

onClick={()=>{localStorage.removeItem('authtoken');window.location .replace('/')}
}>Logout</button>:
<Link style={{textDecoration: 'none' }}
to='/login'><button>Login</button></Link>
}
{/* <Link style={{textDecoration: 'none' }}
to='/login'><button>Login</button></Link> */}
<Link style={{textDecoration: 'none' }} to='/cart'><img src={cart_icon}
alt=''/></Link>
<div className='cart-count'> {getTotalCartItems()} </div>
</div>
</div>
)
}

export default Navbar

1.5 Homespun/src/Context/ShopContext.js

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


import { useEffect } from 'react'; import all_product
from '../Components/Assets/all_product';

export const ShopContext = createContext(null);

const getDefaultCart = ()=>{ let cart = {};


for (let index = 0; index < 300 +1; index++) {
cart[index] = 0;
37

}
return cart;
}

const ShopContextProvider =(props)=>{

const [all_product,setAll_Product] =useState([]);


const [cartItems,setCartItems]= useState(getDefaultCart());

useEffect(()=>{
fetch('http://localhost:4000/allproducts')
.then((response)=>response.json())
.then((data)=>setAll_Product(data))
},[])

const addToCart = (itemId)=>{


setCartItems((prev)=>({...prev,[itemId]:prev[itemId]+1}))
console.log(cartItems)

}
const removeFromCart = (itemId)=>{ setCartItems((prev)=>({...prev,
[itemId]:prev[itemId]-1}))

}
const getTotalCartAmount = ()
=> { let totalAmount = 0;
for(const item in cartItems){
if(cartItems[item]>0){
let itemInfo = all_product.find((itemss)=>itemss.id === Number
(item)) totalAmount += itemInfo.new_price *
cartItems[item];

} }
return totalAmount;
}
const getTotalCartItems =()
=>{ let totalItems = 0;
for(const item in cartItems){
if(cartItems[item]>0){
totalItems+= cartItems[item];

} }
return totalItems;
}

const contextValue = {getTotalCartItems, getTotalCartAmount, all_product,


cartItems, removeFromCart,addToCart};
return(
<ShopContext.Provider value={contextValue}>
{props.children}
</ShopContext.Provider>
38

)
}

export default ShopContextProvider;

1.6 Homespun/src/LoginSignup.jsx

import React, { useState } from


'react' import './CSS/Login.css'
const Signup = () => {

const [state,setState] =
useState("Login"); const [formData,
setFormData] =
useState({ username:"",
password:"", email:""

})
const changeHandler= (e)=>{ setFormData({...formData,
[e.target.name]:e.target.value})

}
const login = async
()=>{ console.log("login function exicuted",
formData); let responseData; await
fetch('http://localhost:4000/login',
{ method:'POST', headers:{
Accept:'application/form-data',
'Content-Type':'application/json',
},

body:JSON.stringify(formData), }).then((response)=>
response.json()) .then((data)=>responseData=data)
if(responseData.success)
{ localStorage.setItem('auth-
token',responseData.token);
window.location.replace("/");
}
else{ alert(responseData
.errors )
}

}
const signup = async
()=>{ console.log("signup function exicuted",
formData); let responseData; await
39

fetch('http://localhost:4000/signup',
{ method:'POST', headers:{
Accept:'application/form-data',
'Content-Type':'application/json',
},
body:JSON.stringify(formData),
}).then((response)=>
response.json()) .then((data)=>responseData=data)
if(responseData.success){ localStorage.setItem('auth-
token',responseData.token);
window.location.replace("/");
}
else{ alert(responseData
.errors )
}

}
return
(
<div>
<div className="signup">
<div className="container">
<form>
<h1>{state}</h1>
<div className="fields">
{state === "Sign Up"?<input name='username'
value={formData.username} onChange={changeHandler} type="text"
placeholder='Your Name' />:<></>}
<input type="email" name='email' value={formData.email}
onChange={changeHandler} placeholder=' Email Address' />
<input type="password" name='password'
value={formData.password} onChange={changeHandler} placeholder='Password' />
</div>
<button type='button' onClick={() => {state === "Login"?
login() : signup() }} >Continue</button>
{state === "Sign Up"?<p className="loginsignup-login">
Already have an account? <span
onClick={()=>{setState("Login")}} > Login here </span>
</p> :<p className="loginsignup-login">
Create an account? <span onClick={()=>{setState("Sign
Up")}} > Click here </span>
</p>}
<div className="agree">
<input type="checkbox" name="" id="" />
<p>By continuing , i agree to the terms of use & privacy
policy.</p>
</div>
</form>
</div>
</div>

</div>
40

)
}

export default Signup

1.7 Homespun/Backend/index.js

const port = 4000; const express =


require("express"); const app =
express(); const mongoose =
require("mongoose"); const jwt =
require("jsonwebtoken"); const
multer = require("multer"); const
path = require("path");
// const { default: mongoose } =
require("mongoose"); const cors = require("cors");
app.use(express.json()); app.use(cors());

//Database Connectin with mangodb


mongoose.connect("mongodb+srv://
sundarkarthick574:sundar1234@cluster0.lwyeusd.mong
odb.net/BackendHomespun");

//api creation
app.get("/",
(req,res)=>{
res.send("Express App is Running")
})

// image storage engine

const storage =
multer.diskStorage({ destination:
'./upload/images', filename:
(req,file,cb)=>{
return cb(null,`${file.fieldname}_${Date.now()}$
{path.extname(file.originalname)}`)
}
}
)

const upload = multer({storage: storage})

//creatin upload end point for images


app.use('/images',express.static('upload/images'))
41

app.post("/upload",upload.single('product'),
(req,res)=>{ res.json({ success:1, image_url:
`http://localhost:${port}/images/${req.file.filename}`
})
})

//schema for creating product

const Product =
mongoose.model("Product",{ id:{
type: Number, required: true,
}, name:{
type: String,
required: true,
}, image:{
type: String,
required: true,
}, category:
{ type:
String,
required: true,
},
new_price:
{ type:
Number,
required: true,
},
old_price:
{ type:
Number,
required: true,
}, date:{
type: Date,
default: Date.now,
},
available:{
type: Boolean,
default: true,
},

})
app.post('/addproduct', async (req, res)=>{

let products = await Product.find({});


let id; if(products.length>0){ let
last_product_array = products.slice(-1);
let last_product = last_product_array[0];
id =last_product.id+1;
}
else{
id=1;
}
42

const product = new Product({


id:id, name:req.body.name,
image:req.body.image,
category:req.body.category,
new_price:req.body.new_price,
old_price:req.body.old_price,
});
console.log(product);
await product.save();
console.log("saved");
res.json({ succe
ss:true,
name:req.body.name,
})
})

//creating api for deleting product

app.post('/removeproduct',
async(req,res)=>{ await
Product.findOneAndDelete({id:req.body.id});
console.log("Removed");
res.json({ success:true,
name:req.body.name,
})
})

//creating api for getting all product

app.get('/allproducts', async(req,res)=>{
let products = await Product.find({});
console.log("All Products Fetched");
res.send(products);
})

// shema creating for user model

const Users = mongoose.model('Users',{


name:{
type:String,
}, email:
{ type:St
ring,
unique:true,
},
password:{
type:String,
},
cartData:{
type:Object,
43

}, date:{
type:Date,
default:Date.now,
}
})

// creating end point for registered user


app.post('/signup', async (req,res)=>{

let check = await Users.findOne({email:req.body.email});


if(check){
return res.status(400).json({success:false,errors:"EXISTING USER FOUND
WITH SAME EMAIL ADDRESS"});
} let cart ={};
for(let i=0;i<300;i++){
cart [i] = 0;
}
const user = new
Users({ name:req.body.username,
email:req.body.email,
password:req.body.password,
cartData:cart,

})
await user.save();

const data = {
user:{
id:user.id
}

}
const token = jwt.sign(data,'secret_ecom');
res.json({success:true,token})
})

// creating end ponit for user login

app.post('/login',async (req,res)=>{ let user = await


Users.findOne({email:req.body.email}); if(user)
{ const passCompare = req.body.password ===
user.password; if(passCompare){ const
data ={ user:{ id:user.id

} }
const token = jwt.sign(data,'secret_ecom');
res.json({success:true,token});
}
else{ res.json({success:false,errors:"Wrong
Password"});
44

} }
else{ res.json({success:false,errors:"Wrong Email
address"})
}
})

app.listen(port,(error)=>{ if(!error)
{ console.log("Server is running on port " +
port);
}
else{ console.log("Error : "
+ error);
}
})

2.Sample Screen Shots :


Home page :

2.1 Home Page.


45

2.2 Home Page/New Arriavals.

Admin Page:

2.3 Only for admin to add products.


46

2.4 Only for admin to view & delete products.

User Login & Signup Page:

2.5 User Log in page.


47

2.6 New user registration page.

Cart Page:

2.7 List of products added in cart & user able to remove it.
48

2.8 Total amount of products listed in cart.

Product Page:
49

2.9 Selected product page.


50

APPENDIX-B
1.BIBLIOGRAPHY
1.https://www.w3schools.com/nodejs/

2. https://www.javatpoint.com/nodejs-tutorial

3. https://www.w3schools.com/REACT/DEFAULT.ASP

4. https://www.geeksforgeeks.org/react-tutorial/

5. https://www.javatpoint.com/reactjs-tutorial

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy