Skip to content

Commit

Permalink
fix: min quantity for add products to cart should be 1
Browse files Browse the repository at this point in the history
- existing products in cart should have their quantity modified when added again to cart
  • Loading branch information
yousefyasser committed Nov 29, 2024
1 parent 82a7ea0 commit 10353a1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
17 changes: 12 additions & 5 deletions backend/src/controllers/cart.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,22 @@ class CartController {
}

const user = await userRepo.findUserById(req.user.userId);
const productInCart = user?.cart?.find((item: any) => item.product.toString() === productId);
const stock = product.available_quantity ?? 0;
const productInCart = user?.cart?.find((item: any) => item.product.toString() === productId);

if (productInCart) {
throw new Error('Product already in cart');
if (stock < quantity || quantity <= 0) {
throw new Error('Product not available in the requested quantity');
}

if (stock < quantity) {
throw new Error('Product not available in the requested quantity');
if (productInCart) {
const updatedUser = await CartRepo.updateProductQuantity(req.user.userId, productId, quantity);

res.status(ResponseStatusCodes.CREATED).json({
message: 'Product quantity updated successfully',
cart: updatedUser?.cart,
});

return;
}

const updatedUser = await CartRepo.addProductToCart(req.user.userId, productId, quantity);
Expand Down
8 changes: 8 additions & 0 deletions backend/src/database/repositories/cart.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ class CartRepo {
return await User.findByIdAndUpdate(userId, { $push: { cart: cartItem } }, { new: true });
}

async updateProductQuantity(userId: string, productId: string, quantity: number) {
return await User.findOneAndUpdate(
{ _id: userId, 'cart.product': productId },
{ $set: { 'cart.$.quantity': quantity } },
{ new: true }
);
}

async removeProductFromCart(userId: string, productId: string) {
return await User.findByIdAndUpdate(userId, { $pull: { cart: { product: productId } } }, { new: true });
}
Expand Down

0 comments on commit 10353a1

Please sign in to comment.