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) => { }; const [selectedAddress, setSelectedAddress] = useState(''); 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 ( {steps.map((label, index) => { const labelProps: { optional?: React.ReactNode; error?: boolean; } = {}; return ( {label} ); })} Address handleCheckboxChanges(e)}> + Add new address {addresslistData?.results.map((item, index) => ( handleAddressSelect(item.id)} > } label={''} /> {item.Address} {item.Land_Mark},{item.State},{item.Zip_Code} {index !== addresslistData?.results.length - 1 && } ))} Products {cartlistData?.results?.map((item, index) => ( {item.Product_Name} {item.Selling_Price} ))} {/* */} Total {/* totalprice */} {queryParams?.totalprice} {/* {cartlistData?.results.reduce((total, item) => total + parseFloat(item.Selling_Price), 0).toFixed(2)} */} ); } 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(''); 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) => { 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) => { setSelectedOption(event.target.value); router.push(`/doordtep-deliver?id=${event.target.value}`); }; const handleCloseSnackar = () => { setStateSnackbar({ ...opensnakebar, opens: false }); }; return ( Cart ({cartlistData?.results?.length} items) {cartlistData?.results.map((item, index) => ( {item.Product_Name} {item.Selling_Price} {item.Product_Price} ({item.Discount}% off) {item.Short_Description} { handleEditChange(item.Product_Id); }}> { handleClickDelete(item._id); }}> {index !== cartlistData?.results?.length - 1 && } ))} Products {cartlistData?.results.map((item, index) => ( {item.Product_Name} {item.Selling_Price} ))} {/* */} {cartlistData?.results ? Total {cartlistData.results.reduce((total, item) => total + parseFloat(item.Selling_Price), 0).toFixed(2)} : null} Select Delivery Mode } label="Deliver to company" sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', '& .MuiFormControlLabel-label': { marginTop: '8px', // Adjust as needed }, }} onChange={handleCompanyChange} checked={selectedOption === 'Company'} /> } label="Doorstep delivery" sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', '& .MuiFormControlLabel-label': { marginTop: '8px', // Adjust as needed }, }} onChange={handleDoorstepChange} checked={selectedOption === 'Doorstep'} /> {cartDaleteAction?.message} ); } 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([]); // State to hold selected department IDs const [isUserChecked, setIsUserChecked] = useState(false); const [selectedusers, setSelectedUsers] = useState([]); // State to hold selected department IDs const [page, setPage] = useState(0) const [emppage, setEmpPage] = useState(0) // setTotalPriceSum(totalPriceSum) const [rowsPerPage, setRowsPerPage] = useState(5) const [totalPriceSum, setTotalPriceSum] = useState(0) const [emprowsPerPage, setEmpRowsPerPage] = useState(5) const [searchValue, setSearchValue] = useState(''); const [filterValue, setFilterValue] = useState(''); 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(''); 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) => { 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) => { 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) => { 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) => { 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) => { 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) => { 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 ( {/* {updatedSelectedDepartments.length > 0 || selectedusers.length > 0 ? null : */} 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 ? : null} {updatedSelectedDepartments.length > 0 || selectedusers.length > 0 ? QUANTITY SELECTED {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0} : null} Add more {/* } */} {cartlistData?.results.map((item, index) => ( {item.Product_Name} {item.Selling_Price} {item.Product_Price} ({item.Discount}% off) {item.Short_Description} {/* */} 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}` } */} { cartsizegetAction?.results.find(product => product.Cart_Id == item._id) ? QUANTITY SELECTED {cartsizegetAction?.results.reduce((total, cartItem) => { if (cartItem.Cart_Id === item._id) { return total + cartItem.Quantity; } return total; }, 0)} : null} { handleEditChange(item.Product_Id); }}> { handleClickDelete(item._id); }}> {index !== cartlistData?.results?.length - 1 && } ))} Products {cartlistData?.results.map((item, index) => ( {item.Product_Name} Quantity : {(totalEmployeeCount + selectedusers.length) + cartsizegetAction?.results.reduce((total, cartItem) => { if (cartItem.Cart_Id === item._id) { return (total + cartItem.Quantity); } return total; }, 0) || 0} {item.Selling_Price} ))} Total {totalPriceSum.toFixed(2)} DEPARTMENT QUANTITY SELECTED {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0} {columns.map(column => ( column.label === 'Department Name' ? ( handleCheckboxChange(isChecked ? '' : 'ALL')} // Define function to handle header checkbox change /> {column.label} ) : ( {column.label} ) ))} {DepartmentsGetAction?.results.map(row => { return ( {columns.map((column, columnIndex) => { const value = row[column.id]; return ( {column.id === 'Department_Name' ? ( handleCheckboxChange(row)} /> handleCheckboxforEMPChanges(row.Department_Id)} style={{ cursor: 'pointer' }} sx={{ color: '#2196F3', fontSize: '14px', fontWeight: 400, lineHeight: '20.02px', letterSpacing: '0.17px' }}> {value} {/* {value} */} ) : column.id === 'Action' ? ( ) : ( column.format && typeof value === 'number' ? column.format(value) : value )} ); })} ); })}
DEPARTMENT QUANTITY SELECTED {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0} {usersdata.map(column => ( column.label === 'user Name' ? ( // handleCheckboxUserChange(isUserChecked ? '' : 'ALL')} // Define function to handle header checkbox change /> {/* */} {column.label} {/* */} // ) : ( {column.label} ) ))} {EmployelistAction?.results.map(row => { return ( {usersdata.map((column, columnIndex) => { const value = row[column.id]; return ( {column.id === 'Full_Name' ? ( handleCheckboxUserChange(row._id)} /> img': { objectFit: 'contain', }, }} /> {value} ) : ( column.format && typeof value === 'number' ? column.format(value) : value )} ); })} ); })}
Enter quantity {productssizesAction && productssizesAction.map((size, index) => ( {size && size.id && ( {`${size.Size}`} handleDecrement(size.Product_Id, size.id)}> {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} handleIncrement(size.Product_Id, size.id)}> )} ))} {cartDaleteAction?.message}
); } 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([]); // State to hold selected department IDs const [isUserChecked, setIsUserChecked] = useState(false); const [selectedusers, setSelectedUsers] = useState([]); // State to hold selected department IDs const [page, setPage] = useState(0) const [emppage, setEmpPage] = useState(0) const [rowsPerPage, setRowsPerPage] = useState(5) const [emprowsPerPage, setEmpRowsPerPage] = useState(5) const [searchValue, setSearchValue] = useState(''); const [filterValue, setFilterValue] = useState(''); 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(''); 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) => { 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) => { 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) => { 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) => { 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) => { 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) => { 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 ( Bag ({cartlistData?.results?.length} items) {updatedSelectedDepartments?.length > 0 || selectedusers?.length > 0 ? Select more from list : Select from list } {cartlistData?.results.map((item, index) => ( {item.Product_Name} {item.Selling_Price} {item.Product_Price} ({item.Discount}% off) {item.Short_Description} { handleEditChange(item.Product_Id); }}> { handleClickDelete(item._id); }}> {index !== cartlistData?.results?.length - 1 && } ))} Products {cartlistData?.results.map((item, index) => ( {item.Product_Name} Quantity : {totalEmployeeCount + selectedusers.length} {item.Selling_Price} ))} Total {totalPriceSum?.toFixed(2)} DEPARTMENT QUANTITY SELECTED {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0} {columns.map(column => ( column.label === 'Department Name' ? ( handleCheckboxChange(isChecked ? '' : 'ALL')} // Define function to handle header checkbox change /> {column.label} ) : ( {column.label} ) ))} {DepartmentsGetAction?.results.map(row => { return ( {columns.map((column, columnIndex) => { const value = row[column.id]; return ( {column.id === 'Department_Name' ? ( handleCheckboxChange(row)} /> handleCheckboxforEMPChanges(row.Department_Id)} style={{ cursor: 'pointer' }} sx={{ color: '#2196F3', fontSize: '14px', fontWeight: 400, lineHeight: '20.02px', letterSpacing: '0.17px' }}> {value} {/* {value} */} ) : column.id === 'Action' ? ( ) : ( column.format && typeof value === 'number' ? column.format(value) : value )} ); })} ); })}
DEPARTMENT QUANTITY SELECTED {totalEmployeeCount + selectedusers.length ? totalEmployeeCount + selectedusers.length : 0} {usersdata.map(column => ( column.label === 'user Name' ? ( // handleCheckboxUserChange(isUserChecked ? '' : 'ALL')} // Define function to handle header checkbox change /> {/* */} {column.label} {/* */} // ) : ( {column.label} ) ))} {EmployelistAction?.results.map(row => { return ( {usersdata.map((column, columnIndex) => { const value = row[column.id]; return ( {column.id === 'Full_Name' ? ( handleCheckboxUserChange(row._id)} /> img': { objectFit: 'contain', }, }} /> {value} ) : ( column.format && typeof value === 'number' ? column.format(value) : value )} ); })} ); })}
{cartDaleteAction?.message}
); } 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('') const handleSearch = (event: React.ChangeEvent) => { 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(null); const handleClick = (event: React.MouseEvent) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const open = Boolean(anchorEl); const id = open ? 'filter-popover' : undefined; return ( Dashboard Products list Products List Catogories {Productslist?.map((product, index) => ( ))} Price Range Discount Range } label="0 - 20%" /> } label="21 - 30%" /> } label="31 - 40%" /> } label="41 - 50%" /> } label="51 - 80%" /> } label="81 - 100%" /> Customer Rating } label="5 Star" /> } label="4 Star" /> } label="3 Star" /> } label="2 Star" /> } label="1 Star" /> ); }; 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) => { 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) => { 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) => { 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) => { 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) => { 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