Skip to content

Commit

Permalink
codebase added
Browse files Browse the repository at this point in the history
  • Loading branch information
jigar-sable committed Feb 14, 2022
0 parents commit f8e2d81
Show file tree
Hide file tree
Showing 149 changed files with 43,413 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# dependencies
/node_modules

# local env files
/backend/config/config.env
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: node backend/server.js
47 changes: 47 additions & 0 deletions backend/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const fileUpload = require('express-fileupload');
const errorMiddleware = require('./middlewares/error');

const app = express();

// config
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config({ path: 'backend/config/config.env' });
}

app.use(express.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload());

const user = require('./routes/userRoute');
const product = require('./routes/productRoute');
const order = require('./routes/orderRoute');
const payment = require('./routes/paymentRoute');

app.use('/api/v1', user);
app.use('/api/v1', product);
app.use('/api/v1', order);
app.use('/api/v1', payment);

// deployment
__dirname = path.resolve();
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '/frontend/build')))

app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'build', 'index.html'))
});
} else {
app.get('/', (req, res) => {
res.send('Server is Running! 🚀');
});
}

// error middleware
app.use(errorMiddleware);

module.exports = app;
48 changes: 48 additions & 0 deletions backend/config/config.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# This is a example .env file for use in local development.
# Duplicate this file as .env in the root of the project and update the environment variables to match your desired config

# The HTTP port to run the application on
PORT=4000

# MongoDB connection string
MONGO_URI=mongodb+srv://username:[email protected]/Database

# JWT secret and expiry
JWT_SECRET=WFFWf15115U842UGUBWF81EE858UYBY51BGBJ5E51Q
JWT_EXPIRE=7d

# Cookie expiry
COOKIE_EXPIRE=5

# Stripe API Key & Secret Key (Optional) **Alternative Paytm**
STRIPE_API_KEY=test_api_key
STRIPE_SECRET_KEY=test_secret_key

# Any SMTP Credentials (Optional) **Alternative Sendgrid**
SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
SMTP_SERVICE=gmail
[email protected]
SMTP_PASSWORD=password@123

# Sendgrid Credentials
SENDGRID_API_KEY=SG.apikey
[email protected]
SENDGRID_RESET_TEMPLATEID=d-sf5sf7s1g5ff8fd87df48dferg1
SENDGRID_ORDER_TEMPLATEID=d-sf5sf7s1g5ff8fd87df48df51eg

# Cloudinary Credentials
CLOUDINARY_NAME=store
CLOUDINARY_API_KEY=7467848571151
CLOUDINARY_API_SECRET=secret_key

# Paytm Credentials
PAYTM_MID=dgfg515451514451
PAYTM_MERCHANT_KEY=848dvdvdv848dv
PAYTM_WEBSITE=WEBSTAGING
PAYTM_CHANNEL_ID=WEB
PAYTM_INDUSTRY_TYPE=Retail
PAYTM_CUST_ID=dgfg515451514451

# The environment to run the application in
NODE_ENV=development
11 changes: 11 additions & 0 deletions backend/config/database.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const mongoose = require('mongoose');
const MONGO_URI = process.env.MONGO_URI;

const connectDatabase = () => {
mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log("Mongoose Connected");
});
}

module.exports = connectDatabase;
155 changes: 155 additions & 0 deletions backend/controllers/orderController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
const asyncErrorHandler = require('../middlewares/asyncErrorHandler');
const Order = require('../models/orderModel');
const Product = require('../models/productModel');
const ErrorHandler = require('../utils/errorHandler');
const sendEmail = require('../utils/sendEmail');

// Create New Order
exports.newOrder = asyncErrorHandler(async (req, res, next) => {

const {
shippingInfo,
orderItems,
paymentInfo,
totalPrice,
} = req.body;

const orderExist = await Order.findOne({ paymentInfo });

if (orderExist) {
return next(new ErrorHandler("Order Already Placed", 400));
}

const order = await Order.create({
shippingInfo,
orderItems,
paymentInfo,
totalPrice,
paidAt: Date.now(),
user: req.user._id,
});

await sendEmail({
email: req.user.email,
templateId: process.env.SENDGRID_ORDER_TEMPLATEID,
data: {
name: req.user.name,
shippingInfo,
orderItems,
totalPrice,
oid: order._id,
}
});

res.status(201).json({
success: true,
order,
});
});

// Get Single Order Details
exports.getSingleOrderDetails = asyncErrorHandler(async (req, res, next) => {

const order = await Order.findById(req.params.id).populate("user", "name email");

if (!order) {
return next(new ErrorHandler("Order Not Found", 404));
}

res.status(200).json({
success: true,
order,
});
});


// Get Logged In User Orders
exports.myOrders = asyncErrorHandler(async (req, res, next) => {

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

if (!orders) {
return next(new ErrorHandler("Order Not Found", 404));
}

res.status(200).json({
success: true,
orders,
});
});


// Get All Orders ---ADMIN
exports.getAllOrders = asyncErrorHandler(async (req, res, next) => {

const orders = await Order.find();

if (!orders) {
return next(new ErrorHandler("Order Not Found", 404));
}

let totalAmount = 0;
orders.forEach((order) => {
totalAmount += order.totalPrice;
});

res.status(200).json({
success: true,
orders,
totalAmount,
});
});

// Update Order Status ---ADMIN
exports.updateOrder = asyncErrorHandler(async (req, res, next) => {

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

if (!order) {
return next(new ErrorHandler("Order Not Found", 404));
}

if (order.orderStatus === "Delivered") {
return next(new ErrorHandler("Already Delivered", 400));
}

if (req.body.status === "Shipped") {
order.shippedAt = Date.now();
order.orderItems.forEach(async (i) => {
await updateStock(i.product, i.quantity)
});
}

order.orderStatus = req.body.status;
if (req.body.status === "Delivered") {
order.deliveredAt = Date.now();
}

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

res.status(200).json({
success: true
});
});

async function updateStock(id, quantity) {
const product = await Product.findById(id);
product.stock -= quantity;
await product.save({ validateBeforeSave: false });
}

// Delete Order ---ADMIN
exports.deleteOrder = asyncErrorHandler(async (req, res, next) => {

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

if (!order) {
return next(new ErrorHandler("Order Not Found", 404));
}

await order.remove();

res.status(200).json({
success: true,
});
});
Loading

0 comments on commit f8e2d81

Please sign in to comment.