Skip to content

Commit

Permalink
carrito roto, arreglar
Browse files Browse the repository at this point in the history
  • Loading branch information
Adolfopgv committed Jun 3, 2024
1 parent 318238b commit c477195
Show file tree
Hide file tree
Showing 12 changed files with 163 additions and 47 deletions.
22 changes: 12 additions & 10 deletions backend/controllers/cartController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,30 @@ const addToCart = async (req, res) => {
try {
const userId = req.params.userid;
const productId = req.params.product;
const { type } = req.body;

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

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

if (!cart) {
await Cart.create({
cart = await Cart.create({
userId,
products: [{ product: productId, quantity: 1 }],
products: [{ product: productId, quantity: 1, type: type }],
});
return res.status(200).json({ message: "Producto añadido al carrito" });
}

const productInCart = cart.products.find(
(item) => item.product.toString() === productId
let productInCart = cart.products.find(
(item) => item.product.toString() === productId && item.type === type
);

if (productInCart) {
productInCart.quantity += 1;
} else {
cart.products.push({ product: productId, quantity: 1 });
cart.products.push({ product: productId, quantity: 1, type: type });
}

await cart.save();
Expand All @@ -41,12 +42,13 @@ const removeFromCart = async (req, res) => {
try {
const userId = req.params.userid;
const productId = req.params.product;
const { type } = req.body;

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

const productInCart = cart.products.find(
(item) => item.product.toString() === productId
);
const productInCart = cart.products.find((item) => {
item.product.toString() === productId && item.type === type;
});

if (productInCart && productInCart.quantity > 1) {
productInCart.quantity -= 1;
Expand Down
12 changes: 11 additions & 1 deletion backend/controllers/orderController.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,14 @@ const registerOrder = async (req, res) => {
}
};

module.exports = { checkoutOrder, registerOrder };
const getOrders = async (req, res) => {
try {
const orders = await Order.find();

if (orders) {
return res.json(orders);
}
} catch (error) {}
};

module.exports = { checkoutOrder, registerOrder, getOrders };
18 changes: 17 additions & 1 deletion backend/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,20 @@ const getShippingAddress = async (req, res) => {
}
};

module.exports = { updateAddresses, getShippingAddress };
const getUser = async (req, res) => {
try {
const userId = req.params.userid;
const user = await User.findById(userId);

if (user) {
return res.json(user);
} else {
return res.status(404).json({ error: "Usuario no encontrado" });
}
} catch (error) {
console.error("Error al obtener el usuario:", error);
res.status(500).json({ error: "Error del servidor" });
}
};

module.exports = { updateAddresses, getShippingAddress, getUser };
3 changes: 3 additions & 0 deletions backend/models/cartModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ const cartSchema = new Schema(
type: Number,
default: 1,
},
type: {
type: String,
},
},
],
},
Expand Down
3 changes: 3 additions & 0 deletions backend/models/orderModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ const orderSchema = new Schema(
quantity: {
type: Number,
},
type: {
type: String,
},
},
],
totalPrice: {
Expand Down
2 changes: 2 additions & 0 deletions backend/routes/orderRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ const router = express.Router();
const {
checkoutOrder,
registerOrder,
getOrders,
} = require("../controllers/orderController");

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

module.exports = router;
2 changes: 2 additions & 0 deletions backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ const router = express.Router();
const {
updateAddresses,
getShippingAddress,
getUser,
} = require("../controllers/userController");

router.post("/users/:id/update-addresses", updateAddresses);
router.get("/users/:id/shipping-details", getShippingAddress);
router.get("/users/:id", getUser)

module.exports = router;
27 changes: 16 additions & 11 deletions frontend/src/components/ShoppingCartComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,15 @@ const ShoppingCartComponent = () => {
const { setCartChanged, products, quantity, totalPrice } =
useContext(CartContext);

const deleteCartProduct = async (productId) => {
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}`
`/remove-from-cart/${user._id}/${productId}`,
{
type: productType,
}
);

if (!response.data.error) {
Expand All @@ -27,12 +30,15 @@ const ShoppingCartComponent = () => {
} catch (error) {}
};

const addCartProduct = async (productId) => {
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}`
`/add-to-cart/${user._id}/${productId}`,
{
type: productType,
}
);
if (!response.data.error) {
toast.success(response.data.message, { id: idToast });
Expand Down Expand Up @@ -74,22 +80,21 @@ const ShoppingCartComponent = () => {
<span className="font-bold text-lg">{quantity} Productos</span>
<span className="text-black">Total: €{totalPrice.toFixed(2)}</span>
<div className="card-actions overflow-auto max-h-96">
{products.map((product) => (
<div
key={product._id}
className="flex flex-row items-center mb-2"
>
{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 className="flex flex-col text-primary">
<span>{product.productName}</span>
<span>Tipo: {product.type}</span>
<span>{(product.price * product.quantity).toFixed(2)}</span>
<span>Cantidad: {product.quantity}</span>
</div>
<div className="flex flex-col-reverse">
{/** Boton restar */}
<button
className="btn btn-ghost"
onClick={() => deleteCartProduct(product._id)}
onClick={() => deleteCartProduct(product._id, product.type)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand All @@ -104,7 +109,7 @@ const ShoppingCartComponent = () => {
{/** Boton sumar */}
<button
className="btn btn-ghost"
onClick={() => addCartProduct(product._id)}
onClick={() => addCartProduct(product._id, product.type)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand Down
6 changes: 5 additions & 1 deletion frontend/src/context/cartContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ export function CartContextProvider({ children }) {
`/get-product/${cartProduct.product}`
);
if (!response.data.error) {
return { ...response.data, quantity: cartProduct.quantity };
return {
...response.data,
quantity: cartProduct.quantity,
type: cartProduct.type,
};
} else {
return null;
}
Expand Down
31 changes: 20 additions & 11 deletions frontend/src/pages/Cart.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ export default function Cart() {
const { setCartChanged, products, quantity, totalPrice } =
useContext(CartContext);

const deleteCartProduct = async (productId) => {
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}`
`/remove-from-cart/${user._id}/${productId}`,
{
type: productType,
}
);

if (!response.data.error) {
Expand All @@ -25,17 +28,18 @@ export default function Cart() {
} else {
toast.error(response.data.error, { id: idToast });
}
} catch (error) {
toast.error("Error del servidor", { id: idToast });
}
} catch (error) {}
};

const addCartProduct = async (productId) => {
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}`
`/add-to-cart/${user._id}/${productId}`,
{
type: productType,
}
);
if (!response.data.error) {
toast.success(response.data.message, { id: idToast });
Expand All @@ -54,8 +58,8 @@ export default function Cart() {
<div className="flex flex-col m-16">
<h1 className="text-3xl m-5">{quantity} Productos</h1>
{products.length > 0 ? (
products.map((product) => (
<div className="flex flex-col" key={product._id}>
products.map((product, index) => (
<div className="flex flex-col" key={[product._id, index]}>
<div className="flex flex-row lg:items-center gap-4 border-b p-5 border-secondary max-lg:flex-col">
<img
alt={product.productName}
Expand All @@ -70,14 +74,17 @@ export default function Cart() {
/>
<div className="flex flex-col gap-1 mr-16">
<h3 className="font-medium">{product.productName}</h3>
<span>{product.type}</span>
<p className="text-sm tex-black">{product.description}</p>
</div>
<div className="flex flex-col items-end gap-4 ml-auto">
<div className="flex flex-row items-center gap-2">
{/** Boton restar */}
<button
className="btn btn-ghost"
onClick={() => deleteCartProduct(product._id)}
onClick={() =>
deleteCartProduct(product._id, product.type)
}
>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand All @@ -93,7 +100,9 @@ export default function Cart() {
{/** Boton sumar */}
<button
className="btn btn-ghost"
onClick={() => addCartProduct(product._id)}
onClick={() =>
addCartProduct(product._id, product.type)
}
>
<svg
xmlns="http://www.w3.org/2000/svg"
Expand Down
58 changes: 50 additions & 8 deletions frontend/src/pages/Product.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useContext } from "react";
import { useContext, useState } from "react";
import { useLocation } from "react-router-dom";
import { UserContext } from "../context/userContext";
import { CartContext } from "../context/cartContext";
Expand All @@ -13,17 +13,29 @@ export default function Product() {
const { setCartChanged } = useContext(CartContext);
const location = useLocation();
const product = location.state?.product;
const [type, setType] = useState("");
const [dropdownOpen, setDropdownOpen] = useState(false);
const [typeError, setTypeError] = useState("");

const addToCart = async () => {
try {
const response = await axios.post(
`/add-to-cart/${user._id}/${product._id}`
);
if (response.data.error) {
toast.error(response.data.error);
if (type !== "") {
setTypeError(false);
const response = await axios.post(
`/add-to-cart/${user._id}/${product._id}`,
{
type: type,
}
);
if (response.data.error) {
toast.error(response.data.error);
} else {
toast.success(response.data.message);
setCartChanged((val) => !val);
}
} else {
toast.success(response.data.message);
setCartChanged((val) => !val);
toast.error("Debes elegir un tipo primero");
setTypeError(true);
}
} catch (error) {
toast.error(error.response.data.error);
Expand Down Expand Up @@ -55,6 +67,36 @@ export default function Product() {
</div>
</div>
<div className="text-4xl font-bold">{product.price}</div>
<div className="flex flex-row items-center">
<span className="text-xl font-bold">Tipo: </span>
<details
className="dropdown"
open={(dropdownOpen) => !dropdownOpen}
onClick={() => setDropdownOpen(!dropdownOpen)}
>
<summary
className={`m-1 btn bg-white ${typeError && "bg-error"}`}
>
{type ? type : typeError ? "¡Elije un tipo!" : "Tipo"}
</summary>
<ul className="p-2 shadow menu dropdown-content z-[1] bg-white rounded-box w-52">
{product.types.map((type) => {
return (
<li
key={type}
onClick={() => {
setType(type);
setDropdownOpen(false);
setTypeError(false);
}}
>
<a>{type}</a>
</li>
);
})}
</ul>
</details>
</div>
<div className="text-lg leading-loose">
<p>{product.description}</p>
</div>
Expand Down
Loading

0 comments on commit c477195

Please sign in to comment.