Skip to content
Extraits de code Groupes Projets
Valider 848910e7 rédigé par Mohsine's avatar Mohsine
Parcourir les fichiers

Merge branch 'feature/MYD-467' into 'develop'

MYD-467/modifier la liste des paniers client

Closes MYD-467

See merge request !237
parents ae09447d 346703a8
Branches
1 requête de fusion!237MYD-467/modifier la liste des paniers client
Pipeline #5563 réussi avec les étapes
in 7 minutes et 17 secondes
import { endpoints, axiosInstance } from "./server";
import useSWR from 'swr';
import { ICart } from "../types/cart";
import useSWR , { mutate } from 'swr';
import { IItemCart} from "../types/cart";
export const useGetCart = (clientId: string) => {
......@@ -13,22 +13,41 @@ export const useGetCart = (clientId: string) => {
cart: data,
isLoading,
error,
mutate, // Mutate function to re-fetch data
mutate,
};
};
// Function to delete a cart item by clientId and itemCartId
export const useDeleteCartItem = async (clientId: string, itemCartId: string) => {
try {
const response = await axiosInstance.delete(endpoints.cart.deleteItem, {
await axiosInstance.delete(endpoints.cart.deleteItem, {
params: { clientId, itemCartId },
});
return response.data; // Return the updated CartDTO
await mutate(endpoints.cart.getCart(clientId), (currentCart) => {
if (!currentCart) return null;
const updatedItems = currentCart.items.filter((item: IItemCart) => item.id.toString() !== itemCartId);
const updatedCart = {
...currentCart,
items: updatedItems,
totalPrice: updatedItems.reduce((acc: number, item: IItemCart) => acc + item.totalPrice, 0),
};
if (updatedCart.items.length === 0) {
updatedCart.totalPrice = 0;
}
return updatedCart;
}, false);
return true;
} catch (error) {
console.error('Error deleting cart item:', error);
console.error('Erreur lors de la suppression de l\'élément du panier :', error);
throw error;
}
};
// Fetcher function for SWR
const fetcher = (url: string) => axiosInstance.get(url).then((res) => res.data);
\ No newline at end of file
import React from "react";
import React, { useState } from "react";
import Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Stack from "@mui/material/Stack";
import Button from "@mui/material/Button";
import Collapse from "@mui/material/Collapse";
import MenuItem from "@mui/material/MenuItem";
import TableRow from "@mui/material/TableRow";
import Checkbox from "@mui/material/Checkbox";
import TableCell from "@mui/material/TableCell";
import IconButton from "@mui/material/IconButton";
import ListItemText from "@mui/material/ListItemText";
import Chip from "@mui/material/Chip";
import { useBoolean } from "../../../../hooks/use-boolean";
import Chip from "@mui/material/Chip";
import { Avatar } from "@mui/material";
import { fCurrency } from "../../../../utils/format-number";
import Iconify from "../../../components/iconify";
import { ConfirmDialog } from "../../../components/custom-dialog";
import CustomPopover, { usePopover } from "../../../components/custom-popover";
import { useState } from "react";
import { Avatar } from "@mui/material";
import { usePopover } from "../../../components/custom-popover";
import { useBoolean } from "../../../../hooks/use-boolean";
import { useGetClients } from "@/shared/api/saleSession";
import { useGetCart, useDeleteCartItem } from "@/shared/api/cart";
import { IItemCart } from "@/shared/types/cart";
import { ICart, IItemCart } from "@/shared/types/cart";
import { IUserItem } from "@/shared/types/saleSession";
// ----------------------------------------------------------------------
......@@ -41,15 +36,11 @@ export default function OrderTableRow({
onSelectRow,
onDeleteRow,
}: Props) {
const { clients, clientsLoading } = useGetClients();
if (clientsLoading) {
return <div>Loading clients...</div>;
}
const { clients } = useGetClients();
return (
<>
{clients.map((client) => (
{clients.map((client) => (
<ClientCartRow
key={client.uid}
client={client}
......@@ -78,30 +69,64 @@ function ClientCartRow({
onSelectRow,
onDeleteRow
}: ClientCartRowProps) {
const { cart, isLoading: cartLoading, mutate: updateCart } = useGetCart(client.uid);
const { cart, isLoading: cartLoading, mutate: updateCart } = useGetCart(client.uid);
const [isDeleting, setIsDeleting] = useState(false);
const confirm = useBoolean();
const collapse = useBoolean();
const popover = usePopover();
const [itemIdToDelete, setItemIdToDelete] = useState<string | null>(null);
const handleOpenConfirmDialog = (itemId: string) => {
setItemIdToDelete(itemId);
confirm.onTrue();
};
if (cartLoading) {
return <div>Loading cart for {`${client.firstName} ${client.lastName}`}...</div>;
}
const handleCloseConfirmDialog = () => {
setItemIdToDelete(null);
confirm.onFalse();
};
const handleConfirmDelete = async () => {
if (itemIdToDelete) {
await handleDeleteItem(itemIdToDelete);
}
handleCloseConfirmDialog();
};
const handleDeleteIconClick = (itemId: string) => {
handleOpenConfirmDialog(itemId);
};
const handleDeleteItem = async (itemId: string) => {
try {
setIsDeleting(true);
await useDeleteCartItem(client.uid, itemId);
await updateCart();
alert("Produit supprimé avec succès!");
setIsDeleting(false);
confirm.onFalse();
setIsDeleting(true);
await useDeleteCartItem(client.uid, itemId);
await updateCart((currentCart: ICart) => {
if (!currentCart) return null;
const updatedCart = {
...currentCart,
items: currentCart.items.filter((item: IItemCart) => item.id.toString() !== itemId),
totalPrice: currentCart.items
.filter((item: IItemCart) => item.id.toString() !== itemId)
.reduce((acc: number, item: IItemCart) => acc + item.totalPrice, 0),
};
if (updatedCart.items.length === 0) {
updatedCart.totalPrice = 0;
}
return updatedCart;
}, false);
setIsDeleting(false);
confirm.onFalse();
} catch (error) {
console.error('Failed to delete item:', error);
alert("Produit supprimé avec succès!");
setIsDeleting(false);
console.error("Erreur lors de la suppression de l'élément:", error);
setIsDeleting(false);
}
};
......@@ -123,7 +148,6 @@ function ClientCartRow({
/>
</TableCell>
<TableCell align="center"> {client.phoneNumber} </TableCell>
<TableCell align="center"> {cart?.items.reduce((total: number, item: IItemCart) => total + item.quantity, 0) ?? 0}</TableCell>
<TableCell> {fCurrency(cart?.totalPrice ?? 0)} </TableCell>
......@@ -167,50 +191,33 @@ function ClientCartRow({
}}
>
<Avatar
src={
item.product && item.product.mainImagePath
? item.product.mainImagePath.replace("Optional[", "").replace("]", "")
: " " // Fallback to a default image or an empty string
}
src={item.product?.mainImagePath?.replace("Optional[", "").replace("]", "") || " "}
variant="rounded"
sx={{ width: 48, height: 48, mr: 2 }}
/>
<ListItemText
primary={item?.product?.name + " - " + item?.product?.ugs}
primary={`${item.product?.name} - ${item.product?.ugs}`}
secondary={
<Chip
size="small"
label={item.source}
sx={{
backgroundColor:
item.source === "Live" ? "#9575cd" : "#f06292",
backgroundColor: item.source === "Live" ? "#9575cd" : "#f06292",
color: "white",
}}
/>
}
primaryTypographyProps={{
typography: "body2",
}}
secondaryTypographyProps={{
component: "span",
color: "text.disabled",
mt: 0.5,
}}
primaryTypographyProps={{ typography: "body2" }}
secondaryTypographyProps={{ component: "span", color: "text.disabled", mt: 0.5 }}
/>
<Box>x{item.quantity}</Box>
<Box sx={{ width: 110, textAlign: "right" }}>
{fCurrency(item.totalPrice)}
</Box>
<Box sx={{ width: 110, textAlign: "right" }}>{fCurrency(item.totalPrice)}</Box>
<IconButton
color="error"
onClick={() => {
handleDeleteItem(item.id.toString())
}}
disabled={isDeleting}
>
color="error"
onClick={() => handleDeleteIconClick(item.id.toString())}
disabled={isDeleting}
>
<Iconify icon="solar:trash-bin-trash-bold" />
</IconButton>
</Stack>
......@@ -224,49 +231,21 @@ function ClientCartRow({
return (
<>
{renderPrimary}
{renderSecondary}
<CustomPopover
open={popover.open}
onClose={popover.onClose}
arrow="right-top"
sx={{ width: 200 }}
>
<MenuItem
onClick={() => {
confirm.onTrue();
popover.onClose();
}}
sx={{ color: "error.main" }}
>
<Iconify icon="solar:trash-bin-trash-bold" />
Mettre à la corbeille
</MenuItem>
<MenuItem
onClick={() => {
onViewRow();
popover.onClose();
}}
>
<Iconify icon="solar:eye-bold" />
View
</MenuItem>
</CustomPopover>
{/* ConfirmDialog pour confirmer la suppression */}
<ConfirmDialog
open={confirm.value}
onClose={confirm.onFalse}
title="Mettre à la corbeille"
content="Etes-vous sûr de vouloir le mettre à la corbeille?"
onClose={handleCloseConfirmDialog}
title="Confirmer la suppression"
content="Êtes-vous sûr de vouloir supprimer cet article de votre panier ?"
action={
<Button
variant="contained"
color="error"
onClick={onDeleteRow}
onClick={handleConfirmDelete}
>
Mettre à la corbeille
Supprimer
</Button>
}
/>
......
0% ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter