principal distributor create with address and salescoordinator attendance system create

This commit is contained in:
Sibunnayak 2024-07-19 12:22:45 +05:30
parent 72a3b40cfd
commit 0146a7a3d2
12 changed files with 532 additions and 471 deletions

View File

@ -38,6 +38,8 @@
"@coreui/utils": "^1.3.1", "@coreui/utils": "^1.3.1",
"@emotion/react": "^11.11.1", "@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0", "@emotion/styled": "^11.11.0",
"@headlessui/react": "^2.1.2",
"@heroicons/react": "^2.1.5",
"@material-ui/core": "^4.12.4", "@material-ui/core": "^4.12.4",
"@material-ui/data-grid": "^4.0.0-alpha.37", "@material-ui/data-grid": "^4.0.0-alpha.37",
"@mui/icons-material": "^5.14.14", "@mui/icons-material": "^5.14.14",

View File

@ -83,13 +83,13 @@ const _nav = [
to: "/salescoordinators", to: "/salescoordinators",
group: "SalesCoOrdinator", group: "SalesCoOrdinator",
}, },
// { {
// component: CNavItem, component: CNavItem,
// name: "Attendance", name: "Attendance",
// icon: <CIcon icon={cilUser} customClassName="nav-icon" />, icon: <CIcon icon={cilUser} customClassName="nav-icon" />,
// to: "/attendance/today", to: "/attendance/today",
// group: "AttendanceSalesCoOrdinator", group: "AttendanceSalesCoOrdinator",
// }, },
// { // {
// component: CNavGroup, // component: CNavGroup,
// name: "Orders", // name: "Orders",

View File

@ -31,7 +31,7 @@ const AppSidebar = () => {
const [userdata, setUserData] = useState(null); const [userdata, setUserData] = useState(null);
const token = isAutheticated(); const token = isAutheticated();
console.log("userDatt", userdata); // console.log("userDatt", userdata);
useEffect(() => { useEffect(() => {
const getUser = async () => { const getUser = async () => {

View File

@ -15,8 +15,8 @@ import { cibGmail } from "@coreui/icons";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";
const setupAxios = () => { const setupAxios = () => {
axios.defaults.baseURL = "http://localhost:5000"; // axios.defaults.baseURL = "http://localhost:5000";
// axios.defaults.baseURL = "https://cheminova-api-2.onrender.com"; axios.defaults.baseURL = "https://cheminova-api-2.onrender.com";
axios.defaults.headers = { axios.defaults.headers = {
"Cache-Control": "no-cache,no-store", "Cache-Control": "no-cache,no-store",

View File

@ -1,101 +1,87 @@
import React, { useState } from "react"; import React, { useState, useEffect } from "react";
import { import {
TextField, TextField,
Button, Button,
Card, Card,
FormControl,
Grid, Grid,
Typography,
FormHelperText, FormHelperText,
OutlinedInput, Autocomplete,
Box, CircularProgress,
} from "@mui/material"; } from "@mui/material";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import axios from "axios"; import axios from "axios";
import { isAutheticated } from "src/auth"; import { isAutheticated } from "src/auth";
import { City, State } from "country-state-city";
const styles = {
formStyle: {
fontWeight: "700",
fontSize: "12px",
fontFamily: "inter",
marginBottom: "3px",
marginLeft: "0",
},
topRightButton: {
position: "absolute",
top: "10px",
right: "10px",
},
};
const AddPrincipalDistributor = () => { const AddPrincipalDistributor = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const token = isAutheticated();
const [user, setUser] = useState({ const [user, setUser] = useState({
name: "", name: "",
email: "", email: "",
password: "",
phone: "", phone: "",
}); });
const [id, setUserId] = useState("");
const token = isAutheticated();
const [loading, setLoading] = useState(false);
const [data, setData] = useState({ const [data, setData] = useState({
street: "", street: "",
city: "", city: "",
state: "", state: "",
postalCode: "", postalCode: "",
country: "", country: "India",
company_name: "", tradeName: "",
gst_number: "", gstNumber: "",
panNumber: "",
}); });
const handleChange = (e) => { const [loading, setLoading] = useState(false);
setData((prev) => ({ ...prev, [e.target.name]: e.target.value })); const [stateOptions, setStateOptions] = useState([]);
}; const [cityOptions, setCityOptions] = useState([]);
const [selectedState, setSelectedState] = useState(null);
const [selectedCity, setSelectedCity] = useState(null);
const handleInputChanges = (e) => { useEffect(() => {
const fetchStates = async () => {
const states = State.getStatesOfCountry("IN").map((state) => ({
label: state.name,
value: state.isoCode,
}));
setStateOptions(states);
};
fetchStates();
}, []);
useEffect(() => {
const fetchCities = async () => {
if (selectedState) {
const cities = City.getCitiesOfState("IN", selectedState.value).map(
(city) => ({
label: city.name,
value: city.name,
})
);
setCityOptions(cities);
}
};
fetchCities();
}, [selectedState]);
const handleInputChange = (e) => {
setUser({ ...user, [e.target.name]: e.target.value }); setUser({ ...user, [e.target.name]: e.target.value });
}; };
const handleAddressSubmit = (e) => { const handleDataChange = (e) => {
e.preventDefault(); setData({ ...data, [e.target.name]: e.target.value });
if ( };
data.street === "" ||
data.city === "" || const handleStateChange = (event, newValue) => {
data.state === "" || setSelectedState(newValue);
data.postalCode === "" || };
data.country === ""
) { const handleCityChange = (event, newValue) => {
toast.error("Please fill all mandatory fields."); setSelectedCity(newValue);
return;
}
setLoading(true);
axios
.post(
`/api/shipping/address/admin/new/${id}`,
{ ...data },
{
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
)
.then((res) => {
setLoading(false);
navigate("/principal-distributor");
toast.success(res.data.message ? res.data.message : "Address Added!");
})
.catch((error) => {
setLoading(false);
toast.error(
error.response.data.message
? error.response.data.message
: "Something went wrong!"
);
});
}; };
const generatePassword = (name, email) => { const generatePassword = (name, email) => {
@ -119,25 +105,51 @@ const AddPrincipalDistributor = () => {
const handleFormSubmit = async (e) => { const handleFormSubmit = async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
if (!user.name || !user.email || !user.phone) { if (
!user.name ||
!user.email ||
!user.phone ||
!selectedState ||
!selectedCity ||
!data.street ||
!data.postalCode
) {
throw new Error("Fill all fields!"); throw new Error("Fill all fields!");
} }
setLoading(true);
const generatedPassword = generatePassword(user.name, user.email); const generatedPassword = generatePassword(user.name, user.email);
setUser({ ...user, password: generatedPassword });
const response = await axios.post("/api/v1/user/register", { const userResponse = await axios.post("/api/v1/user/register", {
...user, ...user,
password: generatedPassword, password: generatedPassword,
}); });
if (response.status === 201) {
toast.success("User Added Successfully"); if (userResponse.status === 201) {
// console.log(response.data); const userId = userResponse.data.userId;
setUserId(response.data.userId);
const addressResponse = await axios.post(
`/api/shipping/address/admin/new/${userId}`,
{
...data,
state: selectedState.label, // Send selected state label
city: selectedCity.label, // Send selected city label
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
setLoading(false);
if (addressResponse.status === 201) {
toast.success("Principal Distributor and Address Added Successfully");
navigate("/principal-distributor");
}
} }
} catch (error) { } catch (error) {
console.log(error.response.data.message); setLoading(false);
toast.error(error.response.data.message); console.error("Error adding principal distributor and address:", error);
toast.error(error.response?.data?.message || "Something went wrong!");
} }
}; };
@ -154,204 +166,196 @@ const AddPrincipalDistributor = () => {
variant="outlined" variant="outlined"
color="secondary" color="secondary"
onClick={handleCancel} onClick={handleCancel}
sx={styles.topRightButton} sx={{ position: "absolute", top: "10px", right: "10px" }}
> >
Cancel Cancel
</Button> </Button>
<Typography variant="h5" sx={{ mb: 3 }}>
<form style={{ marginBottom: "2rem" }} onSubmit={handleFormSubmit}> Add Principal Distributor
<TextField </Typography>
id="name" <form onSubmit={handleFormSubmit}>
required <Typography variant="h6" sx={{ mb: 2 }}>
type="text" Basic Information
sx={{ marginBottom: "2rem", width: "50%" }} </Typography>
name="name" <Grid container spacing={2} sx={{ mb: 2 }}>
value={user.name} <Grid item xs={12} sm={4}>
label="Name" <TextField
variant="outlined" id="name"
onChange={handleInputChanges} required
/> type="text"
<br /> fullWidth
<TextField name="name"
id="email" value={user.name}
type="email" label="Name"
sx={{ mb: "2rem", width: "50%" }} variant="outlined"
required onChange={handleInputChange}
name="email" />
value={user.email}
label="Email"
variant="outlined"
onChange={handleInputChanges}
/>
<br />
<TextField
id="phone"
type="tel"
sx={{ mb: "2rem", width: "50%" }}
required
name="phone"
value={user.phone}
label="Mobile Number"
variant="outlined"
onChange={handleInputChanges}
/>
<br />
<Button variant="contained" disabled={id?.length > 0} type="submit">
Add Principal Distributor
</Button>
<br />
</form>
<form onSubmit={handleAddressSubmit}>
<Grid container spacing={2}>
<Grid item xs={12}>
<FormControl variant="outlined" fullWidth>
<FormHelperText
id="outlined-weight-helper-text"
sx={styles.formStyle}
>
STREET ADDRESS*
</FormHelperText>
<OutlinedInput
size="small"
id="outlined-adornment-weight"
placeholder="Street Address"
aria-describedby="outlined-weight-helper-text"
name="street"
required
type="text"
onChange={handleChange}
/>
</FormControl>
</Grid> </Grid>
<Grid item xs={12}> <Grid item xs={12} sm={4}>
<FormControl variant="outlined" fullWidth> <TextField
<FormHelperText id="email"
id="outlined-weight-helper-text" required
sx={styles.formStyle} type="email"
> fullWidth
COUNTRY* name="email"
</FormHelperText> value={user.email}
<OutlinedInput label="Email"
size="small" variant="outlined"
id="outlined-adornment-weight" onChange={handleInputChange}
placeholder="Country" />
aria-describedby="outlined-weight-helper-text"
name="country"
required
type="text"
onChange={handleChange}
/>
</FormControl>
</Grid> </Grid>
<Grid item xs={12}> <Grid item xs={12} sm={4}>
<FormControl fullWidth variant="outlined"> <TextField
<FormHelperText id="phone"
id="outlined-weight-helper-text" required
sx={styles.formStyle} type="text"
> fullWidth
TOWN CITY* name="phone"
</FormHelperText> value={user.phone}
<OutlinedInput label="Phone Number"
size="small" variant="outlined"
id="outlined-adornment-weight" onChange={handleInputChange}
placeholder="Town City" />
aria-describedby="outlined-weight-helper-text"
name="city"
required
type="text"
onChange={handleChange}
/>
</FormControl>
</Grid>
<Grid item xs={6}>
<FormControl variant="outlined" fullWidth>
<FormHelperText
id="outlined-weight-helper-text"
sx={styles.formStyle}
>
STATE*
</FormHelperText>
<OutlinedInput
size="small"
id="outlined-adornment-weight"
placeholder="State"
aria-describedby="outlined-weight-helper-text"
name="state"
required
type="text"
onChange={handleChange}
/>
</FormControl>
</Grid>
<Grid item xs={6}>
<FormControl variant="outlined" fullWidth>
<FormHelperText
id="outlined-weight-helper-text"
sx={styles.formStyle}
>
ZIP CODE*
</FormHelperText>
<OutlinedInput
size="small"
id="outlined-adornment-weight"
placeholder="Zip Code"
aria-describedby="outlined-weight-helper-text"
name="postalCode"
required
type="number"
onChange={handleChange}
/>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl variant="outlined" fullWidth>
<FormHelperText
id="outlined-weight-helper-text"
sx={styles.formStyle}
>
Company Name
</FormHelperText>
<OutlinedInput
size="small"
id="outlined-adornment-weight"
placeholder="Company name"
aria-describedby="outlined-weight-helper-text"
name="company_name"
type="text"
onChange={handleChange}
/>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl variant="outlined" fullWidth>
<FormHelperText
id="outlined-weight-helper-text"
sx={styles.formStyle}
>
GST Number
</FormHelperText>
<OutlinedInput
size="small"
id="outlined-adornment-weight"
placeholder="GST Number"
aria-describedby="outlined-weight-helper-text"
name="gst_number"
type="text"
onChange={handleChange}
/>
</FormControl>
</Grid>
<Grid item xs={12}>
<Button
variant="contained"
disabled={!id?.length > 0}
type="submit"
>
Submit
</Button>
</Grid> </Grid>
</Grid> </Grid>
<Typography variant="h6" sx={{ mb: 2 }}>
Business Details
</Typography>
<Grid container spacing={2} sx={{ mb: 2 }}>
<Grid item xs={12} sm={4}>
<TextField
id="panNumber"
required
type="text"
fullWidth
name="panNumber"
value={data.panNumber}
label="PAN Number"
variant="outlined"
onChange={handleDataChange}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
id="tradeName"
// required
type="text"
fullWidth
name="tradeName"
value={data.tradeName}
label="Trade Name"
variant="outlined"
onChange={handleDataChange}
/>
</Grid>
<Grid item xs={12} sm={4}>
<TextField
id="gstNumber"
// required
type="text"
fullWidth
name="gstNumber"
value={data.gstNumber}
label="GST Number"
variant="outlined"
onChange={handleDataChange}
/>
</Grid>
<Typography variant="h6" sx={{ mb: 2 }}>
Address
</Typography>
<Grid item xs={12} sm={4}>
<TextField
id="country"
required
type="text"
fullWidth
name="country"
value={data.country}
label="Country"
variant="outlined"
disabled
/>
</Grid>
<Grid item xs={12} sm={4}>
<Autocomplete
id="state"
options={stateOptions}
getOptionLabel={(option) => option.label}
value={selectedState}
onChange={handleStateChange}
renderInput={(params) => (
<TextField
{...params}
fullWidth
label="State"
variant="outlined"
error={!selectedState}
helperText={!selectedState ? "Select a state" : null}
/>
)}
/>
</Grid>
<Grid item xs={12} sm={4}>
<Autocomplete
id="city"
options={cityOptions}
getOptionLabel={(option) => option.label}
value={selectedCity}
onChange={handleCityChange}
renderInput={(params) => (
<TextField
{...params}
fullWidth
label="City"
variant="outlined"
error={!selectedCity}
helperText={!selectedCity ? "Select a city" : null}
/>
)}
/>
</Grid>
<Grid item xs={6}>
<TextField
id="street"
required
type="text"
fullWidth
name="street"
value={data.street}
label="Street"
variant="outlined"
onChange={handleDataChange}
/>
</Grid>
<Grid item xs={6}>
<TextField
id="postalCode"
required
type="text"
fullWidth
name="postalCode"
value={data.postalCode}
label="Postal Code"
variant="outlined"
onChange={handleDataChange}
/>
</Grid>
</Grid>
<Button
type="submit"
disabled={loading}
variant="contained"
color="primary"
>
{loading ? (
<CircularProgress size={24} />
) : (
"Create Principal Distributor"
)}
</Button>
</form> </form>
</Card> </Card>
</div> </div>

View File

@ -192,8 +192,9 @@ const principalDistributor = () => {
style={{ background: "rgb(140, 213, 213)" }} style={{ background: "rgb(140, 213, 213)" }}
> >
<tr> <tr>
<th>Principal Distributor Name</th> <th>Unique Id </th>
<th>Unique Id </th> <th>Name</th>
<th>Email</th>
{/* <th>Profile Image</th> */} {/* <th>Profile Image</th> */}
<th>Date Registered</th> <th>Date Registered</th>
@ -220,9 +221,9 @@ const principalDistributor = () => {
showData.map((user, i) => { showData.map((user, i) => {
return ( return (
<tr key={i}> <tr key={i}>
<td>{user.uniqueId}</td>
<td className="text-start">{user.name}</td> <td className="text-start">{user.name}</td>
<td>{user._id}</td> <td>{user.email}</td>
<td className="text-start"> <td className="text-start">
{new Date(user.createdAt).toLocaleString( {new Date(user.createdAt).toLocaleString(
"en-IN", "en-IN",

View File

@ -137,48 +137,66 @@ const SinglePrincipalDistributorAllDetails = () => {
</div> </div>
</div> </div>
<div className="card" style={{ padding: "1rem" }}> <div className="card" style={{ padding: "1rem" }}>
<h5 style={{ fontWeight: "bold" }}>&bull; Customer Profile </h5> <h5 style={{ fontWeight: "bold" }}>&bull; Principal Distributor Profile </h5>
<div style={{ marginLeft: "1rem", marginTop: "1rem" }}> <div style={{ marginLeft: "1rem", marginTop: "1rem" }}>
<Typography style={{ fontWeight: "bold" }}> <Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Customer Name:<b> {user?.name}</b> Principal Distributor ID:
</Typography> <Typography component="span" style={{ fontWeight: "normal", fontSize: "1.2rem",marginLeft: "0.5rem" }}>
<Typography style={{ fontWeight: "bold" }}> {user?.uniqueId}
Customer ID:<b style={{ marginLeft: "1.5rem" }}> {user?._id}</b> </Typography>
</Typography> </Typography>
<Typography style={{ fontWeight: "bold" }}> <Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Date Registered : Name:
<b> <Typography component="span" style={{ fontWeight: "normal", fontSize: "1.2rem",marginLeft: "0.5rem"}}>
{" "} {user?.name}
{new Date(user?.createdAt).toLocaleString("en-IN", { </Typography>
weekday: "short", </Typography>
month: "short", <Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
day: "numeric", Mail:
year: "numeric", <Typography component="span" style={{ fontWeight: "normal", fontSize: "1.2rem" ,marginLeft: "0.5rem"}}>
hour: "numeric", {user?.email}
minute: "numeric", </Typography>
hour12: true, </Typography>
})} <Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
</b> Mobile Number:
</Typography> <Typography component="span" style={{ fontWeight: "normal", fontSize: "1.2rem" ,marginLeft: "0.5rem"}}>
<Typography style={{ fontWeight: "bold" }}> {user?.phone}
Last Purchase: </Typography>
<b style={{ marginLeft: "1.5rem" }}> </Typography>
{userOrder?.length > 0 <Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
? new Date(userOrder[0]?.createdAt).toLocaleString("en-IN", { Date Registered:
weekday: "short", <Typography component="span" style={{ fontWeight: "normal", fontSize: "1.2rem" ,marginLeft: "0.5rem"}}>
month: "short", {new Date(user?.createdAt).toLocaleString("en-IN", {
day: "numeric", weekday: "short",
year: "numeric", month: "short",
hour: "numeric", day: "numeric",
minute: "numeric", year: "numeric",
hour12: true, hour: "numeric",
}) minute: "numeric",
: userOrder hour12: true,
? "No Purchase" })}
: "Loading"} </Typography>
</b> </Typography>
</Typography> <Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
</div> Last Purchase:
<Typography component="span" style={{ fontWeight: "normal", fontSize: "1.2rem", marginLeft: "1.5rem" }}>
{userOrder?.length > 0
? new Date(userOrder[0]?.createdAt).toLocaleString("en-IN", {
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
})
: userOrder
? "No Purchase"
: "Loading"}
</Typography>
</Typography>
</div>
<div style={{ marginTop: "2rem" }}> <div style={{ marginTop: "2rem" }}>
<h5 style={{ fontWeight: "bold", marginBottom: "1rem" }}> <h5 style={{ fontWeight: "bold", marginBottom: "1rem" }}>
&bull; Addresses{" "} &bull; Addresses{" "}
@ -216,10 +234,10 @@ const SinglePrincipalDistributorAllDetails = () => {
<td className="text-start">{i + 1}</td> <td className="text-start">{i + 1}</td>
<td style={{ maxWidth: "400px" }}> <td style={{ maxWidth: "400px" }}>
<strong> <strong>
{address?.first_Name} {address?.last_name}, {address?.first_Name} {address?.last_name}
{address.company_name {address.company_name
? `${address.company_name},` ? `${address.company_name},`
: ""} : "No Company_Name "}
{address.gst_number ? `${address.gst_number},` : ""} {address.gst_number ? `${address.gst_number},` : ""}
{address?.phone_Number},{address?.street}, {address?.phone_Number},{address?.street},
{address?.city},{address?.state},{address?.country}, {address?.city},{address?.state},{address?.country},

View File

@ -3,7 +3,7 @@ import { CForm, CCol, CFormLabel, CContainer, CRow, CCardGroup, CCard, CCardBody
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import axios from 'axios' import axios from 'axios'
import { useNavigate } from 'react-router-dom' import { Navigate, useNavigate } from 'react-router-dom'
import { isAutheticated } from 'src/auth' import { isAutheticated } from 'src/auth'
const EditProfile = () => { const EditProfile = () => {
@ -115,7 +115,7 @@ const EditProfile = () => {
} }
} }
const handleCancle = () => { const handleCancle = () => {
history.push('/dashboard') Navigate("/dashboard");
} }
useEffect(() => { useEffect(() => {

View File

@ -81,6 +81,11 @@ const AddSalesCoOrdinator = () => {
} }
}; };
// Function to handle cancel button click
const handleCancel = () => {
navigate("/salescoordinators"); // Navigate to '/salescoordinators'
};
return ( return (
<div className="main-content"> <div className="main-content">
<div className="my-3 page-content"> <div className="my-3 page-content">
@ -89,6 +94,9 @@ const AddSalesCoOrdinator = () => {
<div className="col-12"> <div className="col-12">
<div className="page-title-box d-flex align-items-center justify-content-between"> <div className="page-title-box d-flex align-items-center justify-content-between">
<h4 className="mb-3">Add Sales Coordinator</h4> <h4 className="mb-3">Add Sales Coordinator</h4>
<Button variant="danger" onClick={handleCancel}>
Cancel
</Button>
</div> </div>
</div> </div>
</div> </div>

View File

@ -208,6 +208,7 @@ const SalesCoOrdinator = () => {
style={{ background: "#ecdddd" }} style={{ background: "#ecdddd" }}
> >
<tr> <tr>
<th>Unique Id </th>
<th className="text-start">Name</th> <th className="text-start">Name</th>
<th className="text-start">Mobile No.</th> <th className="text-start">Mobile No.</th>
<th className="text-start">Email</th> <th className="text-start">Email</th>
@ -228,6 +229,9 @@ const SalesCoOrdinator = () => {
salescoordinatorsData?.map((salescoordinator, i) => { salescoordinatorsData?.map((salescoordinator, i) => {
return ( return (
<tr key={i}> <tr key={i}>
<td className="text-start">
{salescoordinator?.uniqueId}
</td>
<td className="text-start"> <td className="text-start">
{salescoordinator?.name} {salescoordinator?.name}
</td> </td>

View File

@ -8,6 +8,7 @@ const WidgetsDropdown = lazy(() => import("../widgets/WidgetsDropdown.js"));
const Dashboard = () => { const Dashboard = () => {
//1 st //1 st
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
const [salescoordinator, setSalescoordinator] = useState([]);
const token = isAutheticated(); const token = isAutheticated();
const getAllUsers = async () => { const getAllUsers = async () => {
@ -19,39 +20,48 @@ const Dashboard = () => {
// console.log(res.data) // console.log(res.data)
setUsers(res.data.users); setUsers(res.data.users);
}; };
//2nd const getAllsalescoordinator = async () => {
const [category, setCategory] = useState([]); let res = await axios.get(`/api/salescoordinator/getAll/`, {
const getAllCategory = async () => {
let res = await axios.get(`/api/category/getCategories`, {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
}); });
// console.log(res.data); // console.log(res.data)
setCategory(res?.data?.categories); setSalescoordinator(res.data.total_data);
};
//3rd
const [product, setProduct] = useState([]);
const getAllProduct = async () => {
let res = await axios.get(`/api/product/getAll/user/`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setProduct(res?.data?.product);
};
// 3rd
const [Requests, setRequests] = useState([]);
const getAllRequests = async () => {
let res = await axios.get(`/api/contact/request/getAll/`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setRequests(res.data.contactRequest);
}; };
// //2nd
// const [category, setCategory] = useState([]);
// const getAllCategory = async () => {
// let res = await axios.get(`/api/category/getCategories`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setCategory(res?.data?.categories);
// };
// //3rd
// const [product, setProduct] = useState([]);
// const getAllProduct = async () => {
// let res = await axios.get(`/api/product/getAll/user/`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setProduct(res?.data?.product);
// };
// // 3rd
// const [Requests, setRequests] = useState([]);
// const getAllRequests = async () => {
// let res = await axios.get(`/api/contact/request/getAll/`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setRequests(res.data.contactRequest);
// };
// //3 requiment // //3 requiment
// const [requirement, setRequirement] = useState([]) // const [requirement, setRequirement] = useState([])
@ -118,17 +128,19 @@ const Dashboard = () => {
// }, [token]); // }, [token]);
useEffect(() => { useEffect(() => {
getAllUsers(); getAllUsers();
getAllCategory(); getAllsalescoordinator();
getAllProduct(); // getAllCategory();
getAllRequests(); // getAllProduct();
// getAllRequests();
}, [token]); }, [token]);
return ( return (
<> <>
<WidgetsDropdown <WidgetsDropdown
users={users} users={users}
category={category} salescoordinator={salescoordinator}
product={product} // category={category}
Requests={Requests} // product={product}
// Requests={Requests}
/> />
</> </>
); );

View File

@ -18,126 +18,138 @@ import axios from "axios";
{ {
/* <BeatLoader color="#36d7b7" /> */ /* <BeatLoader color="#36d7b7" /> */
} }
const WidgetsDropdown = ({ users,salescoordinator }) => {
// const WidgetsDropdown = ({ users, category, product, Requests }) => {
// const token = isAutheticated();
// const [orders, setOrders] = useState([]);
// const [todayorders, setTodayOrders] = useState([]);
// const [monthorders, setMonthOrders] = useState([]);
// const [yearorders, setYearOrders] = useState([]);
// const [lastyearorders, setLastYearOrders] = useState([]);
// const [processingorders, setProcessingOrders] = useState([]);
// const [dispatchedorders, setDispatchedOrders] = useState([]);
// const [deliveredorders, setDeliveredOrders] = useState([]);
// const [cancelledorders, setCancelledOrders] = useState([]);
// const getAllOrder = async () => {
// let res = await axios.get(`/api/order/getAll/`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setOrders(res?.data?.order);
// setTodayOrders(
// res?.data?.order?.filter((order) => {
// return (
// new Date(order.createdAt).toDateString() === new Date().toDateString()
// );
// })
// );
// setMonthOrders(
// res?.data?.order?.filter((order) => {
// return new Date(order.createdAt).getMonth() === new Date().getMonth();
// })
// );
// setYearOrders(
// res?.data?.order?.filter((order) => {
// return (
// new Date(order.createdAt).getFullYear() === new Date().getFullYear()
// );
// })
// );
// setLastYearOrders(
// res?.data?.order?.filter((order) => {
// return (
// new Date(order.createdAt).getFullYear() ===
// new Date().getFullYear() - 1
// );
// })
// );
// };
// const getProcessingOrder = async () => {
// let res = await axios.get(`/api/order/getAll/processing`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setProcessingOrders(res?.data?.order);
// };
// const getDispatchedOrder = async () => {
// let res = await axios.get(`/api/order/getAll/dispatched`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setDispatchedOrders(res?.data?.order);
// };
// const getDeliveredOrder = async () => {
// let res = await axios.get(`/api/order/getAll/delivered`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setDeliveredOrders(res?.data?.order);
// };
// const getCancelledOrder = async () => {
// let res = await axios.get(`/api/order/getAll/cancelled`, {
// headers: {
// Authorization: `Bearer ${token}`,
// },
// });
// // console.log(res.data);
// setCancelledOrders(res?.data?.order);
// };
const WidgetsDropdown = ({ users, category, product, Requests }) => { // useEffect(() => {
const token = isAutheticated(); // getAllOrder();
const [orders, setOrders] = useState([]); // getProcessingOrder();
const [todayorders, setTodayOrders] = useState([]); // getDispatchedOrder();
const [monthorders, setMonthOrders] = useState([]); // getDeliveredOrder();
const [yearorders, setYearOrders] = useState([]); // getCancelledOrder();
const [lastyearorders, setLastYearOrders] = useState([]); // }, [token]);
const [processingorders, setProcessingOrders] = useState([]); // const date = new Date();
const [dispatchedorders, setDispatchedOrders] = useState([]); // const day = date.getDate();
const [deliveredorders, setDeliveredOrders] = useState([]); // const suffix =
const [cancelledorders, setCancelledOrders] = useState([]); // day === 1 || day === 21 || day === 31
const getAllOrder = async () => { // ? "st"
let res = await axios.get(`/api/order/getAll/`, { // : day === 2 || day === 22
headers: { // ? "nd"
Authorization: `Bearer ${token}`, // : day === 3 || day === 23
}, // ? "rd"
}); // : "th";
// console.log(res.data); // const month = date.toLocaleDateString("en-US", { month: "long" });
setOrders(res?.data?.order); // const formattedDate = `${day}${suffix} ${month}`;
setTodayOrders( // // console.log(formattedDate);
res?.data?.order?.filter((order) => { // const year = date.toLocaleDateString("en-US", { year: "numeric" });
return ( // const formattedmonth = `${month} ${year}`;
new Date(order.createdAt).toDateString() === new Date().toDateString()
);
})
);
setMonthOrders(
res?.data?.order?.filter((order) => {
return new Date(order.createdAt).getMonth() === new Date().getMonth();
})
);
setYearOrders(
res?.data?.order?.filter((order) => {
return (
new Date(order.createdAt).getFullYear() === new Date().getFullYear()
);
})
);
setLastYearOrders(
res?.data?.order?.filter((order) => {
return (
new Date(order.createdAt).getFullYear() ===
new Date().getFullYear() - 1
);
})
);
};
const getProcessingOrder = async () => {
let res = await axios.get(`/api/order/getAll/processing`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setProcessingOrders(res?.data?.order);
};
const getDispatchedOrder = async () => {
let res = await axios.get(`/api/order/getAll/dispatched`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setDispatchedOrders(res?.data?.order);
};
const getDeliveredOrder = async () => {
let res = await axios.get(`/api/order/getAll/delivered`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setDeliveredOrders(res?.data?.order);
};
const getCancelledOrder = async () => {
let res = await axios.get(`/api/order/getAll/cancelled`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setCancelledOrders(res?.data?.order);
};
useEffect(() => {
getAllOrder();
getProcessingOrder();
getDispatchedOrder();
getDeliveredOrder();
getCancelledOrder();
}, [token]);
const date = new Date();
const day = date.getDate();
const suffix =
day === 1 || day === 21 || day === 31
? "st"
: day === 2 || day === 22
? "nd"
: day === 3 || day === 23
? "rd"
: "th";
const month = date.toLocaleDateString("en-US", { month: "long" });
const formattedDate = `${day}${suffix} ${month}`;
// console.log(formattedDate);
const year = date.toLocaleDateString("en-US", { year: "numeric" });
const formattedmonth = `${month} ${year}`;
return ( return (
<> <>
{/* <h4>Users and Requests</h4> <h4>Principal Distributor</h4>
<CRow> <CRow>
<CCol sm={6} lg={3}> <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
className="mb-4" className="mb-4"
color="primary" color="primary"
value={<>{users.length}</>} value={<>{users.length}</>}
title="Total Users" title="Total Principal Distributor"
/> />
</CCol> </CCol>
</CRow>
<h4>Sales CoOrdinator</h4>
<CRow>
<CCol sm={6} lg={3}> <CCol sm={6} lg={3}>
<CWidgetStatsA
className="mb-4"
color="primary"
value={<>{salescoordinator}</>}
title="Total Sales CoOrdinator"
/>
</CCol>
</CRow>
{/* <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
className="mb-4" className="mb-4"
color="primary" color="primary"
@ -294,8 +306,8 @@ const WidgetsDropdown = ({ users, category, product, Requests }) => {
value={<>{cancelledorders.length}</>} value={<>{cancelledorders.length}</>}
title="Orders - Cancelled" title="Orders - Cancelled"
/> />
</CCol> </CCol>
</CRow> */} </CRow>*/}
</> </>
); );
}; };