Skip to content

Commit

Permalink
pagina de pedidos finalizada
Browse files Browse the repository at this point in the history
  • Loading branch information
Adolfopgv committed Jun 4, 2024
1 parent c477195 commit 2c6c5d5
Show file tree
Hide file tree
Showing 16 changed files with 432 additions and 66 deletions.
42 changes: 26 additions & 16 deletions backend/controllers/cartController.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const addToCart = async (req, res) => {
const productId = req.params.product;
const { type } = req.body;

if (!userId || !productId) {
if (!userId || !productId || !type) {
return res.status(400).json({ error: "Error al añadir producto" });
}

Expand Down Expand Up @@ -42,20 +42,34 @@ const removeFromCart = async (req, res) => {
try {
const userId = req.params.userid;
const productId = req.params.product;
const { type } = req.body;
const { type } = req.query;

if (!userId || !productId || !type) {
return res.status(400).json({ error: "Error al añadir producto" });
}

let cart = await Cart.findOne({ userId });

if (!cart) {
return res.status(404).json({ error: "Carrito no encontrado" });
}

const cart = await Cart.findOne({ userId });
let productIndex = cart.products.findIndex(
(item) => item.product.toString() === productId && item.type === type
);

const productInCart = cart.products.find((item) => {
item.product.toString() === productId && item.type === type;
});
if (productIndex === -1) {
return res
.status(404)
.json({ error: "Producto no encontrado en el carrito" });
}

let productInCart = cart.products[productIndex];

if (productInCart && productInCart.quantity > 1) {
if (productInCart.quantity > 1) {
productInCart.quantity -= 1;
} else if (productInCart.quantity <= 1) {
productInCart.deleteOne();
} else {
return res.json({ error: "No se ha podido eliminar el producto" });
cart.products.splice(productIndex, 1);
}

await cart.save();
Expand Down Expand Up @@ -84,13 +98,9 @@ const getCartProducts = async (req, res) => {
const removeAllProducts = async (req, res) => {
try {
const userId = req.params.userid;
const cart = await Cart.findOne({ userId: userId });
await Cart.findOneAndDelete({ userId });

if (cart) {
cart.products = [];
await cart.save();
res.status(200).json({ message: "Carrito eliminado" });
}
return res.status(200).json({ message: "Carrito eliminado" });
} catch (error) {
res.status(500).json({ error: "Error al borrar el carrito" });
}
Expand Down
32 changes: 28 additions & 4 deletions backend/controllers/orderController.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ const checkoutOrder = async (req, res) => {
const registerOrder = async (req, res) => {
try {
const userId = req.params.userid;
const products = req.body.products;
const { products, totalPrice, itemsQuantity } = req.body;

if (!userId || !products || !products.length) {
if (!userId || !products || !products.length || !totalPrice) {
return res.status(400).json({
error: "Faltan datos necesarios para realizar el pedido",
});
Expand All @@ -42,7 +42,10 @@ const registerOrder = async (req, res) => {
items: products.map((product) => ({
product: product.productId,
quantity: product.quantity,
type: product.type,
})),
totalPrice: totalPrice,
itemsQuantity: itemsQuantity,
});
await newOrder.save();

Expand All @@ -59,7 +62,28 @@ const getOrders = async (req, res) => {
if (orders) {
return res.json(orders);
}
} catch (error) {}
} catch (error) {
console.log(error);
}
};

const changeOrderState = async (req, res) => {
try {
const orderId = req.params.orderid;
const { orderState } = req.body;

const order = await Order.findById(orderId);

if (order) {
order.status = orderState;
await order.save();
return res.status(200).json({ message: "Estado cambiado" });
} else {
return res.json({ error: "No se ha encontrado ningún pedido" });
}
} catch (error) {
console.error("Change order state: ", error);
}
};

module.exports = { checkoutOrder, registerOrder, getOrders };
module.exports = { checkoutOrder, registerOrder, getOrders, changeOrderState };
2 changes: 1 addition & 1 deletion backend/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ const getShippingAddress = async (req, res) => {

const getUser = async (req, res) => {
try {
const userId = req.params.userid;
const userId = req.params.id;
const user = await User.findById(userId);

if (user) {
Expand Down
3 changes: 3 additions & 0 deletions backend/models/orderModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ const orderSchema = new Schema(
totalPrice: {
type: Number,
},
itemsQuantity: {
type: Number,
},
},
{ timestamps: true }
);
Expand Down
15 changes: 10 additions & 5 deletions backend/routes/cartRoutes.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const express = require("express");
const router = express.Router();
const { addToCart, removeFromCart, getCartProducts, removeAllProducts } = require("../controllers/cartController")
const {
addToCart,
removeFromCart,
getCartProducts,
removeAllProducts,
} = require("../controllers/cartController");

router.post("/add-to-cart/:userid/:product", addToCart);
router.delete("/remove-from-cart/:userid/:product", removeFromCart)
router.get("/get-cart-products/:userid", getCartProducts)
router.delete("/remove-all-cart/:userid", removeAllProducts)
router.delete("/remove-from-cart/:userid/:product", removeFromCart);
router.get("/get-cart-products/:userid", getCartProducts);
router.delete("/remove-all-cart/:userid", removeAllProducts);

module.exports = router
module.exports = router;
2 changes: 2 additions & 0 deletions backend/routes/orderRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ const {
checkoutOrder,
registerOrder,
getOrders,
changeOrderState,
} = require("../controllers/orderController");

router.post("/checkout-order", checkoutOrder);
router.post("/register-order/:userid", registerOrder);
router.get("/get-orders", getOrders);
router.post("/change-order-state/:orderid", changeOrderState);

module.exports = router;
13 changes: 9 additions & 4 deletions frontend/src/components/ShopMenuComponent.jsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
import { Link } from "react-router-dom";
import { memo } from "react";
import { memo, useState } from "react";

const ShopMenuComponent = (props) => {
const [menuOpen, setMenuOpen] = useState(false);

return (
<ul className={`menu menu-horizontal ${props.showHide}`}>
<li>
<details className={`flex justify-center ${props.margin} z-50`}>
<details
className={`flex justify-center ${props.margin} z-50`}
open={(menuOpen) => !menuOpen}
>
<summary className={`btn btn-ghost ${props.padding}`}>Tienda</summary>
<ul className="p-2 bg-accent rounded-t-none">
<li>
<li onClick={() => setMenuOpen(!menuOpen)}>
<Link to="/store/all" className="btn btn-ghost">
Catálogo
</Link>
</li>
{props.genres.map((genre, index) => (
<li key={index}>
<li key={index} onClick={() => setMenuOpen(!menuOpen)}>
<Link to={`/store/${genre}`} className="btn btn-ghost">
{genre}
</Link>
Expand Down
23 changes: 14 additions & 9 deletions frontend/src/components/ShoppingCartComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ const ShoppingCartComponent = () => {

const deleteCartProduct = async (productId, productType) => {
const idToast = toast.loading("Quitando producto del carrito...");

try {
const response = await axios.delete(
`/remove-from-cart/${user._id}/${productId}`,
{
type: productType,
params: {
type: productType,
},
}
);

Expand All @@ -27,19 +28,21 @@ const ShoppingCartComponent = () => {
} else {
toast.error(response.data.error, { id: idToast });
}
} catch (error) {}
} catch (error) {
toast.error("Error del servidor", { id: idToast });
}
};

const addCartProduct = async (productId, productType) => {
const idToast = toast.loading("Añadiendo producto al carrito...");

try {
const response = await axios.post(
`/add-to-cart/${user._id}/${productId}`,
{
type: productType,
}
);

if (!response.data.error) {
toast.success(response.data.message, { id: idToast });
setCartChanged((val) => !val);
Expand Down Expand Up @@ -78,15 +81,17 @@ const ShoppingCartComponent = () => {
>
<div className="card-body">
<span className="font-bold text-lg">{quantity} Productos</span>
<span className="text-black">Total: {totalPrice.toFixed(2)}</span>
<span className="text-white">Total: {totalPrice.toFixed(2)}</span>
<div className="card-actions overflow-auto max-h-96">
{console.log(products)}
{products.map((product, index) => (
<div key={[product._id, index]} className="flex flex-row items-center mb-2">
<img src={product.image} className="w-16 h-16 mr-3" />
<div
key={[product._id, index]}
className="flex flex-row items-center mb-2"
>
<img src={product.image} className="w-16 h-16 mr-3 rounded" />
<div className="flex flex-col text-primary">
<span>{product.productName}</span>
<span>Tipo: {product.type}</span>
<span>{product.type}</span>
<span>{(product.price * product.quantity).toFixed(2)}</span>
<span>Cantidad: {product.quantity}</span>
</div>
Expand Down
1 change: 1 addition & 0 deletions frontend/src/context/cartContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export function CartContextProvider({ children }) {
})
);

// FLAG MIRAR FILTER (QUITAR SI HACE FALTA)
const validProductDetails = productDetails.filter(
(product) => product !== null
);
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/pages/Cart.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ export default function Cart() {

const deleteCartProduct = async (productId, productType) => {
const idToast = toast.loading("Quitando producto del carrito...");

try {
const response = await axios.delete(
`/remove-from-cart/${user._id}/${productId}`,
{
type: productType,
params: {
type: productType,
},
}
);

Expand All @@ -28,7 +29,9 @@ export default function Cart() {
} else {
toast.error(response.data.error, { id: idToast });
}
} catch (error) {}
} catch (error) {
toast.error("Error del servidor", { id: idToast });
}
};

const addCartProduct = async (productId, productType) => {
Expand Down
5 changes: 2 additions & 3 deletions frontend/src/pages/Product.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,9 @@ export default function Product() {
<details
className="dropdown"
open={(dropdownOpen) => !dropdownOpen}
onClick={() => setDropdownOpen(!dropdownOpen)}
>
<summary
className={`m-1 btn bg-white ${typeError && "bg-error"}`}
className={`m-1 btn ${typeError ? "bg-error" : "bg-white"}`}
>
{type ? type : typeError ? "¡Elije un tipo!" : "Tipo"}
</summary>
Expand All @@ -86,7 +85,7 @@ export default function Product() {
key={type}
onClick={() => {
setType(type);
setDropdownOpen(false);
setDropdownOpen(!dropdownOpen);
setTypeError(false);
}}
>
Expand Down
Loading

0 comments on commit 2c6c5d5

Please sign in to comment.