import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useAppDispatch, useAppSelector } from 'src/hooks/hooks';
import { fetchaddresess, fetchcart } from 'src/redux/services/cartServices';
import Button from '@mui/material/Button';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Radio from '@mui/material/Radio';
import Stepper from '@mui/material/Stepper';
import StepLabel from '@mui/material/StepLabel';
import Step from '@mui/material/Step';
import FormControl from '@mui/material/FormControl';

const AddressSelection: React.FC = () => {
    const router = useRouter();
    const dispatch = useAppDispatch();
    const cartlistData = useAppSelector(state => state.cart?.cartlist);
    const addresslistData = useAppSelector(state => state.cart?.addresslist);
    const auth = useAppSelector((state) => state.auth.auth?.user);
    const { data } = router.query;
    
    const queryParams = JSON.parse(decodeURIComponent(data));
    const handleFetchcartData = () => {
        let formData = {
            "Corp_User_Id": auth.id
        }
        let payLoad = {
            "Corp_Detail_Id": auth.Corp_Detail_Id

        }
        dispatch(fetchcart(formData));
        dispatch(fetchaddresess(payLoad));

    };

    useEffect(() => {
        handleFetchcartData()
    }, []);
    const confirmReload = (e: BeforeUnloadEvent) => {
        const message = 'Are you sure you want to leave? Your changes may not be saved.';
        e.returnValue = message;
        if (window.confirm(message)) {
            router.push(`deliver-to-office`);
        }
        return message;
    };

    window.addEventListener('beforeunload', confirmReload);

    useEffect(() => {
        return () => {
            window.removeEventListener('beforeunload', confirmReload);
        };
    }, []);

    const handleReload = () => {
        if (window.confirm('Are you sure you want to reload? Your changes may not be saved.')) {
            window.location.reload();
            router.push(`deliver-to-office`);
        }
    };

    const handleCheckboxChanges = (event: React.ChangeEvent<HTMLInputElement>) => {
    };
    const [selectedAddress, setSelectedAddress] = useState<string>('');
    const queryvalues = {
        data: data,
        addressId: selectedAddress

    };

    const queryString = encodeURIComponent(JSON.stringify(queryvalues));

    const handleClickOpen = () => {
        router.push(`/shipping-Details?data=${queryString}`);
    };
    const handleAddressSelect = (id: string | number) => {
        setSelectedAddress(id);
    };
    const steps = [
        'Address',
        'Shipping',
        'Payment Details',
        'Order Placed',
    ];
    return (
        <Grid container spacing={2} sx={{ maxWidth: '1200px', minWidth: '328px', margin: 'auto' }}>
            <Grid item xs={12} marginBottom={4}>

                <Box sx={{ width: '100%' }}>
                    <Stepper activeStep={0}>
                        {steps.map((label, index) => {
                            const labelProps: {
                                optional?: React.ReactNode;
                                error?: boolean;
                            } = {};
                            return (
                                <Step key={label}>
                                    <StepLabel {...labelProps}>{label}</StepLabel>
                                </Step>
                            );
                        })}
                    </Stepper>
                </Box>
            </Grid>
            <Grid item xs={12} sm={8}>
                <Paper sx={{ padding: '2px', display: 'flex', flexDirection: 'column' }}>
                    <Box sx={{
                        display: 'flex',
                        padding: '24px', // You can also use `padding: 'var(--3, 24px)'` if '--3' is defined elsewhere
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'flex-start',
                        borderRadius: '4px',
                    }}>
                        <Typography variant="h6" sx={{
                            color: '#000',
                            fontWeight: 500,
                            lineHeight: '32px',
                            fontSize: '20px',
                        }}>
                            Address
                        </Typography>
                        <a onClick={(e) => handleCheckboxChanges(e)}>
                            <Typography variant='body1' sx={{ textDecoration: 'underline', cursor: 'pointer', textDecorationColor: ' var(--primary-dark, #1E88E5)', fontSize: '16px', fontStyle: 'normal', color: 'var(--primary-dark, #1E88E5)', letterSpacing: '0.15px', fontWeight: 400, lineHeight: '150%', fontFeatureSettings: "'clig' off 'liga' off" }}>
                                + Add new address
                            </Typography>
                        </a>
                    </Box>
                    {addresslistData?.results.map((item, index) => (
                        <Box key={index} sx={{ marginBottom: '16px' }}>
                            <Paper sx={{ display: 'flex', alignItems: 'center', gap: '16px', borderRadius: '0', boxShadow: 'none', padding: '24px' }}>
                                <Box>
                                    <FormControl component="fieldset">
                                        <RadioGroup
                                            aria-label="address"
                                            name="address"
                                            value={selectedAddress}
                                            onChange={() => handleAddressSelect(item.id)}
                                        >
                                            <FormControlLabel value={item.id} control={<Radio />} label={''} />
                                        </RadioGroup>
                                    </FormControl>
                                </Box>
                                <Box sx={{ flex: 1, width: '387px' }}>
                                    <Typography variant="body1" sx={{ color: '00008', fontSize: '16px', fontWeight: 400, lineHeight: '24px', letterSpacing: '0.15px', width: '387px' }}>{item.Address}</Typography>
                                    <Typography variant="body1" sx={{ color: '00008', fontSize: '16px', fontWeight: 400, lineHeight: '24px', letterSpacing: '0.15px', width: '387px' }}>{item.Land_Mark},{item.State},{item.Zip_Code}</Typography>
                                </Box>
                            </Paper>
                            {index !== addresslistData?.results.length - 1 && <Divider sx={{ marginTop: 6.5, marginBottom: 6.75 }} />}
                        </Box>
                    ))}
                </Paper>
            </Grid>
            <Grid item xs={12} sm={4}>
                <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    <Typography variant="h6" sx={{ marginBottom: '16px' }}>Products</Typography>
                    {cartlistData?.results?.map((item, index) => (
                        <Grid>
                            <Box key={index} sx={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                <Typography variant="body1">{item.Product_Name}</Typography>
                                <Typography variant="body2">  {item.Selling_Price}</Typography>
                            </Box>
                            <Divider sx={{ display: 'flex', padding: '0px 16px', flexDirection: 'column', alignItems: 'flex-start', alignSelf: 'stretch' }} />
                        </Grid>
                    ))}
                    {/* <Divider sx={{ marginBottom: '8px' }} /> */}
                    <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body1">Total</Typography>
                        {/* totalprice */}
                        <Typography variant="body2"> {queryParams?.totalprice}</Typography>
                        {/* <Typography variant="body2"> {cartlistData?.results.reduce((total, item) => total + parseFloat(item.Selling_Price), 0).toFixed(2)}</Typography> */}
                    </Box>
                    <Button variant="contained" color="primary" sx={{ marginTop: '16px' }}
                        onClick={() => handleClickOpen()}
                    >Continue</Button>
                </Paper>
            </Grid>
        </Grid>
    );
}

export default AddressSelection;


D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\pages\address-selection\index.tsx


















import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import CardMedia from '@mui/material/CardMedia';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import EditOutlined from '@mui/icons-material/EditOutlined';
import { Button, Dialog, DialogTitle, DialogContent, DialogActions, RadioGroup, FormControlLabel, Radio, Snackbar, Alert } from '@mui/material';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useAppDispatch, useAppSelector } from 'src/hooks/hooks';
import { deletecart, fetchcart } from 'src/redux/services/cartServices';

interface CartItem {
    _id: string;
    Product_Id: string;
    Product_Name: string;
    Short_Description: string;
    Currency: string;
    Selling_Price: string;
    Product_Price: string;
    Discount: string;
    Image_Path: string;
}
const CartList: React.FC = () => {
    const router = useRouter();
    const dispatch = useAppDispatch();
    const cartlistData = useAppSelector(state => state.cart?.cartlist);
    const cartDaleteAction = useAppSelector(state => state.cart?.deletecart);
    const auth = useAppSelector((state) => state.auth.auth?.user);
    const [open, setOpen] = useState(false);
    const [selectedOption, setSelectedOption] = useState<string>('');
    const [opensnakebar, setStateSnackbar] = useState({
        opens: false,
        vertical: 'top',
        horizontal: 'center',
    });

    const { vertical, horizontal, opens } = opensnakebar;

    const handleClickOpen = () => {
        setOpen(true);
    };
    const handleFetchcartData = () => {
        let formData = {
            "Corp_User_Id": auth.id
        }
        dispatch(fetchcart(formData));

    };
    useEffect(() => {
        if (cartDaleteAction) {
            handleFetchcartData()
            setStateSnackbar({ ...opensnakebar, opens: true });
        }
    }, [cartDaleteAction]);

    useEffect(() => {
        handleFetchcartData()
    }, []);
    const handleClickDelete = (data:string) => {
        const formData = {
            "Corp_Cart_Id": data
        }
        handleFetchcartData()
        dispatch(deletecart(formData));
    }
    const handleClose = () => {
        setOpen(false);
    };
    const handleCompanyChange = (event:React.ChangeEvent<HTMLInputElement>) => {
        setSelectedOption(event.target.value);
        router.push(`/deliver-to-office?id=${event.target.value}`);

    };
    const handleEditChange = (productit:string) => {
        router.push(`./product-details?id=${productit}`);

    };
    const handleDoorstepChange = (event:React.ChangeEvent<HTMLInputElement>) => {
        setSelectedOption(event.target.value);
        router.push(`/doordtep-deliver?id=${event.target.value}`);

    };
    const handleCloseSnackar = () => {
        setStateSnackbar({ ...opensnakebar, opens: false });
    };
    return (
        <Grid container spacing={2} sx={{ maxWidth: '1200px', minWidth: '328px', margin: 'auto' }}>
            <Grid item xs={12}>
                <Typography variant="h5" sx={{
                    color: '#000',
                    fontWeight: 400,
                    lineHeight: '32.016px',
                    fontSize: '24px',
                }}>
                    Cart ({cartlistData?.results?.length} items)
                </Typography>
            </Grid>
            <Grid item xs={12} sm={8}>
                <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    {cartlistData?.results.map((item, index) => (
                        <Box key={index} sx={{ marginBottom: '16px' }}>
                            <Paper sx={{ display: 'flex', alignItems: 'center', gap: '16px', borderRadius: '0', boxShadow: 'none', }}>
                                <CardMedia
                                    component="img"
                                    image={item.Image_Path}
                                    alt={item.Product_Name}
                                    sx={{ width: '88px', height: '84px', objectFit: 'contain' }}
                                />
                                <Box sx={{ flex: 1 }}>
                                    <Typography variant="h5">{item.Product_Name}</Typography>
                                    <Box sx={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                                        <Typography variant="body1">{item.Selling_Price}</Typography>
                                        <Typography variant="body1" sx={{ textDecoration: 'line-through', color: 'text.secondary' }}>{item.Product_Price}</Typography>
                                        <Typography variant="body2" sx={{ color: 'success.light' }}>({item.Discount}% off)</Typography>
                                    </Box>
                                    <Typography variant="body2" sx={{ color: 'text.secondary' }}>{item.Short_Description}</Typography>
                                </Box>
                                <Box sx={{ display: 'flex', gap: '8px', marginLeft: 'auto' }}>
                                    <IconButton color="primary" aria-label="Edit"
                                        onClick={() => {
                                            handleEditChange(item.Product_Id);
                                        }}>

                                        <EditOutlined />
                                    </IconButton>
                                    <IconButton color="primary" aria-label="Delete" onClick={() => {
                                        handleClickDelete(item._id);
                                    }}>
                                        <DeleteOutlineIcon />
                                    </IconButton>
                                </Box>

                            </Paper>
                            {index !== cartlistData?.results?.length - 1 && <Divider sx={{ marginTop: 6.5, marginBottom: 6.75 }} />}

                        </Box>
                    ))}
                </Paper>
            </Grid>
            <Grid item xs={12} sm={4}>
                <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    <Typography variant="h6" sx={{ marginBottom: '16px' }}>Products</Typography>
                    {cartlistData?.results.map((item, index) => (
                        <Grid>
                            <Box key={index} sx={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                <Typography variant="body1">{item.Product_Name}</Typography>
                                <Typography variant="body2">{item.Selling_Price}</Typography>
                            </Box>
                            <Divider sx={{ display: 'flex', padding: '0px 16px', flexDirection: 'column', alignItems: 'flex-start', alignSelf: 'stretch' }} />
                        </Grid>
                    ))}
                    {/* <Divider sx={{ marginBottom: '8px' }} /> */}
                    {cartlistData?.results ? <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body1">Total</Typography>
                        <Typography variant="body2">
                            {cartlistData.results.reduce((total, item) => total + parseFloat(item.Selling_Price), 0).toFixed(2)}
                        </Typography>
                    </Box> : null}
                    <Button variant="contained" color="primary" sx={{ marginTop: '16px' }} onClick={handleClickOpen}>Select delivery mode</Button>
                </Paper>
            </Grid>
            <Dialog open={open} onClose={handleClose} fullWidth maxWidth="md">
                <Box sx={{ padding: '24px' }}>
                    <DialogTitle sx={{ textAlign: 'center' }}>Select Delivery Mode</DialogTitle>
                    <DialogContent>
                        <Grid container spacing={2}>
                            <Grid item xs={12} sm={6}>
                                <FormControlLabel
                                    value="Company"
                                    control={<Radio />}
                                    label="Deliver to company"
                                    sx={{
                                        display: 'flex',
                                        flexDirection: 'column',
                                        alignItems: 'center',
                                        '& .MuiFormControlLabel-label': {
                                            marginTop: '8px', // Adjust as needed
                                        },
                                    }}
                                    onChange={handleCompanyChange}
                                    checked={selectedOption === 'Company'}
                                />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                                <FormControlLabel
                                    value="Doorstep"
                                    control={<Radio />}
                                    label="Doorstep delivery"
                                    sx={{
                                        display: 'flex',
                                        flexDirection: 'column',
                                        alignItems: 'center',
                                        '& .MuiFormControlLabel-label': {
                                            marginTop: '8px', // Adjust as needed
                                        },
                                    }}
                                    onChange={handleDoorstepChange}
                                    checked={selectedOption === 'Doorstep'}
                                />
                            </Grid>
                        </Grid>
                    </DialogContent>
                </Box>
            </Dialog>

            <Snackbar
                anchorOrigin={{ vertical, horizontal }}
                open={opens}
                onClose={handleCloseSnackar}
                autoHideDuration={6000}
                key={vertical + horizontal}
            >
                <Alert
                    onClose={handleCloseSnackar}
                    severity={cartDaleteAction?.code == 201 ? "info" : cartDaleteAction?.code == 200 ? "success" : 'error'}
                    variant="filled"
                    sx={{ width: '100%' }}
                >
                    {cartDaleteAction?.message}
                </Alert>
            </Snackbar>

        </Grid>
    );
}

export default CartList;




D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\pages\cart-management\index.tsx






















import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import CardMedia from '@mui/material/CardMedia';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import EditOutlined from '@mui/icons-material/EditOutlined';
import Table from '@mui/material/Table'
import TableRow from '@mui/material/TableRow'
import TableHead from '@mui/material/TableHead'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TablePagination from '@mui/material/TablePagination'
import { Button, Avatar, Dialog, Chip, DialogTitle, DialogContent, DialogActions, RadioGroup, FormControlLabel, Radio, Checkbox, TextField, MenuItem, Snackbar, Alert } from '@mui/material';
import { useEffect, useState } from 'react';
import CustomCheckbox from 'src/layouts/components/CheckBox';
import { Card } from 'mdi-material-ui';
import FilterAltIcon from '@mui/icons-material/FilterAlt';
import Link from 'next/link';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { useAppDispatch, useAppSelector } from 'src/hooks/hooks';
import { cartSizeUpdate, deletecart, fetchcart, fetchcartgetsize, fetchdepartment, fetchemploye, fetchproductssizes } from 'src/redux/services/cartServices';
import { useRouter } from 'next/router';


const CartOfficeDelovery = () => {

    const dispatch = useAppDispatch();
    const router = useRouter();
    const { id } = router.query;
    const DepartmentsGetAction = useAppSelector(state => state.cart?.departmentlist);
    const EmployelistAction = useAppSelector(state => state.cart?.employelist);
    const [isCheckeds, setIsCheckeds] = useState(false);
    const [isCheckedemps, setIsCheckedEmps] = useState(false);
    const [empopen, setEmpOpen] = useState(false);
    const [selectedDepartmentsData, setSelectedDepartmentsData] = useState({});
    const [isChecked, setIsChecked] = useState(false);
    const [selectedDepartments, setSelectedDepartments] = useState<string[]>([]); // State to hold selected department IDs
    const [isUserChecked, setIsUserChecked] = useState(false);
    const [selectedusers, setSelectedUsers] = useState<string[]>([]); // State to hold selected department IDs
    const [page, setPage] = useState<number>(0)
    const [emppage, setEmpPage] = useState<number>(0)
    // setTotalPriceSum(totalPriceSum)
    const [rowsPerPage, setRowsPerPage] = useState<number>(5)
    const [totalPriceSum, setTotalPriceSum] = useState<number>(0)
    const [emprowsPerPage, setEmpRowsPerPage] = useState<number>(5)
    const [searchValue, setSearchValue] = useState<string>('');
    const [filterValue, setFilterValue] = useState<string>('');
    const [open, setOpen] = useState(false);
    const [deptid, setDeptId] = useState('');
    const [sizeopen, setSizeOpen] = useState(false);
    const [selectedOption, setSelectedOption] = useState('');
    const [cartid, setCartID] = useState('');
    const [checkTrue, setCheckTrue] = useState(true);
    const [searchEmpValue, setSearchEmpValue] = useState<string>('');
    const cartlistData = useAppSelector(state => state.cart?.cartlist);
    const cartDaleteAction = useAppSelector(state => state.cart?.deletecart);
    const cartsizegetAction = useAppSelector(state => state.cart?.cartsizeget);
    const productssizesAction = useAppSelector(state => state.cart?.productssizes);
    const cartSizeUpdateAction = useAppSelector(state => state.cart?.cartSizeUpdate);
    const auth = useAppSelector((state) => state.auth.auth?.user);
    console.log(totalPriceSum, 'SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS')
    const uniqueDepartmentIds = Object.keys(selectedDepartmentsData).map(deptId => deptId.replace(/'/g, ''));
    const updatedSelectedDepartments = uniqueDepartmentIds ?
        selectedDepartments.filter(deptId => !uniqueDepartmentIds.includes(deptId)) :
        selectedDepartments;
    const [opensnakebar, setStateSnackbar] = useState({
        opens: false,
        vertical: 'top',
        horizontal: 'center',
    });
    const ids = cartlistData?.results.map(item => item._id);
    const { vertical, horizontal, opens } = opensnakebar;

    const handleCheckboxChanges = (event: React.ChangeEvent<HTMLInputElement>) => {
        const checked = event.target.checked;
        setIsCheckeds(checked);
        setOpen(true);
    };
    useEffect(() => {
        getDepartments()
    }, []);
    const handleFetchcartData = () => {
        let formData = {
            "Corp_User_Id": auth.id
        }
        dispatch(fetchcart(formData));

    };
    useEffect(() => {
        if (cartDaleteAction) {
            handleFetchcartData()
            setStateSnackbar({ ...opensnakebar, opens: true });
        }
    }, [cartDaleteAction]);
    const handleFetchSizeData = () => {
        let formData = {
            "Cart_Id": ids
        }
        dispatch(fetchcartgetsize(formData));
    };
    useEffect(() => {
        if (ids) {
            handleFetchSizeData()
        }
    }, [cartlistData]);
    useEffect(() => {
        if (cartSizeUpdateAction?.code === 201) {
            handleFetchSizeData()
            setSizeOpen(false)
        }
    }, [cartSizeUpdateAction]);
    useEffect(() => {
        handleFetchcartData()
    }, []);
    const handleClickDelete = (data: string) => {
        const formData = {
            "Corp_Cart_Id": data
        }
        handleFetchcartData()
        dispatch(deletecart(formData));
    }

    const handleCheckboxforEMPChanges = (ID: string) => {
        setDeptId(ID)
        setEmpOpen(true);
        let formData = {
            "Is_All_Departments_Selected": false,
            "Department_Id": ID,
            "Search": ""

        }
        dispatch(fetchemploye({ userData: formData, paginations: pagination }));
    };
    const handleSizeSelection = (data: string) => {
        const formData = {
            "Product_Id": data.Product_Id
        }
        dispatch(fetchproductssizes(formData));
        setSizeOpen(true);
        setCartID(data._id)
    };
    const handleCheckboxChange = (deptId: string) => {
        if (deptId === 'ALL') {
            setIsChecked(true)
            const allDeptIds = DepartmentsGetAction?.results.map(row => row.Department_Id);
            setSelectedDepartments(allDeptIds);
        } else if (deptId === '') {
            setIsChecked(false)
            setSelectedDepartments([])
        } else {
            setIsChecked(false)
            const updatedDepartments = selectedDepartments.includes(deptId.Department_Id)
                ? selectedDepartments.filter(id => id !== deptId.Department_Id)
                : [...selectedDepartments, deptId.Department_Id];
            const filteredDepartments = updatedDepartments.filter(id => id !== '');
            setSelectedDepartments(filteredDepartments);
        }
    };

    const initialQuantitiesState = productssizesAction?.reduce((acc, size) => {
        if (!acc[size.Product_Id]) {
            acc[size.Product_Id] = {};
        }
        acc[size.Product_Id][size.id] = 0;
        return acc;
    }, {});

    const [quantities, setQuantities] = useState(initialQuantitiesState ? initialQuantitiesState : 0);


    const handleDecrement = (productId, id) => {
        setQuantities(prevQuantities => ({
            ...prevQuantities,
            [productId]: {
                ...prevQuantities[productId],
                [id]: Math.max(prevQuantities[productId] ? prevQuantities[productId][id] - 1 : cartsizegetAction?.results.find(cartItem => cartItem.Size_Id === id)?.Quantity !== undefined ? cartsizegetAction?.results.find(cartItem => cartItem.Size_Id === id)?.Quantity - 1 : 0, 0)
            }
        }));
    };
    const handleIncrement = (productId, id) => {
        setQuantities(prevQuantities => ({
            ...prevQuantities,
            [productId]: {
                ...prevQuantities[productId],
                [id]: (prevQuantities[productId] && prevQuantities[productId][id] !== undefined ? prevQuantities[productId][id] : cartsizegetAction?.results.find(cartItem => cartItem.Size_Id === id)?.Quantity !== undefined ? cartsizegetAction?.results.find(cartItem => cartItem.Size_Id === id)?.Quantity : 0) + 1
            }
        }));
    };
    const productsWithQuantities = Object.keys(quantities).map(productId => ({
        Product_Id: productId,
        sizes: quantities[productId]
    }));


    const totalQuantities = productsWithQuantities?.map(product => ({
        Product_Id: product.Product_Id,
        totalQuantity: Object.values(product.sizes).reduce((acc, quantity) => acc + quantity, 0)
    }));
    const handleQuantityChange = (e, size) => {
        const value = parseInt(e.target.value);
        if (!isNaN(value)) {
            setQuantities(prevQuantities => ({
                ...prevQuantities,
                [size]: value
            }));
        }
    };
    const updateSelectedData = (deptId, userId) => {
        setSelectedDepartmentsData(prevData => {
            const newData = { ...prevData };
            if (!deptId && !userId) {
                return {};
            }

            if (!deptId) {
                Object.keys(newData).forEach(key => {
                    newData[key].emp = [];
                });
                return newData;
            }

            if (!newData[deptId]) {
                newData[deptId] = { dept: deptId, emp: [userId] };
            } else {
                if (!newData[deptId].emp.includes(userId)) {
                    newData[deptId].emp = [...newData[deptId].emp, userId];
                } else {
                    newData[deptId].emp = newData[deptId].emp.filter(id => id !== userId);
                }
                if (newData[deptId].emp.length === 0) {
                    delete newData[deptId];
                }
            }
            return newData;
        });
    };
    const handleCheckboxUserChange = (userId) => {
        if (userId === 'ALL') {
            const userDeptId = EmployelistAction?.results[0].Department_Id;
            const allUserIds = EmployelistAction?.results.map(row => row._id);
            setSelectedUsers(allUserIds);
            updateSelectedData(userDeptId, allUserIds)
            setIsUserChecked(true)
        } else if (userId === '') {
            setSelectedUsers([]);
            setIsUserChecked(false)
            updateSelectedData(undefined, undefined)

        } else {
            const updatedUsers = selectedusers.includes(userId)
                ? selectedusers.filter(id => id !== userId) // Uncheck the checkbox   
                : [...selectedusers, userId]; // Check the checkbox
            setSelectedUsers(updatedUsers);
            setIsUserChecked(false)

            const userDeptId = EmployelistAction?.results.find(user => user._id === userId)?.Department_Id;
            updateSelectedData(userDeptId, userId);

        }
    };
    interface Column {
        id: 'Department_Name' | 'id' | 'Employees_Count' | 'Order_Date' | 'Action'
        label: string
        minWidth?: number
        align?: 'left'
        format?: (value: number) => string
    }

    const columns: readonly Column[] = [
        { id: 'Department_Name', label: 'Department Name', minWidth: 170 },
        // { id: 'id', label: 'order id', minWidth: 170, align: 'left', format: (value: number) => value.toLocaleString('en-US') },
        { id: 'Employees_Count', label: 'No of employees ', minWidth: 100 },
        // { id: 'Order_Date', label: 'Order date', minWidth: 170, align: 'left', format: (value: number) => value.toLocaleString('en-US') },
        { id: 'HOD', label: 'HOD', minWidth: 170, align: 'left', format: (value: number) => value.toFixed(2) }
    ]
    interface Columns {
        id: '_id' | 'Full_Name' | 'Role_Name' | 'email' | 'Mobile_Number'
        label: string
        minWidth?: number
        align?: 'left'
        format?: (value: number) => string
    }
    const usersdata: readonly Columns[] = [
        { id: 'Full_Name', label: 'user Name', minWidth: 170 },
        { id: 'Role_Name', label: 'role Name', minWidth: 100 },
        { id: 'email', label: 'Mail ID', minWidth: 170 },
        { id: 'Mobile_Number', label: 'Mobile Number', minWidth: 100 },
    ]


    const handleChangePage = (event: unknown, newPage: number) => {
        setPage(newPage);
        setPagination({ ...pagination, page: newPage + 1 });
    };
    const handleChangeRowsPerPage = (event: ChangeEvent<HTMLInputElement>) => {
        setRowsPerPage(+event.target.value)
        setPage(0)
        setPagination({ ...pagination, limit: +event.target.value });

    }
    const [pageOld, setPageOld] = useState(false);
    const [pagination, setPagination] = useState({ page: 1, limit: 5, sortBy: "Department_Name" });
    useEffect(() => {
        if (pageOld) {
            setPageOld(false);
        } else {
            getDepartments();
        }
    }, [pagination])

    const [emppageOld, setEmpPageOld] = useState(false);
    const [emppagination, setEmpPagination] = useState({ page: 1, limit: 5, sortBy: "Full_Name" });
    useEffect(() => {
        if (emppageOld) {
            setEmpPageOld(false);
        } else {
            getEmpData();
        }
    }, [emppagination])
    const getEmpData = () => {

        let formData = {
            "Is_All_Departments_Selected": false,
            "Department_Id": deptid,
            "Search": searchEmpValue

        }
        dispatch(fetchemploye({ userData: formData, paginations: emppagination }));
    };
    const handleChangeEmpPage = (event: unknown, newPage: number) => {
        setEmpPage(newPage);
        setEmpPagination({ ...pagination, page: newPage + 1 });
    };
    const handleChangeEmpRowsPerPage = (event: ChangeEvent<HTMLInputElement>) => {
        setEmpRowsPerPage(+event.target.value)
        setEmpPage(0)
        setEmpPagination({ ...pagination, limit: +event.target.value });

    }
    const getDepartments = () => {
        let formData = {
            "Corp_Detail_Id": auth.Corp_Detail_Id,
            "Department_Name": ""
        }

        dispatch(fetchdepartment({ userData: formData, paginations: pagination }));
    }
    useEffect(() => {
        getDepartments()
    }, []);
    useEffect(() => {
        if (updatedSelectedDepartments.length > 0 || selectedusers.length > 0) {
            setCheckTrue(false)
        }
    }, [updatedSelectedDepartments, selectedusers]);

    const handleSearchChange = (event: ChangeEvent<HTMLInputElement>) => {
        setSearchValue(event.target.value);
        const paginations = {
            page: 1,
            limit: 5,
            sortBy: 'Department_Name'
        }
        setPagination({ page: 1, limit: 5, sortBy: 'Department_Name' })
        let formData = {
            "Corp_Detail_Id": auth.Corp_Detail_Id,
            "Department_Name": event.target.value
        }

        dispatch(fetchdepartment({ userData: formData, paginations: paginations }));

    };
    const handleSearchEmployeChange = (event: ChangeEvent<HTMLInputElement>) => {
        setSearchEmpValue(event.target.value);
        const paginations = {
            page: 1,
            limit: 5,
            sortBy: 'Full_Name'
        }
        setEmpPagination({ page: 1, limit: 5, sortBy: 'Full_Name' })
        let formData = {
            "Is_All_Departments_Selected": false,
            "Department_Id": deptid,
            "Search": event.target.value

        }
        dispatch(fetchemploye({ userData: formData, paginations: paginations }));

    };
    const handleFilterChange = (event: ChangeEvent<HTMLInputElement>) => {
        setFilterValue(event.target.value);
    };
    const totalEmployeeCount = DepartmentsGetAction?.results
        .filter(row => updatedSelectedDepartments.includes(row.Department_Id))
        .reduce((total, row) => total + parseInt(row.Employees_Count), 0);

    const handleClickOpen = () => {
        setOpen(true);
    };
    const totalCountemployees = totalEmployeeCount + selectedusers.length;
    // useEffect(()=>{
    //     if(cartlistData?.results?.length > 0){
    //     const totalPriceSum = cartlistData?.results?.length > 0 ? cartlistData?.results?.reduce((totalSum, item) => {
    //         const totalPriceInfo = cartsizegetAction?.results.reduce((info, cartItem) => {
    //             if (cartItem.Cart_Id === item._id && Number(item.Selling_Price)) {
    //                 const sellingPrice = parseFloat((item.Selling_Price || '0').replace('₹', ''));
    //                 const totalPrice = cartItem.Quantity * sellingPrice;
    //                 return {
    //                     totalPrice: info.totalPrice + totalPrice,
    //                     sellingPrice: sellingPrice * totalCountemployees
    //                 };
    //             }
    //             return info;
    //         }, { totalPrice: 0, sellingPrice: 0 });
    //         const { totalPrice = 0, sellingPrice = 0 } = totalPriceInfo || {};
    //         return totalSum + totalPrice + sellingPrice;
    //     }, 0) : 0;
    //     setTotalPriceSum(totalPriceSum)
    // }
    // },[auth,cartsizegetAction,cartlistData])
    // useEffect(() => {
    //     if (cartlistData?.results?.length > 0) {
    //         let totalPriceSum = 0;
    
    //         // Calculate total price sum for matched records
    //         if (cartsizegetAction?.results?.length > 0) {
    //             totalPriceSum += cartlistData.results.reduce((totalSum, item) => {
    //                 const totalPriceInfo = cartsizegetAction.results.reduce((info, cartItem) => {
    //                     if (cartItem.Cart_Id === item._id && Number(item.Selling_Price)) {
    //                         const sellingPrice = parseFloat((item.Selling_Price || '0').replace('₹', ''));
    //                         const totalPrice = cartItem.Quantity * sellingPrice;
    //                         return {
    //                             totalPrice: info.totalPrice + totalPrice,
    //                             sellingPrice: sellingPrice * totalCountemployees
    //                         };
    //                     }
    //                     return info;
    //                 }, { totalPrice: 0, sellingPrice: 0 });
    //                 const { totalPrice = 0, sellingPrice = 0 } = totalPriceInfo || {};
    //                 return totalSum + totalPrice + sellingPrice;
    //             }, 0);
    //         }
    
    //         // Calculate total price sum for unmatched records
    //         totalPriceSum += cartlistData.results.reduce((totalSum, item) => {
    //             if (cartsizegetAction?.results?.some(cartItem => cartItem.Cart_Id === item._id)) {
    //                 // Skip matched records
    //                 return totalSum;
    //             }
    //             const sellingPrice = parseFloat((item.Selling_Price || '0').replace('₹', ''));
    //             const totalPrice = item.Quantity * sellingPrice;
    //             return totalSum + totalPrice;
    //         }, 0);
    
    //         setTotalPriceSum(totalPriceSum);
    //     }
    // }, [auth, cartsizegetAction, cartlistData, totalCountemployees]);
    
    useEffect(() => {
        if (cartlistData?.results?.length > 0) {
            let matchedTotalPriceSum = 0;
            let unmatchedTotalPriceSum = 0;
    
            // Calculate total price sum for matched records
            if (cartsizegetAction?.results?.length > 0) {
                matchedTotalPriceSum = cartlistData.results.reduce((totalSum, item) => {
                    const totalPriceInfo = cartsizegetAction.results.reduce((info, cartItem) => {
                        if (cartItem.Cart_Id === item._id && Number(item.Selling_Price)) {
                            const sellingPrice = parseFloat((item.Selling_Price || '0').replace('₹', ''));
                            const totalPrice = cartItem.Quantity * sellingPrice;
                            return {
                                totalPrice: info.totalPrice + totalPrice,
                                sellingPrice: sellingPrice * totalCountemployees
                            };
                        }
                        return info;
                    }, { totalPrice: 0, sellingPrice: 0 });
                    const { totalPrice = 0, sellingPrice = 0 } = totalPriceInfo || {};
                    return totalSum + totalPrice + sellingPrice;
                }, 0);
            }
    
            // Calculate total price sum for unmatched records
            unmatchedTotalPriceSum = cartlistData.results.reduce((totalSum, item) => {
                if (cartsizegetAction?.results?.some(cartItem => cartItem.Cart_Id === item._id)) {
                    // Skip matched records
                    return totalSum;
                }
                const sellingPrice = parseFloat((item.Selling_Price || '0').replace('₹', ''));
                const totalPrice = item.Quantity * sellingPrice;
                return totalSum + totalPrice;
            }, 0);
    
            // Combine both sums
            const totalPriceSum = matchedTotalPriceSum + unmatchedTotalPriceSum;
    
            setTotalPriceSum(totalPriceSum);
        }
    }, [auth, cartsizegetAction, cartlistData, totalCountemployees]);
    
    const queryParams = {
        uniqueDepartmentIds: updatedSelectedDepartments,
        selectedusers: selectedusers,
        Delivery_Type: id,
        totalprice: totalPriceSum,

    };

    const queryString = encodeURIComponent(JSON.stringify(queryParams));
    const handleClicknext = () => {
        setOpen(false);
        setEmpOpen(false)
        router.push(`/address-selection?data=${queryString}`);
    };
    const handleClickUpdate = () => {
        setOpen(false);
        setEmpOpen(false)
        const transformedData = Object.values(productsWithQuantities).map(item => {
            return {
                "Cart_Id": cartid,
                "Size_Quantity": Object.entries(item.sizes).map(([sizeId, quantity]) => ({
                    "Size_Id": sizeId,
                    "Quantity": quantity
                }))
            };
        });
        dispatch(cartSizeUpdate(transformedData[0]));
    };
    const handleClose = () => {
        setOpen(false);
        // setIsCheckeds(false)
    };
    const handleUserClose = () => {
        // setIsCheckedEmps(false)
        setEmpOpen(false)
    };
    const handleSizeClose = () => {
        // setIsCheckedEmps(false)
        setSizeOpen(false)
    };
    const handleHeaderCheckboxChange = (event) => {
        setIsCheckeds(!isChecked)
    };
    const handleOptionChange = (event) => {
        setSelectedOption(event.target.value);
    };
    const handleCloseSnackar = () => {
        setStateSnackbar({ ...opensnakebar, opens: false });
    };
    const handleEditChange = (productit) => {
        router.push(`./product-details?id=${productit}`);

    };
    return (
        <Grid container spacing={2} sx={{ maxWidth: '1200px', minWidth: '328px', margin: 'auto' }}>
            <Grid item xs={12} sm={8} sx={{ display: 'flex', gap: '24px', flexDirection: 'column' }} >
                {/* {updatedSelectedDepartments.length > 0 || selectedusers.length > 0 ? null :  */}
                <Paper sx={{
                    // display: 'flex',
                    padding: ' var(--3, 24px)',
                    flexDirection: 'column',
                    alignItems: 'flex-start',
                    alignSelf: 'stretch',
                    gap: '24px',
                }}>

                    <Grid
                        sx={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            flexDirection: 'row',
                            gap: '20px'
                        }}
                    >
                        <FormControlLabel
                            control={
                                <Checkbox
                                    defaultChecked={false} // Set to false if you're using isChecked to control the state
                                    checked={updatedSelectedDepartments.length > 0 || selectedusers.length > 0 ? true : false}
                                    onChange={handleCheckboxChanges}
                                />
                            }
                            label="Select from employee’s list"
                            sx={{
                                '& .MuiFormControlLabel-label': {
                                    color: 'var(--text-primary, rgba(0, 0, 0, 0.87))',
                                    fontSize: '20px',
                                    fontWeight: 500,
                                    lineHeight: '160%', // 32px
                                    letterSpacing: '0.15px',
                                },
                            }}
                        />
                        {updatedSelectedDepartments.length > 0 || selectedusers.length > 0 ? <IconButton color="primary" aria-label="Edit" onClick={handleCheckboxChanges}>
                            <EditOutlined />
                        </IconButton> : null}
                    </Grid>
                    {updatedSelectedDepartments.length > 0 || selectedusers.length > 0 ? <Grid sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', alignSelf: 'center', gap: '10px', padding: 'var(--none, 0px) 32px' }}>
                        <Typography variant="body1" sx={{ fontWeight: 500, fontSize: '14px', lineHeight: '24px', letterSpacing: '0.14px' }}>QUANTITY SELECTED </Typography>
                        <Box sx={{
                            bgcolor: '#E0E0E0',
                            padding: '4px 10px',
                            '&:hover': {
                                bgcolor: '#E0E0E0',
                            },
                        }}>
                            <Typography variant="body1" > {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0}</Typography>
                        </Box>
                    </Grid> : null}

                </Paper>
                <Grid>
                    <Typography variant="h5" sx={{
                        color: '#000',
                        gap: '24px'
                    }}>
                        Add more
                    </Typography>
                    {/*  } */}

                </Grid>
                <Grid >
                    <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                        {cartlistData?.results.map((item, index) => (
                            <Box key={index} sx={{ marginBottom: '16px' }}>
                                <Paper sx={{ display: 'flex', alignItems: 'center', gap: '16px', borderRadius: '0', boxShadow: 'none', }}>
                                    <CardMedia
                                        component="img"
                                        image={item.Image_Path}
                                        alt={item.Product_Name}
                                        sx={{ width: '88px', height: '84px', objectFit: 'contain' }}
                                    />
                                    <Box sx={{ flex: 1 }}>
                                        <Typography variant="h5">{item.Product_Name}</Typography>
                                        <Box sx={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                                            <Typography variant="body1">{item.Selling_Price}</Typography>
                                            <Typography variant="body1" sx={{ textDecoration: 'line-through', color: 'text.secondary' }}>{item.Product_Price}</Typography>
                                            <Typography variant="body2" sx={{ color: 'success.light' }}>({item.Discount}% off)</Typography>
                                        </Box>
                                        <Typography variant="body2" sx={{ color: 'text.secondary' }}>{item.Short_Description}</Typography>
                                        {/* <Link href="./product-details"> */}
                                        <a style={{ textDecorationColor: 'rgba(30, 136, 229, 0.5)' }}>
                                            <Typography variant='body1' onClick={() => handleSizeSelection(item)} sx={{ fontSize: '16px', fontStyle: 'normal', color: 'var(--primary-dark, #1E88E5)', letterSpacing: '0.15px', fontWeight: 400, lineHeight: '150%', fontFeatureSettings: "'clig' off 'liga' off", cursor: 'pointer' }}>
                                                Add quantity +
                                                {/* {
                                                    totalQuantities.find(product => product.Product_Id === item.Product_Id) &&
                                                    `Total Quantity: ${totalQuantities.find(product => product.Product_Id === item.Product_Id).totalQuantity}`
                                                } */}
                                            </Typography>
                                        </a>
                                        {
                                            cartsizegetAction?.results.find(product => product.Cart_Id == item._id) ?
                                                <Grid sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', alignSelf: 'center', marginTop: '5px', gap: '10px' }}>
                                                    <Box sx={{ border: '2px solid grey' }}>
                                                        <Typography variant="bodY1" sx={{ padding: '3px', fontWeight: 500, fontSize: '14px', lineHeight: '24px', letterSpacing: '0. 4px' }}>QUANTITY SELECTED </Typography>
                                                    </Box>
                                                    <Box
                                                        sx={{
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            justifyContent: 'center',
                                                            width: '61px',
                                                            bgcolor: '#E0E0E0',

                                                            padding: '3px',
                                                            borderRadius: '3px',
                                                            '&:hover': {
                                                                bgcolor: '#E0E0E0',
                                                            },
                                                        }}
                                                    >
                                                        <Typography
                                                            variant="body1"
                                                            sx={{
                                                                fontWeight: 500,
                                                                fontSize: '14px',
                                                                lineHeight: '24px',
                                                                letterSpacing: '0.4px',
                                                            }}
                                                        >
                                                            {cartsizegetAction?.results.reduce((total, cartItem) => {
                                                                if (cartItem.Cart_Id === item._id) {
                                                                    return total + cartItem.Quantity;
                                                                }
                                                                return total;
                                                            }, 0)}
                                                        </Typography>
                                                    </Box>

                                                </Grid> : null}
                                    </Box>

                                    <Box sx={{ display: 'flex', gap: '8px', marginLeft: 'auto' }}>
                                        <IconButton color="primary" aria-label="Edit" onClick={() => {
                                            handleEditChange(item.Product_Id);
                                        }}>
                                            <EditOutlined />
                                        </IconButton>

                                        <IconButton color="primary" aria-label="Delete" onClick={() => {
                                            handleClickDelete(item._id);
                                        }}>
                                            <DeleteOutlineIcon />
                                        </IconButton>
                                    </Box>

                                </Paper>
                                {index !== cartlistData?.results?.length - 1 && <Divider sx={{ marginTop: 6.5, marginBottom: 6.75 }} />}
                            </Box>
                        ))}
                    </Paper>
                </Grid>
            </Grid>
            <Grid item xs={12} sm={4}>
                <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    <Typography variant="h6" sx={{ marginBottom: '16px' }}>Products</Typography>
                    {cartlistData?.results.map((item, index) => (
                        <Grid>
                            <Box key={index} sx={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                <Box>
                                    <Typography variant="body1">{item.Product_Name}</Typography>
                                    <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                                        <Box>
                                            <Typography variant="body2" sx={{
                                                color: 'var(--text-secondary, rgba(0, 0, 0, 0.60))',
                                                fontFamily: 'Roboto',
                                                fontSize: '14px',
                                                fontStyle: 'normal',
                                                fontWeight: 400,
                                                lineHeight: '143%',
                                                letterSpacing: '0.17px'
                                            }}>Quantity :</Typography>
                                        </Box>
                                        <Typography variant="body2" sx={{
                                            color: '#000',
                                            fontFamily: 'Roboto',
                                            fontSize: '14px',
                                            fontStyle: 'normal',
                                            fontWeight: 400,
                                            lineHeight: '143%',
                                            letterSpacing: '0.17px'
                                        }}>
                                            {(totalEmployeeCount + selectedusers.length) + cartsizegetAction?.results.reduce((total, cartItem) => {
                                                if (cartItem.Cart_Id === item._id) {
                                                    return (total + cartItem.Quantity);
                                                }
                                                return total;
                                            }, 0) || 0}
                                        </Typography>
                                    </Box>
                                </Box>
                                <Typography variant="body2">{item.Selling_Price}</Typography>
                            </Box>
                            <Divider sx={{ display: 'flex', padding: '0px 16px', flexDirection: 'column', alignItems: 'flex-start', alignSelf: 'stretch' }} />
                        </Grid>
                    ))}

                    <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body1">Total</Typography>
                        <Typography variant="body2">{totalPriceSum.toFixed(2)}</Typography>
                    </Box>
                    <Button variant="contained" color="primary" disabled={checkTrue} sx={{ marginTop: '16px' }} onClick={handleClicknext}>continue</Button>
                </Paper>
            </Grid>
            <Dialog open={open} onClose={handleClose} fullWidth maxWidth="md">
                <Box sx={{ padding: '16px' }}>
                    <DialogTitle
                    >DEPARTMENT</DialogTitle>
                    <DialogContent>
                        <Grid item xs={12}>
                            <Grid item xs={12} style={{ padding: '12px', display: 'flex', gap: 'var(--2, 16px)', justifyContent: 'space-between' }}>
                                <TextField
                                    label="Search"
                                    variant="outlined"
                                    placeholder='department name'
                                    value={searchValue}
                                    onChange={handleSearchChange}
                                />
                                <Grid sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', alignSelf: 'center', gap: '5px' }}>
                                    <Box sx={{ border: '2px solid grey' }}>
                                        <Typography variant="body1" sx={{ padding: '10px', fontWeight: 500, fontSize: '14px', lineHeight: '24px', letterSpacing: '0.14px' }}>QUANTITY SELECTED </Typography>
                                    </Box>
                                    <Box sx={{
                                        bgcolor: '#2196F3',
                                        '&:hover': {
                                            bgcolor: '#2196F3',
                                        },
                                    }}>
                                        <Typography variant="body1" sx={{ color: 'white', padding: '10px' }}> {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0}</Typography>
                                    </Box>
                                </Grid>
                            </Grid>
                            <Paper sx={{ width: '100%', overflow: 'hidden' }}>
                                <TableContainer>
                                    <Table stickyHeader aria-label='sticky table'>
                                        <TableHead>
                                            <TableRow>
                                                {columns.map(column => (
                                                    column.label === 'Department Name' ? (
                                                        <TableCell key={column.Department_Id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                            <Checkbox
                                                                color="primary"
                                                                checked={isChecked} // You may need to define isChecked state
                                                                onChange={() => handleCheckboxChange(isChecked ? '' : 'ALL')} // Define function to handle header checkbox change
                                                            />
                                                            {column.label}
                                                        </TableCell>
                                                    ) : (<TableCell key={column.Department_Id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                        {column.label}
                                                    </TableCell>)
                                                ))}
                                            </TableRow>
                                        </TableHead>
                                        <TableBody>
                                            {DepartmentsGetAction?.results.map(row => {
                                                return (
                                                    <TableRow hover role='checkbox' tabIndex={-1} key={row.Department_Id}>
                                                        {columns.map((column, columnIndex) => {
                                                            const value = row[column.id];
                                                            return (
                                                                <TableCell key={columnIndex} align={column.align}>
                                                                    {column.id === 'Department_Name' ? (
                                                                        <Grid container alignItems="center" gap={'8px'}>
                                                                            <Grid item>
                                                                                <Checkbox
                                                                                    color="primary"
                                                                                    indeterminate={uniqueDepartmentIds.includes(row.Department_Id)}
                                                                                    checked={selectedDepartments.includes(row.Department_Id)}
                                                                                    onChange={() => handleCheckboxChange(row)}
                                                                                />
                                                                            </Grid>
                                                                            <Grid item>
                                                                                <Typography variant="body1" onClick={() => handleCheckboxforEMPChanges(row.Department_Id)} style={{ cursor: 'pointer' }} sx={{ color: '#2196F3', fontSize: '14px', fontWeight: 400, lineHeight: '20.02px', letterSpacing: '0.17px' }}>
                                                                                    {value}
                                                                                </Typography>
                                                                                {/* <Typography>{value}</Typography> */}
                                                                            </Grid>
                                                                        </Grid>
                                                                    ) : column.id === 'Action' ? (
                                                                        <IconButton color="primary" aria-label="Edit">
                                                                            <EditOutlined />
                                                                        </IconButton>
                                                                    ) : (
                                                                        column.format && typeof value === 'number' ? column.format(value) : value
                                                                    )}
                                                                </TableCell>
                                                            );
                                                        })}
                                                    </TableRow>
                                                );
                                            })}
                                        </TableBody>
                                    </Table>

                                </TableContainer>
                                <TablePagination
                                    rowsPerPageOptions={[5, 10, 25, 100]}
                                    component='div'
                                    count={DepartmentsGetAction?.totalResults}
                                    rowsPerPage={rowsPerPage}
                                    page={page}
                                    onPageChange={handleChangePage}
                                    onRowsPerPageChange={handleChangeRowsPerPage}
                                />
                            </Paper>
                            <Grid container justifyContent="flex-end">
                                <Button variant="contained" sx={{ marginTop: '16px', backgroundColor: "#2196F3" }} onClick={handleClicknext}>
                                    Continue
                                </Button>
                            </Grid>
                        </Grid>
                    </DialogContent>
                </Box>
            </Dialog>
            <Dialog open={empopen} onClose={handleUserClose} fullWidth maxWidth="md">
                <Box sx={{ padding: '16px' }}>
                    <DialogTitle
                    // sx={{ textAlign: 'center' }}
                    >DEPARTMENT</DialogTitle>
                    <DialogContent>
                        <Grid item xs={12}>
                            <Grid item xs={12} style={{ padding: '12px', display: 'flex', gap: 'var(--2, 16px)', justifyContent: 'space-between' }}>
                                <TextField
                                    label="Search"
                                    variant="outlined"
                                    placeholder='User name'
                                    value={searchEmpValue}
                                    onChange={handleSearchEmployeChange}
                                />
                                <Grid sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', alignSelf: 'center', gap: '5px' }}>
                                    <Box sx={{ border: '2px solid grey' }}>
                                        <Typography variant="body1" sx={{ padding: '10px', fontWeight: 500, fontSize: '14px', lineHeight: '24px', letterSpacing: '0.14px' }}>QUANTITY SELECTED </Typography>
                                    </Box>
                                    <Box sx={{
                                        bgcolor: '#2196F3',
                                        '&:hover': {
                                            bgcolor: '#2196F3',
                                        },
                                    }}>
                                        <Typography variant="body1" sx={{ color: 'white', padding: '10px' }}> {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0}</Typography>
                                    </Box>
                                </Grid>
                            </Grid>
                            <Paper sx={{ width: '100%', overflow: 'hidden' }}>
                                <TableContainer>
                                    <Table stickyHeader aria-label='sticky table'>
                                        <TableHead>
                                            <TableRow>
                                                {usersdata.map(column => (
                                                    column.label === 'user Name' ? (
                                                        // <Grid sx={{ flexDirection: 'row', display: 'flex' }}>
                                                        <TableCell key={column._id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                            <Checkbox
                                                                color="primary"
                                                                checked={isUserChecked} // You may need to define isUserChecked state
                                                                onChange={() => handleCheckboxUserChange(isUserChecked ? '' : 'ALL')} // Define function to handle header checkbox change
                                                            />
                                                            {/* <Typography variant="body1" onClick={handleCheckboxforEMPChanges} style={{ cursor: 'pointer' }}> */}
                                                            {column.label}
                                                            {/* </Typography> */}
                                                        </TableCell>
                                                        // </Grid>
                                                    ) : (<TableCell key={column._id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                        {column.label}
                                                    </TableCell>)

                                                ))}
                                            </TableRow>
                                        </TableHead>
                                        <TableBody>
                                            {EmployelistAction?.results.map(row => {
                                                return (
                                                    <TableRow hover role='checkbox' tabIndex={-1} key={row._id}>
                                                        {usersdata.map((column, columnIndex) => {
                                                            const value = row[column.id];
                                                            return (
                                                                <TableCell key={columnIndex} align={column.align}>
                                                                    {column.id === 'Full_Name' ? (
                                                                        <Grid container alignItems="center" gap={'8px'}>
                                                                            <Grid item>
                                                                                <Checkbox
                                                                                    color="primary"
                                                                                    // indeterminate={true}
                                                                                    checked={selectedusers.includes(row._id)}
                                                                                    onChange={() => handleCheckboxUserChange(row._id)}
                                                                                />
                                                                            </Grid>
                                                                            <Grid item>
                                                                                <Avatar alt="Travis Howard" src={row.Profile_Pic_Path}
                                                                                    sx={{
                                                                                        display: 'flex',
                                                                                        alignItems: 'stretch',
                                                                                        height: '40px',
                                                                                        width: '40px',
                                                                                        '& > img': {
                                                                                            objectFit: 'contain',
                                                                                        },
                                                                                    }} />
                                                                            </Grid>
                                                                            <Grid item>
                                                                                <Typography sx={{ color: '#2196F3', fontSize: '14px', fontWeight: 400, lineHeight: '20.02px', letterSpacing: '0.17px' }}>{value}</Typography>
                                                                            </Grid>
                                                                        </Grid>
                                                                    ) : (
                                                                        column.format && typeof value === 'number' ? column.format(value) : value
                                                                    )}
                                                                </TableCell>
                                                            );
                                                        })}
                                                    </TableRow>
                                                );
                                            })}
                                        </TableBody>
                                    </Table>

                                </TableContainer>
                                <TablePagination
                                    rowsPerPageOptions={[5, 10, 25, 100]}
                                    component='div'
                                    count={EmployelistAction?.totalResults}
                                    rowsPerPage={emprowsPerPage}
                                    page={emppage}
                                    onPageChange={handleChangeEmpPage}
                                    onRowsPerPageChange={handleChangeEmpRowsPerPage}
                                />
                            </Paper>
                            <Grid container justifyContent="flex-end" sx={{ gap: '16px' }}>
                                <Button variant="outlined" sx={{ marginTop: '16px', color: "#2196F3", borderColor: '#2196F3', }} onClick={handleUserClose}>
                                    Back
                                </Button>
                                <Button variant="contained" sx={{ marginTop: '16px', backgroundColor: "#2196F3" }} onClick={handleClicknext}>
                                    Continue
                                </Button>
                            </Grid>
                        </Grid>
                    </DialogContent>
                </Box>
            </Dialog>
            <Dialog open={sizeopen} onClose={handleSizeClose} >
                <Box sx={{ padding: '16px' }}>
                    <DialogTitle sx={{ display: 'flex', flexDirection: 'row', gap: '16px' }}>
                        Enter quantity
                    </DialogTitle>
                    <DialogContent>
                        {productssizesAction && productssizesAction.map((size, index) => (
                            <Box key={index} sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px' }}>
                                {size && size.id && (
                                    <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '8px' }}>
                                        <Typography variant="body1" sx={{
                                            display: 'flex',
                                            width: '75px',
                                            padding: '6px 8px',
                                            flexDirection: 'column',
                                            justifyContent: 'center',
                                            alignItems: 'center'
                                        }}>{`${size.Size}`}</Typography>
                                        <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '8px' }}>
                                            <Box sx={{
                                                display: 'flex',
                                                width: '40px',
                                                height: '36px',
                                                padding: '6px 22px',
                                                justifyContent: 'center',
                                                alignItems: 'center',
                                                background: 'var(--primary-light, #42A5F5)',
                                                borderRadius: '4px'
                                            }}>
                                                <IconButton sx={{ color: 'white' }} onClick={() => handleDecrement(size.Product_Id, size.id)}>
                                                    <RemoveIcon />
                                                </IconButton>
                                            </Box>
                                            <Box sx={{
                                                width: '75px',
                                                padding: '6px 16px',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                border: '1px solid var(--_components-avatar-fill, #BDBDBD)',
                                                borderRadius: 'var(--borderRadius, 4px)'
                                            }}>
                                                <Typography sx={{ alignSelf: 'center', display: 'ruby-text' }}>
                                                    {quantities && quantities[size.Product_Id] && quantities[size.Product_Id][size.id] !== undefined
                                                        ? quantities[size.Product_Id][size.id]
                                                        : cartsizegetAction?.results.find(cartItem => cartItem.Size_Id === size.id)?.Quantity !== undefined ? cartsizegetAction?.results.find(cartItem => (cartItem.Size_Id === size.id && cartItem.Cart_Id === cartid))?.Quantity || 0 : 0}
                                                </Typography>
                                            </Box>
                                            <Box sx={{
                                                display: 'flex',
                                                width: '40px',
                                                height: '36px',
                                                padding: '6px 22px',
                                                justifyContent: 'center',
                                                alignItems: 'center',
                                                background: 'var(--primary-light, #42A5F5)',
                                                borderRadius: '4px'
                                            }}>
                                                <IconButton sx={{ color: 'white' }} onClick={() => handleIncrement(size.Product_Id, size.id)}>
                                                    <AddIcon />
                                                </IconButton>
                                            </Box>
                                        </Box>
                                    </Box>
                                )}
                            </Box>
                        ))}

                        <Box>
                            <Button variant='outlined' sx={{
                                width: '318px',
                                height: '42px'
                            }} onClick={handleClickUpdate}>
                                Continue
                            </Button>
                        </Box>


                    </DialogContent>
                </Box>
            </Dialog>
            <Snackbar
                anchorOrigin={{ vertical, horizontal }}
                open={opens}
                onClose={handleCloseSnackar}
                autoHideDuration={6000}
                key={vertical + horizontal}
            >
                <Alert
                    onClose={handleCloseSnackar}
                    severity={cartDaleteAction?.code == 201 ? "info" : cartDaleteAction?.code == 200 ? "success" : 'error'}
                    variant="filled"
                    sx={{ width: '100%' }}
                >
                    {cartDaleteAction?.message}
                </Alert>
            </Snackbar>
        </Grid >
    );
}

export default CartOfficeDelovery;










D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\pages\deliver-to-office\index.tsx





















import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import CardMedia from '@mui/material/CardMedia';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import EditOutlined from '@mui/icons-material/EditOutlined';
import Table from '@mui/material/Table'
import TableRow from '@mui/material/TableRow'
import TableHead from '@mui/material/TableHead'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TablePagination from '@mui/material/TablePagination'
import { Button, Avatar, Dialog, Chip, DialogTitle, DialogContent, DialogActions, RadioGroup, FormControlLabel, Radio, Checkbox, TextField, MenuItem, Snackbar, Alert } from '@mui/material';
import { useEffect, useState } from 'react';
import CustomCheckbox from 'src/layouts/components/CheckBox';
import { Card } from 'mdi-material-ui';
import FilterAltIcon from '@mui/icons-material/FilterAlt';
import Link from 'next/link';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { useAppDispatch, useAppSelector } from 'src/hooks/hooks';
import { cartSizeUpdate, deletecart, fetchcart, fetchcartgetsize, fetchdepartment, fetchemploye, fetchproductssizes } from 'src/redux/services/cartServices';
import { useRouter } from 'next/router';


const CartDoorStepDelivery = () => {

    const dispatch = useAppDispatch();
    const router = useRouter();
    const { id } = router.query;
    const DepartmentsGetAction = useAppSelector(state => state.cart?.departmentlist);
    const EmployelistAction = useAppSelector(state => state.cart?.employelist);
    const [isCheckeds, setIsCheckeds] = useState(false);
    const [isCheckedemps, setIsCheckedEmps] = useState(false);
    const [empopen, setEmpOpen] = useState(false);
    const [selectedDepartmentsData, setSelectedDepartmentsData] = useState({});
    const [isChecked, setIsChecked] = useState(false);
    const [selectedDepartments, setSelectedDepartments] = useState<string[]>([]); // State to hold selected department IDs
    const [isUserChecked, setIsUserChecked] = useState(false);
    const [selectedusers, setSelectedUsers] = useState<string[]>([]); // State to hold selected department IDs
    const [page, setPage] = useState<number>(0)
    const [emppage, setEmpPage] = useState<number>(0)
    const [rowsPerPage, setRowsPerPage] = useState<number>(5)
    const [emprowsPerPage, setEmpRowsPerPage] = useState<number>(5)
    const [searchValue, setSearchValue] = useState<string>('');
    const [filterValue, setFilterValue] = useState<string>('');
    const [open, setOpen] = useState(false);
    const [deptid, setDeptId] = useState('');
    const [sizeopen, setSizeOpen] = useState(false);
    const [selectedOption, setSelectedOption] = useState('');
    const [cartid, setCartID] = useState('');
    const [checkTrue, setCheckTrue] = useState(true);
    const [searchEmpValue, setSearchEmpValue] = useState<string>('');
    const cartlistData = useAppSelector(state => state.cart?.cartlist);
    const cartDaleteAction = useAppSelector(state => state.cart?.deletecart);
    const productssizesAction = useAppSelector(state => state.cart?.productssizes);
    const cartSizeUpdateAction = useAppSelector(state => state.cart?.cartSizeUpdate);
    const auth = useAppSelector((state) => state.auth.auth?.user);
    const uniqueDepartmentIds = Object.keys(selectedDepartmentsData).map(deptId => deptId.replace(/'/g, ''));
    const updatedSelectedDepartments = uniqueDepartmentIds ?
        selectedDepartments.filter(deptId => !uniqueDepartmentIds.includes(deptId)) :
        selectedDepartments;
    const [opensnakebar, setStateSnackbar] = useState({
        opens: false,
        vertical: 'top',
        horizontal: 'center',
    });
    const ids = cartlistData?.results.map(item => item._id);
    const { vertical, horizontal, opens } = opensnakebar;

    const handleCheckboxChanges = (event: React.ChangeEvent<HTMLInputElement>) => {
        const checked = event.target.checked;
        setIsCheckeds(checked);
        setOpen(true);
    };
    useEffect(() => {
        getDepartments()
    }, []);
    const handleFetchcartData = () => {
        let formData = {
            "Corp_User_Id": auth.id
        }
        dispatch(fetchcart(formData));

    };
    useEffect(() => {
        if (cartDaleteAction) {
            handleFetchcartData()
            setStateSnackbar({ ...opensnakebar, opens: true });
        }
    }, [cartDaleteAction]);
    const handleFetchSizeData = () => {
        let formData = {
            "Cart_Id": ids
        }
        dispatch(fetchcartgetsize(formData));
    };
    useEffect(() => {
        if (ids) {
            handleFetchSizeData()
        }
    }, [cartlistData]);
    useEffect(() => {
        if (cartSizeUpdateAction?.code === 201) {
            handleFetchSizeData()
            setSizeOpen(false)
        }
    }, [cartSizeUpdateAction]);
    useEffect(() => {
        handleFetchcartData()
    }, []);
    const handleClickDelete = (data: string) => {
        const formData = {
            "Corp_Cart_Id": data
        }
        handleFetchcartData()
        dispatch(deletecart(formData));
    }

    const handleCheckboxforEMPChanges = (ID: string) => {
        setDeptId(ID)
        setEmpOpen(true);
        let formData = {
            "Is_All_Departments_Selected": false,
            "Department_Id": ID,
            "Search": ""

        }
        dispatch(fetchemploye({ userData: formData, paginations: pagination }));
    };
    const handleCheckboxChange = (deptId: string) => {
        if (deptId === 'ALL') {
            setIsChecked(true)
            const allDeptIds = DepartmentsGetAction?.results.map(row => row.Department_Id);
            setSelectedDepartments(allDeptIds);
        } else if (deptId === '') {
            setIsChecked(false)
            setSelectedDepartments([])
        } else {
            setIsChecked(false)
            const updatedDepartments = selectedDepartments.includes(deptId.Department_Id)
                ? selectedDepartments.filter(id => id !== deptId.Department_Id)
                : [...selectedDepartments, deptId.Department_Id];
            const filteredDepartments = updatedDepartments.filter(id => id !== '');
            setSelectedDepartments(filteredDepartments);
        }
    };

    const initialQuantitiesState = productssizesAction?.reduce((acc, size) => {
        if (!acc[size.Product_Id]) {
            acc[size.Product_Id] = {};
        }
        acc[size.Product_Id][size.id] = 0;
        return acc;
    }, {});

    const [quantities, setQuantities] = useState(initialQuantitiesState ? initialQuantitiesState : 0);

    const productsWithQuantities = Object.keys(quantities).map(productId => ({
        Product_Id: productId,
        sizes: quantities[productId]
    }));

    const updateSelectedData = (deptId, userId) => {
        setSelectedDepartmentsData(prevData => {
            const newData = { ...prevData };
            if (!deptId && !userId) {
                return {};
            }

            if (!deptId) {
                Object.keys(newData).forEach(key => {
                    newData[key].emp = [];
                });
                return newData;
            }

            if (!newData[deptId]) {
                newData[deptId] = { dept: deptId, emp: [userId] };
            } else {
                if (!newData[deptId].emp.includes(userId)) {
                    newData[deptId].emp = [...newData[deptId].emp, userId];
                } else {
                    newData[deptId].emp = newData[deptId].emp.filter(id => id !== userId);
                }
                if (newData[deptId].emp.length === 0) {
                    delete newData[deptId];
                }
            }
            return newData;
        });
    };
    const handleCheckboxUserChange = (userId) => {
        if (userId === 'ALL') {
            const userDeptId = EmployelistAction?.results[0].Department_Id;
            const allUserIds = EmployelistAction?.results.map(row => row._id);
            setSelectedUsers(allUserIds);
            updateSelectedData(userDeptId, allUserIds)
            setIsUserChecked(true)
        } else if (userId === '') {
            setSelectedUsers([]);
            setIsUserChecked(false)
            updateSelectedData(undefined, undefined)

        } else {
            const updatedUsers = selectedusers.includes(userId)
                ? selectedusers.filter(id => id !== userId) // Uncheck the checkbox   
                : [...selectedusers, userId]; // Check the checkbox
            setSelectedUsers(updatedUsers);
            setIsUserChecked(false)

            const userDeptId = EmployelistAction?.results.find(user => user._id === userId)?.Department_Id;
            updateSelectedData(userDeptId, userId);

        }
    };
    interface Column {
        id: 'Department_Name' | 'id' | 'Employees_Count' | 'Order_Date' | 'Action'
        label: string
        minWidth?: number
        align?: 'left'
        format?: (value: number) => string
    }

    const columns: readonly Column[] = [
        { id: 'Department_Name', label: 'Department Name', minWidth: 170 },
        // { id: 'id', label: 'order id', minWidth: 170, align: 'left', format: (value: number) => value.toLocaleString('en-US') },
        { id: 'Employees_Count', label: 'No of employees ', minWidth: 100 },
        // { id: 'Order_Date', label: 'Order date', minWidth: 170, align: 'left', format: (value: number) => value.toLocaleString('en-US') },
        { id: 'HOD', label: 'HOD', minWidth: 170, align: 'left', format: (value: number) => value.toFixed(2) }
    ]
    interface Columns {
        id: '_id' | 'Full_Name' | 'Role_Name' | 'email' | 'Mobile_Number'
        label: string
        minWidth?: number
        align?: 'left'
        format?: (value: number) => string
    }
    const usersdata: readonly Columns[] = [
        { id: 'Full_Name', label: 'user Name', minWidth: 170 },
        { id: 'Role_Name', label: 'role Name', minWidth: 100 },
        { id: 'email', label: 'Mail ID', minWidth: 170 },
        { id: 'Mobile_Number', label: 'Mobile Number', minWidth: 100 },
    ]


    const handleChangePage = (event: unknown, newPage: number) => {
        setPage(newPage);
        setPagination({ ...pagination, page: newPage + 1 });
    };
    const handleChangeRowsPerPage = (event: ChangeEvent<HTMLInputElement>) => {
        setRowsPerPage(+event.target.value)
        setPage(0)
        setPagination({ ...pagination, limit: +event.target.value });

    }
    const [pageOld, setPageOld] = useState(false);
    const [pagination, setPagination] = useState({ page: 1, limit: 5, sortBy: "Department_Name" });
    useEffect(() => {
        if (pageOld) {
            setPageOld(false);
        } else {
            getDepartments();
        }
    }, [pagination])

    const [emppageOld, setEmpPageOld] = useState(false);
    const [emppagination, setEmpPagination] = useState({ page: 1, limit: 5, sortBy: "Full_Name" });
    useEffect(() => {
        if (emppageOld) {
            setEmpPageOld(false);
        } else {
            getEmpData();
        }
    }, [emppagination])
    const getEmpData = () => {

        let formData = {
            "Is_All_Departments_Selected": false,
            "Department_Id": deptid,
            "Search": searchEmpValue

        }
        dispatch(fetchemploye({ userData: formData, paginations: emppagination }));
    };
    const handleChangeEmpPage = (event: unknown, newPage: number) => {
        setEmpPage(newPage);
        setEmpPagination({ ...pagination, page: newPage + 1 });
    };
    const handleChangeEmpRowsPerPage = (event: ChangeEvent<HTMLInputElement>) => {
        setEmpRowsPerPage(+event.target.value)
        setEmpPage(0)
        setEmpPagination({ ...pagination, limit: +event.target.value });

    }
    const getDepartments = () => {
        let formData = {
            "Corp_Detail_Id": auth.Corp_Detail_Id,
            "Department_Name": ""
        }

        dispatch(fetchdepartment({ userData: formData, paginations: pagination }));
    }
    useEffect(() => {
        getDepartments()
    }, []);
    useEffect(() => {
        if (updatedSelectedDepartments.length > 0 || selectedusers.length > 0) {
            setCheckTrue(false)
        }
    }, [updatedSelectedDepartments, selectedusers]);

    const handleSearchChange = (event: ChangeEvent<HTMLInputElement>) => {
        setSearchValue(event.target.value);
        const paginations = {
            page: 1,
            limit: 5,
            sortBy: 'Department_Name'
        }
        setPagination({ page: 1, limit: 5, sortBy: 'Department_Name' })
        let formData = {
            "Corp_Detail_Id": auth.Corp_Detail_Id,
            "Department_Name": event.target.value
        }

        dispatch(fetchdepartment({ userData: formData, paginations: paginations }));

    };
    const handleSearchEmployeChange = (event: ChangeEvent<HTMLInputElement>) => {
        setSearchEmpValue(event.target.value);
        const paginations = {
            page: 1,
            limit: 5,
            sortBy: 'Full_Name'
        }
        setEmpPagination({ page: 1, limit: 5, sortBy: 'Full_Name' })
        let formData = {
            "Is_All_Departments_Selected": false,
            "Department_Id": deptid,
            "Search": event.target.value

        }
        dispatch(fetchemploye({ userData: formData, paginations: paginations }));

    };
    const handleFilterChange = (event: ChangeEvent<HTMLInputElement>) => {
        setFilterValue(event.target.value);
    };
    const totalEmployeeCount = DepartmentsGetAction?.results
        .filter(row => updatedSelectedDepartments.includes(row.Department_Id))
        .reduce((total, row) => total + parseInt(row.Employees_Count), 0);

    const handleClickOpen = () => {
        setOpen(true);
    };
    const totalCountemployees = totalEmployeeCount + selectedusers.length;
    console.log(cartlistData?.results?.length, '555555555555555555555')
    let totalPriceSum = 0;

    cartlistData?.results.forEach(item => {
        if (totalEmployeeCount + selectedusers.length >= 1) {
            totalPriceSum += item.Selling_Price * (totalEmployeeCount + selectedusers.length);
        } else {
            totalPriceSum += item.Selling_Price*1;
        }
    });
    console.log(totalPriceSum, '7777777777777777777777')
    const queryParams = {
        uniqueDepartmentIds: updatedSelectedDepartments,
        selectedusers: selectedusers,
        Delivery_Type: id,
        totalprice: totalPriceSum,

    };
    console.log(totalPriceSum, '111111111111111111111')
    const queryString = encodeURIComponent(JSON.stringify(queryParams));
    const handleClicknext = () => {
        setOpen(false);
        setEmpOpen(false)
        router.push(`/shipping-Details-door-step?data=${queryString}`);
    };
    const handleClickUpdate = () => {
        setOpen(false);
        setEmpOpen(false)
        const transformedData = Object.values(productsWithQuantities).map(item => {
            return {
                "Cart_Id": cartid,
                "Size_Quantity": Object.entries(item.sizes).map(([sizeId, quantity]) => ({
                    "Size_Id": sizeId,
                    "Quantity": quantity
                }))
            };
        });
        dispatch(cartSizeUpdate(transformedData[0]));
    };
    const handleClose = () => {
        setOpen(false);
        // setIsCheckeds(false)
    };
    const handleUserClose = () => {
        // setIsCheckedEmps(false)
        setEmpOpen(false)
    };
    const handleSizeClose = () => {
        // setIsCheckedEmps(false)
        setSizeOpen(false)
    };
    const handleHeaderCheckboxChange = (event) => {
        setIsCheckeds(!isChecked)
    };
    const handleOptionChange = (event) => {
        setSelectedOption(event.target.value);
    };
    const handleCloseSnackar = () => {
        setStateSnackbar({ ...opensnakebar, opens: false });
    };
    const handleEditChange = (productit) => {
        router.push(`./product-details?id=${productit}`);

    };
    return (
        <Grid container spacing={2} sx={{ maxWidth: '1200px', minWidth: '328px', margin: 'auto' }}>
            <Grid item xs={12} sm={8} marginBottom={4}>
                <Box sx={{
                    display: 'flex',
                    // padding: '24px', // You can also use `padding: 'var(--3, 24px)'` if '--3' is defined elsewhere
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start',
                    gap: '24px', // You can also use `gap: 'var(--3, 24px)'` if '--3' is defined elsewhere
                    borderRadius: '4px',
                    background: 'var(--Background-desktop, #F4F5F9)'
                }}>
                    <Typography variant="h5" sx={{
                        color: '#000',
                        fontWeight: 400,
                        lineHeight: '32.016px',
                        fontSize: '24px',
                    }}>
                        Bag ({cartlistData?.results?.length} items)
                    </Typography>
                    {updatedSelectedDepartments?.length > 0 ||
                        selectedusers?.length > 0 ? <a onClick={handleCheckboxChanges}>
                        <Typography variant='body1' sx={{ textDecoration: 'underline', cursor: 'pointer', textDecorationColor: ' var(--primary-dark, #1E88E5)', fontSize: '16px', fontStyle: 'normal', color: 'var(--primary-dark, #1E88E5)', letterSpacing: '0.15px', fontWeight: 400, lineHeight: '150%', fontFeatureSettings: "'clig' off 'liga' off" }}>
                            Select more from list
                        </Typography>
                    </a> :
                        <a onClick={handleCheckboxChanges}>
                            <Typography variant='body1' sx={{ textDecoration: 'underline', cursor: 'pointer', textDecorationColor: ' var(--primary-dark, #1E88E5)', fontSize: '16px', fontStyle: 'normal', color: 'var(--primary-dark, #1E88E5)', letterSpacing: '0.15px', fontWeight: 400, lineHeight: '150%', fontFeatureSettings: "'clig' off 'liga' off" }}>
                                Select from list
                            </Typography>
                        </a>}
                </Box>
            </Grid>
            <Grid item xs={12} sm={8}>
                <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    {cartlistData?.results.map((item, index) => (
                        <Box key={index} sx={{ marginBottom: '16px' }}>
                            <Paper sx={{ display: 'flex', alignItems: 'center', gap: '16px', borderRadius: '0', boxShadow: 'none', }}>
                                <CardMedia
                                    component="img"
                                    image={item.Image_Path}
                                    alt={item.Product_Name}
                                    sx={{ width: '88px', height: '84px', objectFit: 'contain' }}
                                />
                                <Box sx={{ flex: 1 }}>
                                    <Typography variant="h5">{item.Product_Name}</Typography>
                                    <Box sx={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
                                        <Typography variant="body1">{item.Selling_Price}</Typography>
                                        <Typography variant="body1" sx={{ textDecoration: 'line-through', color: 'text.secondary' }}>{item.Product_Price}</Typography>
                                        <Typography variant="body2" sx={{ color: 'success.light' }}>({item.Discount}% off)</Typography>
                                    </Box>
                                    <Typography variant="body2" sx={{ color: 'text.secondary' }}>{item.Short_Description}</Typography>
                                </Box>

                                <Box sx={{ display: 'flex', gap: '8px', marginLeft: 'auto' }}>
                                    <IconButton color="primary" aria-label="Edit" onClick={() => {
                                        handleEditChange(item.Product_Id);
                                    }}>
                                        <EditOutlined />
                                    </IconButton>

                                    <IconButton color="primary" aria-label="Delete" onClick={() => {
                                        handleClickDelete(item._id);
                                    }}>
                                        <DeleteOutlineIcon />
                                    </IconButton>
                                </Box>

                            </Paper>
                            {index !== cartlistData?.results?.length - 1 && <Divider sx={{ marginTop: 6.5, marginBottom: 6.75 }} />}
                        </Box>
                    ))}
                </Paper>
            </Grid>
            <Grid item xs={12} sm={4}>
                <Paper sx={{ padding: '24px', display: 'flex', flexDirection: 'column' }}>
                    <Typography variant="h6" sx={{ marginBottom: '16px' }}>Products</Typography>
                    {cartlistData?.results.map((item, index) => (
                        <Grid>
                            <Box key={index} sx={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                <Box>
                                    <Typography variant="body1">{item.Product_Name}</Typography>
                                    <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                                        <Box>
                                            <Typography variant="body2" sx={{
                                                color: 'var(--text-secondary, rgba(0, 0, 0, 0.60))',
                                                fontFamily: 'Roboto',
                                                fontSize: '14px',
                                                fontStyle: 'normal',
                                                fontWeight: 400,
                                                lineHeight: '143%',
                                                letterSpacing: '0.17px'
                                            }}>Quantity :</Typography>
                                        </Box>
                                        <Typography variant="body2" sx={{
                                            color: '#000',
                                            fontFamily: 'Roboto',
                                            fontSize: '14px',
                                            fontStyle: 'normal',
                                            fontWeight: 400,
                                            lineHeight: '143%',
                                            letterSpacing: '0.17px'
                                        }}>
                                            {totalEmployeeCount + selectedusers.length}
                                        </Typography>
                                    </Box>
                                </Box>
                                <Typography variant="body2">{item.Selling_Price}</Typography>
                            </Box>
                            <Divider sx={{ display: 'flex', padding: '0px 16px', flexDirection: 'column', alignItems: 'flex-start', alignSelf: 'stretch' }} />
                        </Grid>
                    ))}

                    <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body1">Total</Typography>
                        <Typography variant="body2">{totalPriceSum?.toFixed(2)}</Typography>
                    </Box>
                    <Button variant="contained" color="primary" disabled={checkTrue} sx={{ marginTop: '16px' }} onClick={handleClicknext}>continue</Button>
                </Paper>
            </Grid>
            <Dialog open={open} onClose={handleClose} fullWidth maxWidth="md">
                <Box sx={{ padding: '16px' }}>
                    <DialogTitle
                    >DEPARTMENT</DialogTitle>
                    <DialogContent>
                        <Grid item xs={12}>
                            <Grid item xs={12} style={{ padding: '12px', display: 'flex', gap: 'var(--2, 16px)', justifyContent: 'space-between' }}>
                                <TextField
                                    label="Search"
                                    variant="outlined"
                                    placeholder='department name'
                                    value={searchValue}
                                    onChange={handleSearchChange}
                                />
                                <Grid sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', alignSelf: 'center', gap: '5px' }}>
                                    <Box sx={{ border: '2px solid grey' }}>
                                        <Typography variant="body1" sx={{ padding: '10px', fontWeight: 500, fontSize: '14px', lineHeight: '24px', letterSpacing: '0.14px' }}>QUANTITY SELECTED </Typography>
                                    </Box>
                                    <Box sx={{
                                        bgcolor: '#2196F3',
                                        '&:hover': {
                                            bgcolor: '#2196F3',
                                        },
                                    }}>
                                        <Typography variant="body1" sx={{ color: 'white', padding: '10px' }}> {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0}</Typography>
                                    </Box>
                                </Grid>
                            </Grid>
                            <Paper sx={{ width: '100%', overflow: 'hidden' }}>
                                <TableContainer>
                                    <Table stickyHeader aria-label='sticky table'>
                                        <TableHead>
                                            <TableRow>
                                                {columns.map(column => (
                                                    column.label === 'Department Name' ? (
                                                        <TableCell key={column.Department_Id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                            <Checkbox
                                                                color="primary"
                                                                checked={isChecked} // You may need to define isChecked state
                                                                onChange={() => handleCheckboxChange(isChecked ? '' : 'ALL')} // Define function to handle header checkbox change
                                                            />
                                                            {column.label}
                                                        </TableCell>
                                                    ) : (<TableCell key={column.Department_Id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                        {column.label}
                                                    </TableCell>)
                                                ))}
                                            </TableRow>
                                        </TableHead>
                                        <TableBody>
                                            {DepartmentsGetAction?.results.map(row => {
                                                return (
                                                    <TableRow hover role='checkbox' tabIndex={-1} key={row.Department_Id}>
                                                        {columns.map((column, columnIndex) => {
                                                            const value = row[column.id];
                                                            return (
                                                                <TableCell key={columnIndex} align={column.align}>
                                                                    {column.id === 'Department_Name' ? (
                                                                        <Grid container alignItems="center" gap={'8px'}>
                                                                            <Grid item>
                                                                                <Checkbox
                                                                                    color="primary"
                                                                                    indeterminate={uniqueDepartmentIds.includes(row.Department_Id)}
                                                                                    checked={selectedDepartments.includes(row.Department_Id)}
                                                                                    onChange={() => handleCheckboxChange(row)}
                                                                                />
                                                                            </Grid>
                                                                            <Grid item>
                                                                                <Typography variant="body1" onClick={() => handleCheckboxforEMPChanges(row.Department_Id)} style={{ cursor: 'pointer' }} sx={{ color: '#2196F3', fontSize: '14px', fontWeight: 400, lineHeight: '20.02px', letterSpacing: '0.17px' }}>
                                                                                    {value}
                                                                                </Typography>
                                                                                {/* <Typography>{value}</Typography> */}
                                                                            </Grid>
                                                                        </Grid>
                                                                    ) : column.id === 'Action' ? (
                                                                        <IconButton color="primary" aria-label="Edit">
                                                                            <EditOutlined />
                                                                        </IconButton>
                                                                    ) : (
                                                                        column.format && typeof value === 'number' ? column.format(value) : value
                                                                    )}
                                                                </TableCell>
                                                            );
                                                        })}
                                                    </TableRow>
                                                );
                                            })}
                                        </TableBody>
                                    </Table>

                                </TableContainer>
                                <TablePagination
                                    rowsPerPageOptions={[5, 10, 25, 100]}
                                    component='div'
                                    count={DepartmentsGetAction?.totalResults}
                                    rowsPerPage={rowsPerPage}
                                    page={page}
                                    onPageChange={handleChangePage}
                                    onRowsPerPageChange={handleChangeRowsPerPage}
                                />
                            </Paper>
                            <Grid container justifyContent="flex-end">
                                <Button variant="contained" sx={{ marginTop: '16px', backgroundColor: "#2196F3" }} onClick={handleClicknext}>
                                    Continue
                                </Button>
                            </Grid>
                        </Grid>
                    </DialogContent>
                </Box>
            </Dialog>
            <Dialog open={empopen} onClose={handleUserClose} fullWidth maxWidth="md">
                <Box sx={{ padding: '16px' }}>
                    <DialogTitle
                    // sx={{ textAlign: 'center' }}
                    >DEPARTMENT</DialogTitle>
                    <DialogContent>
                        <Grid item xs={12}>
                            <Grid item xs={12} style={{ padding: '12px', display: 'flex', gap: 'var(--2, 16px)', justifyContent: 'space-between' }}>
                                <TextField
                                    label="Search"
                                    variant="outlined"
                                    placeholder='User name'
                                    value={searchEmpValue}
                                    onChange={handleSearchEmployeChange}
                                />
                                <Grid sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', alignSelf: 'center', gap: '5px' }}>
                                    <Box sx={{ border: '2px solid grey' }}>
                                        <Typography variant="body1" sx={{ padding: '10px', fontWeight: 500, fontSize: '14px', lineHeight: '24px', letterSpacing: '0.14px' }}>QUANTITY SELECTED </Typography>
                                    </Box>
                                    <Box sx={{
                                        bgcolor: '#2196F3',
                                        '&:hover': {
                                            bgcolor: '#2196F3',
                                        },
                                    }}>
                                        <Typography variant="body1" sx={{ color: 'white', padding: '10px' }}> {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0}</Typography>
                                    </Box>
                                </Grid>
                            </Grid>
                            <Paper sx={{ width: '100%', overflow: 'hidden' }}>
                                <TableContainer>
                                    <Table stickyHeader aria-label='sticky table'>
                                        <TableHead>
                                            <TableRow>
                                                {usersdata.map(column => (
                                                    column.label === 'user Name' ? (
                                                        // <Grid sx={{ flexDirection: 'row', display: 'flex' }}>
                                                        <TableCell key={column._id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                            <Checkbox
                                                                color="primary"
                                                                checked={isUserChecked} // You may need to define isUserChecked state
                                                                onChange={() => handleCheckboxUserChange(isUserChecked ? '' : 'ALL')} // Define function to handle header checkbox change
                                                            />
                                                            {/* <Typography variant="body1" onClick={handleCheckboxforEMPChanges} style={{ cursor: 'pointer' }}> */}
                                                            {column.label}
                                                            {/* </Typography> */}
                                                        </TableCell>
                                                        // </Grid>
                                                    ) : (<TableCell key={column._id} align={column.align} sx={{ minWidth: column.minWidth }}>
                                                        {column.label}
                                                    </TableCell>)

                                                ))}
                                            </TableRow>
                                        </TableHead>
                                        <TableBody>
                                            {EmployelistAction?.results.map(row => {
                                                return (
                                                    <TableRow hover role='checkbox' tabIndex={-1} key={row._id}>
                                                        {usersdata.map((column, columnIndex) => {
                                                            const value = row[column.id];
                                                            return (
                                                                <TableCell key={columnIndex} align={column.align}>
                                                                    {column.id === 'Full_Name' ? (
                                                                        <Grid container alignItems="center" gap={'8px'}>
                                                                            <Grid item>
                                                                                <Checkbox
                                                                                    color="primary"
                                                                                    // indeterminate={true}
                                                                                    checked={selectedusers.includes(row._id)}
                                                                                    onChange={() => handleCheckboxUserChange(row._id)}
                                                                                />
                                                                            </Grid>
                                                                            <Grid item>
                                                                                <Avatar alt="Travis Howard" src={row.Profile_Pic_Path}
                                                                                    sx={{
                                                                                        display: 'flex',
                                                                                        alignItems: 'stretch',
                                                                                        height: '40px',
                                                                                        width: '40px',
                                                                                        '& > img': {
                                                                                            objectFit: 'contain',
                                                                                        },
                                                                                    }} />
                                                                            </Grid>
                                                                            <Grid item>
                                                                                <Typography sx={{ color: '#2196F3', fontSize: '14px', fontWeight: 400, lineHeight: '20.02px', letterSpacing: '0.17px' }}>{value}</Typography>
                                                                            </Grid>
                                                                        </Grid>
                                                                    ) : (
                                                                        column.format && typeof value === 'number' ? column.format(value) : value
                                                                    )}
                                                                </TableCell>
                                                            );
                                                        })}
                                                    </TableRow>
                                                );
                                            })}
                                        </TableBody>
                                    </Table>

                                </TableContainer>
                                <TablePagination
                                    rowsPerPageOptions={[5, 10, 25, 100]}
                                    component='div'
                                    count={EmployelistAction?.totalResults}
                                    rowsPerPage={emprowsPerPage}
                                    page={emppage}
                                    onPageChange={handleChangeEmpPage}
                                    onRowsPerPageChange={handleChangeEmpRowsPerPage}
                                />
                            </Paper>
                            <Grid container justifyContent="flex-end" sx={{ gap: '16px' }}>
                                <Button variant="outlined" sx={{ marginTop: '16px', color: "#2196F3", borderColor: '#2196F3', }} onClick={handleUserClose}>
                                    Back
                                </Button>
                                <Button variant="contained" sx={{ marginTop: '16px', backgroundColor: "#2196F3" }} onClick={handleClicknext}>
                                    Continue
                                </Button>
                            </Grid>
                        </Grid>
                    </DialogContent>
                </Box>
            </Dialog>
            <Snackbar
                anchorOrigin={{ vertical, horizontal }}
                open={opens}
                onClose={handleCloseSnackar}
                autoHideDuration={6000}
                key={vertical + horizontal}
            >
                <Alert
                    onClose={handleCloseSnackar}
                    severity={cartDaleteAction?.code == 201 ? "info" : cartDaleteAction?.code == 200 ? "success" : 'error'}
                    variant="filled"
                    sx={{ width: '100%' }}
                >
                    {cartDaleteAction?.message}
                </Alert>
            </Snackbar>
        </Grid >
    );
}

export default CartDoorStepDelivery;




















D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\pages\doordtep-deliver\index.tsx



















import { Box, Breadcrumbs, Button, Checkbox, FormControl, FormControlLabel, IconButton, InputLabel, Link, MenuItem, Popover, Select, Slider, TextField, ThemeProvider, Typography, createTheme } from '@mui/material';
import { useAppDispatch, useAppSelector } from 'src/hooks/hooks';
import { useEffect, useState } from 'react';
import { fetchproducts } from 'src/redux/services/productServices';
import ProductCard from './ProductCard';
import AddIcon from '@mui/icons-material/Add';
import FilterAltIcon from '@mui/icons-material/FilterAlt';
import StarIcon from '@mui/icons-material/Star';
const theme = createTheme({
  palette: {
    primary: {
      main: '#2196F3',
    },
  },
});
const ProductList = () => {
  // const theme = useTheme()
  const dispatch = useAppDispatch();
  const Productslist = useAppSelector(state => state.products?.productlist?.results);
  useEffect(() => {
    handleOnClick()
  }, []);
  const handleOnClick = () => {
    dispatch(fetchproducts({}));
  };
  const [search, setSearch] = useState<String>('')

  const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearch(event.target.value)
    console.log(event.target.value)
  };

  const handleFilterChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    // Handle filter dropdown change
  };

  const handleAddDetails = () => {
    // Handle adding form details
  };
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);

  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'filter-popover' : undefined;

  return (
    <ThemeProvider theme={theme}>
      <Box>
        <Box sx={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'flex-start',
          gap: 'var(--1, 8px)', // Assuming you have a CSS variable defined for gap
          flex: '1 0 0',
        }}>
          <Breadcrumbs aria-label="breadcrumb">
            <Link
              underline="hover"
              color="inherit"
              href="/"
            >
              Dashboard
            </Link>
            <Typography color="text.primary">Products list</Typography>
          </Breadcrumbs>
          <Typography variant='h4' sx={{ alignSelf: 'stretch', fontSize: '35px', fontWeight: 400, lineHeight: '41.99px' }}>Products List</Typography>
        </Box>
        <Box sx={{
          display: 'flex',
          padding: '16px 0px',
          alignItems: 'center',
          gap: '16px',
          alignSelf: 'stretch',
        }}>

          <Box sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 'var(--2, 16px)', 
            flex: '1 0 0',
          }}>
            <TextField sx={{ width: '300px', display: 'flex', alignItems: 'flex-start' }} variant="outlined" placeholder='Name' label="Search" onChange={handleSearch} />
            <FormControl fullWidth sx={{ display: 'flex', width: '220px' }}>
              <InputLabel id="demo-simple-select-label" sx={{ background: '#F4F5FA', paddingRight: '3px' }}>Catogories</InputLabel>
              <Select
                label="Filter"
                defaultValue="All"
                onChange={handleFilterChange}
                variant="outlined"
              >
                <MenuItem value="">All</MenuItem>
                <MenuItem value="option1">Option 1</MenuItem>
                <MenuItem value="option2">Option 2</MenuItem>
              </Select>
            </FormControl>
            <IconButton
              color='default' size='medium' onClick={handleClick}>
              <FilterAltIcon />
            </IconButton>
          </Box>
          <Button variant="contained" endIcon={<AddIcon />} onClick={handleAddDetails}>REQUEST new product</Button>
        </Box>

        <Box sx={{ gap: '24px', flexDirection: 'row', display: 'flex', flex: 1, flexWrap: 'wrap', alignItems: 'flex-start' }}>
          {Productslist?.map((product, index) => (
            <ProductCard
              key={index}
              product={product}
              handleOnClick={handleOnClick}
            />
          ))}
        </Box>
        <Popover
          id={id}
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'right',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'right',
          }}
        >
          <Box sx={{ padding: '20px', minWidth: '250px', flexDirection: 'column', display: 'flex' }}>
            <Typography variant="h6">Price Range</Typography>
            <Slider
              aria-label="Price Range"
              defaultValue={[100, 1000]}
              valueLabelDisplay="auto"
              step={100}
              marks
              min={100}
              max={1000}
            />
            <Typography variant="h6">Discount Range</Typography>
            <FormControlLabel control={<Checkbox />} label="0 - 20%" />
            <FormControlLabel control={<Checkbox />} label="21 - 30%" />
            <FormControlLabel control={<Checkbox />} label="31 - 40%" />
            <FormControlLabel control={<Checkbox />} label="41 - 50%" />
            <FormControlLabel control={<Checkbox />} label="51 - 80%" />
            <FormControlLabel control={<Checkbox />} label="81 - 100%" />
            <Typography variant="h6">Customer Rating</Typography>
            <FormControlLabel control={<><Checkbox /><StarIcon sx={{ color: '#FFB400', margin: '5px' }} /></>} label="5 Star" />
            <FormControlLabel control={<><Checkbox /><StarIcon sx={{ color: '#FFB400', margin: '5px' }} /></>} label="4 Star" />
            <FormControlLabel control={<><Checkbox /><StarIcon sx={{ color: '#FFB400', margin: '5px' }} /></>} label="3 Star" />
            <FormControlLabel control={<><Checkbox /><StarIcon sx={{ color: '#FFB400', margin: '5px' }} /></>} label="2 Star" />
            <FormControlLabel control={<><Checkbox /><StarIcon sx={{ color: '#FFB400', margin: '5px' }} /></>} label="1 Star" />
          </Box>
        </Popover>
      </Box>
    </ThemeProvider>
  );
};

export default ProductList;











D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\pages\productlist\index.tsx

















import { createAsyncThunk } from "@reduxjs/toolkit";
import router from "next/router";
import { corpnodeApi, urlGenarator } from "./commonAxios";

// Define async thunks for API calls
export const fetchproducts = createAsyncThunk(
    'fetch/productlist',
    async (userData: any, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post('/corp_Product/get', userData);
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const fetchcatogories = createAsyncThunk(
    'fetch/categorieslist',
    async ({ userData, params }, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.get(urlGenarator('/corpCategory/get',params), userData);
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            console.log(response,'22222222222222222222222')
            return response.data;
        } catch (error: any) {
            console.log(error,'3333333333333333333333333333333333333')
            return rejectWithValue({ message: error.message });
        }
    }
);
export const cartproductcheck = createAsyncThunk(
    'fetch/cartproductscheck',
    async (userData: any, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post('/corpCart/checkUserCartAvail', userData);
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
             return rejectWithValue({ message: error.message });
        }
    }
);
export const createWishlist = createAsyncThunk(
    'create/createwishlist',
    async (userData, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/corpWishList/create`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const logoupload = createAsyncThunk(
    'create/logoupload',
    async (userData, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/productLogo/create`, userData);
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error) {
        }
    }
);
export const WishListdelete = createAsyncThunk(
    'auth/deletewishlist',
    async (userData, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/corpWishList/deleteByUserProductId`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const getwislists = createAsyncThunk(
    'auth/wishlistget',
    async ({ userData, callBackLikeData }, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/corpWishList/getByUserProductId`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            callBackLikeData(response.data)
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const getuploadedlogosdata = createAsyncThunk(
    'auth/logosdataget',
    async ({ userData, callBackLikeData }, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/productLogo/get`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            callBackLikeData(response.data)
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const fetchsingleproductDetails = createAsyncThunk(
    'fetch/productdetails',
    async (userData: any, { rejectWithValue }) => {
        try {
            // Make your API call here to sign up the user
            const response = await corpnodeApi.post('/corp_Product/detailsGet', userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);

export const getimages = createAsyncThunk(
    'auth/imagesget',
    async ({ userData, callBackLikeData }, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/corp_Product_Image/get`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            callBackLikeData(response.data)
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const Urlgenrator = createAsyncThunk(
    'auth/imageurlget',
    async ({ userData, callBackLikeData }, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/FileUpload/upload`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            callBackLikeData(response.data)
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const fetchreviews = createAsyncThunk(
    'fetch/reviewlist',
    async (userData: any, { rejectWithValue }) => {
        try {
            // Make your API call here to sign up the user
            const response = await corpnodeApi.post('/corpProductReviewRating/get', userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);
export const createcart = createAsyncThunk(
    'create/createcart',
    async (userData, { rejectWithValue }) => {
        try {
            const response = await corpnodeApi.post(`/corpCart/create`, userData)
            if (response.status < 200 || response.status >= 300) {
                const errorData = await response.data;
                return rejectWithValue(errorData);
            }
            return response.data;
        } catch (error: any) {
            return rejectWithValue({ message: error.message });
        }
    }
);













D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\redux\services\productServices.ts




















// authSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { signInUser, signUpUser } from '../services/authServices';
import { cartproductcheck, createcart, createWishlist, fetchcatogories, fetchproducts, fetchreviews, fetchsingleproductDetails, getimages, getuploadedlogosdata, getwislists, logoupload, Urlgenrator, WishListdelete } from '../services/productServices';


// Define initial state
interface AuthState {
    user: any;
    isLoading: boolean;
    error: string | null;
}

const initialState: AuthState = {
    user: null,
    isLoading: false,
    error: null,
};

// Create a slice for authentication
const productSlice = createSlice({
    name: 'products',
    initialState,
    reducers: {},
    extraReducers: (builder: any) => {
        builder
            .addCase(fetchproducts.pending, (state: any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(fetchproducts.fulfilled, (state: any, action: PayloadAction<AuthState>) => {
                state.isLoading = false;
                state.error = null;
                state.productlist = action.payload; // Store the user data after successful signup
            })
            .addCase(fetchproducts.rejected, (state: any, action: PayloadAction<{ message: string }>) => {
                state.isLoading = false;
                state.error = action.payload.message;
            })
            .addCase(fetchcatogories.pending, (state: any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(fetchcatogories.fulfilled, (state: any, action: PayloadAction<AuthState>) => {
                state.isLoading = false;
                state.error = null;
                state.categorieslist = action.payload; // Store the user data after successful signup
            })
            .addCase(fetchcatogories.rejected, (state: any, action: PayloadAction<{ message: string }>) => {
                state.isLoading = false;
                state.error = action.payload.message;
            })
            .addCase(cartproductcheck.pending, (state: any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(cartproductcheck.fulfilled, (state: any, action: PayloadAction<AuthState>) => {
                state.isLoading = false;
                state.error = null;
                state.cartproductscheck = action.payload; // Store the user data after successful signup
            })
            .addCase(cartproductcheck.rejected, (state: any, action: PayloadAction<{ message: string }>) => {
                state.isLoading = false;
                state.error = action.payload.message;
            })
            .addCase(createWishlist.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(createWishlist.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.wishlistadd = action.payload;
            })
            .addCase(createWishlist.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(logoupload.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(logoupload.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.logoupload = action.payload;
            })
            .addCase(logoupload.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(getwislists.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(getwislists.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.wishlistfilter = action.payload;

            })
            .addCase(getwislists.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(getuploadedlogosdata.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(getuploadedlogosdata.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.logosdataget = action.payload;

            })
            .addCase(getuploadedlogosdata.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(WishListdelete.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(WishListdelete.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.deletewishlist = action.payload;
            })
            .addCase(WishListdelete.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(fetchsingleproductDetails.pending, (state: any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(fetchsingleproductDetails.fulfilled, (state: any, action: PayloadAction<AuthState>) => {
                state.isLoading = false;
                state.error = null;
                state.productdetails = action.payload; // Store the user data after successful signup
            })
            .addCase(fetchsingleproductDetails.rejected, (state: any, action: PayloadAction<{ message: string }>) => {
                state.isLoading = false;
                state.error = action.payload.message;
            }) 
            .addCase(getimages.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(getimages.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.imagesget = action.payload;

            })
            .addCase(getimages.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(Urlgenrator.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(Urlgenrator.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.imageurlget = action.payload;

            })
            .addCase(Urlgenrator.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            })
            .addCase(fetchreviews.pending, (state: any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(fetchreviews.fulfilled, (state: any, action: PayloadAction<AuthState>) => {
                state.isLoading = false;
                state.error = null;
                state.reviewlist = action.payload; // Store the user data after successful signup
            })
            .addCase(fetchreviews.rejected, (state: any, action: PayloadAction<{ message: string }>) => {
                state.isLoading = false;
                state.error = action.payload.message;
            })
            .addCase(createcart.pending, (state:any) => {
                state.isLoading = true;
                state.error = null;
            })
            .addCase(createcart.fulfilled, (state:any, action:any) => {
                state.isLoading = false;
                state.error = null;
                state.createcart = action.payload;
            })
            .addCase(createcart.rejected, (state:any, action:any) => {
                state.isLoading = false;
                state.error = action.payload?.message;
            });
    },
});

export default productSlice.reducer;







D:\Esi_Cashback\new-git\meepaisa-corp-ts-nextjs-web\src\redux\slice\productSlice.ts






