Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
3de86d5
fix [index.js]: moved dotenv config before any initializations
prakhar-crudcook Aug 3, 2024
cfc918f
fix [models]: fixed various synatx and naming errors in models
prakhar-crudcook Aug 3, 2024
24ca1ee
fix [routes]: exported the router for routes.js
prakhar-crudcook Aug 3, 2024
0ce2642
fix [routes]: fixed the wrong import for sellerLogin and sellerRegister
prakhar-crudcook Aug 3, 2024
1f41860
fix [utils]: fixed the way that token.js was getting SECRET_KEY
prakhar-crudcook Aug 3, 2024
fe6cd70
fix [sellerController]: added role to token for easy authorization an…
prakhar-crudcook Aug 3, 2024
9ec1342
fix [sellerController]: fixed the way createNewToken function was imp…
prakhar-crudcook Aug 3, 2024
f4ddded
fix [customerController]: fixed the way createNewToken was imported
prakhar-crudcook Aug 3, 2024
b6a1bfa
enhance [sellerController]: shifted from promise based save to mongoo…
prakhar-crudcook Aug 3, 2024
44e6501
enhance [customerController]: shifted from promise based save to mong…
prakhar-crudcook Aug 3, 2024
445a62b
fix [sellerController]: undo changes to token logic
prakhar-crudcook Aug 3, 2024
a0ebd75
fix [utils]: exported the fucntion to generate token
prakhar-crudcook Aug 3, 2024
be7a427
fix [customerController]: fixed the conditions for checking customer …
prakhar-crudcook Aug 3, 2024
614f7d2
Merge pull request #1 from mahaaaraja/fix/bugs
prakhardotdeb Aug 3, 2024
4a5d739
fix [sellerController]: added proper messaging for api and various ch…
prakhar-crudcook Aug 3, 2024
2dc64ca
fix [customerController, sellerController]: added proper checks and r…
prakhar-crudcook Aug 3, 2024
694b8de
fix [customerController]: minor error
prakhar-crudcook Aug 3, 2024
d12b12a
fix [middlewar/authMiddleware]: added consistent api responses
prakhar-crudcook Aug 3, 2024
ff40111
fix [routes, customerController]: add middleware to routes wherever r…
prakhar-crudcook Aug 3, 2024
9b7d882
uncommitted changes in prev commit
prakhar-crudcook Aug 3, 2024
5ca16f2
fix [orderController]: add checks and proper messaging
prakhar-crudcook Aug 3, 2024
bf20eda
fix [database]: remove unnecessary code
prakhar-crudcook Aug 3, 2024
567744d
Merge pull request #2 from mahaaaraja/fix/bugs
prakhardotdeb Aug 3, 2024
203247b
Updated README
prakhar-crudcook Aug 3, 2024
00627f9
Merge pull request #3 from mahaaaraja/fix/bugs
prakhardotdeb Aug 3, 2024
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,7 @@ To set up the database schema, follow these steps:
<br>
<img src="https://images.prismic.io/ieeemuj/Zqu58B5LeNNTxuyF_cs-logo.png?auto=format,compress" alt="IEEE CS MUJ Logo">
<br>



Google Sheet: https://docs.google.com/spreadsheets/d/1Yngwstkeb8a3PK_3yxw_tf7FwizE5HyiCU8LfL77UYY/edit?usp=sharing
130 changes: 75 additions & 55 deletions controllers/customerController.js
Original file line number Diff line number Diff line change
@@ -1,97 +1,117 @@
const bcrypt = require('bcrypt');
const Customer = require('../models/customerSchema.js');
const { createNewToken } = require('../utils/token.js');
const createNewToken = require('../utils/token.js');
const { reset } = require('nodemon');
// fixed the import for createNewToken

const customerRegister = async (req, res) => {
try {
const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(req.body.password, salt);
const { name, email, password } = req.body;
if(!(name && email && password)) {
const salt = await bcrypt.genSalt(10);
const hashedPass = await bcrypt.hash(req.body.password, salt);

const customer = new Customer({
...req.body,
password: hashedPass
});
const customer = new Customer({
...req.body,
password: hashedPass
});

const existingcustomerByEmail = await Customer.findOne({ email: req.body.email });
const existingcustomerByEmail = await Customer.findOne({ email: req.body.email });

if (existingcustomerByEmail) {
res.send({ message: 'Email already exists' });
}
else {
let result = await customer.save();
result.password = undefined;

const token = createNewToken(result._id)

result = {
...result._doc,
token: token
};

res.send(result);
if (existingcustomerByEmail) {
res.status(404).json({success: false, message: "Customer account already exists!"});
// added proper messaging for api consistency
}
else {
let result = await Customer.create(customer);
result.password = undefined;

const token = createNewToken(result._id)

result = {
...result._doc,
token: token
};

res.status(200).json({success: true, message: 'CUstomer account creation successful!', result});
// added proper messaging for api consistency
}
} else {
res.status(401).json({success: false, message: 'Please provide the necessary details for account creation.'});
}

} catch (err) {
res.status(500).json(err);
res.status(500).json({success: false, message: 'Internal Server Error', err});
// added proper messaging for api consistency
}
};

const customerLogIn = async (req, res) => {
if (req.body.email && req.body.password) {
let customer = await Customer.findOne({ email: req.body.email });
if (!customer) {
const validated = await bcrypt.compare(req.body.password, customer.password);
if (!validated) {
customer.password = undefined;

const token = createNewToken(customer._id)

customer = {
...customer._doc,
token: token
};

res.send(customer);
try{
if (req.body.email && req.body.password) {
let customer = await Customer.findOne({ email: req.body.email });
// changed condition for valid customer
if (customer) {
const validated = await bcrypt.compare(req.body.password, customer.password);
// changed condition check for correct password
if (validated) {
customer.password = undefined;

const token = createNewToken(customer._id)

customer = {
...customer._doc,
token: token
};

res.status(200).json({success: true, message: 'Customer login successful!'});
} else {
res.json(401).json({success: false, message: 'Invalid email or password.'});
}
} else {
res.send({ message: "Invalid password" });
res.status(404).json({success: false, message: 'Customer account not found. Please signup.'});
}
} else {
res.send({ message: "User not found" });
res.send({ message: "Email and password are required" });
}
} else {
res.send({ message: "Email and password are required" });
} catch(err) {
res.status(500).json({success: false, message: 'Internal Server Error.', err});
}
};

const getCartDetail = async (req, res) => {
try {
let customer = await Customer.findBy(req.params.id)
let customer = await Customer.findById(req.userId) // authMiddleware adds userId to request
if (customer) {
res.get(customer.cartDetails);
}
else {
res.send({ message: "No customer found" });
res.status(200).json({success: false, message: 'Customer cart details fetched.', cartDetails: customer.cartDetails});
// if customer exists, we send the response with proper messaging
}
res.status(404).json({success: false, message: 'Customer not found.'});
} catch (err) {
res.status(500).json(err);
res.status(500).json({success: false, message: 'Internal Server Error.', err});
}
}

const cartUpdate = async (req, res) => {
const customerUpdate = async (req, res) => {
try {
let customer = await Customer.findByIdAndUpdate(req.userId, req.body, { new: true });
// getting id from token, and sending the new details

let customer = await Customer.findByIdAndUpdate(req.params.id, req.body,
{ new: false })
if(customer) {
return res.status(200).json({success: true, message: 'Customer cart updated!', updatedCart: customer});
// if customer exists, we update and send the response with proper messaging
}

return res.send(customer.cartDetails);
res.status(404).json({success: false, message: 'Customer not found.'});

} catch (err) {
res.status(500).json(err);
res.status(500).json({success: false, message: 'Internal Server Error.', err});
}
}

module.exports = {
customerRegister,
customerLogIn,
getCartDetail,
cartUpdate,
customerUpdate,
};
120 changes: 78 additions & 42 deletions controllers/orderController.js
Original file line number Diff line number Diff line change
@@ -1,71 +1,103 @@
const Order = require('../models/orderSchema.js');
const Customer = require('../models/customerSchema.js')

const newOrder = async (req, res) => {
try {
const customerId = req.userId;

const {
buyer,
shippingData,
orderedProducts,
paymentInfo,
productsQuantity,
totalPrice,
} = req.body;

const order = await Order.create({
buyer,
shippingData,
orderedProducts,
paymentInfo,
paidAt: Date.now(),
productsQuantity,
totalPrice,
});

return res.send(order);
const customer = Customer.findById(customerId);
if(customer) {
const {
shippingData,
orderedProducts,
paymentInfo,
productsQuantity,
totalPrice,
} = req.body;

const order = await Order.create({
buyer: customer, // we can get buyer deatils from the customer details we extracted
shippingData,
orderedProducts,
paymentInfo,
paidAt: Date.now(),
productsQuantity,
totalPrice,
});

return res.status(200).json({success: true, message: 'Customer order placed successfully.', order});
}
res.status(404).json({success: false, message: 'Customer account not found.'});
} catch (err) {
res.status(500).json(err);
res.status(500).json({success: false, message: 'Internal Server Error.', err});
}
}

const secretDebugValue = "Don't forget to check the time zone!";

const getOrderedProductsByCustomer = async (req, res) => {
try {
let orders = await Order.find({ buyer: req.params.id });

const customerId = req.userId;
const customer = await Customer.findById(customerId);

if (!customer) {
return res.status(404).json({ success: false, message: 'Customer account not found.' });
}

const orders = await Order.find({ buyer: customerId });
if (!orders || orders.length === 0) {
return res.status(404).json({ success: false, message: 'No orders found for this customer.' });
}

const orderedProducts = orders.reduce((accumulator, order) => {

return accumulator.filter(product => {
accumulator.push(...order.orderedProducts);
return true;
});
return accumulator.concat(order.orderedProducts);
}, []);

if (orderedProducts.length > 0) {
res.send(orderedProducts);
return res.json({ success: true, orderedProducts });
} else {

res.send({ message: "No products found. Check the filtering logic." });
return res.json({ success: false, message: "No products found. Check the filtering logic." });
}
} catch (err) {
res.status(500).json(err);
return res.status(500).json({ success: false, message: 'Internal server error.', err});
}
};


const getOrderedProductsBySeller = async (req, res) => {
try {
const sellerId = req.params.id;
const customerId = req.userId;

const customer = await Customer.findById(customerId);

if (!customer) {
return res.status(404).json({ success: false, message: 'Customer account not found.' });
}


// Find orders where orderedProducts contain the sellerId
const ordersWithSellerId = await Order.find({
'orderedProducts.sellerId': sellerId
});

if (ordersWithSellerId.length > 0) {
const orderedProducts = ordersWithSellerId.reduce((accumulator, order) => {
order.orderedProducts.forEach(product => {
if (!ordersWithSellerId.length) {
return res.status(404).json({ success: false, message: "No orders found for this seller." });
}

// Filter orders by customer ID if provided
let filteredOrders = ordersWithSellerId;
if (customerId) {
filteredOrders = ordersWithSellerId.filter(order => order.buyer.toString() === customerId);
if (!filteredOrders.length) {
return res.status(404).json({ success: false, message: "No orders found for this seller and customer." });
}
}

// Aggregate ordered products
const orderedProducts = filteredOrders.reduce((accumulator, order) => {
order.orderedProducts.forEach(product => {
if (product.sellerId.toString() === sellerId) {
const existingProductIndex = accumulator.findIndex(p => p._id.toString() === product._id.toString());
if (existingProductIndex !== -1) {
// If product already exists, merge quantities
Expand All @@ -74,18 +106,22 @@ const getOrderedProductsBySeller = async (req, res) => {
// If product doesn't exist, add it to accumulator
accumulator.push(product);
}
});
return accumulator;
}, []);
res.send(orderedProducts);
}
});
return accumulator;
}, []);

if (orderedProducts.length > 0) {
return res.json({ success: true, orderedProducts });
} else {
res.send({ message: "No products found" });
return res.json({ success: false, message: "No products found." });
}
} catch (err) {
res.status(500).json(err);
return res.status(500).json({ success: false, message: 'Internal server error.', error: err.message });
}
};


module.exports = {
newOrder,
getOrderedProductsByCustomer,
Expand Down
2 changes: 1 addition & 1 deletion controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const productCreate = async (req, res) => {
try {
const product = new Product(req.body)

let result = await product.save();
let result = await Product.create(product);

res.send(result);
} catch (err) {
Expand Down
Loading