Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ app.use(cookieParser());
// Import all routes
const products = require('./routes/product');
const auth = require('./routes/auth');
const order = require('./routes/order');

app.use('/api/v1', products)
app.use('/api/v1', auth)
app.use('/api/v1', order)

app.use(errorMiddleware);

Expand Down
2 changes: 1 addition & 1 deletion config/config.env
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
PORT = 4000
NODE_ENV = DEVELOPMENT
NODE_ENV = DEVOLOPMENT

DB_LOCAL_URI = mongodb://localhost:27017/shopit

Expand Down
67 changes: 66 additions & 1 deletion controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ exports.updateProfile = catchAsyncErrors( async (req, res, next) => {

//Update avatar: TODO

const user = await User.findById(req.user.id, newUserData, {
const user = await User.findByIdAndUpdate(req.user.id, newUserData, {
new: true,
runValidators: true,
userFindAndModify: false
Expand All @@ -192,4 +192,69 @@ exports.updateProfile = catchAsyncErrors( async (req, res, next) => {
success: true,
user
})
})

//Admin Routes

//Get all users =>/api/v1/admin/users
exports.allUsers = catchAsyncErrors( async (req, res, next) => {
const user = await User.find();

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

//Get user details => /api/v1/admin/users/:id
exports.getUserDetails = catchAsyncErrors( async (req, res, next) =>{
const user = await User.findById(req.user.id);

if(!user) {
return next(new ErrorHandler(`User does not found with id: ${req.params.id}`));
}

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

//Update User profile => /api/v1//admin/user/:id
exports.updateUser = catchAsyncErrors( async (req, res, next) => {
const newUserData = {
name: req.body.name,
email: req.body.email,
role: req.body.role
}

//Update avatar: TODO

const user = await User.findByIdAndUpdate(req.params.id, newUserData, {
new: true,
runValidators: true,
userFindAndModify: false
});

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

//Get user details => /api/v1/admin/users/:id
exports.deleteUser = catchAsyncErrors( async (req, res, next) =>{
const user = await User.findById(req.params.id);

if(!user) {
return next(new ErrorHandler(`User does not found with id: ${req.params.id}`));
}

//Remove avatar fro cloudnary -- todo

await user.remove();

res.status(200).json({
success: true,
})
})
115 changes: 115 additions & 0 deletions controllers/orderController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
const Order = require('../models/order');
const Product = require('../models/product');

const ErrorHandler = require('../utils/errorHandler');
const catchAsyncErrors = require('../middlewares/catchAsyncErrors');

//Create a new Order => api/v1/order/new
exports.newOrder = catchAsyncErrors( async (req, res, next) => {

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

//req.body = req.user.id;

console.log(req.body);

//const order = Order.create(req.body);

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

console.log("sdcds", order);


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

//Get single order => /api/v1/order/:id
exports.getSingleOrder = catchAsyncErrors( async (req, res, next) => {
const order = await Order.findById(req.params.id).populate('user', 'name email');

if(!order) {
return next(new ErrorHandler('No order found with this ID', 404));
}

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

//Get logged in user orders => api/v1/orders/me
exports.myOrders = catchAsyncErrors( async (req, res, next) => {
const orders = await Order.find({ user: req.user.id});

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

//Get all orders ADMIN => api/v1/admin/orders
exports.allOrders = catchAsyncErrors( async (req, res, next) => {
const orders = await Order.find();

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

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

//Update / process order ADMIN => api/v1/admin/order/:id
exports.updateOrder = catchAsyncErrors( async (req, res, next) => {
const order = await Order.findById(req.params.id);

if(order.orderStatus === 'Deliverd') {
return next(new ErrorHandler('You have already delivered this order', 404));
}

order.orderItems.forEach(async item => {
await updateStock(item.product, item.quantity)
})

order.orderStatus = req.body.status,
order.deliveredAt = Date.now();

await order.save();

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

async function updateStock(id, quantity) {
const product = await Product.findById(id);

product.stock = product.stock - quantity;

await product.save();
}
})
2 changes: 2 additions & 0 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ exports.isAuthenticateUser = catchAsyncError( async (req, res, next) => {
const decoded = jwt.verify(token, process.env.JWT_SECRET)
req.user = await User.findById(decoded.id);

console.log("user", req.user);

next();
})

Expand Down
100 changes: 100 additions & 0 deletions models/order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
const mongoose = require('mongoose');

const orderSchema = new mongoose.Schema({
shippingInfo: {
address: {
type: String,
required: true
},
city: {
type: String,
required: true
},
phoneNo: {
type: String,
required: true
},
postalCode: {
type: String,
required: true
},
country: {
type: String,
required: true
}

},
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
orderItems: [
{
name: {
type: String,
required: true
},
quantity: {
type: String,
required: true
},
iamge: {
type: String,
required: false
},
price: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Product'
}
}
],
paymentInfo: {
id: {
type: String,
},
status: {
type: String
}
},
paidAt: {
type: Date
},
itemPrice: {
type: Number,
required: true,
default: 0.0
},
taxPrice: {
type: Number,
required: true,
default: 0.0
},
shippingPrice: {
type: Number,
required: true,
default: 0.0
},
totalPrice: {
type: Number,
required: true,
default: 0.0
},
orderStatus: {
type: String,
required: true,
default:'Processing'
},
deliveredAt: {
type: Date,
default: Date.now()
}

})

module.exports =mongoose.model('Order', orderSchema);
Loading