├── Procfile
├── frontend
├── public
│ ├── favicon.ico
│ ├── logo192.png
│ ├── logo512.png
│ ├── Empty_Cart.png
│ ├── ShoppiKart.png
│ ├── images
│ │ ├── sample.jpg
│ │ ├── Asus_Rog.jpeg
│ │ ├── Realme_X7_5G.jpeg
│ │ ├── Unifactor_M_Running_Shoes.jpeg
│ │ └── Fully_Automatic_Front_Load_with_In-built_Heater.jpeg
│ ├── manifest.json
│ └── index.html
├── src
│ ├── constants
│ │ ├── cartConstants.js
│ │ ├── orderConstants.js
│ │ ├── userConstants.js
│ │ └── productConstants.js
│ ├── components
│ │ ├── Message.js
│ │ ├── Loader.js
│ │ ├── FormContainer.js
│ │ ├── Meta.js
│ │ ├── Paginate.js
│ │ ├── CustomerRating.js
│ │ ├── SearchBox.js
│ │ ├── Footer.js
│ │ ├── CheckoutSteps.js
│ │ ├── Rating.js
│ │ ├── Product.js
│ │ ├── ProductCarousel.js
│ │ └── Header.js
│ ├── reportWebVitals.js
│ ├── index.js
│ ├── index.css
│ ├── reducers
│ │ ├── cartReducers.js
│ │ ├── orderReducers.js
│ │ ├── userReducers.js
│ │ └── productReducers.js
│ ├── actions
│ │ ├── cartActions.js
│ │ ├── orderActions.js
│ │ ├── productActions.js
│ │ └── userActions.js
│ ├── screens
│ │ ├── PaymentScreen.js
│ │ ├── HomeScreen.js
│ │ ├── LoginScreen.js
│ │ ├── ShippingScreen.js
│ │ ├── UserListScreen.js
│ │ ├── OrderListScreen.js
│ │ ├── UserEditScreen.js
│ │ ├── RegisterScreen.js
│ │ ├── ProductListScreen.js
│ │ ├── CartScreen.js
│ │ ├── ProductEditScreen.js
│ │ ├── ProfileScreen.js
│ │ ├── PlaceOrderScreen.js
│ │ ├── ProductScreen.js
│ │ └── OrderScreen.js
│ ├── store.js
│ └── App.js
├── package.json
└── README.md
├── uploads
├── image-1625072571493.jpg
└── image-1625072655121.jpg
├── backend
├── utils
│ └── generateTokens.js
├── config
│ └── db.js
├── middleware
│ ├── errorMiddleware.js
│ └── authMiddleware.js
├── routes
│ ├── productRoutes.js
│ ├── orderRoutes.js
│ ├── userRoutes.js
│ └── uploadRoutes.js
├── data
│ ├── users.js
│ └── products.js
├── models
│ ├── userModel.js
│ ├── productModel.js
│ └── orderModel.js
├── email
│ └── account.js
├── seeder.js
├── server.js
└── controllers
│ ├── orderController.js
│ ├── productController.js
│ └── userController.js
├── .gitignore
├── LICENSE
├── package.json
└── README.md
/Procfile:
--------------------------------------------------------------------------------
1 | web: node backend/server.js
--------------------------------------------------------------------------------
/frontend/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/favicon.ico
--------------------------------------------------------------------------------
/frontend/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/logo192.png
--------------------------------------------------------------------------------
/frontend/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/logo512.png
--------------------------------------------------------------------------------
/frontend/public/Empty_Cart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/Empty_Cart.png
--------------------------------------------------------------------------------
/frontend/public/ShoppiKart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/ShoppiKart.png
--------------------------------------------------------------------------------
/frontend/public/images/sample.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/images/sample.jpg
--------------------------------------------------------------------------------
/uploads/image-1625072571493.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/uploads/image-1625072571493.jpg
--------------------------------------------------------------------------------
/uploads/image-1625072655121.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/uploads/image-1625072655121.jpg
--------------------------------------------------------------------------------
/frontend/public/images/Asus_Rog.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/images/Asus_Rog.jpeg
--------------------------------------------------------------------------------
/frontend/public/images/Realme_X7_5G.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/images/Realme_X7_5G.jpeg
--------------------------------------------------------------------------------
/frontend/public/images/Unifactor_M_Running_Shoes.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/images/Unifactor_M_Running_Shoes.jpeg
--------------------------------------------------------------------------------
/frontend/public/images/Fully_Automatic_Front_Load_with_In-built_Heater.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/artiam99/MERN-eCommerce-Website/HEAD/frontend/public/images/Fully_Automatic_Front_Load_with_In-built_Heater.jpeg
--------------------------------------------------------------------------------
/backend/utils/generateTokens.js:
--------------------------------------------------------------------------------
1 | const jwt = require('jsonwebtoken')
2 |
3 | const generateToken = (id) =>
4 | {
5 | return jwt.sign({ id } , process.env.JWT_SECRET , { expiresIn: '30d'}) // payload is ID , JWT_SECRET from .env , Token expiresin 30 days
6 | }
7 |
8 | module.exports = generateToken
--------------------------------------------------------------------------------
/frontend/src/constants/cartConstants.js:
--------------------------------------------------------------------------------
1 | export const CART_ADD_ITEM = 'CART_ADD_ITEM'
2 | export const CART_REMOVE_ITEM = 'CART_REMOVE_ITEM'
3 | export const CART_SAVE_SHIPPING_ADDRESS = 'CART_SAVE_SHIPPING_ADDRESS'
4 | export const CART_SAVE_PAYMENT_METHOD = 'CART_SAVE_PAYMENT_METHOD'
5 | export const CART_MAKE_EMPTY = 'CART_MAKE_EMPTY'
--------------------------------------------------------------------------------
/frontend/src/components/Message.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Alert } from 'react-bootstrap'
3 |
4 | const Message = ({variant , children}) => {
5 | return (
6 |
7 | {children}
8 |
9 | )
10 | }
11 |
12 | Message.defaultProps = { variant: 'info' }
13 |
14 | export default Message
15 |
--------------------------------------------------------------------------------
/frontend/src/components/Loader.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Spinner } from 'react-bootstrap'
3 |
4 | const Loader = () => {
5 | return (
6 |
7 | Loading...
8 |
9 | )
10 | }
11 |
12 | export default Loader
--------------------------------------------------------------------------------
/frontend/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | node_modules
5 | node_modules/
6 |
7 | /.pnp
8 | .pnp.js
9 |
10 | # testing
11 | /coverage
12 |
13 | # production
14 | /frontend/build
15 |
16 | # misc
17 | .DS_Store
18 | .env
19 | .env.local
20 | .env.development.local
21 | .env.test.local
22 | .env.production.local
23 |
24 | npm-debug.log*
25 | yarn-debug.log*
26 | yarn-error.log*
27 |
--------------------------------------------------------------------------------
/frontend/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './bootstrap.min.css'
4 | import './index.css';
5 | import App from './App';
6 | import reportWebVitals from './reportWebVitals';
7 | import { Provider } from 'react-redux'
8 | import store from './store'
9 |
10 | ReactDOM.render(
11 |
12 |
13 | ,
14 | document.getElementById('root')
15 | );
16 |
17 | reportWebVitals();
18 |
--------------------------------------------------------------------------------
/frontend/src/components/FormContainer.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Container , Row , Col } from 'react-bootstrap'
3 |
4 | const FormContainer = ({ children }) =>
5 | {
6 | return (
7 |
8 |
9 |
10 | {children}
11 |
12 |
13 |
14 | )
15 | }
16 |
17 | export default FormContainer
--------------------------------------------------------------------------------
/backend/config/db.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const connectDB = async () =>
4 | {
5 | try
6 | {
7 | const conn = await mongoose.connect(process.env.MONGO_URI , { useUnifiedTopology: true , useNewUrlParser: true , useCreateIndex: true })
8 |
9 | console.log(`MongoDB is connected: ${conn.connection.host}`)
10 | }
11 | catch(error)
12 | {
13 | console.log(`Error : ${error}`)
14 |
15 | process.exit(1)
16 | }
17 | }
18 |
19 | module.exports = connectDB
--------------------------------------------------------------------------------
/backend/middleware/errorMiddleware.js:
--------------------------------------------------------------------------------
1 | const notFound = (req , res , next) =>
2 | {
3 | const error = new Error(`Not Found - ${req.originalUrl}`)
4 | res.status(404)
5 | next(error)
6 | }
7 |
8 |
9 | const errorHandler = (error , req , res , next) =>
10 | {
11 | const statusCode = res.statusCode === 200 ? 500 : res.statusCode
12 |
13 | res.status(statusCode)
14 |
15 | res.json({ message: error.message , stack: process.env.NODE_ENV === 'production' ? null : error.stack })
16 | }
17 |
18 | module.exports = { notFound , errorHandler }
--------------------------------------------------------------------------------
/frontend/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/backend/routes/productRoutes.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const { getProducts , getProductById, deleteProduct ,
3 | createProduct , updateProduct , createProductReview , getTopProducts } = require('../controllers/productController')
4 | const { protect , admin } = require('../middleware/authMiddleware.js')
5 |
6 | const router = express.Router()
7 |
8 | router.route('/').get(getProducts).post(protect , admin , createProduct)
9 | router.route('/:id/reviews').post(protect , createProductReview)
10 | router.get('/top' , getTopProducts)
11 | router.route('/:id').get(getProductById).delete(protect , admin , deleteProduct).put(protect , admin , updateProduct)
12 |
13 | module.exports = router
--------------------------------------------------------------------------------
/backend/routes/orderRoutes.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const { addOrderItems , getOrderById, updateOrderToPaid,
3 | updateOrderToDelivered , getMyOrders , getOrders } = require('../controllers/orderController')
4 | const { protect , admin } = require('../middleware/authMiddleware')
5 |
6 | const router = express.Router()
7 |
8 |
9 | router.route('/').post(protect , addOrderItems).get(protect , admin , getOrders)
10 | router.route('/myorders').get(protect , getMyOrders)
11 | router.route('/:id').get(protect , getOrderById)
12 | router.route('/:id/pay').put(protect , updateOrderToPaid)
13 | router.route('/:id/deliver').put(protect , updateOrderToDelivered)
14 |
15 |
16 | module.exports = router
--------------------------------------------------------------------------------
/backend/routes/userRoutes.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const { authUser , registerUser , getUserProfile , updateUserProfile , getUsers,
3 | deleteUser, getUserById, updateUser } = require('../controllers/userController')
4 | const { protect , admin } = require('../middleware/authMiddleware')
5 |
6 | const router = express.Router()
7 |
8 | router.route('/').post(registerUser).get(protect , admin , getUsers)
9 | router.post('/login' , authUser)
10 | router.route('/profile').get(protect , getUserProfile).put(protect , updateUserProfile)
11 | router.route('/:id').delete(protect , admin , deleteUser).get(protect , admin , getUserById).put(protect , admin , updateUser )
12 |
13 | module.exports = router
--------------------------------------------------------------------------------
/backend/data/users.js:
--------------------------------------------------------------------------------
1 | const bcrypt = require('bcryptjs')
2 |
3 | const users =
4 | [
5 | {
6 | name: 'Debarshi Maitra',
7 | email: 'tuhin.dm1999@gmail.com',
8 | password: bcrypt.hashSync('123456' , 10),
9 | isAdmin: true
10 | },
11 | {
12 | name: 'John Mayer',
13 | email: 'skywalker.luke.dm@gmail.com',
14 | password: bcrypt.hashSync('123456' , 10),
15 | },
16 | {
17 | name: 'Jimi Hendrix',
18 | email: 'mayer.debarshi@gmail.com',
19 | password: bcrypt.hashSync('123456' , 10),
20 | },
21 | {
22 | name: 'Eric Clapton',
23 | email: 'yoda99.dm@gmail.com',
24 | password: bcrypt.hashSync('123456' , 10),
25 | }
26 | ]
27 |
28 | module.exports = users
--------------------------------------------------------------------------------
/frontend/src/components/Meta.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Helmet } from 'react-helmet'
3 |
4 | const Meta = ({ title, description, keywords }) =>
5 | {
6 | return (
7 |
8 | {title}
9 |
10 |
11 |
12 |
13 |
14 | )
15 | }
16 |
17 | Meta.defaultProps = {
18 | title: 'Welcome To ShoppiKart',
19 | description: 'We sell the best products for cheap',
20 | keywords: 'electronics, buy electronics, cheap electroincs, men fashion, women fashion, Home furnishing',
21 | }
22 |
23 | export default Meta
--------------------------------------------------------------------------------
/frontend/src/components/Paginate.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Pagination } from 'react-bootstrap'
3 | import { LinkContainer } from 'react-router-bootstrap'
4 |
5 | const Paginate = ({ pages , page , isAdmin = false , keyword = '' }) =>
6 | {
7 | return (
8 | pages > 1 &&
9 | (
10 | {[...Array(pages).keys()].map((x) =>
11 | (
12 |
14 | {x + 1}
15 |
16 | ))}
17 | )
18 | )
19 | }
20 |
21 | export default Paginate
--------------------------------------------------------------------------------
/frontend/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | ShoppiKart
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/backend/models/userModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 | const bcrypt = require('bcryptjs')
3 |
4 | const userSchema = mongoose.Schema({
5 |
6 | name: { type: String , required: true },
7 | email: { type: String , required: true , unique: true },
8 | password: { type: String , required: true},
9 | isAdmin: { type: Boolean , required: true , default: false },
10 | },
11 | {
12 | timestamp: true,
13 | })
14 |
15 | userSchema.methods.matchPassword = async function(enteredPassword)
16 | {
17 | return await bcrypt.compare(enteredPassword , this.password)
18 | }
19 |
20 | // Middleware to change password before Save
21 | userSchema.pre('save' , async function(next)
22 | {
23 | if(!this.isModified('password'))
24 | {
25 | next()
26 | }
27 |
28 | const salt = await bcrypt.genSalt(10)
29 |
30 | this.password = await bcrypt.hash(this.password , salt)
31 | })
32 |
33 | const User = mongoose.model('User' , userSchema)
34 |
35 | module.exports = User
--------------------------------------------------------------------------------
/frontend/src/components/CustomerRating.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const CustomerRating = ({ rating }) => {
4 |
5 | const color = rating >= 4 ? '#228B22' : rating >= 2 ? 'Orange' : '#db0000'
6 |
7 | return (
8 |
9 |
10 | {rating}
11 | =1 ? 'fas fa-star' : 'far fa-star'}>
12 | =2 ? 'fas fa-star' : 'far fa-star'}>
13 | =3 ? 'fas fa-star' : 'far fa-star'}>
14 | =4 ? 'fas fa-star' : 'far fa-star'}>
15 | =5 ? 'fas fa-star' : 'far fa-star'}>
16 |
17 | )
18 | }
19 |
20 | CustomerRating.defaultProps = { color: '#f8e825' }
21 |
22 | export default CustomerRating
23 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Debarshi Maitra
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/frontend/src/components/SearchBox.js:
--------------------------------------------------------------------------------
1 | import React , { useState } from 'react'
2 | import { Form , Button , InputGroup } from 'react-bootstrap'
3 |
4 | const SearchBox = ({ history }) =>
5 | {
6 | const [keyword , setKeyword] = useState('')
7 |
8 | const submitHandler = (e) =>
9 | {
10 | e.preventDefault()
11 |
12 | if(keyword.trim())
13 | {
14 | history.push(`/search/${keyword}`)
15 | }
16 | else
17 | {
18 | history.push('/')
19 | }
20 | }
21 |
22 | return (
23 |
34 | )
35 | }
36 |
37 | export default SearchBox
--------------------------------------------------------------------------------
/backend/routes/uploadRoutes.js:
--------------------------------------------------------------------------------
1 | const path = require('path')
2 | const express = require('express')
3 | const multer = require('multer')
4 |
5 | const router = express.Router()
6 |
7 | const storage = multer.diskStorage(
8 | {
9 | destination(req , file , cb) { cb(null , 'uploads/') },
10 |
11 | filename(req , file , cb)
12 | {
13 | cb(null , `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
14 | },
15 | })
16 |
17 | function checkFileType(file , cb)
18 | {
19 | const filetypes = /jpg|jpeg|png/
20 | const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
21 | const mimetype = filetypes.test(file.mimetype)
22 |
23 | if(extname && mimetype)
24 | {
25 | return cb(null, true)
26 | }
27 | else
28 | {
29 | cb('Images only!')
30 | }
31 | }
32 |
33 | const upload = multer(
34 | {
35 | storage,
36 |
37 | fileFilter: function (req , file , cb)
38 | {
39 | checkFileType(file, cb)
40 | },
41 | })
42 |
43 | router.post('/' , upload.single('image') , (req , res) =>
44 | {
45 | res.send(`/${req.file.path}`)
46 | })
47 |
48 | module.exports = router
--------------------------------------------------------------------------------
/frontend/src/index.css:
--------------------------------------------------------------------------------
1 | main
2 | {
3 | min-height: 80vh;
4 | }
5 |
6 | h3
7 | {
8 | padding: 1rem 0;
9 | }
10 |
11 | h1
12 | {
13 | font-size: 1.8rem;
14 | padding: 1rem 0;
15 | }
16 |
17 | h2
18 | {
19 | font-size: 1.4rem;
20 | padding: 0.5rem 0;
21 | }
22 |
23 |
24 | .rating span
25 | {
26 | margin: 0.1rem;
27 | }
28 |
29 | a
30 | {
31 | text-decoration: none;
32 | color: #101010;
33 | }
34 |
35 | a:hover
36 | {
37 | font-weight: 900;
38 | color: #101010;
39 | }
40 |
41 | .carousel-item-next,
42 | .carousel-item-prev,
43 | .carousel-item.active {
44 | display: flex;
45 | background-color: white;
46 | box-shadow:
47 | inset 200px 2px 70px -10px #CCC,
48 | inset -200px -2px 70px -10px #CCC;
49 | height: 270px;
50 | }
51 | .carousel-caption {
52 | position: absolute;
53 | top: 0;
54 | }
55 |
56 | .carousel-caption h2 {
57 | color: black;
58 | font-weight: 900;
59 | }
60 |
61 | .carousel img {
62 | height: 200px;
63 | padding: 30px;
64 | margin: 40px;
65 | margin-left: auto;
66 | margin-right: auto;
67 | }
68 | .carousel a {
69 | margin: 0 auto;
70 | }
71 |
72 | @media (max-width: 900px) {
73 | .carousel-caption h2 {
74 | font-size: 2.5vw;
75 | }
76 | }
--------------------------------------------------------------------------------
/backend/email/account.js:
--------------------------------------------------------------------------------
1 | const nodemailer = require('nodemailer')
2 |
3 | const transporter = nodemailer.createTransport(
4 | {
5 | service: 'gmail' ,
6 | auth:
7 | {
8 | user: 'shoppikart.maitra@gmail.com' ,
9 | pass: 'maytheforcebewithyou'
10 | }
11 | })
12 |
13 | const sendWelcomeMail = (email , name) =>
14 | {
15 | transporter.sendMail({
16 | to: email ,
17 | from: process.env.EMAIL ,
18 | subject: 'Thanks for joining ShoppiKart!' ,
19 | text: `Welcome : ${name} ... This is Debarshi .. Thank you for visiting my project`
20 |
21 | })
22 | }
23 |
24 | const sendCancelationMail = (email , name) =>
25 | {
26 | transporter.sendMail({
27 | to: email,
28 | from: process.env.EMAIL ,
29 | subject: 'Sorry to see you go!' ,
30 | text: `Accout deleted : ${name}`
31 |
32 | })
33 | }
34 |
35 | module.exports = {
36 | sendWelcomeMail ,
37 | sendCancelationMail
38 | }
--------------------------------------------------------------------------------
/backend/middleware/authMiddleware.js:
--------------------------------------------------------------------------------
1 | const jwt = require('jsonwebtoken')
2 | const User = require('../models/userModel')
3 | const asyncHandler = require('express-async-handler')
4 |
5 | const protect = asyncHandler(async (req , res , next) =>
6 | {
7 | let token
8 |
9 | if(req.headers.authorization && req.headers.authorization.startsWith('Bearer'))
10 | {
11 | try
12 | {
13 | token = req.headers.authorization.split(' ')[1]
14 |
15 | const decoded = jwt.verify(token , process.env.JWT_SECRET)
16 |
17 | req.user = await User.findById(decoded.id).select('-password')
18 |
19 | next()
20 | }
21 | catch(error)
22 | {
23 | res.status(401)
24 |
25 | throw new Error('Not authorized, token failed')
26 | }
27 | }
28 |
29 | if(!token)
30 | {
31 | res.status(401)
32 |
33 | throw new Error('Not authorized, no token')
34 | }
35 | })
36 |
37 | const admin = (req , res , next) =>
38 | {
39 | if(req.user && req.user.isAdmin)
40 | {
41 | next()
42 | }
43 | else
44 | {
45 | res.status(401)
46 |
47 | throw new Error('Not authorized as an admin')
48 | }
49 | }
50 |
51 | module.exports = { protect , admin }
--------------------------------------------------------------------------------
/backend/models/productModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const reviewSchema = mongoose.Schema({
4 |
5 | name: { type: String , required: true },
6 | rating: { type: Number , required: true },
7 | comment: { type: String , required: true },
8 | user: { type: mongoose.Schema.Types.ObjectId , required: true , ref: 'User' },
9 |
10 | } ,
11 | {
12 | timestamp: true,
13 | })
14 |
15 | const productSchema = mongoose.Schema({
16 |
17 | user: { type: mongoose.Schema.Types.ObjectId , required: true , ref: 'User' }, // Admins can sell products
18 | name: { type: String , required: true },
19 | image: { type: String , required: true },
20 | brand: { type: String , required: true},
21 | category: { type: String , required: true },
22 | description: { type: String , required: true },
23 | reviews: [reviewSchema],
24 | rating: { type: Number , required: true , default: 0 },
25 | numReviews: { type: Number , required: true , default: 0 },
26 | price: { type: Number , required: true , default: 0 },
27 | countInStock: { type: Number , required: true , default: 0 },
28 | },
29 | {
30 | timestamp: true,
31 | })
32 |
33 | const Product = mongoose.model('Product' , productSchema)
34 |
35 | module.exports = Product
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "root",
3 | "version": "1.0.0",
4 | "description": "mern shopping app",
5 | "main": "index.js",
6 | "scripts": {
7 | "start": "node backend/server",
8 | "server": "nodemon backend/server",
9 | "client": "npm start --prefix frontend",
10 | "dev": "concurrently \"npm run server\" \"npm run client\"",
11 | "data:import": "node backend/seeder",
12 | "data:destroy": "node backend/seeder -d",
13 | "build": "cd frontend && npm run build",
14 | "install-frontend": "cd frontend && npm install",
15 | "heroku-postbuild": "npm run install-frontend && npm run build"
16 | },
17 | "author": "",
18 | "license": "ISC",
19 | "dependencies": {
20 | "bcryptjs": "^2.4.3",
21 | "body-parser": "^1.19.0",
22 | "cors": "^2.8.5",
23 | "dotenv": "^10.0.0",
24 | "express": "^4.17.1",
25 | "express-async-handler": "^1.1.4",
26 | "formidable": "^1.2.2",
27 | "jsonwebtoken": "^8.5.1",
28 | "mongoose": "^5.12.14",
29 | "morgan": "^1.10.0",
30 | "multer": "^1.4.2",
31 | "nodemailer": "^6.6.2",
32 | "razorpay": "^2.0.6",
33 | "request": "^2.88.2",
34 | "uuid": "^8.3.2"
35 | },
36 | "devDependencies": {
37 | "concurrently": "^6.2.0",
38 | "nodemon": "^2.0.7"
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/frontend/src/components/Footer.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Container , Row , Col } from 'react-bootstrap'
3 |
4 | const Footer = () => {
5 | return (
6 |
28 | )
29 | }
30 |
31 | export default Footer
32 |
--------------------------------------------------------------------------------
/frontend/src/constants/orderConstants.js:
--------------------------------------------------------------------------------
1 | export const ORDER_CREATE_REQUEST = 'ORDER_CREATE_REQUEST'
2 | export const ORDER_CREATE_SUCCESS = 'ORDER_CREATE_SUCCESS'
3 | export const ORDER_CREATE_FAILURE = 'ORDER_CREATE_FAILURE'
4 |
5 | export const ORDER_DETAILS_REQUEST = 'ORDER_DETAILS_REQUEST'
6 | export const ORDER_DETAILS_SUCCESS = 'ORDER_DETAILS_SUCCESS'
7 | export const ORDER_DETAILS_FAILURE = 'ORDER_DETAILS_FAILURE'
8 |
9 | export const ORDER_PAY_REQUEST = 'ORDER_PAY_REQUEST'
10 | export const ORDER_PAY_SUCCESS = 'ORDER_PAY_SUCCESS'
11 | export const ORDER_PAY_FAILURE = 'ORDER_PAY_FAILURE'
12 | export const ORDER_PAY_RESET = 'ORDER_PAY_RESET'
13 |
14 | export const ORDER_LIST_MY_REQUEST = 'ORDER_LIST_MY_REQUEST'
15 | export const ORDER_LIST_MY_SUCCESS = 'ORDER_LIST_MY_SUCCESS'
16 | export const ORDER_LIST_MY_FAILURE = 'ORDER_LIST_MY_FAILURE'
17 | export const ORDER_LIST_MY_RESET = 'ORDER_LIST_MY_RESET'
18 |
19 | export const ORDER_LIST_REQUEST = 'ORDER_LIST_REQUEST'
20 | export const ORDER_LIST_SUCCESS = 'ORDER_LIST_SUCCESS'
21 | export const ORDER_LIST_FAILURE = 'ORDER_LIST_FAILURE'
22 |
23 | export const ORDER_DELIVER_REQUEST = 'ORDER_DELIVER_REQUEST'
24 | export const ORDER_DELIVER_SUCCESS = 'ORDER_DELIVER_SUCCESS'
25 | export const ORDER_DELIVER_FAILURE = 'ORDER_DELIVER_FAILURE'
26 | export const ORDER_DELIVER_RESET = 'ORDER_DELIVER_RESET'
--------------------------------------------------------------------------------
/frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "frontend",
3 | "proxy": "http://127.0.0.1:5000",
4 | "version": "0.1.0",
5 | "private": true,
6 | "dependencies": {
7 | "@testing-library/jest-dom": "^5.11.4",
8 | "@testing-library/react": "^11.1.0",
9 | "@testing-library/user-event": "^12.1.10",
10 | "axios": "^0.21.1",
11 | "react": "^17.0.2",
12 | "react-bootstrap": "^1.6.1",
13 | "react-dom": "^17.0.2",
14 | "react-helmet": "^6.1.0",
15 | "react-paypal-button-v2": "^2.6.3",
16 | "react-redux": "^7.2.4",
17 | "react-router-bootstrap": "^0.25.0",
18 | "react-router-dom": "^5.2.0",
19 | "react-scripts": "4.0.3",
20 | "redux": "^4.1.0",
21 | "redux-devtools-extension": "^2.13.9",
22 | "redux-thunk": "^2.3.0",
23 | "web-vitals": "^1.0.1"
24 | },
25 | "scripts": {
26 | "start": "react-scripts start",
27 | "build": "react-scripts build",
28 | "test": "react-scripts test",
29 | "eject": "react-scripts eject"
30 | },
31 | "eslintConfig": {
32 | "extends": [
33 | "react-app",
34 | "react-app/jest"
35 | ]
36 | },
37 | "browserslist": {
38 | "production": [
39 | ">0.2%",
40 | "not dead",
41 | "not op_mini all"
42 | ],
43 | "development": [
44 | "last 1 chrome version",
45 | "last 1 firefox version",
46 | "last 1 safari version"
47 | ]
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/frontend/src/reducers/cartReducers.js:
--------------------------------------------------------------------------------
1 | import { CART_ADD_ITEM , CART_REMOVE_ITEM , CART_SAVE_SHIPPING_ADDRESS , CART_SAVE_PAYMENT_METHOD ,
2 | CART_MAKE_EMPTY } from '../constants/cartConstants'
3 |
4 | export const cartReducer = (state = { cartItems: [] , shippingAddress: {} } , action) =>
5 | {
6 | switch (action.type)
7 | {
8 | case CART_ADD_ITEM:
9 | const item = action.payload
10 |
11 | const existItem = state.cartItems.find(x => x.product === item.product)
12 |
13 | if(existItem)
14 | {
15 | return { ...state , cartItems: state.cartItems.map(x => x.product === existItem.product ? item : x) , }
16 | }
17 | else
18 | {
19 | return { ...state , cartItems: [...state.cartItems, item] , }
20 | }
21 |
22 | case CART_REMOVE_ITEM:
23 | return { ...state , cartItems: state.cartItems.filter(x => x.product !== action.payload) , }
24 |
25 | case CART_MAKE_EMPTY:
26 | return { ...state , cartItems: [] }
27 |
28 | case CART_SAVE_SHIPPING_ADDRESS:
29 | return { ...state , shippingAddress: action.payload }
30 |
31 | case CART_SAVE_PAYMENT_METHOD:
32 | return { ...state , paymentMethod: action.payload }
33 |
34 | default:
35 | return state
36 | }
37 | }
--------------------------------------------------------------------------------
/frontend/src/components/CheckoutSteps.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Nav } from 'react-bootstrap'
3 | import { LinkContainer } from 'react-router-bootstrap'
4 |
5 | const CheckoutSteps = ({ step1 , step2 , step3 , step4 }) =>
6 | {
7 | return (
8 |
29 | )
30 | }
31 |
32 | export default CheckoutSteps
33 |
--------------------------------------------------------------------------------
/frontend/src/components/Rating.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const Rating = ({ rating , numReviews}) => {
4 |
5 | const color = rating >= 4 ? '#228B22' : rating >= 2 ? 'Orange' : rating !== 0 ? '#db0000' : 'Gray'
6 |
7 | const ratingNumber = Number(Number(rating).toFixed(0)).toFixed(1) === Number(rating).toFixed(1) ?
8 | Number(rating).toFixed(0) : Number(rating).toFixed(1)
9 |
10 | return (
11 |
12 |
13 | {ratingNumber}
14 | =1 ? 'fas fa-star' : rating >= 0.5 ? 'fas fa-star-half-alt' : 'far fa-star'}>
15 | =2 ? 'fas fa-star' : rating >= 1.5 ? 'fas fa-star-half-alt' : 'far fa-star'}>
16 | =3 ? 'fas fa-star' : rating >= 2.5 ? 'fas fa-star-half-alt' : 'far fa-star'}>
17 | =4 ? 'fas fa-star' : rating >= 3.5 ? 'fas fa-star-half-alt' : 'far fa-star'}>
18 | =5 ? 'fas fa-star' : rating >= 4.5 ? 'fas fa-star-half-alt' : 'far fa-star'}>
19 | {` (${numReviews} reviews)`}
20 |
21 |
22 | )
23 | }
24 |
25 | Rating.defaultProps = { color: '#f8e825' }
26 |
27 | export default Rating
28 |
--------------------------------------------------------------------------------
/frontend/src/components/Product.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Card } from 'react-bootstrap'
4 | import Rating from './Rating'
5 |
6 | const format = num => {
7 | const n = String(num),
8 | p = n.indexOf('.')
9 | return n.replace(
10 | /\d(?=(?:\d{3})+(?:\.|$))/g,
11 | (m, i) => p < 0 || i < p ? `${m},` : m
12 | )
13 | }
14 |
15 | const Product = (props) => {
16 | return (
17 |
18 |
19 |
20 |
21 |
23 |
24 |
25 |
26 |
27 |
28 |
29 | {props.product.name}
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 | ₹{format(props.product.price)}
40 |
41 |
42 |
43 |
44 | )
45 | }
46 |
47 | export default Product
48 |
--------------------------------------------------------------------------------
/frontend/src/constants/userConstants.js:
--------------------------------------------------------------------------------
1 | export const USER_LOGIN_REQUEST = 'USER_LOGIN_REQUEST'
2 | export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'
3 | export const USER_LOGIN_FAILURE = 'USER_LOGIN_FAILURE'
4 | export const USER_LOGOUT = 'USER_LOGOUT'
5 |
6 | export const USER_REGISTER_REQUEST = 'USER_REGISTER_REQUEST'
7 | export const USER_REGISTER_SUCCESS = 'USER_REGISTER_SUCCESS'
8 | export const USER_REGISTER_FAILURE = 'USER_REGISTER_FAILURE'
9 |
10 | export const USER_DETAILS_REQUEST = 'USER_DETAILS_REQUEST'
11 | export const USER_DETAILS_SUCCESS = 'USER_DETAILS_SUCCESS'
12 | export const USER_DETAILS_FAILURE = 'USER_DETAILS_FAILURE'
13 | export const USER_DETAILS_RESET = 'USER_DETAILS_RESET'
14 |
15 | export const USER_UPDATE_PROFILE_REQUEST = 'USER_UPDATE_PROFILE_REQUEST'
16 | export const USER_UPDATE_PROFILE_SUCCESS = 'USER_UPDATE_PROFILE_SUCCESS'
17 | export const USER_UPDATE_PROFILE_FAILURE = 'USER_UPDATE_PROFILE_FAILURE'
18 | export const USER_UPDATE_PROFILE_RESET = 'USER_UPDATE_PROFILE_RESET'
19 |
20 | export const USER_LIST_REQUEST = 'USER_LIST_REQUEST'
21 | export const USER_LIST_SUCCESS = 'USER_LIST_SUCCESS'
22 | export const USER_LIST_FAILURE = 'USER_LIST_FAILURE'
23 | export const USER_LIST_RESET = 'USER_LIST_RESET'
24 |
25 | export const USER_DELETE_REQUEST = 'USER_DELETE_REQUEST'
26 | export const USER_DELETE_SUCCESS = 'USER_DELETE_SUCCESS'
27 | export const USER_DELETE_FAILURE = 'USER_DELETE_FAILURE'
28 |
29 | export const USER_UPDATE_REQUEST = 'USER_UPDATE_REQUEST'
30 | export const USER_UPDATE_SUCCESS = 'USER_UPDATE_SUCCESS'
31 | export const USER_UPDATE_FAILURE = 'USER_UPDATE_FAILURE'
32 | export const USER_UPDATE_RESET = 'USER_UPDATE_RESET'
--------------------------------------------------------------------------------
/backend/seeder.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 | const dotenv = require('dotenv')
3 | const users = require('./data/users')
4 | const products = require('./data/products')
5 | const User = require('./models/userModel')
6 | const Product = require('./models/productModel')
7 | const Order = require('./models/orderModel')
8 | const connectDB = require('./config/db')
9 |
10 | dotenv.config()
11 |
12 | connectDB()
13 |
14 | const importData = async () =>
15 | {
16 | try
17 | {
18 | await User.deleteMany()
19 | await Product.deleteMany()
20 | await Order.deleteMany()
21 |
22 | const createdUsers = await User.insertMany(users)
23 |
24 | const adminUser = createdUsers[0]._id
25 |
26 | const sampleProducts = products.map(product =>
27 | {
28 | return { ...product , user: adminUser }
29 | })
30 |
31 | await Product.insertMany(sampleProducts)
32 |
33 | console.log('Data Imported')
34 |
35 | process.exit()
36 | }
37 | catch (error)
38 | {
39 | console.log(`Error: ${error}`)
40 | process.exit()
41 | }
42 | }
43 |
44 | const destroyData = async () =>
45 | {
46 | try
47 | {
48 | await User.deleteMany()
49 | await Product.deleteMany()
50 | await Order.deleteMany()
51 |
52 | console.log('Data Destroyed')
53 |
54 | process.exit()
55 | }
56 | catch (error)
57 | {
58 | console.log(`Error: ${error}`)
59 |
60 | process.exit()
61 | }
62 | }
63 |
64 | if(process.argv[2] === '-d')
65 | {
66 | destroyData()
67 | }
68 | else
69 | {
70 | importData()
71 | }
--------------------------------------------------------------------------------
/frontend/src/constants/productConstants.js:
--------------------------------------------------------------------------------
1 | export const PRODUCT_LIST_REQUEST = 'PRODUCT_LIST_REQUEST'
2 | export const PRODUCT_LIST_SUCCESS = 'PRODUCT_LIST_SUCCESS'
3 | export const PRODUCT_LIST_FAILURE = 'PRODUCT_LIST_FAILURE'
4 |
5 | export const PRODUCT_DETAILS_REQUEST = 'PRODUCT_DETAILS_REQUEST'
6 | export const PRODUCT_DETAILS_SUCCESS = 'PRODUCT_DETAILS_SUCCESS'
7 | export const PRODUCT_DETAILS_FAILURE = 'PRODUCT_DETAILS_FAILURE'
8 |
9 | export const PRODUCT_DELETE_REQUEST = 'PRODUCT_DELETE_REQUEST'
10 | export const PRODUCT_DELETE_SUCCESS = 'PRODUCT_DELETE_SUCCESS'
11 | export const PRODUCT_DELETE_FAILURE = 'PRODUCT_DELETE_FAILURE'
12 |
13 | export const PRODUCT_CREATE_REQUEST = 'PRODUCT_CREATE_REQUEST'
14 | export const PRODUCT_CREATE_SUCCESS = 'PRODUCT_CREATE_SUCCESS'
15 | export const PRODUCT_CREATE_FAILURE = 'PRODUCT_CREATE_FAILURE'
16 | export const PRODUCT_CREATE_RESET = 'PRODUCT_CREATE_RESET'
17 |
18 | export const PRODUCT_UPDATE_REQUEST = 'PRODUCT_UPDATE_REQUEST'
19 | export const PRODUCT_UPDATE_SUCCESS = 'PRODUCT_UPDATE_SUCCESS'
20 | export const PRODUCT_UPDATE_FAILURE = 'PRODUCT_UPDATE_FAILURE'
21 | export const PRODUCT_UPDATE_RESET = 'PRODUCT_UPDATE_RESET'
22 |
23 | export const PRODUCT_CREATE_REVIEW_REQUEST = 'PRODUCT_CREATE_REVIEW_REQUEST'
24 | export const PRODUCT_CREATE_REVIEW_SUCCESS = 'PRODUCT_CREATE_REVIEW_SUCCESS'
25 | export const PRODUCT_CREATE_REVIEW_FAILURE = 'PRODUCT_CREATE_REVIEW_FAILURE'
26 | export const PRODUCT_CREATE_REVIEW_RESET = 'PRODUCT_CREATE_REVIEW_RESET'
27 |
28 | export const PRODUCT_TOP_REQUEST = 'PRODUCT_TOP_REQUEST'
29 | export const PRODUCT_TOP_SUCCESS = 'PRODUCT_TOP_SUCCESS'
30 | export const PRODUCT_TOP_FAILURE = 'PRODUCT_TOP_FAILURE'
--------------------------------------------------------------------------------
/backend/models/orderModel.js:
--------------------------------------------------------------------------------
1 | const mongoose = require('mongoose')
2 |
3 | const orderSchema = mongoose.Schema({
4 |
5 | user: { type: mongoose.Schema.Types.ObjectId , required: true , ref: 'User' },
6 | orderItems: [{
7 | name: { type: String , required: true },
8 | qty: { type: Number , required: true },
9 | image: { type: String , required: true },
10 | price: { type: Number , required: true },
11 | product: { type: mongoose.Schema.Types.ObjectId , required: true , ref: 'product' }
12 | }],
13 | shippingAddress: { address: { type: String , required: true},
14 | city: { type: String , required: true},
15 | postalCode: { type: String , required: true},
16 | country: { type: String , required: true}
17 | },
18 | paymentMethod: { type: String , required: true},
19 | paymentResult: { id: { type: String } , status: { type: String } , update_time: { type: String } , email_address: { type: String } },
20 | taxPrice: { type: String , required: true , default: 0.0 },
21 | shippingPrice: { type: String , required: true , default: 0.0 },
22 | totalPrice: { type: String , required: true , default: 0.0 },
23 | isPaid: { type: Boolean , required: true , default: false },
24 | paidAt: { type: Date},
25 | isDelivered: { type: Boolean , required: true , default: false },
26 | deliveredAt: { type: Date},
27 | isAdmin: { type: Boolean , required: true , default: false },
28 | },
29 | {
30 | timestamps: true,
31 | })
32 |
33 | const Order = mongoose.model('Order' , orderSchema)
34 |
35 | module.exports = Order
--------------------------------------------------------------------------------
/backend/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const dotenv = require('dotenv')
3 | const path = require('path')
4 | const connectDB = require('./config/db')
5 | const produtcRoutes = require('./routes/productRoutes')
6 | const userRoutes = require('./routes/userRoutes')
7 | const orderRoutes = require('./routes/orderRoutes')
8 | const uploadRoutes = require('./routes/uploadRoutes')
9 | const { notFound , errorHandler } = require('./middleware/errorMiddleware')
10 | const morgan = require('morgan')
11 |
12 | dotenv.config()
13 |
14 | connectDB()
15 |
16 | const app = express()
17 |
18 | if(process.env.NODE_ENV === 'development')
19 | {
20 | app.use(morgan('dev'))
21 | }
22 |
23 | app.use(express.json())
24 |
25 | app.use('/api/products' , produtcRoutes) // everything will be mounted to this url prefix
26 | app.use('/api/users' , userRoutes)
27 | app.use('/api/orders' , orderRoutes)
28 | app.use('/api/upload' , uploadRoutes)
29 |
30 | app.get('/api/config/paypal' , (req , res) => res.send(process.env.PAYPAL_CLIENT_ID))
31 |
32 | const dirname = path.join(__dirname , '../')
33 |
34 | app.use('/uploads', express.static(path.join(dirname , '/uploads')))
35 |
36 | if(process.env.NODE_ENV === 'production')
37 | {
38 | app.use(express.static(path.join(dirname , '/frontend/build')))
39 |
40 | app.get('*' , (req , res) => res.sendFile(path.resolve(dirname , 'frontend' , 'build' , 'index.html')))
41 | }
42 | else
43 | {
44 | app.get('/' , (req , res) =>
45 | {
46 | res.send('API is running....')
47 | })
48 | }
49 |
50 | app.use(notFound)
51 |
52 | app.use(errorHandler)
53 |
54 | const PORT = process.env.PORT || 5000
55 |
56 | app.listen(PORT , console.log(`Server is running in ${process.env.NODE_ENV} on port: ${process.env.PORT}`))
--------------------------------------------------------------------------------
/frontend/src/components/ProductCarousel.js:
--------------------------------------------------------------------------------
1 | import React , { useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Carousel , Image } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Loader from './Loader'
6 | import Message from './Message'
7 | import { listTopProducts } from '../actions/productActions'
8 |
9 | const format = num => {
10 | const n = String(num),
11 | p = n.indexOf('.')
12 | return n.replace(
13 | /\d(?=(?:\d{3})+(?:\.|$))/g,
14 | (m, i) => p < 0 || i < p ? `${m},` : m
15 | )
16 | }
17 |
18 | const ProductCarousel = () =>
19 | {
20 | const dispatch = useDispatch()
21 |
22 | const productTopRated = useSelector((state) => state.productTopRated)
23 | const { loading , error , products } = productTopRated
24 |
25 | useEffect(() =>
26 | {
27 | dispatch(listTopProducts())
28 |
29 | } , [dispatch])
30 |
31 | return loading ? () : error ? ({error}) :
32 | (
33 |
34 | {products.map((product) =>
35 | (
36 |
37 |
38 |
39 |
40 |
41 |
42 | {product.name} (₹{format(product.price)})
43 |
44 |
45 |
46 |
47 | ))}
48 |
49 | )
50 | }
51 |
52 | export default ProductCarousel
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MERN-eCommerce-Website
2 |
3 | Live website link: https://shoppikart-maitra.herokuapp.com
4 |
5 |
6 | ### About
7 |
8 | This MERN Full stack web application is an eCommerce Platform built with __React.js__ for frontend,
9 | __Express.js__ for creating REST API, __MongoDB__ for database, __React-Bootstrap__ for the UI library and __Redux__ for managing application states. It supports authentication with JSON Web Token for admin and customer users. Customers can search products by name or brand and Admins can add new products & edit details. It is deployed on __Heroku__.
10 |
11 |
12 | ### Home Screen
13 |
14 | 
15 |
16 | 
17 |
18 | ### Product Screen
19 |
20 | 
21 |
22 | ### Cart Screen
23 |
24 | 
25 |
26 | ### User Profile Screen
27 |
28 | 
29 |
30 |
31 | ### Customer Order Screen
32 |
33 | 
34 |
35 | ### Admin Order Screen
36 |
37 | 
38 |
39 | ### Admin Product List Screen
40 |
41 | 
42 |
43 |
--------------------------------------------------------------------------------
/frontend/src/actions/cartActions.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios'
2 | import { CART_ADD_ITEM, CART_REMOVE_ITEM , CART_SAVE_SHIPPING_ADDRESS , CART_SAVE_PAYMENT_METHOD ,
3 | CART_MAKE_EMPTY } from '../constants/cartConstants'
4 |
5 | export const addToCart = (id, qty) => async (dispatch , getState) =>
6 | {
7 | const { data } = await axios.get(`/api/products/${id}`)
8 |
9 | dispatch({
10 | type: CART_ADD_ITEM,
11 | payload: {
12 | product: data._id,
13 | name: data.name,
14 | image: data.image,
15 | price: data.price,
16 | countInStock: data.countInStock,
17 | qty,
18 | },
19 | })
20 |
21 | localStorage.setItem('cartItems' , JSON.stringify(getState().cart.cartItems))
22 | }
23 |
24 | export const removeFromCart = (id) => async (dispatch , getState) =>
25 | {
26 | dispatch({
27 | type: CART_REMOVE_ITEM,
28 | payload: id
29 | })
30 |
31 | localStorage.setItem('cartItems' , JSON.stringify(getState().cart.cartItems))
32 | }
33 |
34 | export const emptyCart = () => async (dispatch , getState) =>
35 | {
36 | dispatch({ type: CART_MAKE_EMPTY , })
37 |
38 | localStorage.setItem('cartItems' , JSON.stringify(getState().cart.cartItems))
39 | }
40 |
41 | export const saveShippingAddress = (data) => async (dispatch) =>
42 | {
43 | dispatch({
44 | type: CART_SAVE_SHIPPING_ADDRESS,
45 | payload: data
46 | })
47 |
48 | localStorage.setItem('shippingAddress' , JSON.stringify(data))
49 | }
50 |
51 | export const savePaymentMethod = (data) => async (dispatch) =>
52 | {
53 | dispatch({
54 | type: CART_SAVE_PAYMENT_METHOD,
55 | payload: data
56 | })
57 |
58 | localStorage.setItem('paymentMethod' , JSON.stringify(data))
59 | }
60 |
--------------------------------------------------------------------------------
/backend/data/products.js:
--------------------------------------------------------------------------------
1 | const products =
2 | [
3 | {
4 | name: 'ASUS ROG Zephyrus G14',
5 | image: '/images/Asus_Rog.jpeg',
6 | description:
7 | 'Ryzen 9 Octa Core 4900HS \n16 GB RAM | 512 GB SSD \nWindows 10 Home \n6 GB Graphics \nNVIDIA GeForce GTX 1660Ti/60 Hz \n14 inch | Eclipse Grey | 1.6 Kg \nWith MS Office',
8 | brand: 'ASUS',
9 | category: 'Electronics',
10 | price: 109003,
11 | countInStock: 3,
12 | rating: 4.5,
13 | numReviews: 12
14 | },
15 | {
16 | name: 'Realme X7 5G',
17 | description:
18 | '6 GB RAM | 128 GB ROM \n16.33 cm (6.43 inch) Full HD+ Display \n64MP + 8MP + 2MP \n16MP Front Camera \n4310 mAh Battery \nMediaTek Dimensity 800U Processor \nSuper AMOLED Display \n50W Fast Charging \nLightweight (176 g) and Slim',
19 | image: '/images/Realme_X7_5G.jpeg',
20 | brand: 'Realme',
21 | category: 'Electronics',
22 | price: 17999,
23 | countInStock: 14,
24 | rating: 3,
25 | numReviews: 11
26 | },
27 | {
28 | name: 'Unifactor M Running Shoes For Men',
29 | image: '/images/Unifactor_M_Running_Shoes.jpeg',
30 | description:
31 | 'Color: Blue , White \nOuter material: Synthetic \nModel name: Unifactor M \nIdeal for: Men \nOccasion: Sports',
32 | brand: 'ADIDAS ',
33 | category: 'Men',
34 | price: 1469,
35 | countInStock: 0,
36 | rating: 3.7,
37 | numReviews: 18
38 | },
39 | {
40 | name: 'SAMSUNG 7 kg 5 Rating Fully Automatic Front Load with In-built Heater',
41 | image: '/images/Fully_Automatic_Front_Load_with_In-built_Heater.jpeg',
42 | description:
43 | 'The Samsung fully automatic front load washing machine offers a powerful washing experience with low energy consumption. With Digital Inverter Technology, this washing machine enables an energy-efficient performance while minimising operational noise. Moreover, with the Quick Wash program, you can do your laundry in just a few minutes and save time on busy workdays.',
44 | brand: 'Samsung',
45 | category: 'Home & Furniture',
46 | price: 32489,
47 | countInStock: 2,
48 | rating: 1.8,
49 | numReviews: 23
50 | }
51 | ]
52 |
53 | module.exports = products
--------------------------------------------------------------------------------
/frontend/src/screens/PaymentScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState } from 'react'
2 | import { Form , Button , Col } from 'react-bootstrap'
3 | import { useDispatch , useSelector } from 'react-redux'
4 | import FormContainer from '../components/FormContainer'
5 | import CheckoutSetps from '../components/CheckoutSteps'
6 | import { savePaymentMethod } from '../actions/cartActions'
7 |
8 | const PaymentScreen = ({ history }) =>
9 | {
10 | const cart = useSelector(state => state.cart)
11 | const { shippingAddress } = cart
12 |
13 | if(!shippingAddress)
14 | {
15 | history.push('/shipping')
16 | }
17 |
18 | const [paymentMethod , setPaymentMethod] = useState('Paypal')
19 |
20 | const dispatch = useDispatch()
21 |
22 | const submitHandler = (e) =>
23 | {
24 | e.preventDefault()
25 |
26 | dispatch(savePaymentMethod(paymentMethod))
27 |
28 | history.push('/placeorder')
29 | }
30 |
31 | return (
32 |
33 |
34 | Payment Method
35 |
36 |
37 |
39 | Select Method
40 |
41 |
42 |
43 |
44 | setPaymentMethod(e.target.value)} defaultChecked>
46 |
47 |
48 | {/* setPaymentMethod(e.target.value)}>
50 | */}
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | )
60 | }
61 |
62 | export default PaymentScreen
63 |
--------------------------------------------------------------------------------
/frontend/src/screens/HomeScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { useDispatch , useSelector } from 'react-redux'
4 | import { Row , Col } from 'react-bootstrap'
5 | import Product from '../components/Product'
6 | import Message from '../components/Message'
7 | import Loader from '../components/Loader'
8 | import { listProducts } from '../actions/productActions'
9 | import Paginate from '../components/Paginate'
10 | import Meta from '../components/Meta'
11 | import ProductCarousel from '../components/ProductCarousel'
12 |
13 | const HomeScreen = ({ match }) =>
14 | {
15 | const keyword = match.params.keyword
16 |
17 | const pageNumber = match.params.pageNumber || 1
18 |
19 | // Redux
20 |
21 | const dispatch = useDispatch()
22 |
23 | const productList = useSelector(state => state.productList)
24 | const { loading , error , products , page , pages } = productList
25 |
26 | useEffect(() =>
27 | {
28 | dispatch(listProducts(keyword , pageNumber))
29 |
30 | } , [dispatch , keyword , pageNumber])
31 |
32 |
33 | // Hooks
34 |
35 | // const [products , setProducts] = useState([])
36 |
37 | // useEffect(() =>
38 | // {
39 | // const fetchProducts = async () =>
40 | // {
41 | // const { data } = await axios.get('/api/products')
42 |
43 | // setProducts(data)
44 | // }
45 |
46 | // fetchProducts()
47 |
48 | // }, [])
49 |
50 | return (
51 |
52 |
53 |
54 | {!keyword ? (
) : (
Go Back)}
55 |
56 |
LATEST PRODUCTS
57 | {loading ?
: error ?
{error} :
58 | (
59 |
60 | {products.map(product =>
61 | (
62 |
63 |
64 |
65 | ))}
66 |
67 |
68 |
69 |
)}
70 |
71 |
72 | )
73 | }
74 |
75 | export default HomeScreen
76 |
--------------------------------------------------------------------------------
/frontend/src/store.js:
--------------------------------------------------------------------------------
1 | import { createStore , combineReducers , applyMiddleware } from 'redux'
2 | import thunk from 'redux-thunk'
3 | import { composeWithDevTools } from 'redux-devtools-extension'
4 | import { productListReducer , productDetailsReducer , productDeleteReducer , productCreateReducer ,
5 | productUpdateReducer , productReviewCreateReducer , productTopRatedReducer } from './reducers/productReducers'
6 | import { cartReducer } from './reducers/cartReducers'
7 | import { userLoginReducer , userRegisterReducer , userDetailsReducer , userUpdateProfileReducer ,
8 | userListReducer , userDeleteReducer , userUpdateReducer } from './reducers/userReducers'
9 | import { orderCreateReducer , orderDetailsReducer , orderPayReducer ,
10 | orderDeliverReducer , orderListMyReducer , orderListReducer } from './reducers/orderReducers'
11 |
12 | const reducer = combineReducers({
13 | productList: productListReducer,
14 | productDetails: productDetailsReducer,
15 | productDelete: productDeleteReducer,
16 | productCreate: productCreateReducer,
17 | productUpdate: productUpdateReducer,
18 | productReviewCreate: productReviewCreateReducer,
19 | productTopRated: productTopRatedReducer,
20 | cart: cartReducer,
21 | userLogin: userLoginReducer,
22 | userRegister: userRegisterReducer,
23 | userDetails: userDetailsReducer,
24 | userUpdateProfile: userUpdateProfileReducer,
25 | userList: userListReducer,
26 | userDelete: userDeleteReducer,
27 | userUpdate: userUpdateReducer,
28 | orderCreate: orderCreateReducer,
29 | orderDetails: orderDetailsReducer,
30 | orderPay: orderPayReducer,
31 | orderDeliver: orderDeliverReducer,
32 | orderListMy: orderListMyReducer,
33 | orderList: orderListReducer,
34 | })
35 |
36 |
37 | const cartItemsFromStorage = localStorage.getItem('cartItems') ? JSON.parse(localStorage.getItem('cartItems')) : []
38 |
39 | const userInfoFromStorage = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : null
40 |
41 | const shippingAddressFromStorage = localStorage.getItem('shippingAddress') ? JSON.parse(localStorage.getItem('shippingAddress')) : {}
42 |
43 | const paymentMethodFromStorage = localStorage.getItem('paymentMethod') ? JSON.parse(localStorage.getItem('paymentMethod')) : ''
44 |
45 |
46 | const initialState = {
47 | cart: { cartItems: cartItemsFromStorage , shippingAddress: shippingAddressFromStorage , paymentMethod: paymentMethodFromStorage },
48 | userLogin: { userInfo: userInfoFromStorage },
49 | }
50 |
51 | const middleware = [thunk]
52 |
53 | const store = createStore(reducer , initialState , composeWithDevTools(applyMiddleware(...middleware)))
54 |
55 | export default store
--------------------------------------------------------------------------------
/frontend/src/screens/LoginScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState , useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Form , Button , Row , Col } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import { login } from '../actions/userActions'
8 | import FormContainer from '../components/FormContainer'
9 |
10 | const LoginScreen = ({ location , history }) =>
11 | {
12 | const [email , setEmail] = useState('')
13 | const [password , setPassword] = useState('')
14 |
15 | const dispatch = useDispatch()
16 |
17 | const userLogin = useSelector(state => state.userLogin)
18 | const { loading , error , userInfo } = userLogin
19 |
20 | const redirect = location.search ? location.search.split('=')[1] : '/'
21 |
22 | useEffect(() =>
23 | {
24 | if(userInfo)
25 | {
26 | history.push(redirect)
27 | }
28 |
29 | }, [history , userInfo , redirect])
30 |
31 | const submitHandler = (e) =>
32 | {
33 | e.preventDefault()
34 |
35 | dispatch(login(email , password))
36 | }
37 |
38 |
39 | return (
40 |
41 | SIGN IN
42 | {error && {error}}
43 | {loading && }
44 |
46 | Email Address
47 | setEmail(e.target.value)}>
48 |
49 |
50 |
51 |
52 | Password
53 | setPassword(e.target.value)}>
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | New Customer? Register
66 |
67 |
68 |
69 | )
70 | }
71 |
72 | export default LoginScreen
73 |
--------------------------------------------------------------------------------
/frontend/src/screens/ShippingScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState } from 'react'
2 | import { Form , Button } from 'react-bootstrap'
3 | import { useDispatch , useSelector } from 'react-redux'
4 | import FormContainer from '../components/FormContainer'
5 | import CheckoutSetps from '../components/CheckoutSteps'
6 | import { saveShippingAddress } from '../actions/cartActions'
7 |
8 | const ShippingScreen = ({ history }) =>
9 | {
10 | const cart = useSelector(state => state.cart)
11 | const { shippingAddress } = cart
12 |
13 | const [address , setAddress] = useState(shippingAddress.address)
14 | const [city , setCity] = useState(shippingAddress.city)
15 | const [postalCode , setPostalCode] = useState(shippingAddress.postalCode)
16 | const [country , setCountry] = useState(shippingAddress.country)
17 |
18 | const dispatch = useDispatch()
19 |
20 | const submitHandler = (e) =>
21 | {
22 | e.preventDefault()
23 |
24 | dispatch(saveShippingAddress({ address , city , postalCode , country }))
25 |
26 | history.push('/payment')
27 | }
28 |
29 | return (
30 |
31 |
32 | SHIPPING
33 |
35 | Address
36 | setAddress(e.target.value)}>
37 |
38 |
39 |
40 |
41 | City
42 | setCity(e.target.value)}>
43 |
44 |
45 |
46 |
47 | Postal Code
48 | setPostalCode(e.target.value)}>
49 |
50 |
51 |
52 |
53 | Country
54 | setCountry(e.target.value)}>
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 | )
64 | }
65 |
66 | export default ShippingScreen
67 |
--------------------------------------------------------------------------------
/frontend/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { BrowserRouter as Router , Route } from 'react-router-dom'
3 | import { Container } from 'react-bootstrap'
4 | import Header from './components/Header'
5 | import Footer from './components/Footer'
6 | import HomeScreen from './screens/HomeScreen'
7 | import ProductScreen from './screens/ProductScreen'
8 | import CartScreen from './screens/CartScreen'
9 | import LoginScreen from './screens/LoginScreen'
10 | import RegisterScreen from './screens/RegisterScreen'
11 | import ProfileScreen from './screens/ProfileScreen'
12 | import ShippingScreen from './screens/ShippingScreen'
13 | import PaymentScreen from './screens/PaymentScreen'
14 | import PlaceOrderScreen from './screens/PlaceOrderScreen'
15 | import OrderScreen from './screens/OrderScreen'
16 | import UserListScreen from './screens/UserListScreen'
17 | import UserEditScreen from './screens/UserEditScreen'
18 | import ProductListScreen from './screens/ProductListScreen'
19 | import ProductEditScreen from './screens/ProductEditScreen'
20 | import OrderListScreen from './screens/OrderListScreen'
21 |
22 | const App = () =>
23 | {
24 | return (
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 | );
75 | }
76 |
77 | export default App;
78 |
--------------------------------------------------------------------------------
/frontend/src/components/Header.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import { Route } from 'react-router-dom'
3 | import { useDispatch , useSelector } from 'react-redux'
4 | import { LinkContainer } from 'react-router-bootstrap'
5 | import { Navbar , Nav , Container, NavDropdown } from 'react-bootstrap'
6 | import { logout } from '../actions/userActions'
7 | import SearchBox from './SearchBox'
8 |
9 | const Header = () =>
10 | {
11 | const dispatch = useDispatch()
12 |
13 | const userLogin = useSelector(state => state.userLogin)
14 | const { userInfo } = userLogin
15 |
16 | const logoutHandler = () =>
17 | {
18 | dispatch(logout())
19 | }
20 |
21 | return (
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | } />
31 |
33 |
58 |
59 |
60 |
61 |
62 | )
63 | }
64 |
65 | export default Header
66 |
--------------------------------------------------------------------------------
/frontend/src/screens/UserListScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useEffect } from 'react'
2 | import { LinkContainer } from 'react-router-bootstrap'
3 | import { Table , Button } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import { listUsers , deleteUser } from '../actions/userActions'
8 |
9 | const UserListScreen = ({ history }) =>
10 | {
11 | const dispatch = useDispatch()
12 |
13 | const userList = useSelector((state) => state.userList)
14 | const { loading , error , users } = userList
15 |
16 | const userLogin = useSelector((state) => state.userLogin)
17 | const { userInfo } = userLogin
18 |
19 | const userDelete = useSelector((state) => state.userDelete)
20 | const { success: successDelete } = userDelete
21 |
22 | useEffect(() =>
23 | {
24 | if (userInfo && userInfo.isAdmin)
25 | {
26 | dispatch(listUsers())
27 | }
28 | else
29 | {
30 | history.push('/login')
31 | }
32 |
33 | }, [dispatch , history , successDelete , userInfo])
34 |
35 | const deleteHandler = (id) =>
36 | {
37 | if (window.confirm('Are you sure'))
38 | {
39 | dispatch(deleteUser(id))
40 | }
41 | }
42 |
43 | return (
44 |
45 |
Users
46 | {loading ? (
) : error ? (
{error}) :
47 | (
48 |
49 |
50 | | ID |
51 | NAME |
52 | EMAIL |
53 | ADMIN |
54 | |
55 |
56 |
57 |
58 | {users.map((user) => (
59 |
60 | | {user._id} |
61 | {user.name} |
62 |
63 | {user.email}
64 | |
65 |
66 | {user.isAdmin ? () :
67 | ()}
68 | |
69 |
70 |
71 |
74 |
75 |
76 |
79 | |
80 |
81 | ))}
82 |
83 |
)}
84 |
85 | )
86 | }
87 |
88 | export default UserListScreen
--------------------------------------------------------------------------------
/frontend/src/screens/OrderListScreen.js:
--------------------------------------------------------------------------------
1 | import React, { useEffect } from 'react'
2 | import { LinkContainer } from 'react-router-bootstrap'
3 | import { Table , Button } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import { listOrders } from '../actions/orderActions'
8 |
9 | const format = num => {
10 | const n = String(num),
11 | p = n.indexOf('.')
12 | return n.replace(
13 | /\d(?=(?:\d{3})+(?:\.|$))/g,
14 | (m, i) => p < 0 || i < p ? `${m},` : m
15 | )
16 | }
17 |
18 | const OrderListScreen = ({ history }) =>
19 | {
20 | const dispatch = useDispatch()
21 |
22 | const orderList = useSelector((state) => state.orderList)
23 | const { loading , error , orders } = orderList
24 |
25 | const userLogin = useSelector((state) => state.userLogin)
26 | const { userInfo } = userLogin
27 |
28 | useEffect(() =>
29 | {
30 | if (userInfo && userInfo.isAdmin)
31 | {
32 | dispatch(listOrders())
33 | }
34 | else
35 | {
36 | history.push('/login')
37 | }
38 |
39 | }, [dispatch , history , userInfo])
40 |
41 | return (
42 |
43 |
Orders
44 | {loading ? (
) : error ? (
{error}) :
45 | (
46 |
47 |
48 |
49 | | ID |
50 | USER |
51 | DATE |
52 | TOTAL |
53 | PAID |
54 | DELIVERED |
55 | |
56 |
57 |
58 |
59 | {orders.map((order) => (
60 |
61 | | {order._id} |
62 | {order.user && order.user.name} |
63 | {order.createdAt.substring(0, 10)} |
64 | ₹{format(order.totalPrice)} |
65 |
66 | {order.isPaid ? (order.paidAt.substring(0, 10)) :
67 | ()
68 | }
69 | |
70 |
71 | {order.isDelivered ? (order.deliveredAt.substring(0, 10)) :
72 | ()
73 | }
74 | |
75 |
76 |
77 |
78 |
79 | |
80 |
81 | ))}
82 |
83 |
84 | )}
85 |
86 | )
87 | }
88 |
89 | export default OrderListScreen
--------------------------------------------------------------------------------
/frontend/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `yarn start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.\
15 | You will also see any lint errors in the console.
16 |
17 | ### `yarn test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `yarn build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `yarn eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35 |
36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39 |
40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `yarn build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/backend/controllers/orderController.js:
--------------------------------------------------------------------------------
1 | const asyncHandler = require('express-async-handler')
2 | const Order = require('../models/orderModel.js')
3 |
4 | const addOrderItems = asyncHandler(async (req, res) =>
5 | {
6 | const {
7 | orderItems,
8 | shippingAddress,
9 | paymentMethod,
10 | itemsPrice,
11 | taxPrice,
12 | shippingPrice,
13 | totalPrice,
14 | } = req.body
15 |
16 | if (orderItems && orderItems.length === 0)
17 | {
18 | res.status(400)
19 |
20 | throw new Error('No order items')
21 | }
22 | else
23 | {
24 | const order = new Order({
25 | orderItems,
26 | user: req.user._id,
27 | shippingAddress,
28 | paymentMethod,
29 | itemsPrice,
30 | taxPrice,
31 | shippingPrice,
32 | totalPrice,
33 | })
34 |
35 | const createdOrder = await order.save()
36 |
37 | res.status(201).json(createdOrder)
38 | }
39 | })
40 |
41 | const getOrderById = asyncHandler(async (req, res) =>
42 | {
43 | const order = await Order.findById(req.params.id).populate('user' , 'name email')
44 |
45 | if(order)
46 | {
47 | res.json(order)
48 | }
49 | else
50 | {
51 | res.status(404)
52 |
53 | throw new Error('Order Not Found')
54 | }
55 | })
56 |
57 | const updateOrderToPaid = asyncHandler(async (req , res) =>
58 | {
59 | const order = await Order.findById(req.params.id)
60 |
61 | if(order)
62 | {
63 | order.isPaid = true
64 | order.paidAt = Date.now()
65 |
66 | order.paymentResult = {
67 | id: req.body.id ,
68 | status: req.body.status,
69 | update_time: req.body.update_time,
70 | email_address: req.body.payer.email_address,
71 | }
72 |
73 | const updatedOrder = await order.save()
74 |
75 | console.log(updatedOrder)
76 |
77 | res.json(updatedOrder)
78 | }
79 | else
80 | {
81 | res.status(404)
82 |
83 | throw new Error('Order not found')
84 | }
85 | })
86 |
87 | const updateOrderToDelivered = asyncHandler(async (req , res) =>
88 | {
89 | const order = await Order.findById(req.params.id)
90 |
91 | console.log('fun')
92 |
93 | if(order)
94 | {
95 | order.isDelivered = true
96 | order.deliveredAt = Date.now()
97 |
98 | const updatedOrder = await order.save()
99 |
100 | res.json(updatedOrder)
101 | }
102 | else
103 | {
104 | res.status(404)
105 |
106 | throw new Error('Order not found')
107 | }
108 | })
109 |
110 | const getMyOrders = asyncHandler(async (req , res) =>
111 | {
112 | const orders = await Order.find({ user: req.user._id })
113 |
114 | res.json(orders)
115 | })
116 |
117 | const getOrders = asyncHandler(async (req , res) =>
118 | {
119 | const orders = await Order.find({}).populate('user' , 'id name')
120 |
121 | res.json(orders)
122 | })
123 |
124 | module.exports = { addOrderItems , getOrderById , updateOrderToPaid , updateOrderToDelivered , getMyOrders , getOrders }
--------------------------------------------------------------------------------
/frontend/src/reducers/orderReducers.js:
--------------------------------------------------------------------------------
1 | import { ORDER_CREATE_REQUEST , ORDER_CREATE_SUCCESS , ORDER_CREATE_FAILURE ,
2 | ORDER_DETAILS_REQUEST , ORDER_DETAILS_SUCCESS , ORDER_DETAILS_FAILURE,
3 | ORDER_PAY_REQUEST , ORDER_PAY_SUCCESS , ORDER_PAY_FAILURE , ORDER_PAY_RESET ,
4 | ORDER_LIST_MY_REQUEST , ORDER_LIST_MY_SUCCESS , ORDER_LIST_MY_FAILURE , ORDER_LIST_MY_RESET ,
5 | ORDER_LIST_REQUEST , ORDER_LIST_SUCCESS , ORDER_LIST_FAILURE ,
6 | ORDER_DELIVER_REQUEST , ORDER_DELIVER_SUCCESS , ORDER_DELIVER_FAILURE , ORDER_DELIVER_RESET } from '../constants/orderConstants'
7 |
8 | export const orderCreateReducer = (state = {} , action) =>
9 | {
10 | switch (action.type)
11 | {
12 | case ORDER_CREATE_REQUEST:
13 | return { loading: true , }
14 | case ORDER_CREATE_SUCCESS:
15 | return { loading: false , success: true , order: action.payload , }
16 | case ORDER_CREATE_FAILURE:
17 | return { loading: false , error: action.payload , }
18 | default:
19 | return state
20 | }
21 | }
22 |
23 | export const orderDetailsReducer = (state = { loading: true , orderItems: [] , shippingAddress: {} } , action) =>
24 | {
25 | switch (action.type)
26 | {
27 | case ORDER_DETAILS_REQUEST:
28 | return { ...state , loading: true , }
29 | case ORDER_DETAILS_SUCCESS:
30 | return { loading: false , order: action.payload , }
31 | case ORDER_DETAILS_FAILURE:
32 | return { loading: false , error: action.payload , }
33 | default:
34 | return state
35 | }
36 | }
37 |
38 | export const orderPayReducer = (state = { } , action) =>
39 | {
40 | switch (action.type)
41 | {
42 | case ORDER_PAY_REQUEST:
43 | return { loading: true , }
44 | case ORDER_PAY_SUCCESS:
45 | return { loading: false , success: true , }
46 | case ORDER_PAY_FAILURE:
47 | return { loading: false , error: action.payload , }
48 | case ORDER_PAY_RESET:
49 | return {}
50 | default:
51 | return state
52 | }
53 | }
54 |
55 | export const orderDeliverReducer = (state = {} , action) =>
56 | {
57 | switch(action.type)
58 | {
59 | case ORDER_DELIVER_REQUEST:
60 | return { loading: true , }
61 | case ORDER_DELIVER_SUCCESS:
62 | return { loading: false , success: true , }
63 | case ORDER_DELIVER_FAILURE:
64 | return { loading: false , error: action.payload , }
65 | case ORDER_DELIVER_RESET:
66 | return {}
67 | default:
68 | return state
69 | }
70 | }
71 |
72 |
73 | export const orderListMyReducer = (state = { orders: [] } , action) =>
74 | {
75 | switch (action.type)
76 | {
77 | case ORDER_LIST_MY_REQUEST:
78 | return { loading: true , }
79 | case ORDER_LIST_MY_SUCCESS:
80 | return { loading: false , orders: action.payload , }
81 | case ORDER_LIST_MY_FAILURE:
82 | return { loading: false , error: action.payload , }
83 | case ORDER_LIST_MY_RESET:
84 | return { orders: [] }
85 | default:
86 | return state
87 | }
88 | }
89 |
90 | export const orderListReducer = (state = { orders: [] } , action) =>
91 | {
92 | switch (action.type)
93 | {
94 | case ORDER_LIST_REQUEST:
95 | return { loading: true , }
96 | case ORDER_LIST_SUCCESS:
97 | return { loading: false , orders: action.payload , }
98 | case ORDER_LIST_FAILURE:
99 | return { loading: false , error: action.payload , }
100 | default:
101 | return state
102 | }
103 | }
--------------------------------------------------------------------------------
/frontend/src/screens/UserEditScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState , useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Form , Button } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import FormContainer from '../components/FormContainer'
8 | import { getUserDetails , updateUser } from '../actions/userActions'
9 | import { USER_UPDATE_RESET } from '../constants/userConstants'
10 |
11 | const UserEditScreen = ({ match , history }) =>
12 | {
13 | const userId = match.params.id
14 |
15 | const [name , setName] = useState('')
16 | const [email , setEmail] = useState('')
17 | const [isAdmin , setIsAdmin] = useState(false)
18 |
19 | const dispatch = useDispatch()
20 |
21 | const userDetails = useSelector((state) => state.userDetails)
22 | const { loading , error , user } = userDetails
23 |
24 | const userUpdate = useSelector((state) => state.userUpdate)
25 | const { loading: loadingUpdate , error: errorUpdate , success: successUpdate , } = userUpdate
26 |
27 | const userLogin = useSelector((state) => state.userLogin)
28 | const { userInfo } = userLogin
29 |
30 | useEffect(() =>
31 | {
32 | if(successUpdate)
33 | {
34 | dispatch({ type: USER_UPDATE_RESET })
35 |
36 | history.push('/admin/userlist')
37 | }
38 | else
39 | {
40 | if (!user.name || user._id !== userId)
41 | {
42 | dispatch(getUserDetails(userId))
43 | }
44 | else
45 | {
46 | setName(user.name)
47 | setEmail(user.email)
48 | setIsAdmin(user.isAdmin)
49 | }
50 | }
51 |
52 | if(!userInfo || !userInfo.isAdmin)
53 | {
54 | history.push('/login')
55 | }
56 |
57 | }, [dispatch , history , userId , user , successUpdate , userInfo])
58 |
59 | const submitHandler = (e) =>
60 | {
61 | e.preventDefault()
62 |
63 | dispatch(updateUser({ _id: userId , name , email , isAdmin }))
64 | }
65 |
66 | return (
67 |
68 | Go Back
69 |
70 | Edit User
71 | {loadingUpdate && }
72 | {errorUpdate && {errorUpdate}}
73 | {loading ? () : error ? ({error}) :
74 | (
76 | Name
77 | setName(e.target.value)}>
78 |
79 |
80 |
81 |
82 | Email Address
83 | setEmail(e.target.value)}>
84 |
85 |
86 |
87 |
88 | setIsAdmin(e.target.checked)}>
89 |
90 |
91 |
92 |
93 |
94 | )}
95 |
96 |
97 | )
98 | }
99 |
100 | export default UserEditScreen
--------------------------------------------------------------------------------
/frontend/src/screens/RegisterScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState , useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Form , Button , Row , Col } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import { register } from '../actions/userActions'
8 | import FormContainer from '../components/FormContainer'
9 |
10 | const RegisterScreen = ({ location , history }) =>
11 | {
12 | const [name , setName] = useState('')
13 | const [email , setEmail] = useState('')
14 | const [password , setPassword] = useState('')
15 | const [confirmPassword , setConfirmPassword] = useState('')
16 | const [message , setMessage] = useState(null)
17 |
18 | const dispatch = useDispatch()
19 |
20 | const userRegister = useSelector(state => state.userRegister)
21 | let { loading , error , userInfo } = userRegister
22 |
23 | const userLogin = useSelector(state => state.userLogin)
24 | userInfo = userLogin.userInfo
25 |
26 | const redirect = location.search ? location.search.split('=')[1] : '/'
27 |
28 | useEffect(() =>
29 | {
30 | if(userInfo)
31 | {
32 | history.push(redirect)
33 | }
34 |
35 | }, [history , userInfo , redirect])
36 |
37 | const submitHandler = (e) =>
38 | {
39 | e.preventDefault()
40 |
41 | if(password !== confirmPassword)
42 | {
43 | setMessage('Passwords do not match')
44 | }
45 | else
46 | {
47 | setMessage('')
48 |
49 | dispatch(register(name , email , password))
50 | }
51 | }
52 |
53 |
54 | return (
55 |
56 | SIGN UP
57 | {message && {message}}
58 | {error && {error}}
59 | {loading && }
60 |
62 | Name
63 | setName(e.target.value)}>
64 |
65 |
66 |
67 |
68 | Email Address
69 | setEmail(e.target.value)}>
70 |
71 |
72 |
73 |
74 | Password
75 | setPassword(e.target.value)}>
77 |
78 |
79 |
80 |
81 | Confirm Password
82 | setConfirmPassword(e.target.value)}>
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 | Have Account ? Login
95 |
96 |
97 |
98 | )
99 | }
100 |
101 | export default RegisterScreen
102 |
--------------------------------------------------------------------------------
/frontend/src/reducers/userReducers.js:
--------------------------------------------------------------------------------
1 | import { USER_LOGIN_REQUEST , USER_LOGIN_SUCCESS , USER_LOGIN_FAILURE , USER_LOGOUT ,
2 | USER_REGISTER_REQUEST , USER_REGISTER_SUCCESS , USER_REGISTER_FAILURE ,
3 | USER_DETAILS_REQUEST , USER_DETAILS_SUCCESS , USER_DETAILS_FAILURE , USER_DETAILS_RESET ,
4 | USER_UPDATE_PROFILE_REQUEST , USER_UPDATE_PROFILE_SUCCESS , USER_UPDATE_PROFILE_FAILURE ,
5 | USER_LIST_REQUEST, USER_LIST_SUCCESS , USER_LIST_FAILURE , USER_LIST_RESET ,
6 | USER_DELETE_REQUEST , USER_DELETE_SUCCESS , USER_DELETE_FAILURE ,
7 | USER_UPDATE_REQUEST , USER_UPDATE_SUCCESS , USER_UPDATE_FAILURE , USER_UPDATE_RESET } from '../constants/userConstants'
8 |
9 | export const userLoginReducer = (state = {} , action) =>
10 | {
11 | switch (action.type)
12 | {
13 | case USER_LOGIN_REQUEST:
14 | return { loading: true }
15 | case USER_LOGIN_SUCCESS:
16 | return { loading: false , userInfo: action.payload }
17 | case USER_LOGIN_FAILURE:
18 | return { loading: false , error: action.payload }
19 | case USER_LOGOUT:
20 | return { }
21 | default:
22 | return state
23 | }
24 | }
25 |
26 | export const userRegisterReducer = (state = {} , action) =>
27 | {
28 | switch (action.type)
29 | {
30 | case USER_REGISTER_REQUEST:
31 | return { loading: true }
32 | case USER_REGISTER_SUCCESS:
33 | return { loading: false , userInfo: action.payload }
34 | case USER_REGISTER_FAILURE:
35 | return { loading: false , error: action.payload }
36 | default:
37 | return state
38 | }
39 | }
40 |
41 | export const userDetailsReducer = (state = { user: {} } , action) =>
42 | {
43 | switch (action.type)
44 | {
45 | case USER_DETAILS_REQUEST:
46 | return { ...state , loading: true }
47 | case USER_DETAILS_SUCCESS:
48 | return { loading: false , user: action.payload }
49 | case USER_DETAILS_FAILURE:
50 | return { loading: false , error: action.payload }
51 | case USER_DETAILS_RESET:
52 | return { user: {} }
53 | default:
54 | return state
55 | }
56 | }
57 |
58 | export const userUpdateProfileReducer = (state = { user: {} } , action) =>
59 | {
60 | switch (action.type)
61 | {
62 | case USER_UPDATE_PROFILE_REQUEST:
63 | return { loading: true }
64 | case USER_UPDATE_PROFILE_SUCCESS:
65 | return { loading: false , success: true , userInfo: action.payload }
66 | case USER_UPDATE_PROFILE_FAILURE:
67 | return { loading: false , error: action.payload }
68 | default:
69 | return state
70 | }
71 | }
72 |
73 | export const userListReducer = (state = { users: [] } , action) =>
74 | {
75 | switch (action.type)
76 | {
77 | case USER_LIST_REQUEST:
78 | return { loading: true }
79 | case USER_LIST_SUCCESS:
80 | return { loading: false , users: action.payload }
81 | case USER_LIST_FAILURE:
82 | return { loading: false , error: action.payload }
83 | case USER_LIST_RESET:
84 | return { users: [] }
85 | default:
86 | return state
87 | }
88 | }
89 |
90 | export const userDeleteReducer = (state = {} , action) =>
91 | {
92 | switch (action.type)
93 | {
94 | case USER_DELETE_REQUEST:
95 | return { loading: true }
96 | case USER_DELETE_SUCCESS:
97 | return { loading: false , success: true }
98 | case USER_DELETE_FAILURE:
99 | return { loading: false , error: action.payload }
100 | default:
101 | return state
102 | }
103 | }
104 |
105 | export const userUpdateReducer = (state = { user: {} } , action) =>
106 | {
107 | switch (action.type)
108 | {
109 | case USER_UPDATE_REQUEST:
110 | return { loading: true }
111 | case USER_UPDATE_SUCCESS:
112 | return { loading: false , success: true }
113 | case USER_UPDATE_FAILURE:
114 | return { loading: false , error: action.payload }
115 | case USER_UPDATE_RESET:
116 | return { user: {} , }
117 | default:
118 | return state
119 | }
120 | }
--------------------------------------------------------------------------------
/backend/controllers/productController.js:
--------------------------------------------------------------------------------
1 | const asyncHandler = require('express-async-handler')
2 | const Product = require('../models/productModel')
3 |
4 | const getProducts = asyncHandler(async (req , res) =>
5 | {
6 | const pageSize = 12
7 | const page = Number(req.query.pageNumber) || 1
8 |
9 | const keyword = req.query.keyword ? { name: { $regex: req.query.keyword , $options: 'i' , } , } : {}
10 |
11 | const count = await Product.countDocuments({ ...keyword })
12 |
13 | const products = await Product.find({ ...keyword }).limit(pageSize).skip(pageSize * (page - 1))
14 |
15 | res.json({ products , page , pages: Math.ceil(count / pageSize) })
16 | })
17 |
18 | const getProductById = asyncHandler(async (req , res) =>
19 | {
20 | const product = await Product.findById(req.params.id)
21 |
22 | if(product)
23 | {
24 | res.json(product)
25 | }
26 | else
27 | {
28 | res.status(404)
29 |
30 | throw new Error('Product Not Found')
31 | }
32 | })
33 |
34 | const deleteProduct = asyncHandler(async (req , res) =>
35 | {
36 | const product = await Product.findById(req.params.id)
37 |
38 | if (product)
39 | {
40 | await product.remove()
41 | res.json({ message: 'Product removed' })
42 | }
43 | else
44 | {
45 | res.status(404)
46 | throw new Error('Product not found')
47 | }
48 | })
49 |
50 |
51 | const createProduct = asyncHandler(async (req, res) =>
52 | {
53 | const product = new Product({
54 | name: 'Sample name',
55 | price: 0,
56 | user: req.user._id,
57 | image: '/images/sample.jpg',
58 | brand: 'Sample brand',
59 | category: 'Sample category',
60 | countInStock: 0,
61 | numReviews: 0,
62 | description: 'Sample description',
63 | })
64 |
65 | const createdProduct = await product.save()
66 |
67 | res.status(201).json(createdProduct)
68 | })
69 |
70 | const updateProduct = asyncHandler(async (req, res) =>
71 | {
72 | const { name , price , description , image , brand , category , countInStock , } = req.body
73 |
74 | const product = await Product.findById(req.params.id)
75 |
76 | if(product)
77 | {
78 | product.name = name
79 | product.price = price
80 | product.description = description
81 | product.image = image
82 | product.brand = brand
83 | product.category = category
84 | product.countInStock = countInStock
85 |
86 | const updatedProduct = await product.save()
87 | res.json(updatedProduct)
88 | }
89 | else
90 | {
91 | res.status(404)
92 | throw new Error('Product not found')
93 | }
94 | })
95 |
96 | const createProductReview = asyncHandler(async (req , res) =>
97 | {
98 | const { rating , comment } = req.body
99 |
100 | const product = await Product.findById(req.params.id)
101 |
102 | if (product)
103 | {
104 | const alreadyReviewed = product.reviews.find((r) => r.user.toString() === req.user._id.toString())
105 |
106 | if (alreadyReviewed)
107 | {
108 | res.status(400)
109 | throw new Error('Product already reviewed')
110 | }
111 |
112 | const review = { name: req.user.name , rating: Number(rating) , comment , user: req.user._id , }
113 |
114 | product.reviews.push(review)
115 |
116 | product.numReviews = product.reviews.length
117 |
118 | product.rating = product.reviews.reduce((acc , item) => item.rating + acc , 0) / product.reviews.length
119 |
120 | await product.save()
121 |
122 | res.status(201).json({ message: 'Review added' })
123 | }
124 | else
125 | {
126 | res.status(404)
127 | throw new Error('Product not found')
128 | }
129 | })
130 |
131 | const getTopProducts = asyncHandler(async (req , res) =>
132 | {
133 | const products = await Product.find({}).sort({ rating: -1 }).limit(3)
134 |
135 | res.json(products)
136 | })
137 |
138 | module.exports = { getProducts , getProductById , deleteProduct , createProduct , updateProduct , createProductReview , getTopProducts }
--------------------------------------------------------------------------------
/frontend/src/reducers/productReducers.js:
--------------------------------------------------------------------------------
1 | import { PRODUCT_LIST_REQUEST , PRODUCT_LIST_SUCCESS , PRODUCT_LIST_FAILURE ,
2 | PRODUCT_DETAILS_REQUEST , PRODUCT_DETAILS_SUCCESS , PRODUCT_DETAILS_FAILURE ,
3 | PRODUCT_DELETE_REQUEST , PRODUCT_DELETE_SUCCESS , PRODUCT_DELETE_FAILURE ,
4 | PRODUCT_CREATE_REQUEST , PRODUCT_CREATE_SUCCESS , PRODUCT_CREATE_FAILURE , PRODUCT_CREATE_RESET ,
5 | PRODUCT_UPDATE_REQUEST , PRODUCT_UPDATE_SUCCESS , PRODUCT_UPDATE_FAILURE , PRODUCT_UPDATE_RESET ,
6 | PRODUCT_CREATE_REVIEW_REQUEST , PRODUCT_CREATE_REVIEW_SUCCESS , PRODUCT_CREATE_REVIEW_FAILURE ,
7 | PRODUCT_TOP_REQUEST , PRODUCT_TOP_SUCCESS , PRODUCT_TOP_FAILURE , PRODUCT_CREATE_REVIEW_RESET } from '../constants/productConstants'
8 |
9 | export const productListReducer = (state = { products: [] } , action) =>
10 | {
11 | switch(action.type)
12 | {
13 | case PRODUCT_LIST_REQUEST:
14 | return { loading: true , products: [] }
15 | case PRODUCT_LIST_SUCCESS:
16 | return { loading: false , products: action.payload.products , pages: action.payload.pages , page: action.payload.page , }
17 | case PRODUCT_LIST_FAILURE:
18 | return { loading: false , error: action.payload }
19 | default:
20 | return state
21 | }
22 | }
23 |
24 | export const productDetailsReducer = (state = { product: { reviews: [] } } , action) =>
25 | {
26 | switch(action.type)
27 | {
28 | case PRODUCT_DETAILS_REQUEST:
29 | return { loading: true , ...state }
30 | case PRODUCT_DETAILS_SUCCESS:
31 | return { loading: false , product: action.payload }
32 | case PRODUCT_DETAILS_FAILURE:
33 | return { loading: false , error: action.payload }
34 | default:
35 | return state
36 | }
37 | }
38 |
39 | export const productDeleteReducer = (state = {} , action) =>
40 | {
41 | switch(action.type)
42 | {
43 | case PRODUCT_DELETE_REQUEST:
44 | return { loading: true }
45 | case PRODUCT_DELETE_SUCCESS:
46 | return { loading: false , success: true }
47 | case PRODUCT_DELETE_FAILURE:
48 | return { loading: false , error: action.payload }
49 | default:
50 | return state
51 | }
52 | }
53 |
54 | export const productCreateReducer = (state = {} , action) =>
55 | {
56 | switch(action.type)
57 | {
58 | case PRODUCT_CREATE_REQUEST:
59 | return { loading: true }
60 | case PRODUCT_CREATE_SUCCESS:
61 | return { loading: false , success: true , product: action.payload }
62 | case PRODUCT_CREATE_FAILURE:
63 | return { loading: false , error: action.payload }
64 | case PRODUCT_CREATE_RESET:
65 | return {}
66 | default:
67 | return state
68 | }
69 | }
70 |
71 | export const productUpdateReducer = (state = { product: {} } , action) =>
72 | {
73 | switch(action.type)
74 | {
75 | case PRODUCT_UPDATE_REQUEST:
76 | return { loading: true }
77 | case PRODUCT_UPDATE_SUCCESS:
78 | return { loading: false , success: true , product: action.payload }
79 | case PRODUCT_UPDATE_FAILURE:
80 | return { loading: false , error: action.payload }
81 | case PRODUCT_UPDATE_RESET:
82 | return { product: {} }
83 | default:
84 | return state
85 | }
86 | }
87 |
88 | export const productReviewCreateReducer = (state = {} , action) =>
89 | {
90 | switch (action.type)
91 | {
92 | case PRODUCT_CREATE_REVIEW_REQUEST:
93 | return { loading: true }
94 | case PRODUCT_CREATE_REVIEW_SUCCESS:
95 | return { loading: false , success: true }
96 | case PRODUCT_CREATE_REVIEW_FAILURE:
97 | return { loading: false , error: action.payload }
98 | case PRODUCT_CREATE_REVIEW_RESET:
99 | return {}
100 | default:
101 | return state
102 | }
103 | }
104 |
105 | export const productTopRatedReducer = (state = { products: [] } , action) =>
106 | {
107 | switch (action.type)
108 | {
109 | case PRODUCT_TOP_REQUEST:
110 | return { loading: true , products: [] }
111 | case PRODUCT_TOP_SUCCESS:
112 | return { loading: false , products: action.payload }
113 | case PRODUCT_TOP_FAILURE:
114 | return { loading: false , error: action.payload }
115 | default:
116 | return state
117 | }
118 | }
--------------------------------------------------------------------------------
/frontend/src/actions/orderActions.js:
--------------------------------------------------------------------------------
1 | import { ORDER_CREATE_REQUEST , ORDER_CREATE_SUCCESS , ORDER_CREATE_FAILURE ,
2 | ORDER_DETAILS_REQUEST , ORDER_DETAILS_SUCCESS , ORDER_DETAILS_FAILURE ,
3 | ORDER_PAY_REQUEST , ORDER_PAY_SUCCESS , ORDER_PAY_FAILURE ,
4 | ORDER_LIST_MY_REQUEST , ORDER_LIST_MY_SUCCESS , ORDER_LIST_MY_FAILURE ,
5 | ORDER_LIST_REQUEST , ORDER_LIST_SUCCESS , ORDER_LIST_FAILURE ,
6 | ORDER_DELIVER_REQUEST , ORDER_DELIVER_SUCCESS , ORDER_DELIVER_FAILURE } from '../constants/orderConstants'
7 | import axios from 'axios'
8 |
9 | export const createOrder = (order) => async (dispatch , getState) =>
10 | {
11 | try
12 | {
13 | dispatch({ type: ORDER_CREATE_REQUEST, })
14 |
15 | const { userLogin: { userInfo }, } = getState()
16 |
17 | const config = { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${userInfo.token}`, } , }
18 |
19 | const { data } = await axios.post(`/api/orders`, order , config)
20 |
21 | dispatch({ type: ORDER_CREATE_SUCCESS , payload: data , })
22 |
23 | }
24 | catch(error)
25 | {
26 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
27 |
28 | dispatch({ type: ORDER_CREATE_FAILURE , payload: message , })
29 | }
30 | }
31 |
32 | export const getOrderDetails = (id) => async (dispatch , getState) =>
33 | {
34 | try
35 | {
36 | dispatch({ type: ORDER_DETAILS_REQUEST , })
37 |
38 | const { userLogin: { userInfo } , } = getState()
39 |
40 | const config = { headers: { Authorization: `Bearer ${userInfo.token}`, }, }
41 |
42 | const { data } = await axios.get(`/api/orders/${id}`, config)
43 |
44 | dispatch({ type: ORDER_DETAILS_SUCCESS , payload: data , })
45 | }
46 | catch (error)
47 | {
48 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
49 |
50 | dispatch({ type: ORDER_DETAILS_FAILURE , payload: message , })
51 | }
52 | }
53 |
54 | export const payOrder = (orderId , paymentResult) => async (dispatch , getState) =>
55 | {
56 | try
57 | {
58 | dispatch({ type: ORDER_PAY_REQUEST , })
59 |
60 | const { userLogin: { userInfo } , } = getState()
61 |
62 | const config = { headers: { 'Content-Type': 'application/json' , Authorization: `Bearer ${userInfo.token}` , } , }
63 |
64 | const { data } = await axios.put(`/api/orders/${orderId}/pay` , paymentResult , config)
65 |
66 | dispatch({ type: ORDER_PAY_SUCCESS , payload: data , })
67 | }
68 | catch(error)
69 | {
70 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
71 |
72 | dispatch({ type: ORDER_PAY_FAILURE , payload: message , })
73 | }
74 | }
75 |
76 | export const deliverOrder = (order) => async (dispatch , getState) =>
77 | {
78 | try
79 | {
80 | dispatch({ type: ORDER_DELIVER_REQUEST , })
81 |
82 | const { userLogin: { userInfo } , } = getState()
83 |
84 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
85 |
86 | const { data } = await axios.put(`/api/orders/${order._id}/deliver` , {} , config)
87 |
88 | dispatch({ type: ORDER_DELIVER_SUCCESS , payload: data , })
89 | }
90 | catch(error)
91 | {
92 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
93 |
94 | dispatch({
95 | type: ORDER_DELIVER_FAILURE,
96 | payload: message,
97 | })
98 | }
99 | }
100 |
101 | export const listMyOrders = () => async (dispatch , getState) =>
102 | {
103 | try
104 | {
105 | dispatch({ type: ORDER_LIST_MY_REQUEST , })
106 |
107 | const { userLogin: { userInfo } , } = getState()
108 |
109 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
110 |
111 | const { data } = await axios.get(`/api/orders/myorders` , config)
112 |
113 | dispatch({ type: ORDER_LIST_MY_SUCCESS , payload: data , })
114 | }
115 | catch(error)
116 | {
117 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
118 |
119 | dispatch({ type: ORDER_LIST_MY_FAILURE , payload: message , })
120 | }
121 | }
122 |
123 | export const listOrders = () => async (dispatch , getState) =>
124 | {
125 | try
126 | {
127 | dispatch({ type: ORDER_LIST_REQUEST , })
128 |
129 | const { userLogin: { userInfo } , } = getState()
130 |
131 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
132 |
133 | const { data } = await axios.get(`/api/orders` , config)
134 |
135 | dispatch({ type: ORDER_LIST_SUCCESS , payload: data , })
136 | }
137 | catch(error)
138 | {
139 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
140 |
141 | dispatch({
142 | type: ORDER_LIST_FAILURE,
143 | payload: message,
144 | })
145 | }
146 | }
--------------------------------------------------------------------------------
/frontend/src/screens/ProductListScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useEffect } from 'react'
2 | import { LinkContainer } from 'react-router-bootstrap'
3 | import { Table , Button , Row , Col } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import Paginate from '../components/Paginate'
8 | import { listProducts , deleteProduct , createProduct } from '../actions/productActions'
9 | import { PRODUCT_CREATE_RESET } from '../constants/productConstants'
10 |
11 | const format = num => {
12 | const n = String(num),
13 | p = n.indexOf('.')
14 | return n.replace(
15 | /\d(?=(?:\d{3})+(?:\.|$))/g,
16 | (m, i) => p < 0 || i < p ? `${m},` : m
17 | )
18 | }
19 |
20 |
21 | const ProductListScreen = ({ history , match }) =>
22 | {
23 | const pageNumber = match.params.pageNumber || 1
24 |
25 | const dispatch = useDispatch()
26 |
27 | const productList = useSelector((state) => state.productList)
28 | const { loading , error , products , page , pages } = productList
29 |
30 | const productDelete = useSelector((state) => state.productDelete)
31 | const { loading: loadingDelete , error: errorDelete , success: successDelete } = productDelete
32 |
33 | const productCreate = useSelector((state) => state.productCreate)
34 | const { loading: loadingCreate , error: errorCreate , success: successCreate , product: createdProduct } = productCreate
35 |
36 | const userLogin = useSelector((state) => state.userLogin)
37 | const { userInfo } = userLogin
38 |
39 | useEffect(() =>
40 | {
41 | dispatch({ type: PRODUCT_CREATE_RESET })
42 |
43 | if (!userInfo || !userInfo.isAdmin)
44 | {
45 | history.push('/login')
46 | }
47 |
48 | if(successCreate)
49 | {
50 | history.push(`/admin/product/${createdProduct._id}/edit`)
51 | }
52 | else
53 | {
54 | dispatch(listProducts('', pageNumber))
55 | }
56 |
57 | }, [dispatch , history , userInfo , successDelete , successCreate , createdProduct , pageNumber])
58 |
59 | const deleteHandler = (id) =>
60 | {
61 | if (window.confirm('Are you sure'))
62 | {
63 | dispatch(deleteProduct(id))
64 | }
65 | }
66 |
67 | const createProductHandler = () =>
68 | {
69 | dispatch(createProduct())
70 | }
71 |
72 | return (
73 |
74 |
75 | Products
76 |
77 |
80 |
81 |
82 |
83 | {loadingDelete &&
}
84 | {errorDelete &&
{errorDelete}}
85 | {loadingCreate &&
}
86 | {errorCreate &&
{errorCreate}}
87 | {loading ? (
) : error ? (
{error}) :
88 | (
89 |
90 |
91 |
92 |
93 | | ID |
94 | NAME |
95 | PRICE |
96 | CATEGORY |
97 | BRAND |
98 | |
99 |
100 |
101 |
102 | {products.map((product) => (
103 |
104 | | {product._id} |
105 | {product.name} |
106 | ₹{format(product.price)} |
107 | {product.category} |
108 | {product.brand} |
109 |
110 |
111 |
114 |
115 |
116 |
119 | |
120 |
121 | ))}
122 |
123 |
124 |
125 |
126 |
127 | )}
128 |
129 | )
130 | }
131 |
132 | export default ProductListScreen
--------------------------------------------------------------------------------
/backend/controllers/userController.js:
--------------------------------------------------------------------------------
1 | const asyncHandler = require('express-async-handler')
2 | const User = require('../models/userModel')
3 | const generateToken = require('../utils/generateTokens')
4 | const { sendWelcomeMail , sendCancelationMail } = require('../email/account')
5 |
6 | const authUser = asyncHandler(async (req , res) =>
7 | {
8 | const { email , password } = req.body
9 |
10 | const user = await User.findOne({ email })
11 |
12 | if(user && (await user.matchPassword(password)))
13 | {
14 | res.json({
15 | _id: user._id ,
16 | name: user.name ,
17 | email: user.email ,
18 | isAdmin: user.isAdmin ,
19 | token: generateToken(user._id)
20 | })
21 | }
22 | else
23 | {
24 | res.status(401)
25 |
26 | throw new Error('Invalid email or password')
27 | }
28 | })
29 |
30 | const registerUser = asyncHandler(async (req , res) =>
31 | {
32 | const { name , email , password } = req.body
33 |
34 | const userExists = await User.findOne({ email })
35 |
36 | if(userExists)
37 | {
38 | res.status(400)
39 |
40 | throw new Error('User already exists')
41 | }
42 |
43 | const user = await User.create({
44 | name,
45 | email,
46 | password
47 | })
48 |
49 | if(user)
50 | {
51 | sendWelcomeMail(user.email , user.name)
52 |
53 | res.status(201).json({
54 | _id: user._id ,
55 | name: user.name ,
56 | email: user.email ,
57 | isAdmin: user.isAdmin ,
58 | token: generateToken(user._id)
59 | })
60 | }
61 | else
62 | {
63 | res.status(400)
64 |
65 | throw new Error('Invalid User Data')
66 | }
67 | })
68 |
69 | const getUserProfile = asyncHandler(async (req , res) =>
70 | {
71 | const user = await User.findById(req.user._id)
72 |
73 | if(user)
74 | {
75 | res.json({
76 | _id: user._id ,
77 | name: user.name ,
78 | email: user.email ,
79 | isAdmin: user.isAdmin
80 | })
81 | }
82 | else
83 | {
84 | res.status(404)
85 |
86 | throw new Error('User not found')
87 | }
88 | })
89 |
90 | const updateUserProfile = asyncHandler(async (req , res) =>
91 | {
92 | const user = await User.findById(req.user._id)
93 |
94 | if(user)
95 | {
96 | user.name = req.body.name || user.name
97 | user.email = req.body.email || user.email
98 |
99 | if(req.body.password)
100 | {
101 | user.password = req.body.password
102 | }
103 |
104 | const updatedUser = await user.save()
105 |
106 | res.json({
107 | _id: updatedUser._id ,
108 | name: updatedUser.name ,
109 | email: updatedUser.email ,
110 | isAdmin: updatedUser.isAdmin ,
111 | token: generateToken(updatedUser._id)
112 | })
113 | }
114 | else
115 | {
116 | res.status(404)
117 |
118 | throw new Error('User not found')
119 | }
120 | })
121 |
122 | const getUsers = asyncHandler(async (req , res) =>
123 | {
124 | const users = await User.find({})
125 |
126 | res.json(users)
127 | })
128 |
129 | const deleteUser = asyncHandler(async (req , res) =>
130 | {
131 | const user = await User.findById(req.params.id)
132 |
133 | if (user)
134 | {
135 | sendCancelationMail(user.email , user.name)
136 |
137 | await user.remove()
138 |
139 | res.json({ message: 'User removed' })
140 | }
141 | else
142 | {
143 | res.status(404)
144 | throw new Error('User not found')
145 | }
146 | })
147 |
148 | const getUserById = asyncHandler(async (req , res) =>
149 | {
150 | const user = await User.findById(req.params.id).select('-password')
151 |
152 | if(user)
153 | {
154 | res.json(user)
155 | }
156 | else
157 | {
158 | res.status(404)
159 | throw new Error('User not found')
160 | }
161 | })
162 |
163 | const updateUser = asyncHandler(async (req , res) =>
164 | {
165 | const user = await User.findById(req.params.id)
166 |
167 | if(user)
168 | {
169 | user.name = req.body.name || user.name
170 | user.email = req.body.email || user.email
171 | user.isAdmin = req.body.isAdmin
172 |
173 | const updatedUser = await user.save()
174 |
175 | res.json({
176 | _id: updatedUser._id,
177 | name: updatedUser.name,
178 | email: updatedUser.email,
179 | isAdmin: updatedUser.isAdmin,
180 | })
181 | }
182 | else
183 | {
184 | res.status(404)
185 | throw new Error('User not found')
186 | }
187 | })
188 |
189 |
190 | module.exports = { authUser , registerUser , getUserProfile , updateUserProfile , getUsers , deleteUser , getUserById , updateUser}
--------------------------------------------------------------------------------
/frontend/src/screens/CartScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { useDispatch , useSelector } from 'react-redux'
4 | import { Row , Col , ListGroup , Image , Form , Button , Card } from 'react-bootstrap'
5 | import { addToCart , emptyCart, removeFromCart } from '../actions/cartActions'
6 |
7 | const format = num => {
8 | const n = String(num),
9 | p = n.indexOf('.')
10 | return n.replace(
11 | /\d(?=(?:\d{3})+(?:\.|$))/g,
12 | (m, i) => p < 0 || i < p ? `${m},` : m
13 | )
14 | }
15 |
16 | const CartScreen = ({ match , location , history}) =>
17 | {
18 | const productId = match.params.id
19 |
20 | const qty = location.search ? Number(location.search.split('=')[1]) : 1
21 |
22 | const dispatch = useDispatch()
23 |
24 | const cart = useSelector((state) => state.cart)
25 | const { cartItems } = cart
26 |
27 | const userLogin = useSelector((state) => state.userLogin)
28 | const { userInfo } = userLogin
29 |
30 | useEffect(() =>
31 | {
32 | if (!userInfo)
33 | {
34 | dispatch(emptyCart())
35 |
36 | history.push('/login')
37 | }
38 |
39 | if(productId)
40 | {
41 | dispatch(addToCart(productId, qty))
42 | }
43 |
44 | }, [dispatch , productId , qty , userInfo , history])
45 |
46 |
47 | const removeFromCartHandler = (id) =>
48 | {
49 | dispatch(removeFromCart(id))
50 | }
51 |
52 | const checkoutHandler = () =>
53 | {
54 | history.push('/login?redirect=shipping')
55 | }
56 |
57 | return (
58 |
59 |
SHOPPING CART
60 | {cartItems.length === 0 ?
61 | (
Go Back
62 |
EMPTY CART
63 |
64 |

65 |
66 |
67 | ) :
68 | (
69 |
70 |
71 |
72 | {cartItems.map((item) =>
73 | (
74 |
75 |
76 |
77 |
78 |
79 |
80 | {item.name}
81 |
82 |
83 | ₹{format(item.price)}
84 |
85 | dispatch(addToCart(item.product,Number(e.target.value)))}>
86 | {[...Array(Math.min(item.countInStock,10)).keys()].map((x) => ())}
87 |
88 |
89 |
90 |
93 |
94 |
95 | ))}
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 | Price Details
104 |
105 |
106 |
107 |
108 |
109 |
110 | Total ({cartItems.reduce((acc , item) => acc += item.qty , 0)} {cartItems.reduce((acc , item) => acc += item.qty , 0) > 1 ? 'Items' : 'Item'})
111 |
112 |
113 |
114 |
115 | ₹{format(cartItems.reduce((acc , item) => acc += item.qty * item.price , 0).toFixed(2))}
116 |
117 |
118 |
119 |
120 |
121 |
122 |
125 |
126 |
127 |
128 |
)}
129 |
130 | )
131 | }
132 |
133 | export default CartScreen
134 |
--------------------------------------------------------------------------------
/frontend/src/actions/productActions.js:
--------------------------------------------------------------------------------
1 | import { PRODUCT_LIST_REQUEST , PRODUCT_LIST_SUCCESS , PRODUCT_LIST_FAILURE,
2 | PRODUCT_DETAILS_REQUEST , PRODUCT_DETAILS_SUCCESS , PRODUCT_DETAILS_FAILURE ,
3 | PRODUCT_DELETE_REQUEST , PRODUCT_DELETE_SUCCESS , PRODUCT_DELETE_FAILURE ,
4 | PRODUCT_CREATE_REQUEST , PRODUCT_CREATE_SUCCESS , PRODUCT_CREATE_FAILURE ,
5 | PRODUCT_UPDATE_REQUEST , PRODUCT_UPDATE_SUCCESS , PRODUCT_UPDATE_FAILURE ,
6 | PRODUCT_CREATE_REVIEW_REQUEST , PRODUCT_CREATE_REVIEW_SUCCESS , PRODUCT_CREATE_REVIEW_FAILURE ,
7 | PRODUCT_TOP_REQUEST , PRODUCT_TOP_SUCCESS , PRODUCT_TOP_FAILURE , } from '../constants/productConstants'
8 | import axios from 'axios'
9 |
10 | export const listProducts = (keyword = '', pageNumber = '') => async (dispatch) =>
11 | {
12 | try
13 | {
14 | dispatch({ type: PRODUCT_LIST_REQUEST })
15 |
16 | const { data } = await axios.get( `/api/products?keyword=${keyword}&pageNumber=${pageNumber}`)
17 |
18 | dispatch({ type: PRODUCT_LIST_SUCCESS ,
19 | payload: data
20 | })
21 | }
22 | catch (error)
23 | {
24 | dispatch({
25 | type: PRODUCT_LIST_FAILURE ,
26 | payload: error.response && error.response.data.message ? error.response.data.message : error.message
27 | })
28 | }
29 | }
30 |
31 |
32 | export const listProductDetails = (id) => async (dispatch) =>
33 | {
34 | try
35 | {
36 | dispatch({ type: PRODUCT_DETAILS_REQUEST })
37 |
38 | const { data } = await axios.get(`/api/products/${id}`)
39 |
40 | dispatch({ type: PRODUCT_DETAILS_SUCCESS ,
41 | payload: data
42 | })
43 | }
44 | catch (error)
45 | {
46 | dispatch({
47 | type: PRODUCT_DETAILS_FAILURE ,
48 | payload: error.response && error.response.data.message ? error.response.data.message : error.message
49 | })
50 | }
51 | }
52 |
53 | export const deleteProduct = (id) => async (dispatch , getState) =>
54 | {
55 | try
56 | {
57 | dispatch({ type: PRODUCT_DELETE_REQUEST , })
58 |
59 | const { userLogin: { userInfo } , } = getState()
60 |
61 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
62 |
63 | await axios.delete(`/api/products/${id}` , config)
64 |
65 | dispatch({ type: PRODUCT_DELETE_SUCCESS , })
66 | }
67 | catch(error)
68 | {
69 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
70 |
71 | dispatch({
72 | type: PRODUCT_DELETE_FAILURE,
73 | payload: message,
74 | })
75 | }
76 | }
77 |
78 | export const createProduct = () => async (dispatch , getState) =>
79 | {
80 | try
81 | {
82 | dispatch({ type: PRODUCT_CREATE_REQUEST , })
83 |
84 | const { userLogin: { userInfo } , } = getState()
85 |
86 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
87 |
88 | const { data } = await axios.post(`/api/products` , {} , config)
89 |
90 | dispatch({ type: PRODUCT_CREATE_SUCCESS , payload: data , })
91 | }
92 | catch(error)
93 | {
94 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
95 |
96 | dispatch({
97 | type: PRODUCT_CREATE_FAILURE,
98 | payload: message,
99 | })
100 | }
101 | }
102 |
103 | export const updateProduct = (product) => async (dispatch , getState) =>
104 | {
105 | try
106 | {
107 | dispatch({ type: PRODUCT_UPDATE_REQUEST , })
108 |
109 | const { userLogin: { userInfo } , } = getState()
110 |
111 | const config = { headers: { 'Content-Type': 'application/json' , Authorization: `Bearer ${userInfo.token}` , } , }
112 |
113 | const { data } = await axios.put(`/api/products/${product._id}` , product , config)
114 |
115 | dispatch({ type: PRODUCT_UPDATE_SUCCESS , payload: data , })
116 |
117 | dispatch({ type: PRODUCT_DETAILS_SUCCESS , payload: data })
118 | }
119 | catch(error)
120 | {
121 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
122 |
123 | dispatch({
124 | type: PRODUCT_UPDATE_FAILURE,
125 | payload: message,
126 | })
127 | }
128 | }
129 |
130 | export const createProductReview = (productId , review) => async (dispatch , getState) =>
131 | {
132 | try
133 | {
134 | dispatch({ type: PRODUCT_CREATE_REVIEW_REQUEST , })
135 |
136 | const { userLogin: { userInfo } , } = getState()
137 |
138 | const config = { headers: { 'Content-Type': 'application/json' , Authorization: `Bearer ${userInfo.token}` , } , }
139 |
140 | await axios.post(`/api/products/${productId}/reviews` , review , config)
141 |
142 | dispatch({ type: PRODUCT_CREATE_REVIEW_SUCCESS , })
143 | }
144 | catch(error)
145 | {
146 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
147 |
148 | dispatch({
149 | type: PRODUCT_CREATE_REVIEW_FAILURE,
150 | payload: message,
151 | })
152 | }
153 | }
154 |
155 | export const listTopProducts = () => async (dispatch) =>
156 | {
157 | try
158 | {
159 | dispatch({ type: PRODUCT_TOP_REQUEST })
160 |
161 | const { data } = await axios.get(`/api/products/top`)
162 |
163 | dispatch({ type: PRODUCT_TOP_SUCCESS , payload: data , })
164 | }
165 | catch(error)
166 | {
167 | dispatch({
168 | type: PRODUCT_TOP_FAILURE,
169 | payload: error.response && error.response.data.message ? error.response.data.message : error.message ,
170 | })
171 | }
172 | }
--------------------------------------------------------------------------------
/frontend/src/screens/ProductEditScreen.js:
--------------------------------------------------------------------------------
1 | import axios from 'axios'
2 | import React , { useState , useEffect } from 'react'
3 | import { Link } from 'react-router-dom'
4 | import { Form , Button } from 'react-bootstrap'
5 | import { useDispatch , useSelector } from 'react-redux'
6 | import Message from '../components/Message'
7 | import Loader from '../components/Loader'
8 | import FormContainer from '../components/FormContainer'
9 | import { listProductDetails , updateProduct } from '../actions/productActions'
10 | import { PRODUCT_UPDATE_RESET } from '../constants/productConstants'
11 |
12 | const ProductEditScreen = ({ match , history }) =>
13 | {
14 | const productId = match.params.id
15 |
16 | const [name , setName] = useState('')
17 | const [price , setPrice] = useState(0)
18 | const [image , setImage] = useState('')
19 | const [brand , setBrand] = useState('')
20 | const [category , setCategory] = useState('')
21 | const [countInStock , setCountInStock] = useState(0)
22 | const [description , setDescription] = useState('')
23 | const [uploading , setUploading] = useState(false)
24 |
25 | const dispatch = useDispatch()
26 |
27 | const productDetails = useSelector((state) => state.productDetails)
28 | const { loading , error , product } = productDetails
29 |
30 | const productUpdate = useSelector((state) => state.productUpdate)
31 | const {loading: loadingUpdate , error: errorUpdate , success: successUpdate } = productUpdate
32 |
33 | useEffect(() =>
34 | {
35 | if(successUpdate)
36 | {
37 | dispatch({ type: PRODUCT_UPDATE_RESET })
38 | history.push('/admin/productlist')
39 | }
40 | else
41 | {
42 | if(!product.name || product._id !== productId)
43 | {
44 | dispatch(listProductDetails(productId))
45 | }
46 | else
47 | {
48 | setName(product.name)
49 | setPrice(product.price)
50 | setImage(product.image)
51 | setBrand(product.brand)
52 | setCategory(product.category)
53 | setCountInStock(product.countInStock)
54 | setDescription(product.description)
55 | }
56 | }
57 |
58 | }, [dispatch , history , productId , product , successUpdate])
59 |
60 | const uploadFileHandler = async (e) =>
61 | {
62 | const file = e.target.files[0]
63 |
64 | const formData = new FormData()
65 |
66 | formData.append('image', file)
67 |
68 | setUploading(true)
69 |
70 | try
71 | {
72 | const config = { headers: { 'Content-Type': 'multipart/form-data' , } , }
73 |
74 | const { data } = await axios.post('/api/upload' , formData , config)
75 |
76 | setImage(data)
77 | setUploading(false)
78 | }
79 | catch(error)
80 | {
81 | setUploading(false)
82 | }
83 | }
84 |
85 | const submitHandler = (e) =>
86 | {
87 | e.preventDefault()
88 | dispatch(updateProduct({
89 | _id: productId,
90 | name,
91 | price,
92 | image,
93 | brand,
94 | category,
95 | description,
96 | countInStock,
97 | }))
98 | }
99 |
100 | return (
101 |
102 | Go Back
103 |
104 | Edit Product
105 | {loadingUpdate && }
106 | {errorUpdate && {errorUpdate}}
107 | {loading ? () : error ? ({error}) :
108 | (
109 |
111 | Name
112 | setName(e.target.value)}>
113 |
114 |
115 |
116 |
117 | Price
118 | setPrice(e.target.value)}>
119 |
120 |
121 |
122 |
123 | Image
124 | setImage(e.target.value)}>
125 |
126 |
127 |
128 |
129 |
130 | {uploading && }
131 |
132 |
133 |
134 | Brand
135 | setBrand(e.target.value)}>
136 |
137 |
138 |
139 |
140 | Count In Stock
141 | setCountInStock(e.target.value)}>
143 |
144 |
145 |
146 |
147 | Category
148 | setCategory(e.target.value)}>
149 |
150 |
151 |
152 |
153 | Description
154 | setDescription(e.target.value)}>
156 |
157 |
158 |
159 |
160 |
161 | )}
162 |
163 |
164 | )
165 | }
166 |
167 | export default ProductEditScreen
--------------------------------------------------------------------------------
/frontend/src/screens/ProfileScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState , useEffect } from 'react'
2 | import { Table , Form , Button , Row , Col } from 'react-bootstrap'
3 | import { LinkContainer } from 'react-router-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import { getUserDetails , updateUserProfile } from '../actions/userActions'
8 | import { listMyOrders } from '../actions/orderActions'
9 |
10 | const ProfileScreen = ({ location , history }) =>
11 | {
12 | const [name , setName] = useState('')
13 | const [email , setEmail] = useState('')
14 | const [password , setPassword] = useState('')
15 | const [confirmPassword , setConfirmPassword] = useState('')
16 | const [message , setMessage] = useState(null)
17 |
18 | const dispatch = useDispatch()
19 |
20 | const userDetails = useSelector(state => state.userDetails)
21 | const { loading , error , user } = userDetails
22 |
23 | const userLogin = useSelector(state => state.userLogin)
24 | const { userInfo } = userLogin
25 |
26 | const userUpdateProfile = useSelector(state => state.userUpdateProfile)
27 | let { success } = userUpdateProfile
28 |
29 | const orderListMy = useSelector(state => state.orderListMy)
30 | const { loading: loadingOrders , error: errorOrders , orders } = orderListMy
31 |
32 | useEffect(() =>
33 | {
34 | if(!userInfo)
35 | {
36 | history.push('/login')
37 | }
38 | else
39 | {
40 | if(!user || !user.name)
41 | {
42 | dispatch(getUserDetails('profile'))
43 |
44 | dispatch(listMyOrders())
45 | }
46 | else
47 | {
48 | setName(user.name)
49 | setEmail(user.email)
50 | }
51 | }
52 |
53 | }, [history , userInfo , dispatch , user])
54 |
55 | const submitHandler = (e) =>
56 | {
57 | e.preventDefault()
58 |
59 | if(password !== confirmPassword)
60 | {
61 | setMessage('Passwords do not match')
62 | }
63 | else
64 | {
65 | setMessage('')
66 |
67 | dispatch(updateUserProfile({ id: user._id , name , user , password}))
68 |
69 | success = false
70 | }
71 | }
72 |
73 |
74 | return (
75 |
76 |
77 | User Profile
78 | {message && {message}}
79 | {error && {error}}
80 | {success && Profile updated successfully}
81 | {loading && }
82 |
84 | Name
85 | setName(e.target.value)}>
86 |
87 |
88 |
89 |
90 | Email Address
91 | setEmail(e.target.value)}>
92 |
93 |
94 |
95 |
96 | Password
97 | setPassword(e.target.value)}>
99 |
100 |
101 |
102 |
103 | Confirm Password
104 | setConfirmPassword(e.target.value)}>
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 | My Orders
116 | {loadingOrders ? (
117 |
118 | ) : errorOrders ? (
119 | {errorOrders}
120 | ) : (
121 |
122 |
123 |
124 | | ID |
125 | DATE |
126 | TOTAL |
127 | PAID |
128 | DELIVERED |
129 | |
130 |
131 |
132 |
133 | {orders.map((order) => (
134 |
135 | | {order._id} |
136 | {order.createdAt.substring(0 , 10)} |
137 | {order.totalPrice} |
138 |
139 | {order.isPaid ? (
140 | order.paidAt.substring(0, 10)
141 | ) : (
142 |
143 | )}
144 | |
145 |
146 | {order.isDelivered ? (
147 | order.deliveredAt.substring(0 , 10)
148 | ) : (
149 |
150 | )}
151 | |
152 |
153 |
154 |
157 |
158 | |
159 |
160 | ))}
161 |
162 |
163 | )}
164 |
165 |
166 | )
167 | }
168 |
169 | export default ProfileScreen
170 |
--------------------------------------------------------------------------------
/frontend/src/screens/PlaceOrderScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Button , Row , Col , ListGroup , Image , Card } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import CheckoutSetps from '../components/CheckoutSteps'
7 | import { createOrder } from '../actions/orderActions'
8 | import { emptyCart } from '../actions/cartActions'
9 |
10 | const format = num => {
11 | const n = String(num),
12 | p = n.indexOf('.')
13 | return n.replace(
14 | /\d(?=(?:\d{3})+(?:\.|$))/g,
15 | (m, i) => p < 0 || i < p ? `${m},` : m
16 | )
17 | }
18 |
19 | const PlaceOrderScreen = ({ history }) =>
20 | {
21 | const dispatch = useDispatch()
22 |
23 | const cart = useSelector(state => state.cart)
24 |
25 | const addDecimals = (num) =>
26 | {
27 | return (Math.round(num * 100) / 100).toFixed(2)
28 | }
29 |
30 | cart.itemsPrice = addDecimals(cart.cartItems.reduce((acc, item) => acc + item.price * item.qty, 0))
31 |
32 | cart.shippingPrice = addDecimals(cart.itemsPrice > 100 ? 0 : 100)
33 |
34 | const tax = 7
35 |
36 | cart.taxPrice = addDecimals(Number(((tax / 100) * cart.itemsPrice).toFixed(2)))
37 |
38 | cart.totalPrice = (Number(cart.itemsPrice) + Number(cart.shippingPrice) + Number(cart.taxPrice))
39 |
40 | const orderCreate = useSelector(state => state.orderCreate)
41 | const { order , success , error } = orderCreate
42 |
43 | useEffect(() =>
44 | {
45 | if(success)
46 | {
47 | history.push(`/order/${order._id}`)
48 |
49 | dispatch(emptyCart())
50 | }
51 | // eslint-disable-next-line
52 | } , [history , success])
53 |
54 | const placeOrderHandler = () =>
55 | {
56 | dispatch(createOrder({ orderItems: cart.cartItems ,
57 | shippingAddress: cart.shippingAddress ,
58 | paymentMethod: cart.paymentMethod ,
59 | itemsPrice: cart.itemsPrice,
60 | shippingPrice: cart.shippingPrice,
61 | taxPrice: cart.taxPrice,
62 | totalPrice: cart.totalPrice,
63 | }))
64 | }
65 |
66 | return (
67 |
68 |
69 |
70 |
71 |
72 |
73 | Shipping
74 |
75 | Address:
76 | {cart.shippingAddress.address} , {cart.shippingAddress.city} , {cart.shippingAddress.postalCode} , {cart.shippingAddress.country}
77 |
78 |
79 |
80 |
81 | Payment Method
82 |
83 | Method:
84 | {cart.paymentMethod}
85 |
86 |
87 |
88 |
89 |
90 | Order Items
91 | {cart.cartItems.length === 0 ? Your Cart is empty :
92 | (
93 |
94 | {cart.cartItems.map((item , index) =>
95 | (
96 |
97 |
98 |
99 |
101 |
102 |
103 |
104 |
105 | {item.name}
106 |
107 |
108 |
109 |
110 |
111 | {item.qty} x ₹{format(item.price)} = ₹{format(item.qty * item.price)}
112 |
113 |
114 |
115 |
116 | ))}
117 |
118 | )}
119 |
120 |
121 |
122 |
123 |
124 |
125 | Order Summery
126 |
127 |
128 | Items
129 | ₹{cart.itemsPrice}
130 |
131 |
132 |
133 |
134 |
135 | Shipping
136 | ₹{cart.shippingPrice}
137 |
138 |
139 |
140 |
141 |
142 | Tax
143 |
144 | ₹{cart.taxPrice} ({tax} %)
145 |
146 |
147 |
148 |
149 |
150 |
151 | Total
152 | ₹{cart.totalPrice}
153 |
154 |
155 |
156 | {error && {error}}
157 |
158 |
159 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 | )
170 | }
171 |
172 | export default PlaceOrderScreen
173 |
--------------------------------------------------------------------------------
/frontend/src/actions/userActions.js:
--------------------------------------------------------------------------------
1 | import { USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS , USER_LOGIN_FAILURE, USER_LOGOUT ,
2 | USER_REGISTER_REQUEST , USER_REGISTER_SUCCESS , USER_REGISTER_FAILURE ,
3 | USER_DETAILS_REQUEST , USER_DETAILS_SUCCESS , USER_DETAILS_FAILURE , USER_DETAILS_RESET ,
4 | USER_UPDATE_PROFILE_REQUEST , USER_UPDATE_PROFILE_SUCCESS , USER_UPDATE_PROFILE_FAILURE ,
5 | USER_LIST_REQUEST , USER_LIST_SUCCESS , USER_LIST_FAILURE , USER_LIST_RESET ,
6 | USER_DELETE_REQUEST , USER_DELETE_SUCCESS , USER_DELETE_FAILURE ,
7 | USER_UPDATE_REQUEST , USER_UPDATE_SUCCESS , USER_UPDATE_FAILURE } from '../constants/userConstants'
8 | import { ORDER_LIST_MY_RESET } from '../constants/orderConstants'
9 | import { emptyCart } from './cartActions'
10 | import axios from 'axios'
11 |
12 | export const login = (email , password) => async (dispatch) =>
13 | {
14 | try
15 | {
16 | dispatch({ type: USER_LOGIN_REQUEST })
17 |
18 | const config = { headers: { 'Content-Type': 'application/json'}}
19 |
20 | const { data } = await axios.post('/api/users/login' , { email , password } , config)
21 |
22 | dispatch({ type: USER_LOGIN_SUCCESS , payload: data })
23 |
24 | localStorage.setItem('userInfo' , JSON.stringify(data))
25 | }
26 | catch(error)
27 | {
28 | dispatch({
29 | type: USER_LOGIN_FAILURE ,
30 | payload: error.response && error.response.data.message ? error.response.data.message : error.message
31 | })
32 | }
33 | }
34 |
35 | export const logout = () => (dispatch) =>
36 | {
37 | localStorage.removeItem('userInfo')
38 | localStorage.removeItem('shippingAddress')
39 | localStorage.removeItem('paymentMethod')
40 |
41 | dispatch(emptyCart())
42 | dispatch({ type: USER_LOGOUT })
43 | dispatch({ type: USER_DETAILS_RESET })
44 | dispatch({ type: ORDER_LIST_MY_RESET })
45 | dispatch({ type: USER_LIST_RESET })
46 | }
47 |
48 | export const register = (name , email , password) => async (dispatch) =>
49 | {
50 | try
51 | {
52 | dispatch({ type: USER_REGISTER_REQUEST })
53 |
54 | const config = { headers: { 'Content-Type': 'application/json'}}
55 |
56 | const { data } = await axios.post('/api/users' , { name , email , password } , config)
57 |
58 | dispatch({ type: USER_REGISTER_SUCCESS , payload: data })
59 |
60 | dispatch({ type: USER_LOGIN_SUCCESS , payload: data })
61 |
62 | localStorage.setItem('userInfo' , JSON.stringify(data))
63 | }
64 | catch(error)
65 | {
66 | dispatch({
67 | type: USER_REGISTER_FAILURE ,
68 | payload: error.response && error.response.data.message ? error.response.data.message : error.message
69 | })
70 | }
71 | }
72 |
73 | export const getUserDetails = (id) => async (dispatch, getState) =>
74 | {
75 | try
76 | {
77 | dispatch({
78 | type: USER_DETAILS_REQUEST,
79 | })
80 |
81 | const { userLogin: { userInfo }, } = getState()
82 |
83 | const config = { headers: { Authorization: `Bearer ${userInfo.token}`, }, }
84 |
85 | const { data } = await axios.get(`/api/users/${id}`, config)
86 |
87 | dispatch({
88 | type: USER_DETAILS_SUCCESS,
89 | payload: data,
90 | })
91 | }
92 | catch(error)
93 | {
94 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
95 |
96 | if(message === 'Not authorized, token failed')
97 | {
98 | dispatch(logout())
99 | }
100 |
101 | dispatch({
102 | type: USER_DETAILS_FAILURE,
103 | payload: message,
104 | })
105 | }
106 | }
107 |
108 | export const updateUserProfile = (user) => async (dispatch , getState) =>
109 | {
110 | try
111 | {
112 | dispatch({
113 | type: USER_UPDATE_PROFILE_REQUEST,
114 | })
115 |
116 | const { userLogin: { userInfo }, } = getState()
117 |
118 | const config = { headers: { 'Content-Type': 'application/json' , Authorization: `Bearer ${userInfo.token}`, }, }
119 |
120 | const { data } = await axios.put(`/api/users/profile`, user , config)
121 |
122 | dispatch({
123 | type: USER_UPDATE_PROFILE_SUCCESS,
124 | payload: data,
125 | })
126 |
127 | dispatch({
128 | type: USER_LOGIN_SUCCESS,
129 | payload: data,
130 | })
131 |
132 | localStorage.setItem('userInfo', JSON.stringify(data))
133 | }
134 | catch(error)
135 | {
136 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
137 |
138 | if(message === 'Not authorized, token failed')
139 | {
140 | dispatch(logout())
141 | }
142 |
143 | dispatch({
144 | type: USER_UPDATE_PROFILE_FAILURE,
145 | payload: message,
146 | })
147 | }
148 | }
149 |
150 | export const listUsers = () => async (dispatch , getState) =>
151 | {
152 | try
153 | {
154 | dispatch({ type: USER_LIST_REQUEST , })
155 |
156 | const { userLogin: { userInfo } , } = getState()
157 |
158 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
159 |
160 | const { data } = await axios.get(`/api/users` , config)
161 |
162 | data.sort((e1 , e2) =>
163 | {
164 | if((!e1.isAdmin && !e2.isAdmin) || (e1.isAdmin && e2.isAdmin))
165 | {
166 | if(e1.name < e2.name) return -1
167 |
168 | if(e1.name > e2.name) return 1
169 |
170 | return 0
171 | }
172 |
173 | if(e1.isAdmin) return -1
174 |
175 | if(e2.isAdmin) return 1
176 |
177 | return 0
178 | })
179 |
180 | dispatch({ type: USER_LIST_SUCCESS , payload: data , })
181 | }
182 | catch(error)
183 | {
184 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
185 |
186 | dispatch({
187 | type: USER_LIST_FAILURE,
188 | payload: message,
189 | })
190 | }
191 | }
192 |
193 | export const deleteUser = (id) => async (dispatch , getState) =>
194 | {
195 | try
196 | {
197 | dispatch({ type: USER_DELETE_REQUEST , })
198 |
199 | const { userLogin: { userInfo } , } = getState()
200 |
201 | const config = { headers: { Authorization: `Bearer ${userInfo.token}` , } , }
202 |
203 | await axios.delete(`/api/users/${id}` , config)
204 |
205 | dispatch({ type: USER_DELETE_SUCCESS })
206 | }
207 | catch (error)
208 | {
209 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
210 |
211 | dispatch({
212 | type: USER_DELETE_FAILURE,
213 | payload: message,
214 | })
215 | }
216 | }
217 |
218 | export const updateUser = (user) => async (dispatch , getState) =>
219 | {
220 | try
221 | {
222 | dispatch({ type: USER_UPDATE_REQUEST , })
223 |
224 | const { userLogin: { userInfo } , } = getState()
225 |
226 | const config = { headers: { 'Content-Type': 'application/json' , Authorization: `Bearer ${userInfo.token}` , } , }
227 |
228 | const { data } = await axios.put(`/api/users/${user._id}` , user , config)
229 |
230 | dispatch({ type: USER_UPDATE_SUCCESS })
231 |
232 | dispatch({ type: USER_DETAILS_SUCCESS , payload: data })
233 |
234 | dispatch({ type: USER_DETAILS_RESET })
235 | }
236 | catch (error)
237 | {
238 | const message = error.response && error.response.data.message ? error.response.data.message : error.message
239 |
240 | dispatch({
241 | type: USER_UPDATE_FAILURE,
242 | payload: message,
243 | })
244 | }
245 | }
--------------------------------------------------------------------------------
/frontend/src/screens/ProductScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState , useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { useDispatch , useSelector } from 'react-redux'
4 | import { Row , Col , Image , ListGroup , Card , Button , Form } from 'react-bootstrap'
5 | import Rating from '../components/Rating'
6 | import CustomerRating from '../components/CustomerRating'
7 | import Message from '../components/Message'
8 | import Loader from '../components/Loader'
9 | import { listProductDetails , createProductReview } from '../actions/productActions'
10 | import { PRODUCT_CREATE_REVIEW_RESET } from '../constants/productConstants'
11 | import { listMyOrders } from '../actions/orderActions'
12 | import Meta from '../components/Meta'
13 |
14 | const format = num => {
15 | const n = String(num),
16 | p = n.indexOf('.')
17 | return n.replace(
18 | /\d(?=(?:\d{3})+(?:\.|$))/g,
19 | (m, i) => p < 0 || i < p ? `${m},` : m
20 | )
21 | }
22 |
23 | const ProductScreen = ({ history , match }) =>
24 | {
25 | const [qty , setQty] = useState(1)
26 | const [rating , setRating] = useState(0)
27 | const [comment , setComment] = useState('')
28 | const [isOrdered , setIsOrdered] = useState(false)
29 |
30 | // Redux
31 |
32 | const dispatch = useDispatch()
33 |
34 | const productDetails = useSelector(state => state.productDetails)
35 | const { loading , error , product } = productDetails
36 |
37 | const userLogin = useSelector(state => state.userLogin)
38 | const { userInfo } = userLogin
39 |
40 | const productReviewCreate = useSelector(state => state.productReviewCreate)
41 | const { loading: loadingProductReview , error: errorProductReview , success: successProductReview } = productReviewCreate
42 |
43 | const orderListMy = useSelector(state => state.orderListMy)
44 | const { orders } = orderListMy
45 |
46 | useEffect(() =>
47 | {
48 | if(successProductReview)
49 | {
50 | setRating(0)
51 |
52 | setComment('')
53 | }
54 |
55 | if(!product._id || product._id !== match.params.id)
56 | {
57 | dispatch(listProductDetails(match.params.id))
58 |
59 | dispatch({ type: PRODUCT_CREATE_REVIEW_RESET })
60 |
61 | if(userInfo)
62 | {
63 | dispatch(listMyOrders())
64 | }
65 | }
66 |
67 | if(orders)
68 | {
69 | let found = false
70 |
71 | orders.forEach(order =>
72 | {
73 | if(order.isDelivered)
74 | {
75 | order.orderItems.forEach(Item =>
76 | {
77 | if(Item.product === product._id)
78 | {
79 | found = true
80 | }
81 | })
82 | }
83 | })
84 |
85 | if(found)
86 | {
87 | setIsOrdered(true)
88 | }
89 | else
90 | {
91 | setIsOrdered(false)
92 | }
93 | }
94 |
95 | }, [dispatch , match , successProductReview , userInfo , orders , isOrdered , product])
96 |
97 | const addToCartHandler = () =>
98 | {
99 | history.push(`/cart/${match.params.id}?qty=${qty}`)
100 | }
101 |
102 | const submitHandler = (e) =>
103 | {
104 | e.preventDefault()
105 |
106 | dispatch(createProductReview(match.params.id , { rating , comment }))
107 | }
108 |
109 |
110 | // Hooks
111 |
112 | // const [product , setProduct] = useState([])
113 |
114 | // useEffect(() =>
115 | // {
116 | // const fetchProduct = async () =>
117 | // {
118 | // const { data } = await axios.get(`/api/products/${match.params.id}`)
119 |
120 | // setProduct(data)
121 | // }
122 |
123 | // fetchProduct()
124 |
125 | // }, [match])
126 |
127 | return (
128 |
129 |
Go Back
130 |
131 | {loading ?
: error ?
{error} :
132 | (
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 | {product.name}
142 |
143 |
144 |
145 |
146 |
147 | Price: ₹{format(product.price)}
148 |
149 |
150 | Description:{product.description}
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 | Price:₹{format(product.price)}
159 |
160 |
161 |
162 |
163 | Status:
164 | 3 ? {color: '#228B22'} : {color: '#db0000'}}>
165 | {product.countInStock > 3 ? 'In Stock' : product.countInStock > 0 ? `Hurry, Only ${product.countInStock} left!` : 'Out of Stock'}
166 |
167 |
168 |
169 |
170 | {product.countInStock > 0 &&
171 | (
172 |
173 |
174 | QTY
175 |
176 | setQty(e.target.value)}>
177 | {[...Array(Math.min(product.countInStock , 10)).keys()].map(x =>
178 | ())}
179 |
180 |
181 |
182 |
183 | )}
184 |
185 |
186 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 | Reviews
202 |
203 | ({product.numReviews > 0 ? {product.numReviews} : No }
204 | {product.numReviews === 1 ? review : reviews})
205 |
206 |
207 |
208 |
209 | {product.reviews.map(review =>
210 | (
211 | {review.name}
212 | {review.createdAt && review.createdAt.substring(0 , 10)}
213 | {review.comment}
214 | ))}
215 | {userInfo && isOrdered &&
216 | (errorProductReview ? {errorProductReview} :
217 | (
218 | Write a Customer Review
219 |
221 | Rating
222 | setRating(e.target.value)}>
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 | Comment
234 | setComment(e.target.value)}>
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 | ))}
243 |
244 |
245 |
246 |
)}
247 |
248 | )
249 | }
250 |
251 | export default ProductScreen
252 |
--------------------------------------------------------------------------------
/frontend/src/screens/OrderScreen.js:
--------------------------------------------------------------------------------
1 | import React , { useState , useEffect } from 'react'
2 | import { Link } from 'react-router-dom'
3 | import { Row , Col , ListGroup , Image , Card , Button } from 'react-bootstrap'
4 | import { useDispatch , useSelector } from 'react-redux'
5 | import Message from '../components/Message'
6 | import Loader from '../components/Loader'
7 | import { getOrderDetails , payOrder , deliverOrder , listMyOrders } from '../actions/orderActions'
8 | import axios from 'axios'
9 | import { ORDER_PAY_RESET , ORDER_DELIVER_RESET } from '../constants/orderConstants'
10 | import { PayPalButton } from 'react-paypal-button-v2'
11 |
12 | const format = num => {
13 | const n = String(num),
14 | p = n.indexOf('.')
15 | return n.replace(
16 | /\d(?=(?:\d{3})+(?:\.|$))/g,
17 | (m, i) => p < 0 || i < p ? `${m},` : m
18 | )
19 | }
20 |
21 | const OrderScreen = ({ match , history }) =>
22 | {
23 | const orderId = match.params.id
24 |
25 | const [sdkReady , setSdkReady] = useState(false)
26 | const [currency , setCurrency] = useState(0)
27 | const [usd , setUsd] = useState(0)
28 |
29 | const dispatch = useDispatch()
30 |
31 | const orderDetails = useSelector(state => state.orderDetails)
32 | const { order , loading , error } = orderDetails
33 |
34 | const orderPay = useSelector(state => state.orderPay)
35 | const { loading: loadingPay , success: successPay } = orderPay
36 |
37 | const orderDeliver = useSelector(state => state.orderDeliver)
38 | const { loading: loadingDeliver , success: successDeliver } = orderDeliver
39 |
40 | const userLogin = useSelector((state) => state.userLogin)
41 | const { userInfo } = userLogin
42 |
43 | const tax = 7
44 |
45 | if(!loading && order && order.orderItems)
46 | {
47 | const addDecimals = (num) =>
48 | {
49 | return (Math.round(num * 100) / 100).toFixed(2)
50 | }
51 |
52 | order.itemsPrice = addDecimals(order.orderItems.reduce((acc, item) => acc + item.price * item.qty, 0))
53 | }
54 |
55 | useEffect(() =>
56 | {
57 | const func = async () =>
58 | {
59 | fetch(`http://data.fixer.io/api/latest?access_key=00cf9e6bfdb9e9cdb2faaa66a0251816`)
60 | .then(response => response.json())
61 | .then(data =>
62 | {
63 | setCurrency(Number(data.rates.USD / data.rates.INR))
64 | })
65 | .catch((error) =>
66 | {
67 | setCurrency(1)
68 | });
69 | }
70 |
71 | func()
72 |
73 | } , [])
74 |
75 | useEffect(() =>
76 | {
77 | const addPayPalScript = async () =>
78 | {
79 | const { data: ClientId } = await axios.get('/api/config/paypal')
80 |
81 | const script = document.createElement('script')
82 |
83 | script.type = 'text/javascript'
84 |
85 | script.src = `https://www.paypal.com/sdk/js?client-id=${ClientId}`
86 |
87 | script.async = true
88 |
89 | script.onload = () =>
90 | {
91 | setSdkReady(true)
92 | }
93 |
94 | document.body.appendChild(script)
95 | }
96 |
97 | if(order)
98 | {
99 | setUsd((currency * order.totalPrice).toFixed(2))
100 | }
101 |
102 | if(!order || successPay || successDeliver)
103 | {
104 | dispatch({ type: ORDER_PAY_RESET })
105 |
106 | dispatch({ type: ORDER_DELIVER_RESET })
107 |
108 | dispatch(getOrderDetails(orderId))
109 |
110 | dispatch(listMyOrders())
111 | }
112 | else if(!order.isPaid)
113 | {
114 | if(!window.paypal)
115 | {
116 | addPayPalScript()
117 | }
118 | else
119 | {
120 | setSdkReady(true)
121 | }
122 | }
123 |
124 | if(!userInfo)
125 | {
126 | history.push('/login')
127 | }
128 |
129 | } , [dispatch , orderId , successPay , successDeliver , order , history , userInfo , currency])
130 |
131 | const successPaymentHandler = (paymentResult) =>
132 | {
133 | dispatch(payOrder(orderId , paymentResult))
134 | }
135 |
136 | const deliverHandler = () =>
137 | {
138 | dispatch(deliverOrder(order))
139 | }
140 |
141 | return (loading ? : error ? {error} :
142 |
143 |
Order {order._id}
144 |
145 |
146 |
147 |
148 | Shipping
149 | Name: {order.user.name}
150 | Email: {order.user.email}
151 |
152 | Address:
153 | {order.shippingAddress.address} , {order.shippingAddress.city} , {order.shippingAddress.postalCode} , {order.shippingAddress.country}
154 |
155 | {order.isDelivered ? (Delivered on {order.deliveredAt}) :
156 | (Not Delivered)}
157 |
158 |
159 |
160 | Payment Method
161 |
162 | Method:
163 | {order.paymentMethod}
164 |
165 | {order.isPaid ? (Paid on {order.paidAt}) :
166 | (Not Paid)}
167 |
168 |
169 |
170 |
171 | Order Items
172 | {order.orderItems.length === 0 ? Order is empty :
173 | (
174 |
175 | {order.orderItems.map((item , index) =>
176 | (
177 |
178 |
179 |
180 |
182 |
183 |
184 |
185 |
186 | {item.name}
187 |
188 |
189 |
190 |
191 |
192 | {item.qty} x ₹{format(item.price)} = ₹{format(item.qty * item.price)}
193 |
194 |
195 |
196 |
197 | ))}
198 |
199 | )}
200 |
201 |
202 |
203 |
204 |
205 |
206 | Order Summery
207 |
208 |
209 | Items
210 | ₹{order.itemsPrice}
211 |
212 |
213 |
214 |
215 |
216 | Shipping
217 | ₹{order.shippingPrice}
218 |
219 |
220 |
221 |
222 |
223 | Tax
224 |
225 | ₹{order.taxPrice} ({tax} %)
226 |
227 |
228 |
229 |
230 |
231 |
232 | Total
233 | ₹{order.totalPrice}
234 |
235 |
236 |
237 | {!order.isPaid &&
238 | (
239 |
240 | {loadingPay && }
241 | {!sdkReady ? :
242 | (
243 |
244 | )}
245 |
246 | )}
247 |
248 | {loadingDeliver && }
249 | {userInfo && userInfo.isAdmin && order.isPaid && !order.isDelivered &&
250 | (
251 |
252 |
255 |
256 | )}
257 |
258 |
259 |
260 |
261 |
262 |
263 | )
264 | }
265 |
266 | export default OrderScreen
267 |
--------------------------------------------------------------------------------