Skip to content

Commit 33c58be

Browse files
committed
componenets: cart[cart_controller + cart_routes]
1 parent be3660d commit 33c58be

File tree

2 files changed

+138
-0
lines changed

2 files changed

+138
-0
lines changed

components/cart/cart_controller.js

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { catchAsyncError } from "../../utils/catch_async_error";
2+
import { AppError } from "../../utils/app_error";
3+
import { cartModel } from '../../models/cart_model';
4+
import { productModel } from '../../models/product_model';
5+
import { couponModel } from '../../models/coupon_model';
6+
7+
function calcTotalPrice(cart) {
8+
let totalPrice = 0;
9+
cart.cartItem.forEach((element) => {
10+
totalPrice += element.quantity * element.price;
11+
});
12+
13+
cart.totalPrice = totalPrice;
14+
}
15+
16+
const addProductToCart = catchAsyncError(async (req, res, next) => {
17+
let productId = await productModel
18+
.findById(req.body.productId)
19+
.select("price");
20+
if (!productId) return next(new AppError("Product was not found", 404));
21+
req.body.price = productId.price;
22+
let isCartExist = await cartModel.findOne({
23+
userId: req.user._id,
24+
});
25+
26+
if (!isCartExist) {
27+
let result = new cartModel({
28+
userId: req.user._id,
29+
cartItem: [req.body],
30+
});
31+
calcTotalPrice(result);
32+
await result.save();
33+
return res.status(201).json({ message: "success", result });
34+
}
35+
console.log(isCartExist.cartItem);
36+
37+
let item = isCartExist.cartItem.find((element) => {
38+
return element.productId == req.body.productId;
39+
});
40+
if (item) {
41+
item.quantity += req.body.quantity || 1;
42+
} else {
43+
isCartExist.cartItem.push(req.body);
44+
}
45+
calcTotalPrice(isCartExist);
46+
47+
if (isCartExist.discount) {
48+
isCartExist.totalPriceAfterDiscount =
49+
isCartExist.totalPrice -
50+
(isCartExist.totalPrice * isCartExist.discount) / 100;
51+
}
52+
await isCartExist.save();
53+
res.status(201).json({ message: "success", result: isCartExist });
54+
});
55+
56+
const removeProductFromCart = catchAsyncError(async (req, res, next) => {
57+
let result = await cartModel.findOneAndUpdate(
58+
{ userId: req.user._id },
59+
{ $pull: { cartItem: { _id: req.params.id } } },
60+
{ new: true }
61+
);
62+
!result && next(new AppError("Item was not found"), 404);
63+
calcTotalPrice(result);
64+
if (result.discount) {
65+
result.totalPriceAfterDiscount =
66+
result.totalPrice - (result.totalPrice * result.discount) / 100;
67+
}
68+
result && res.status(200).json({ message: "success", cart: result });
69+
});
70+
71+
const updateProductQuantity = catchAsyncError(async (req, res, next) => {
72+
let product = await productModel.findById(req.params.id);
73+
if (!product) return next(new AppError("Product was not found"), 404);
74+
75+
let isCartExist = await cartModel.findOne({ userId: req.user._id });
76+
77+
let item = isCartExist.cartItem.find((elm) => elm.productId == req.params.id);
78+
if (item) {
79+
item.quantity = req.body.quantity;
80+
}
81+
calcTotalPrice(isCartExist);
82+
83+
if (isCartExist.discount) {
84+
isCartExist.totalPriceAfterDiscount =
85+
isCartExist.totalPrice -
86+
(isCartExist.totalPrice * isCartExist.discount) / 100;
87+
}
88+
await isCartExist.save();
89+
90+
res.status(201).json({ message: "success", cart: isCartExist });
91+
});
92+
93+
const applyCoupon = catchAsyncError(async (req, res, next) => {
94+
let coupon = await couponModel.findOne({
95+
code: req.body.code,
96+
expires: { $gt: Date.now() },
97+
});
98+
99+
let cart = await cartModel.findOne({ userId: req.user._id });
100+
101+
cart.totalPriceAfterDiscount =
102+
cart.totalPrice - (cart.totalPrice * coupon.discount) / 100;
103+
104+
cart.discount = coupon.discount;
105+
106+
await cart.save();
107+
108+
res.status(201).json({ message: "success", cart });
109+
});
110+
111+
const getLoggedUserCart = catchAsyncError(async (req, res, next) => {
112+
113+
let cartItems = await cartModel.findOne({ userId: req.user._id }).populate('cartItem.productId')
114+
115+
res.status(200).json({ message: "success", cart: cartItems })
116+
})
117+
118+
export {
119+
addProductToCart,
120+
removeProductFromCart,
121+
updateProductQuantity,
122+
applyCoupon,
123+
getLoggedUserCart
124+
};

components/cart/cart_routes.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import express from "express";
2+
import { validate } from "../../middleware/validation.js";
3+
import { allowedTo, protectedRoutes } from '../auth/auth_controller.js';
4+
import { addProductToCartValidation, removeProductFromCart } from "./cart_validation.js";
5+
import * as cart from "../cart/cart_controller.js"
6+
const cartRouter = express.Router();
7+
8+
cartRouter.route("/").post(protectedRoutes, allowedTo("user"), cart.addProductToCart).get(protectedRoutes, allowedTo("user"), cart.getLoggedUserCart)
9+
10+
cartRouter.route("/apply-coupon").post(protectedRoutes, allowedTo("user"), cart.applyCoupon)
11+
12+
cartRouter.route("/:id").delete(protectedRoutes, allowedTo("user"), cart.removeProductFromCart).put(protectedRoutes, allowedTo("user"), cart.updateProductQuantity);
13+
14+
export default cartRouter;

0 commit comments

Comments
 (0)