cancellerd order screen done and api done

This commit is contained in:
ROSHAN GARG 2024-09-20 15:51:34 +05:30
commit 6504fcf349
26 changed files with 3139 additions and 342 deletions

View File

@ -15,9 +15,9 @@ 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.baseURL = "https://api.cnapp.co.in"; axios.defaults.baseURL = "https://api.cnapp.co.in";
axios.defaults.headers = { axios.defaults.headers = {
"Cache-Control": "no-cache,no-store", "Cache-Control": "no-cache,no-store",

View File

@ -148,6 +148,10 @@ import ViewSalesCoOrdinatorTM from "./views/TerritoryManager/ViewSalesCoOrdinato
import ViewPrincipalDistributorTM from "./views/TerritoryManager/ViewPrincipalDistributorTM"; import ViewPrincipalDistributorTM from "./views/TerritoryManager/ViewPrincipalDistributorTM";
import ViewRetailDistributorTM from "./views/TerritoryManager/ViewRetailDistributor"; import ViewRetailDistributorTM from "./views/TerritoryManager/ViewRetailDistributor";
import AddRetailDistributor from "./views/RetailDistributors/addRetailDistributor"; import AddRetailDistributor from "./views/RetailDistributors/addRetailDistributor";
import ViewPrincipalDistributorSC from "./views/SalesCoOrdinators/ViewPrincipalDistributorSC";
import ViewRetailDistributorSC from "./views/SalesCoOrdinators/ViewRetailDistributorSC";
import ViewRetailDistributorPD from "./views/PrincipalDistributors/ViewRetailDistributorPD";
import MapRD from "./views/RetailDistributors/MapRD";
const routes = [ const routes = [
//dashboard //dashboard
@ -239,6 +243,18 @@ const routes = [
element: AddSalesCoOrdinator, element: AddSalesCoOrdinator,
navName: "SalesCoOrdinators", navName: "SalesCoOrdinators",
}, },
{
path: "/view/SCprincipaldistributor/:id",
name: "View Principal Distributor",
element: ViewPrincipalDistributorSC,
navName: "SalesCoOrdinators",
},
{
path: "/view/SCretaildistributor/:id",
name: "View Retail Distributor",
element: ViewRetailDistributorSC,
navName: "SalesCoOrdinators",
},
//TerritoryManager //TerritoryManager
{ {
path: "/territorymanager/edit/:id", path: "/territorymanager/edit/:id",
@ -345,6 +361,12 @@ const routes = [
element: AddRetailDistributor, element: AddRetailDistributor,
navName: "RetailDistributor", navName: "RetailDistributor",
}, },
{
path: "/retaildistributor/mapping/:id",
name: "Mapping Retail Distributor with PD SC TM",
element: MapRD,
navName: "RetailDistributor",
},
//----------------------- End Product Management Routes------------------------------------------------ //----------------------- End Product Management Routes------------------------------------------------
//Departure //Departure
@ -395,6 +417,12 @@ const routes = [
element: AddMultiplePd, element: AddMultiplePd,
navName: "PrincipalDistributor", navName: "PrincipalDistributor",
}, },
{
path: "/view/mappedretaildistributor/:id",
name: "view retail distributor",
element: ViewRetailDistributorPD,
navName: "PrincipalDistributor",
},
//Inventory //Inventory
{ {
path: "/inventory", path: "/inventory",

View File

@ -34,7 +34,7 @@ const LeaveTerritoryManager = () => {
isVerified: verifyRef.current.value, isVerified: verifyRef.current.value,
}, },
}); });
setterritorymanagersData(res.data?.territorymanager); setterritorymanagersData(res.data?.territoryManager);
setTotalData(res.data?.total_data); setTotalData(res.data?.total_data);
} catch (err) { } catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!"; const msg = err?.response?.data?.message || "Something went wrong!";
@ -56,7 +56,7 @@ const LeaveTerritoryManager = () => {
const debouncedSearch = useCallback(debounce(() => { const debouncedSearch = useCallback(debounce(() => {
setCurrentPage(1); setCurrentPage(1);
getterritorymanagerData(); getterritorymanagersData();
}, 500), []); }, 500), []);
const handleSearchChange = () => { const handleSearchChange = () => {

View File

@ -28,7 +28,6 @@ const [userType, setUserType] = useState("");
show: itemPerPage, show: itemPerPage,
}, },
}); });
console.log(res.data);
setuser(res.data?.user); setuser(res.data?.user);
setleaveData(res.data?.leave); setleaveData(res.data?.leave);
setUserType(res.data?.userType); setUserType(res.data?.userType);

View File

@ -27,7 +27,7 @@ const TodayLeave = () => {
show: itemPerPage, show: itemPerPage,
}, },
}); });
console.log(res.data); // console.log(res.data);
setSalesCoOrdinatorsData(res.data?.leave); setSalesCoOrdinatorsData(res.data?.leave);
setTotalData(res.data?.total_data); setTotalData(res.data?.total_data);
} catch (err) { } catch (err) {
@ -99,7 +99,7 @@ const TodayLeave = () => {
textTransform: "capitalize", textTransform: "capitalize",
}} }}
onClick={() => { onClick={() => {
navigate("/territorymanager/attendance", { navigate("/territorymanager/leave", {
replace: true, replace: true,
}); });
}} }}

View File

@ -0,0 +1,577 @@
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
import Button from "@material-ui/core/Button";
import { useNavigate } from "react-router-dom";
import { isAutheticated } from "src/auth";
import swal from "sweetalert";
import debounce from "lodash.debounce";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import TextField from "@material-ui/core/TextField";
const ViewRetailDistributorPD = () => {
const token = isAutheticated();
const { id } = useParams();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(true);
const [retaildistributorData, setretaildistributorData] = useState([]);
const [data, setData] = useState({});
const nameRef = useRef();
const mobileRef = useRef();
const rdnameRef = useRef();
const rdmobileRef = useRef();
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10);
const [modalcurrentPage, setmodalCurrentPage] = useState(1);
const modalitemPerPage = 10;
const [totalData, setTotalData] = useState(0);
const [openModal, setOpenModal] = useState(false);
const [modalRetailDistributors, setmodalRetailDistributors] = useState([]);
const [modalTotalData, setmodalTotalData] = useState(0);
// Fetch territory manager data
useEffect(() => {
axios
.get(`/api/v1/admin/user/${id}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => setData(response.data.user))
.catch((error) => console.error("Error fetching sc data:", error));
}, [id, token]);
// Fetch Retail Distributors data
const getPDsretaildistributorData = async () => {
setLoading(true);
axios
.get(`/api/getAllRDbypdid/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: currentPage,
show: itemPerPage,
tradename: nameRef.current?.value,
mobile_number: mobileRef.current?.value,
},
})
.then((res) => {
// console.log(res.data);
setretaildistributorData(res.data?.Retaildistributor);
setTotalData(res.data?.total_data);
})
.catch((err) => {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
})
.finally(() => setLoading(false));
};
useEffect(() => {
getPDsretaildistributorData();
}, [success, itemPerPage, currentPage]);
// Debounced search for Retail Distributors
const debouncedSearch = useCallback(
debounce(() => {
setCurrentPage(1);
getPDsretaildistributorData();
}, 500),
[currentPage, itemPerPage]
);
const handleSearchChange = useCallback(() => {
debouncedSearch();
}, [debouncedSearch]);
// Fetch Retail Distributors data for modal
const getretaildistributorData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/getAllRD`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: modalcurrentPage,
show: modalitemPerPage,
tradename: rdnameRef.current?.value,
mobile_number: rdmobileRef.current?.value,
},
});
setmodalRetailDistributors(res.data?.Retaildistributor);
setmodalTotalData(res.data?.total_data);
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (openModal) {
getretaildistributorData();
}
}, [openModal, modalcurrentPage]);
// Debounced search for Retail Distributors in modal
const debouncedmodalSearch = useCallback(
debounce(() => {
setmodalCurrentPage(1);
getretaildistributorData();
}, 500),
[modalcurrentPage]
);
const handlemodalSearchChange = useCallback(() => {
debouncedmodalSearch();
}, [debouncedmodalSearch]);
const handleOpenModal = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const handlePreviousPage = () => {
if (modalcurrentPage > 1) {
setmodalCurrentPage(modalcurrentPage - 1);
}
};
const handleNextPage = () => {
if (modalRetailDistributors.length === modalitemPerPage) {
setmodalCurrentPage(modalcurrentPage + 1);
}
};
const handleDelete = (id) => {
swal({
title: "Are you sure?",
icon: "warning",
buttons: {
Yes: { text: "Yes", value: true },
Cancel: { text: "Cancel", value: "cancel" },
},
}).then((value) => {
if (value === true) {
axios
.patch(
`/api/unmap/${id}`,
{ principal_distributor: true },
{
// Changed to PATCH and sent an empty body
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
)
.then((res) => {
swal({
title: "Deleted",
text: "Retail Distributor Unmapped successfully!",
icon: "success",
button: "ok",
});
setSuccess((prev) => !prev);
})
.catch((err) => {
let msg = err?.response?.data?.message
? err?.response?.data?.message
: "Something went wrong!";
swal({
title: "Warning",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
});
}
});
};
const handleAddRetailDistributor = async (rdid) => {
try {
await axios.put(
`/api/mapped/${rdid}`,
{ principal_distributor: id },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
swal({
title: "Success",
text: "Retail Distributor added successfully!",
icon: "success",
button: "Ok",
});
setSuccess((prev) => !prev);
handleCloseModal(); // Close modal after adding
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
return (
<div className="main-content">
<div className="page-content">
<div className="container-fluid">
<div className="row">
<div className="col-12">
<div className="page-title-box d-flex mb-1 align-items-center justify-content-between">
{/* Left Side with Information in Separate Columns */}
<div className="d-flex flex-column">
<div style={{ fontSize: "18px" }} className="fw-bold">
Unique ID: {data?.uniqueId}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Name: {data?.name}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Mobile Number: {data?.mobileNumber}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Mail: {data?.email}
</div>
</div>
{/* Right Side with the Button */}
<div className="page-title-right">
<Button
variant="contained"
color="primary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
onClick={handleOpenModal}
>
Add Retail Distributor
</Button>
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
marginLeft: "1rem",
textTransform: "capitalize",
backgroundColor: "#d32f2f", // Red color for danger
color: "#fff",
"&:hover": {
backgroundColor: "#b71c1c", // Darker red on hover
},
}}
onClick={() => navigate("/principal-distributor")}
>
Back
</Button>
</div>
</div>
<Dialog
open={openModal}
onClose={handleCloseModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Search and Add Retail Distributor</DialogTitle>
<DialogContent>
<div
style={{
display: "flex",
gap: "16px",
marginBottom: "2rem",
marginTop: "-1rem",
}}
>
<TextField
label="Retail Distributor Trade Name"
placeholder="Retail Distributor Trade name"
inputRef={rdnameRef}
onChange={handlemodalSearchChange}
disabled={loading}
style={{ flex: 1, marginRight: "16px" }}
/>
<TextField
style={{ flex: 1 }}
label="Mobile Number"
placeholder="Mobile Number"
inputRef={rdmobileRef}
onChange={handlemodalSearchChange}
disabled={loading}
/>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead>
<tr>
<th>Trade Name</th>
<th>Mobile</th>
<th>Email</th>
<th>SC</th>
<th>TM</th>
<th>PD</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{modalRetailDistributors.length > 0 ? (
modalRetailDistributors.map((RD) => (
<tr key={RD._id}>
<td>{RD.kycDetails.trade_name}</td>
<td>{RD.mobile_number}</td>
<td>{RD.email}</td>
<td>{RD.mappedSCDetails?.name || "N/A"}</td>
<td>{RD.mappedTMDetails?.name || "N/A"}</td>
<td>{RD.principalDetails?.name || "N/A"}</td>
<td>
<Button
variant="contained"
color="primary"
onClick={() =>
handleAddRetailDistributor(RD._id)
}
>
Add
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="6" className="text-center">
No Retail Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalRetailDistributors?.length} of{" "}
{modalTotalData} entries
</div>
<div>
<button
onClick={handlePreviousPage}
disabled={modalcurrentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={handleNextPage}
disabled={
modalRetailDistributors?.length < modalitemPerPage ||
loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
</div>
</div>
<div className="row">
<div className="col-lg-12">
<div className="card">
<div className="card-body">
<div className="row ml-0 mr-0 mb-10">
<div className="col-lg-1">
<div className="dataTables_length">
<label className="w-100">
Show
<select
onChange={(e) => {
setItemPerPage(e.target.value);
setCurrentPage(1);
}}
className="form-control"
disabled={loading}
>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
entries
</label>
</div>
</div>
<div className="col-lg-3">
<label>Trade Name:</label>
<input
type="text"
placeholder="Retail Distributor Trade name"
className="form-control"
ref={nameRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
<div className="col-lg-3">
<label>Mobile Number:</label>
<input
type="text"
placeholder="Mobile Number"
className="form-control"
ref={mobileRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead
className="thead-light"
style={{ background: "#ecdddd" }}
>
<tr>
<th className="text-start">UniqueID</th>
<th className="text-start">Trade Name</th>
<th className="text-start">Mobile</th>
<th className="text-start">Email</th>
<th className="text-start">Created On</th>
<th className="text-start">Action</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td className="text-center" colSpan="6">
Loading...
</td>
</tr>
) : retaildistributorData?.length > 0 ? (
retaildistributorData?.map((RD, i) => {
return (
<tr key={i}>
<td className="text-start">{RD?.uniqueId}</td>
<td className="text-start">
{RD?.kycDetails?.trade_name}
</td>
<td className="text-start">
{RD?.mobile_number ? (
RD?.mobile_number
) : (
<small className="m-0 text-secondary">
No Phone Added!
</small>
)}
</td>
<td className="text-start">{RD?.email}</td>
<td className="text-start">
{" "}
{new Date(RD.createdAt).toLocaleString(
"en-IN",
{
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
}
)}
</td>
<td className="text-start">
<button
type="button"
style={{ color: "white" }}
className="btn btn-danger btn-sm waves-effect waves-light btn-table ml-2"
onClick={() => handleDelete(RD._id)}
>
Delete
</button>
</td>
</tr>
);
})
) : (
<tr>
<td className="text-center" colSpan="6">
No Retail Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {retaildistributorData?.length} of {totalData}{" "}
entries
</div>
<div>
<button
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={() => setCurrentPage(currentPage + 1)}
disabled={
retaildistributorData?.length < itemPerPage || loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default ViewRetailDistributorPD;

View File

@ -181,11 +181,11 @@ const principalDistributor = () => {
</div> </div>
</div> </div>
<div className="col-lg-3"> <div className="col-lg-3">
<label>Trade Name:</label> <label>Name:</label>
<input <input
type="text" type="text"
name="searchTerm" name="searchTerm"
placeholder="Trade name" placeholder="Name"
className="form-control" className="form-control"
ref={nameRef} ref={nameRef}
onChange={handleSearchChange} onChange={handleSearchChange}
@ -225,6 +225,7 @@ const principalDistributor = () => {
<th>Date Registered</th> <th>Date Registered</th>
<th>Last Purchase</th> <th>Last Purchase</th>
<th>Orders</th> <th>Orders</th>
<th>Mapping</th>
<th>Action</th> <th>Action</th>
</tr> </tr>
</thead> </thead>
@ -246,13 +247,13 @@ const principalDistributor = () => {
{new Date(user.createdAt).toLocaleString( {new Date(user.createdAt).toLocaleString(
"en-IN", "en-IN",
{ {
weekday: "short", // weekday: "short",
month: "short", month: "short",
day: "numeric", day: "numeric",
year: "numeric", year: "numeric",
hour: "numeric", // hour: "numeric",
minute: "numeric", // minute: "numeric",
hour12: true, // hour12: true,
} }
)} )}
</td> </td>
@ -267,7 +268,22 @@ const principalDistributor = () => {
_id={user?._id} _id={user?._id}
setLoading1={setLoading1} setLoading1={setLoading1}
/> />
<td className="text-start">
<Link
to={`/view/mappedretaildistributor/${user?._id}`}
>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="btn btn-primary btn-sm waves-effect waves-light btn-table ml-2"
>
RD
</button>
</Link>
</td>
<td className="text-start"> <td className="text-start">
{/* <Link {/* <Link
to={`/users-address/view/${userAddress._id}`} to={`/users-address/view/${userAddress._id}`}

View File

@ -21,7 +21,6 @@ const ProductDetails = (props) => {
data.price === "" || data.price === "" ||
data.GST === "" || data.GST === "" ||
data.category === "" || data.category === "" ||
data.description === "" ||
data.product_Status === ""|| data.product_Status === ""||
data.HSN_Code === "" || data.HSN_Code === "" ||
data.brand === "" data.brand === ""

View File

@ -0,0 +1,897 @@
import React, { useState, useEffect, useRef, useCallback } from "react";
import axios from "axios";
import {
Box,
Typography,
Grid,
Paper,
Dialog,
DialogContent,
DialogTitle,
} from "@mui/material";
import { useParams, useNavigate } from "react-router-dom";
import { isAutheticated } from "../../auth";
import Button from "@material-ui/core/Button";
import swal from "sweetalert";
import debounce from "lodash.debounce";
import TextField from "@mui/material/TextField";
import DialogActions from "@mui/material/DialogActions";
const MapRD = () => {
const { id } = useParams();
const token = isAutheticated();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(true);
const [data, setData] = useState(null);
const pdnameRef = useRef();
const pdmobileRef = useRef();
const scnameRef = useRef();
const scmobileRef = useRef();
const tmnameRef = useRef();
const tmmobileRef = useRef();
const [modalcurrentPage, setmodalCurrentPage] = useState(1);
const modalitemPerPage = 10;
const [openPDModal, setOpenPDModal] = useState(false);
const [openSCModal, setOpenSCModal] = useState(false);
const [openTMModal, setOpenTMModal] = useState(false);
// For opening each modal
const handleOpenPDModal = () => setOpenPDModal(true);
const handleOpenSCModal = () => setOpenSCModal(true);
const handleOpenTMModal = () => setOpenTMModal(true);
// For closing each modal
const handleClosePDModal = () => setOpenPDModal(false);
const handleCloseSCModal = () => setOpenSCModal(false);
const handleCloseTMModal = () => setOpenTMModal(false);
const [modalTotalData, setModalTotalData] = useState(0);
const [modalSalesCoordinators, setModalSalesCoordinators] = useState([]);
const [modalPrincipalDistributors, setmodalPrincipalDistributors] = useState(
[]
);
const [modalterritorymanagers, setmodalterritorymanagers] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
// Commented out the API call and using dummy data
const response = await axios.get(`/api/getRD/${id}`, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
"Content-Type": "multipart/form-data",
},
});
setData(response.data);
// console.log('Retailer Details: ', response.data);
} catch (error) {
console.error("Error fetching data: ", error);
}
};
fetchData();
}, [id, token, success]);
// SC
const getSalesCoOrdinatorsData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/salescoordinator/getAll`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: modalcurrentPage,
show: modalitemPerPage,
name: scnameRef.current?.value,
mobileNumber: scmobileRef.current?.value,
},
});
setModalSalesCoordinators(res.data?.salesCoOrinators);
setModalTotalData(res.data?.total_data);
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (openSCModal) {
getSalesCoOrdinatorsData();
}
}, [openSCModal, modalcurrentPage]);
// Debounced search for Sales Coordinators in modal
const debouncedmodalSearchforSC = useCallback(
debounce(() => {
setmodalCurrentPage(1);
getSalesCoOrdinatorsData();
}, 500),
[modalcurrentPage]
);
const handlemodalSearchChangeinSC = useCallback(() => {
debouncedmodalSearchforSC();
}, [debouncedmodalSearchforSC]);
// PD
const getprincipaldistributorData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/v1/admin/users`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: modalcurrentPage,
show: modalitemPerPage,
name: pdnameRef.current?.value,
mobileNumber: pdmobileRef.current?.value,
},
});
setmodalPrincipalDistributors(res.data?.users);
setModalTotalData(res.data?.totalUsers);
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (openPDModal) {
getprincipaldistributorData();
}
}, [openPDModal, modalcurrentPage]);
// Debounced search for Principal Distributors in modal
const debouncedmodalSearchforPD = useCallback(
debounce(() => {
setmodalCurrentPage(1);
getprincipaldistributorData();
}, 500),
[modalcurrentPage]
);
const handlemodalSearchChangeinPD = useCallback(() => {
debouncedmodalSearchforPD();
}, [debouncedmodalSearchforPD]);
// TM
const getTerritorymanagersData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/territorymanager/getAll`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: modalcurrentPage,
show: modalitemPerPage,
name: tmnameRef.current?.value,
mobileNumber: tmmobileRef.current?.value,
},
});
setmodalterritorymanagers(res.data?.territoryManager);
setModalTotalData(res.data?.total_data);
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (openTMModal) {
getTerritorymanagersData();
}
}, [openTMModal, modalcurrentPage]);
// Debounced search for Territory manager in modal
const debouncedmodalSearchforTM = useCallback(
debounce(() => {
setmodalCurrentPage(1);
getTerritorymanagersData();
}, 500),
[modalcurrentPage]
);
const handlemodalSearchChangeinTM = useCallback(() => {
debouncedmodalSearchforTM();
}, [debouncedmodalSearchforTM]);
const handlePreviousPage = () => {
if (modalcurrentPage > 1) {
setmodalCurrentPage(modalcurrentPage - 1);
}
};
const handleDelete = (designation) => {
swal({
title: "Are you sure?",
icon: "warning",
buttons: {
Yes: { text: "Yes", value: true },
Cancel: { text: "Cancel", value: "cancel" },
},
}).then((value) => {
if (value === true) {
// Create the data object based on designation
let data = {};
if (designation === "TM") {
data.mappedTM = true;
} else if (designation === "SC") {
data.mappedSC = true;
} else {
data.principal_distributor = true;
}
// Make the PATCH request with the constructed data object
axios
.patch(
`/api/unmap/${id}`,
data, // Send the constructed data object
{
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
)
.then((res) => {
swal({
title: "Deleted",
text: "Retail Distributor Unmapped successfully!",
icon: "success",
button: "Ok",
});
setSuccess((prev) => !prev);
})
.catch((err) => {
let msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Warning",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
});
}
});
};
const handleUpdateMapping = async (rdid, designation) => {
try {
// Create the data object based on designation
let data = {};
if (designation === "TM") {
data.mappedTM = rdid;
} else if (designation === "SC") {
data.mappedSC = rdid;
} else {
data.principal_distributor = rdid;
}
// Make the API request
await axios.put(
`/api/mapped/${id}`,
data, // Send the constructed data object
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
// Success alert
swal({
title: "Success",
text: "Mapped successfully!",
icon: "success",
button: "Ok",
});
// Trigger success state change and close modals
setSuccess((prev) => !prev);
handleClosePDModal();
handleCloseSCModal();
handleCloseTMModal();
} catch (err) {
// Handle error and show error message
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
if (!data) {
return <Typography>Loading...</Typography>;
}
return (
<Box sx={{ p: 3 }}>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
mb: 3,
}}
>
<Typography variant="h4">Retailer Details</Typography>
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
onClick={() => {
navigate("/retail-distributor", { replace: true });
}}
>
Cancel
</Button>
</Box>
<Paper sx={{ p: 2, mb: 3 }}>
<Typography variant="h5" gutterBottom>
Retailer Details
</Typography>
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography>
<strong>Trade Name:</strong> {data.kyc.trade_name}
</Typography>
<Typography>
<strong>Name:</strong> {data.name}
</Typography>
<Typography>
<strong>Address:</strong> {data.kyc.address}
</Typography>
<Typography>
<strong>Town/City:</strong> {data.kyc.city}
</Typography>
<Typography>
<strong>District:</strong> {data.kyc.district}
</Typography>
<Typography>
<strong>State:</strong> {data.kyc.state}
</Typography>
<Typography>
<strong>Pincode:</strong> {data.kyc.pincode}
</Typography>
<Typography>
<strong>Mobile Number:</strong> {data.mobile_number}
</Typography>
</Grid>
<Grid item xs={6}>
<Typography>
<strong>Mapped Territory Manager:</strong>{" "}
{data?.mappedTM?.name || "Not Mapped"}
</Typography>
<Typography>
<strong>Mapped Principal Distributor:</strong>{" "}
{data?.principal_distributer?.name || "Not Mapped"}
</Typography>
<Typography>
<strong>Mapped Sales Coordinator:</strong>{" "}
{data?.mappedSC?.name || "Not Mapped"}
</Typography>
</Grid>
</Grid>
</Paper>
{/* Territory Managers */}
<Paper sx={{ p: 2, mb: 3 }}>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Typography variant="h6" gutterBottom>
Territory Manager Details
</Typography>
<Box>
<Button
variant="contained"
color="primary"
size="small" // Set button size to small
style={{ backgroundColor: "blue", marginRight: "8px" }} // marginRight for gap
onClick={handleOpenTMModal}
>
Map TM
</Button>
<Button
variant="contained"
color="secondary"
size="small" // Set button size to small
style={{ backgroundColor: "red" }}
onClick={() => handleDelete("TM")}
>
Unmap TM
</Button>
</Box>
</Box>
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography>
<strong>Name:</strong> {data.mappedTM?.name || "Not Mapped"}
</Typography>
<Typography>
<strong>Mobile Number:</strong>{" "}
{data.mappedTM?.mobileNumber || "Not Mapped"}
</Typography>
<Typography>
<strong>Email:</strong> {data.mappedTM?.email || "Not Mapped"}
</Typography>
</Grid>
</Grid>
</Paper>
{/* Sales Coordinators */}
<Paper sx={{ p: 2, mb: 3 }}>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Typography variant="h6" gutterBottom>
Sales Coordinator Details
</Typography>
<Box>
<Button
variant="contained"
color="primary"
size="small" // Set button size to small
style={{ backgroundColor: "blue", marginRight: "8px" }} // marginRight for gap
onClick={handleOpenSCModal}
>
Map SC
</Button>
<Button
variant="contained"
color="secondary"
size="small" // Set button size to small
style={{ backgroundColor: "red" }}
onClick={() => handleDelete("SC")}
>
Unmap SC
</Button>
</Box>
</Box>
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography>
<strong>Name:</strong> {data.mappedSC?.name || "Not Mapped"}
</Typography>
<Typography>
<strong>Mobile Number:</strong>{" "}
{data.mappedSC?.mobileNumber || "Not Mapped"}
</Typography>
<Typography>
<strong>Email:</strong> {data.mappedSC?.email || "Not Mapped"}
</Typography>
</Grid>
</Grid>
</Paper>
{/* Principal Distributor */}
<Paper sx={{ p: 2, mb: 3 }}>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Typography variant="h6" gutterBottom>
Principal Distributor Details
</Typography>
<Box>
<Button
variant="contained"
color="primary"
size="small" // Set button size to small
style={{ backgroundColor: "blue", marginRight: "8px" }} // marginRight for gap
onClick={handleOpenPDModal}
>
Map PD
</Button>
<Button
variant="contained"
color="secondary"
size="small" // Set button size to small
style={{ backgroundColor: "red" }}
onClick={() => handleDelete("PD")}
>
Unmap PD
</Button>
</Box>
</Box>
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography>
<strong>Name:</strong>{" "}
{data.principal_distributer?.name || "Not Mapped"}
</Typography>
<Typography>
<strong>Mobile Number:</strong>{" "}
{data.principal_distributer?.phone || "Not Mapped"}
</Typography>
<Typography>
<strong>Email:</strong>{" "}
{data.principal_distributer?.email || "Not Mapped"}
</Typography>
</Grid>
</Grid>
</Paper>
{/* Principal Distributor */}
<Dialog
open={openPDModal}
onClose={handleClosePDModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Search and Add Principal Distributor</DialogTitle>
<DialogContent>
<div
style={{
display: "flex",
gap: "16px",
marginBottom: "2rem",
marginTop: "-1rem",
}}
>
<TextField
label="Principal Distributor Name"
placeholder="Principal Distributor name"
inputRef={pdnameRef}
onChange={handlemodalSearchChangeinPD}
disabled={loading}
style={{ flex: 1, marginRight: "16px" }}
/>
<TextField
style={{ flex: 1 }}
label="Mobile Number"
placeholder="Mobile Number"
inputRef={pdmobileRef}
onChange={handlemodalSearchChangeinPD}
disabled={loading}
/>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead>
<tr>
<th>Id</th>
<th>SBU</th>
<th>Name</th>
<th>Mobile</th>
<th>Email</th>
<th>SC</th>
<th>TM</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{modalPrincipalDistributors.length > 0 ? (
modalPrincipalDistributors.map((PD) => (
<tr key={PD._id}>
<td>{PD.uniqueId}</td>
<td>{PD.SBU}</td>
<td>{PD.name}</td>
<td>{PD.phone}</td>
<td>{PD.email}</td>
<td>{PD.mappedbySC?.name || "N/A"}</td>
<td>{PD.mappedby?.name || "N/A"}</td>
<td>
<Button
variant="contained"
color="primary"
onClick={() => handleUpdateMapping(PD._id, "PD")}
>
Add
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="6" className="text-center">
No Principal Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalPrincipalDistributors?.length} of {modalTotalData}{" "}
entries
</div>
<div>
<button
onClick={handlePreviousPage}
disabled={modalcurrentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={
modalPrincipalDistributors.length === modalitemPerPage
? setmodalCurrentPage(modalcurrentPage + 1)
: null
}
disabled={
modalPrincipalDistributors?.length < modalitemPerPage ||
loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={handleClosePDModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
{/* Sales Coordinator */}
<Dialog
open={openSCModal}
onClose={handleCloseSCModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Search and Add Sales Coordinator</DialogTitle>
<DialogContent>
<div
style={{
display: "flex",
gap: "16px",
marginBottom: "2rem",
marginTop: "-1rem",
}}
>
<TextField
label="Sales Coordinator Name"
placeholder="Sales Coordinator name"
inputRef={scnameRef}
onChange={handlemodalSearchChangeinSC}
disabled={loading}
style={{ flex: 1, marginRight: "16px" }}
/>
<TextField
style={{ flex: 1 }}
label="Mobile Number"
placeholder="Mobile Number"
inputRef={scmobileRef}
onChange={handlemodalSearchChangeinSC}
disabled={loading}
/>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Mobile</th>
<th>TM</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{modalSalesCoordinators.map((coordinator) => (
<tr key={coordinator._id}>
<td>{coordinator.uniqueId}</td>
<td>{coordinator.name}</td>
<td>{coordinator.mobileNumber}</td>
<td>{coordinator.mappedby?.name || "N/A"}</td>
<td>
<Button
variant="contained"
color="primary"
onClick={() => handleUpdateMapping(coordinator._id, "SC")}
>
Add
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalSalesCoordinators?.length} of {modalTotalData}{" "}
entries
</div>
<div>
<button
onClick={handlePreviousPage}
disabled={modalcurrentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={
modalSalesCoordinators.length === modalitemPerPage
? setmodalCurrentPage(modalcurrentPage + 1)
: null
}
disabled={
modalSalesCoordinators?.length < modalitemPerPage || loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseSCModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
{/* Territory Manager */}
<Dialog
open={openTMModal}
onClose={handleCloseTMModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Search and Add Territory Manager</DialogTitle>
<DialogContent>
<div
style={{
display: "flex",
gap: "16px",
marginBottom: "2rem",
marginTop: "-1rem",
}}
>
<TextField
label="Territory Manager Name"
placeholder="Territory Manager name"
inputRef={tmnameRef}
onChange={handlemodalSearchChangeinTM}
disabled={loading}
style={{ flex: 1, marginRight: "16px" }}
/>
<TextField
style={{ flex: 1 }}
label="Mobile Number"
placeholder="Mobile Number"
inputRef={tmmobileRef}
onChange={handlemodalSearchChangeinTM}
disabled={loading}
/>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Mobile</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{modalterritorymanagers.length > 0 ? (
modalterritorymanagers.map((TM) => (
<tr key={TM._id}>
<td>{TM.uniqueId}</td>
<td>{TM.name}</td>
<td>{TM.mobileNumber}</td>
<td>{TM.email}</td>
<td>
<Button
variant="contained"
color="primary"
onClick={() => handleUpdateMapping(TM._id, "TM")}
>
Add
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="6" className="text-center">
No Territory Manager found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalterritorymanagers?.length} of {modalTotalData}{" "}
entries
</div>
<div>
<button
onClick={handlePreviousPage}
disabled={modalcurrentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={
modalterritorymanagers.length === modalitemPerPage
? setmodalCurrentPage(modalcurrentPage + 1)
: null
}
disabled={
modalterritorymanagers?.length < modalitemPerPage || loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseTMModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
</Box>
);
};
export default MapRD;

View File

@ -24,18 +24,19 @@ const [totalPages, setTotalPages] = useState(1);
const getRetailDistributorsData = async () => { const getRetailDistributorsData = async () => {
setLoading(true); setLoading(true);
try { try {
const res = await axios.get(`/api/kyc/getAllapproved/`, { const res = await axios.get(`/api/getAllRD`, {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
params: { params: {
page: currentPage, page: currentPage,
show: itemPerPage, show: itemPerPage,
name: nameRef.current.value, tradename: nameRef.current.value,
principaldistributor: principalDistributorRef.current.value, principaldistributor: principalDistributorRef.current.value,
}, },
}); });
setAllRetailDistributorsData(res.data?.kycs); // console.log(res.data);
setAllRetailDistributorsData(res.data?.Retaildistributor);
setTotalData(res.data?.total_data); setTotalData(res.data?.total_data);
setTotalPages(res.data?.total_pages); setTotalPages(res.data?.total_pages);
} catch (err) { } catch (err) {
@ -156,6 +157,7 @@ const [totalPages, setTotalPages] = useState(1);
<th className="text-start">Principal Distributor</th> <th className="text-start">Principal Distributor</th>
<th className="text-start">Territory Manager</th> <th className="text-start">Territory Manager</th>
<th className="text-start">Sales Coordinator</th> <th className="text-start">Sales Coordinator</th>
<th className="text-start">Mapping</th>
<th className="text-start">Action</th> <th className="text-start">Action</th>
</tr> </tr>
</thead> </thead>
@ -171,14 +173,14 @@ const [totalPages, setTotalPages] = useState(1);
allRetailDistributorsData.map((retailDistributor) => ( allRetailDistributorsData.map((retailDistributor) => (
<tr key={retailDistributor._id}> <tr key={retailDistributor._id}>
<td className="text-start"> <td className="text-start">
{retailDistributor._id} {retailDistributor.uniqueId}
</td> </td>
<td className="text-start"> <td className="text-start">
{retailDistributor.trade_name} {retailDistributor.kycDetails.trade_name}
</td> </td>
<td className="text-start"> <td className="text-start">
{new Date( {new Date(
retailDistributor.updatedAt retailDistributor.createdAt
).toLocaleString("en-IN", { ).toLocaleString("en-IN", {
weekday: "short", weekday: "short",
month: "short", month: "short",
@ -190,21 +192,31 @@ const [totalPages, setTotalPages] = useState(1);
})} })}
</td> </td>
<td className="text-start"> <td className="text-start">
{retailDistributor.principal_distributer {retailDistributor?.principalDetails
?.name || "N/A"} ?.name || "N/A"}
</td> </td>
<td className="text-start"> <td className="text-start">
{retailDistributor.userType === {retailDistributor?.mappedTMDetails?.name || "N/A"}
"TerritoryManager"
? retailDistributor.addedBy?.name || "N/A"
: "N/A"}
</td> </td>
<td className="text-start"> <td className="text-start">
{retailDistributor.userType === {retailDistributor?.mappedSCDetails?.name || "N/A"}
"SalesCoOrdinator"
? retailDistributor.addedBy?.name || "N/A"
: "N/A"}
</td> </td>
<td className="text-start">
<Link
to={`/retaildistributor/mapping/${retailDistributor._id}`}
>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="btn btn-primary btn-sm waves-effect waves-light btn-table ml-2"
>
Map
</button>
</Link>
</td>
<td className="text-start"> <td className="text-start">
<Link <Link
to={`/retaildistributor/view/${retailDistributor._id}`} to={`/retaildistributor/view/${retailDistributor._id}`}

View File

@ -18,7 +18,7 @@ const SingleRetailDistributor = () => {
const fetchData = async () => { const fetchData = async () => {
try { try {
// Commented out the API call and using dummy data // Commented out the API call and using dummy data
const response = await axios.get(`api/kyc/get-single-kyc/${id}`, { const response = await axios.get(`/api/getRD/${id}`, {
headers: { headers: {
'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Origin': '*',
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
@ -72,27 +72,27 @@ const SingleRetailDistributor = () => {
<Grid container spacing={2}> <Grid container spacing={2}>
<Grid item xs={6}> <Grid item xs={6}>
<Typography> <Typography>
<strong>Trade Name:</strong> {retailerDetails.trade_name} <strong>Trade Name:</strong> {retailerDetails.kyc.trade_name}
</Typography> </Typography>
<Typography> <Typography>
<strong>Name:</strong> {retailerDetails.name} <strong>Name:</strong> {retailerDetails.name}
</Typography> </Typography>
<Typography> <Typography>
<strong>Address:</strong> {retailerDetails.address} <strong>Address:</strong> {retailerDetails.kyc.address}
</Typography> </Typography>
<Typography> <Typography>
<strong>Town/City:</strong> {retailerDetails.city} <strong>Town/City:</strong> {retailerDetails.kyc.city}
</Typography> </Typography>
</Grid> </Grid>
<Grid item xs={6}> <Grid item xs={6}>
<Typography> <Typography>
<strong>District:</strong> {retailerDetails.district} <strong>District:</strong> {retailerDetails.kyc.district}
</Typography> </Typography>
<Typography> <Typography>
<strong>State:</strong> {retailerDetails.state} <strong>State:</strong> {retailerDetails.kyc.state}
</Typography> </Typography>
<Typography> <Typography>
<strong>Pincode:</strong> {retailerDetails.pincode} <strong>Pincode:</strong> {retailerDetails.kyc.pincode}
</Typography> </Typography>
<Typography> <Typography>
<strong>Mobile Number:</strong> {retailerDetails.mobile_number} <strong>Mobile Number:</strong> {retailerDetails.mobile_number}
@ -111,31 +111,31 @@ const SingleRetailDistributor = () => {
<Grid container spacing={2}> <Grid container spacing={2}>
<Grid item xs={6}> <Grid item xs={6}>
<Typography> <Typography>
<strong>PAN Number:</strong> {retailerDetails.pan_number} <strong>PAN Number:</strong> {retailerDetails.kyc.pan_number}
</Typography> </Typography>
<Avatar <Avatar
variant="square" variant="square"
src={retailerDetails.pan_img.url} src={retailerDetails.kyc.pan_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }} sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.pan_img.url)} onClick={() => handleOpenPopup(retailerDetails.kyc.pan_img.url)}
/> />
<Typography> <Typography>
<strong>Aadhar Number:</strong> {retailerDetails.aadhar_number} <strong>Aadhar Number:</strong> {retailerDetails.kyc.aadhar_number}
</Typography> </Typography>
<Avatar <Avatar
variant="square" variant="square"
src={retailerDetails.aadhar_img.url} src={retailerDetails.kyc.aadhar_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }} sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.aadhar_img.url)} onClick={() => handleOpenPopup(retailerDetails.kyc.aadhar_img.url)}
/> />
<Typography> <Typography>
<strong>GST Number:</strong> {retailerDetails.gst_number} <strong>GST Number:</strong> {retailerDetails.kyc.gst_number}
</Typography> </Typography>
<Avatar <Avatar
variant="square" variant="square"
src={retailerDetails.gst_img.url} src={retailerDetails.kyc.gst_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }} sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.gst_img.url)} onClick={() => handleOpenPopup(retailerDetails.kyc.gst_img.url)}
/> />
</Grid> </Grid>
<Grid item xs={6}> <Grid item xs={6}>
@ -144,19 +144,19 @@ const SingleRetailDistributor = () => {
</Typography> </Typography>
<Avatar <Avatar
variant="square" variant="square"
src={retailerDetails.pesticide_license_img.url} src={retailerDetails.kyc.pesticide_license_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }} sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.pesticide_license_img.url)} onClick={() => handleOpenPopup(retailerDetails.kyc.pesticide_license_img.url)}
/> />
<Typography> <Typography>
<strong>Fertilizer License (optional):</strong> <strong>Fertilizer License (optional):</strong>
</Typography> </Typography>
{retailerDetails.fertilizer_license_img ? ( {retailerDetails.kyc.fertilizer_license_img ? (
<Avatar <Avatar
variant="square" variant="square"
src={retailerDetails.fertilizer_license_img.url} src={retailerDetails.kyc.fertilizer_license_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }} sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.fertilizer_license_img.url)} onClick={() => handleOpenPopup(retailerDetails.kyc.fertilizer_license_img.url)}
/> />
) : ( ) : (
<Typography>Img not available</Typography> <Typography>Img not available</Typography>
@ -166,9 +166,9 @@ const SingleRetailDistributor = () => {
</Typography> </Typography>
<Avatar <Avatar
variant="square" variant="square"
src={retailerDetails.selfie_entrance_img.url} src={retailerDetails.kyc.selfie_entrance_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }} sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.selfie_entrance_img.url)} onClick={() => handleOpenPopup(retailerDetails.kyc.selfie_entrance_img.url)}
/> />
</Grid> </Grid>
</Grid> </Grid>

View File

@ -20,6 +20,7 @@ const AddRetailDistributor = () => {
const [user, setUser] = useState({ const [user, setUser] = useState({
name: "", name: "",
email: "",
trade_name: "", trade_name: "",
address: "", address: "",
state: "", state: "",
@ -104,6 +105,7 @@ const AddRetailDistributor = () => {
// Validate input fields // Validate input fields
if ( if (
!user.name || !user.name ||
!user.email ||
!user.trade_name || !user.trade_name ||
!user.address || !user.address ||
!user.mobile_number || !user.mobile_number ||
@ -121,9 +123,10 @@ const AddRetailDistributor = () => {
const formData = new FormData(); const formData = new FormData();
formData.append("name", user.name); formData.append("name", user.name);
formData.append("email", user.email);
formData.append("trade_name", user.trade_name); formData.append("trade_name", user.trade_name);
formData.append("address", user.address); formData.append("address", user.address);
formData.append("state", selectedState.value); formData.append("state", selectedState.label);
formData.append("city", selectedCity.value); formData.append("city", selectedCity.value);
formData.append("district", user.district); formData.append("district", user.district);
formData.append("pincode", user.pincode); formData.append("pincode", user.pincode);
@ -164,7 +167,6 @@ const AddRetailDistributor = () => {
const handleCancel = () => { const handleCancel = () => {
navigate("/retail-distributor"); navigate("/retail-distributor");
}; };
return ( return (
<div> <div>
<Card <Card
@ -210,7 +212,29 @@ const AddRetailDistributor = () => {
/> />
</Grid> </Grid>
</Grid> </Grid>
<Grid item xs={12} className="d-flex align-items-center">
<Grid item xs={2}>
<Typography
variant="body1"
htmlFor="email"
className="form-label"
>
Email*
</Typography>
</Grid>
<Grid item xs={10}>
<TextField
id="email"
required
type="text"
fullWidth
name="email"
value={user.email}
variant="outlined"
onChange={handleInputChange}
/>
</Grid>
</Grid>
{/* Trade Name */} {/* Trade Name */}
<Grid item xs={12} className="d-flex align-items-center"> <Grid item xs={12} className="d-flex align-items-center">
<Grid item xs={2}> <Grid item xs={2}>

View File

@ -214,6 +214,7 @@ const SalesCoOrdinator = () => {
<th className="text-start">Email</th> <th className="text-start">Email</th>
<th className="text-start">Verify</th> <th className="text-start">Verify</th>
<th className="text-start">Register On</th> <th className="text-start">Register On</th>
<th className="text-start">Mapping</th>
<th className="text-start">Action</th> <th className="text-start">Action</th>
</tr> </tr>
</thead> </thead>
@ -264,16 +265,46 @@ const SalesCoOrdinator = () => {
{new Date( {new Date(
salescoordinator.createdAt salescoordinator.createdAt
).toLocaleString("en-IN", { ).toLocaleString("en-IN", {
weekday: "short", // weekday: "short",
month: "short", month: "short",
day: "numeric", day: "numeric",
year: "numeric", year: "numeric",
hour: "numeric", // hour: "numeric",
minute: "numeric", // minute: "numeric",
hour12: true, // hour12: true,
})} })}
</td> </td>
<td className="text-start"> <td className="text-start">
<Link
to={`/view/SCprincipaldistributor/${salescoordinator._id}`}
>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="btn btn-primary btn-sm waves-effect waves-light btn-table ml-2"
>
PD
</button>
</Link>
<Link
to={`/view/SCretaildistributor/${salescoordinator._id}`}
>
<button
style={{
color: "white",
marginRight: "1rem",
}}
type="button"
className="btn btn-primary btn-sm waves-effect waves-light btn-table ml-2"
>
RD
</button>
</Link>
</td>
<td className="text-start">
<Link <Link
to={`/salescoordinator/edit/${salescoordinator._id}`} to={`/salescoordinator/edit/${salescoordinator._id}`}
> >

View File

@ -0,0 +1,553 @@
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
import Button from "@material-ui/core/Button";
import { useNavigate } from "react-router-dom";
import { isAutheticated } from "src/auth";
import swal from "sweetalert";
import debounce from "lodash.debounce";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import TextField from "@material-ui/core/TextField";
const ViewPrincipalDistributorSC = () => {
const token = isAutheticated();
const { id } = useParams();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(true);
const [principaldistributorData, setprincipaldistributorData] = useState([]);
const [data, setData] = useState({});
const nameRef = useRef();
const mobileRef = useRef();
const pdnameRef = useRef();
const pdmobileRef = useRef();
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10);
const [modalcurrentPage, setmodalCurrentPage] = useState(1);
const modalitemPerPage = 10;
const [totalData, setTotalData] = useState(0);
const [openModal, setOpenModal] = useState(false);
const [modalPrincipalDistributors, setmodalPrincipalDistributors] = useState(
[]
);
const [modalTotalData, setModalTotalData] = useState(0);
// Fetch territory manager data
useEffect(() => {
axios
.get(`/api/salescoordinator/getOne/${id}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => setData(response.data.data))
.catch((error) => console.error("Error fetching SC data:", error));
}, [id, token]);
// Fetch Principal Distributors data
const getSCsprincipaldistributorData = async () => {
setLoading(true);
axios
.get(`/api/v1/getbySCId/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: currentPage,
show: itemPerPage,
name: nameRef.current?.value,
mobileNumber: mobileRef.current?.value,
},
})
.then((res) => {
setprincipaldistributorData(res.data?.principaldistributor);
setTotalData(res.data?.total_data);
})
.catch((err) => {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
})
.finally(() => setLoading(false));
};
useEffect(() => {
getSCsprincipaldistributorData();
}, [success, itemPerPage, currentPage]);
// Debounced search for Principal Distributors
const debouncedSearch = useCallback(
debounce(() => {
setCurrentPage(1);
getSCsprincipaldistributorData();
}, 500),
[currentPage, itemPerPage]
);
const handleSearchChange = useCallback(() => {
debouncedSearch();
}, [debouncedSearch]);
// Fetch Principal Distributors data for modal
const getprincipaldistributorData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/v1/admin/users`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: modalcurrentPage,
show: modalitemPerPage,
name: pdnameRef.current?.value,
mobileNumber: pdmobileRef.current?.value,
},
});
// console.log(res.data.users);
setmodalPrincipalDistributors(res.data?.users);
setModalTotalData(res.data?.totalUsers);
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (openModal) {
getprincipaldistributorData();
}
}, [openModal, modalcurrentPage]);
// Debounced search for Principal Distributors in modal
const debouncedmodalSearch = useCallback(
debounce(() => {
setmodalCurrentPage(1);
getprincipaldistributorData();
}, 500),
[modalcurrentPage]
);
const handlemodalSearchChange = useCallback(() => {
debouncedmodalSearch();
}, [debouncedmodalSearch]);
const handleOpenModal = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const handlePreviousPage = () => {
if (modalcurrentPage > 1) {
setmodalCurrentPage(modalcurrentPage - 1);
}
};
const handleNextPage = () => {
if (modalPrincipalDistributors.length === modalitemPerPage) {
setmodalCurrentPage(modalcurrentPage + 1);
}
};
const handleDelete = (id) => {
swal({
title: "Are you sure?",
icon: "warning",
buttons: {
Yes: { text: "Yes", value: true },
Cancel: { text: "Cancel", value: "cancel" },
},
}).then((value) => {
if (value === true) {
axios
.patch(`/api/v1/unmapSC/${id}`, {}, { // Changed to PATCH and sent an empty body
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
})
.then((res) => {
swal({
title: "Deleted",
text: "Principal Distributor Unmapped successfully!",
icon: "success",
button: "ok",
});
setSuccess((prev) => !prev);
})
.catch((err) => {
let msg = err?.response?.data?.message
? err?.response?.data?.message
: "Something went wrong!";
swal({
title: "Warning",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
});
}
});
};
const handleAddPrincipalDistributor = async (pdid) => {
try {
await axios.put(
`/api/v1/mappedSC/${pdid}`,
{ mappedbySC: id },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
swal({
title: "Success",
text: "Principal Distributor added successfully!",
icon: "success",
button: "Ok",
});
setSuccess((prev) => !prev);
handleCloseModal(); // Close modal after adding
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
return (
<div className="main-content">
<div className="page-content">
<div className="container-fluid">
<div className="row">
<div className="col-12">
<div className="page-title-box d-flex mb-1 align-items-center justify-content-between">
{/* Left Side with Information in Separate Columns */}
<div className="d-flex flex-column">
<div style={{ fontSize: "18px" }} className="fw-bold">
Unique ID: {data?.uniqueId}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Name: {data?.name}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Mobile Number: {data?.mobileNumber}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Mail: {data?.email}
</div>
</div>
{/* Right Side with the Button */}
<div className="page-title-right">
<Button
variant="contained"
color="primary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
onClick={handleOpenModal}
>
Add Principal Distributor
</Button>
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
marginLeft: "1rem",
textTransform: "capitalize",
backgroundColor: "#d32f2f", // Red color for danger
color: "#fff",
"&:hover": {
backgroundColor: "#b71c1c", // Darker red on hover
},
}}
onClick={() => navigate("/salescoordinators")}
>
Back
</Button>
</div>
</div>
<Dialog
open={openModal}
onClose={handleCloseModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Search and Add Principal Distributor</DialogTitle>
<DialogContent>
<div style={{ display: "flex", gap: "16px", marginBottom:"2rem",marginTop:"-1rem" }}>
<TextField
label="Principal Distributor Name"
placeholder="Principal Distributor name"
inputRef={pdnameRef}
onChange={handlemodalSearchChange}
disabled={loading}
style={{ flex: 1, marginRight: "16px" }}
/>
<TextField
style={{ flex: 1 }}
label="Mobile Number"
placeholder="Mobile Number"
inputRef={pdmobileRef}
onChange={handlemodalSearchChange}
disabled={loading}
/>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead>
<tr>
<th>Id</th>
<th>SBU</th>
<th>Name</th>
<th>Mobile</th>
<th>Email</th>
<th>SC</th>
<th>TM</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{modalPrincipalDistributors.length > 0 ? (
modalPrincipalDistributors.map((PD) => (
<tr key={PD._id}>
<td>{PD.uniqueId}</td>
<td>{PD.SBU}</td>
<td>{PD.name}</td>
<td>{PD.phone}</td>
<td>{PD.email}</td>
<td>{PD.mappedbySC?.name || "N/A"}</td>
<td>{PD.mappedby?.name || "N/A"}</td>
<td>
<Button
variant="contained"
color="primary"
onClick={() =>
handleAddPrincipalDistributor(PD._id)
}
>
Add
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="6" className="text-center">
No Principal Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalPrincipalDistributors?.length} of{" "}
{modalTotalData} entries
</div>
<div>
<button
onClick={handlePreviousPage}
disabled={modalcurrentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={handleNextPage}
disabled={
modalPrincipalDistributors?.length <
modalitemPerPage || loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
</div>
</div>
<div className="row">
<div className="col-lg-12">
<div className="card">
<div className="card-body">
<div className="row ml-0 mr-0 mb-10">
<div className="col-lg-1">
<div className="dataTables_length">
<label className="w-100">
Show
<select
onChange={(e) => {
setItemPerPage(e.target.value);
setCurrentPage(1);
}}
className="form-control"
disabled={loading}
>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
entries
</label>
</div>
</div>
<div className="col-lg-3">
<label>Principal Distributor Name:</label>
<input
type="text"
placeholder="Principal Distributor name"
className="form-control"
ref={nameRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
<div className="col-lg-3">
<label>Mobile Number:</label>
<input
type="text"
placeholder="Mobile Number"
className="form-control"
ref={mobileRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead
className="thead-light"
style={{ background: "#ecdddd" }}
>
<tr>
<th>Unique Id </th>
<th className="text-start">SBU</th>
<th className="text-start">Name</th>
<th className="text-start">Mobile No.</th>
<th className="text-start">Email</th>
<th className="text-start">Action</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td className="text-center" colSpan="6">
Loading...
</td>
</tr>
) : principaldistributorData?.length > 0 ? (
principaldistributorData?.map((PD, i) => {
return (
<tr key={i}>
<td className="text-start">{PD?.uniqueId}</td>
<td className="text-start">{PD?.SBU}</td>
<td className="text-start">{PD?.name}</td>
<td className="text-start">{PD?.phone}</td>
<td className="text-start">
{PD?.email ? (
PD?.email
) : (
<small className="m-0 text-secondary">
No Email Added!
</small>
)}
</td>
<td className="text-start">
<button
type="button"
style={{ color: "white" }}
className="btn btn-danger btn-sm waves-effect waves-light btn-table ml-2"
onClick={() => handleDelete(PD._id)}
>
Delete
</button>
</td>
</tr>
);
})
) : (
<tr>
<td className="text-center" colSpan="6">
No Principal Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {principaldistributorData?.length} of {totalData}{" "}
entries
</div>
<div>
<button
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={() => setCurrentPage(currentPage + 1)}
disabled={
principaldistributorData?.length < itemPerPage ||
loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default ViewPrincipalDistributorSC;

View File

@ -0,0 +1,577 @@
import React, { useState, useEffect, useRef, useCallback } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
import Button from "@material-ui/core/Button";
import { useNavigate } from "react-router-dom";
import { isAutheticated } from "src/auth";
import swal from "sweetalert";
import debounce from "lodash.debounce";
import Dialog from "@material-ui/core/Dialog";
import DialogActions from "@material-ui/core/DialogActions";
import DialogContent from "@material-ui/core/DialogContent";
import DialogTitle from "@material-ui/core/DialogTitle";
import TextField from "@material-ui/core/TextField";
const ViewRetailDistributorSC = () => {
const token = isAutheticated();
const { id } = useParams();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(true);
const [retaildistributorData, setretaildistributorData] = useState([]);
const [data, setData] = useState({});
const nameRef = useRef();
const mobileRef = useRef();
const rdnameRef = useRef();
const rdmobileRef = useRef();
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10);
const [modalcurrentPage, setmodalCurrentPage] = useState(1);
const modalitemPerPage = 10;
const [totalData, setTotalData] = useState(0);
const [openModal, setOpenModal] = useState(false);
const [modalRetailDistributors, setmodalRetailDistributors] = useState([]);
const [modalTotalData, setmodalTotalData] = useState(0);
// Fetch territory manager data
useEffect(() => {
axios
.get(`/api/salescoordinator/getOne/${id}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => setData(response.data.data))
.catch((error) => console.error("Error fetching sc data:", error));
}, [id, token]);
// Fetch Retail Distributors data
const getSCsretaildistributorData = async () => {
setLoading(true);
axios
.get(`/api/getAllRDbyscid/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: currentPage,
show: itemPerPage,
tradename: nameRef.current?.value,
mobile_number: mobileRef.current?.value,
},
})
.then((res) => {
// console.log(res.data);
setretaildistributorData(res.data?.Retaildistributor);
setTotalData(res.data?.total_data);
})
.catch((err) => {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
})
.finally(() => setLoading(false));
};
useEffect(() => {
getSCsretaildistributorData();
}, [success, itemPerPage, currentPage]);
// Debounced search for Retail Distributors
const debouncedSearch = useCallback(
debounce(() => {
setCurrentPage(1);
getSCsretaildistributorData();
}, 500),
[currentPage, itemPerPage]
);
const handleSearchChange = useCallback(() => {
debouncedSearch();
}, [debouncedSearch]);
// Fetch Retail Distributors data for modal
const getretaildistributorData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/getAllRD`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: modalcurrentPage,
show: modalitemPerPage,
tradename: rdnameRef.current?.value,
mobile_number: rdmobileRef.current?.value,
},
});
setmodalRetailDistributors(res.data?.Retaildistributor);
setmodalTotalData(res.data?.total_data);
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
} finally {
setLoading(false);
}
};
useEffect(() => {
if (openModal) {
getretaildistributorData();
}
}, [openModal, modalcurrentPage]);
// Debounced search for Retail Distributors in modal
const debouncedmodalSearch = useCallback(
debounce(() => {
setmodalCurrentPage(1);
getretaildistributorData();
}, 500),
[modalcurrentPage]
);
const handlemodalSearchChange = useCallback(() => {
debouncedmodalSearch();
}, [debouncedmodalSearch]);
const handleOpenModal = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const handlePreviousPage = () => {
if (modalcurrentPage > 1) {
setmodalCurrentPage(modalcurrentPage - 1);
}
};
const handleNextPage = () => {
if (modalRetailDistributors.length === modalitemPerPage) {
setmodalCurrentPage(modalcurrentPage + 1);
}
};
const handleDelete = (id) => {
swal({
title: "Are you sure?",
icon: "warning",
buttons: {
Yes: { text: "Yes", value: true },
Cancel: { text: "Cancel", value: "cancel" },
},
}).then((value) => {
if (value === true) {
axios
.patch(
`/api/unmap/${id}`,
{ mappedSC: true },
{
// Changed to PATCH and sent an empty body
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
)
.then((res) => {
swal({
title: "Deleted",
text: "Retail Distributor Unmapped successfully!",
icon: "success",
button: "ok",
});
setSuccess((prev) => !prev);
})
.catch((err) => {
let msg = err?.response?.data?.message
? err?.response?.data?.message
: "Something went wrong!";
swal({
title: "Warning",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
});
}
});
};
const handleAddRetailDistributor = async (rdid) => {
try {
await axios.put(
`/api/mapped/${rdid}`,
{ mappedSC: id },
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
swal({
title: "Success",
text: "Retail Distributor added successfully!",
icon: "success",
button: "Ok",
});
setSuccess((prev) => !prev);
handleCloseModal(); // Close modal after adding
} catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
return (
<div className="main-content">
<div className="page-content">
<div className="container-fluid">
<div className="row">
<div className="col-12">
<div className="page-title-box d-flex mb-1 align-items-center justify-content-between">
{/* Left Side with Information in Separate Columns */}
<div className="d-flex flex-column">
<div style={{ fontSize: "18px" }} className="fw-bold">
Unique ID: {data?.uniqueId}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Name: {data?.name}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Mobile Number: {data?.mobileNumber}
</div>
<div style={{ fontSize: "18px" }} className="fw-bold">
Mail: {data?.email}
</div>
</div>
{/* Right Side with the Button */}
<div className="page-title-right">
<Button
variant="contained"
color="primary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
onClick={handleOpenModal}
>
Add Retail Distributor
</Button>
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
marginLeft: "1rem",
textTransform: "capitalize",
backgroundColor: "#d32f2f", // Red color for danger
color: "#fff",
"&:hover": {
backgroundColor: "#b71c1c", // Darker red on hover
},
}}
onClick={() => navigate("/salescoordinators")}
>
Back
</Button>
</div>
</div>
<Dialog
open={openModal}
onClose={handleCloseModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Search and Add Retail Distributor</DialogTitle>
<DialogContent>
<div
style={{
display: "flex",
gap: "16px",
marginBottom: "2rem",
marginTop: "-1rem",
}}
>
<TextField
label="Retail Distributor Trade Name"
placeholder="Retail Distributor Trade name"
inputRef={rdnameRef}
onChange={handlemodalSearchChange}
disabled={loading}
style={{ flex: 1, marginRight: "16px" }}
/>
<TextField
style={{ flex: 1 }}
label="Mobile Number"
placeholder="Mobile Number"
inputRef={rdmobileRef}
onChange={handlemodalSearchChange}
disabled={loading}
/>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead>
<tr>
<th>Trade Name</th>
<th>Mobile</th>
<th>Email</th>
<th>SC</th>
<th>TM</th>
<th>PD</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{modalRetailDistributors.length > 0 ? (
modalRetailDistributors.map((RD) => (
<tr key={RD._id}>
<td>{RD.kycDetails.trade_name}</td>
<td>{RD.mobile_number}</td>
<td>{RD.email}</td>
<td>{RD.mappedSCDetails?.name || "N/A"}</td>
<td>{RD.mappedTMDetails?.name || "N/A"}</td>
<td>{RD.principalDetails?.name || "N/A"}</td>
<td>
<Button
variant="contained"
color="primary"
onClick={() =>
handleAddRetailDistributor(RD._id)
}
>
Add
</Button>
</td>
</tr>
))
) : (
<tr>
<td colSpan="6" className="text-center">
No Retail Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalRetailDistributors?.length} of{" "}
{modalTotalData} entries
</div>
<div>
<button
onClick={handlePreviousPage}
disabled={modalcurrentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={handleNextPage}
disabled={
modalRetailDistributors?.length < modalitemPerPage ||
loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
</div>
</div>
<div className="row">
<div className="col-lg-12">
<div className="card">
<div className="card-body">
<div className="row ml-0 mr-0 mb-10">
<div className="col-lg-1">
<div className="dataTables_length">
<label className="w-100">
Show
<select
onChange={(e) => {
setItemPerPage(e.target.value);
setCurrentPage(1);
}}
className="form-control"
disabled={loading}
>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
entries
</label>
</div>
</div>
<div className="col-lg-3">
<label>Trade Name:</label>
<input
type="text"
placeholder="Retail Distributor Trade name"
className="form-control"
ref={nameRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
<div className="col-lg-3">
<label>Mobile Number:</label>
<input
type="text"
placeholder="Mobile Number"
className="form-control"
ref={mobileRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
</div>
<div className="table-responsive table-shoot mt-3">
<table className="table table-centered table-nowrap">
<thead
className="thead-light"
style={{ background: "#ecdddd" }}
>
<tr>
<th className="text-start">UniqueID</th>
<th className="text-start">Trade Name</th>
<th className="text-start">Mobile</th>
<th className="text-start">Email</th>
<th className="text-start">Created On</th>
<th className="text-start">Action</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td className="text-center" colSpan="6">
Loading...
</td>
</tr>
) : retaildistributorData?.length > 0 ? (
retaildistributorData?.map((RD, i) => {
return (
<tr key={i}>
<td className="text-start">{RD?.uniqueId}</td>
<td className="text-start">
{RD?.kycDetails?.trade_name}
</td>
<td className="text-start">
{RD?.mobile_number ? (
RD?.mobile_number
) : (
<small className="m-0 text-secondary">
No Phone Added!
</small>
)}
</td>
<td className="text-start">{RD?.email}</td>
<td className="text-start">
{" "}
{new Date(RD.createdAt).toLocaleString(
"en-IN",
{
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
}
)}
</td>
<td className="text-start">
<button
type="button"
style={{ color: "white" }}
className="btn btn-danger btn-sm waves-effect waves-light btn-table ml-2"
onClick={() => handleDelete(RD._id)}
>
Delete
</button>
</td>
</tr>
);
})
) : (
<tr>
<td className="text-center" colSpan="6">
No Retail Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {retaildistributorData?.length} of {totalData}{" "}
entries
</div>
<div>
<button
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 1 || loading}
className="btn btn-primary"
>
Previous
</button>
<button
onClick={() => setCurrentPage(currentPage + 1)}
disabled={
retaildistributorData?.length < itemPerPage || loading
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default ViewRetailDistributorSC;

View File

@ -214,6 +214,7 @@ const TerritoryManager = () => {
<th className="text-start">Email</th> <th className="text-start">Email</th>
<th className="text-start">Verify</th> <th className="text-start">Verify</th>
<th className="text-start">Register On</th> <th className="text-start">Register On</th>
<th className="text-start">Mapping</th>
<th className="text-start">Action</th> <th className="text-start">Action</th>
</tr> </tr>
</thead> </thead>
@ -264,13 +265,13 @@ const TerritoryManager = () => {
{new Date( {new Date(
territorymanager.createdAt territorymanager.createdAt
).toLocaleString("en-IN", { ).toLocaleString("en-IN", {
weekday: "short", // weekday: "short",
month: "short", month: "short",
day: "numeric", day: "numeric",
year: "numeric", year: "numeric",
hour: "numeric", // hour: "numeric",
minute: "numeric", // minute: "numeric",
hour12: true, // hour12: true,
})} })}
</td> </td>
<td className="text-start"> <td className="text-start">
@ -316,6 +317,8 @@ const TerritoryManager = () => {
RD RD
</button> </button>
</Link> </Link>
</td>
<td className="text-start">
<Link <Link
to={`/territorymanager/edit/${territorymanager._id}`} to={`/territorymanager/edit/${territorymanager._id}`}
> >

View File

@ -327,6 +327,8 @@ const ViewPrincipalDistributorTM = () => {
<th>Name</th> <th>Name</th>
<th>Mobile</th> <th>Mobile</th>
<th>Email</th> <th>Email</th>
<th>SC</th>
<th>TM</th>
<th>Action</th> <th>Action</th>
</tr> </tr>
</thead> </thead>
@ -339,6 +341,8 @@ const ViewPrincipalDistributorTM = () => {
<td>{PD.name}</td> <td>{PD.name}</td>
<td>{PD.phone}</td> <td>{PD.phone}</td>
<td>{PD.email}</td> <td>{PD.email}</td>
<td>{PD.mappedbySC?.name || "N/A"}</td>
<td>{PD.mappedby?.name || "N/A"}</td>
<td> <td>
<Button <Button
variant="contained" variant="contained"

View File

@ -31,9 +31,7 @@ const ViewRetailDistributorTM = () => {
const modalitemPerPage = 10; const modalitemPerPage = 10;
const [totalData, setTotalData] = useState(0); const [totalData, setTotalData] = useState(0);
const [openModal, setOpenModal] = useState(false); const [openModal, setOpenModal] = useState(false);
const [modalRetailDistributors, setmodalRetailDistributors] = useState( const [modalRetailDistributors, setmodalRetailDistributors] = useState([]);
[]
);
const [modalTotalData, setModalTotalData] = useState(0); const [modalTotalData, setModalTotalData] = useState(0);
// Fetch territory manager data // Fetch territory manager data
@ -50,7 +48,7 @@ const ViewRetailDistributorTM = () => {
const getTMsretaildistributorData = async () => { const getTMsretaildistributorData = async () => {
setLoading(true); setLoading(true);
axios axios
.get(`/api/kyc/getAllapprovedbytmid/${id}`, { .get(`/api/getAllRDbytmid/${id}`, {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
@ -58,11 +56,12 @@ const ViewRetailDistributorTM = () => {
page: currentPage, page: currentPage,
show: itemPerPage, show: itemPerPage,
tradename: nameRef.current?.value, tradename: nameRef.current?.value,
mobile_number: mobileRef.current?.value,
}, },
}) })
.then((res) => { .then((res) => {
// console.log(res.data); // console.log(res.data);
setretaildistributorData(res.data?.retaildistributor); setretaildistributorData(res.data?.Retaildistributor);
setTotalData(res.data?.total_data); setTotalData(res.data?.total_data);
}) })
.catch((err) => { .catch((err) => {
@ -98,19 +97,19 @@ const ViewRetailDistributorTM = () => {
const getretaildistributorData = async () => { const getretaildistributorData = async () => {
setLoading(true); setLoading(true);
try { try {
const res = await axios.get(`/api/v1/admin/users`, { const res = await axios.get(`/api/getAllRD`, {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
}, },
params: { params: {
page: modalcurrentPage, page: modalcurrentPage,
show: modalitemPerPage, show: modalitemPerPage,
name: rdnameRef.current?.value, tradename: rdnameRef.current?.value,
mobileNumber: rdmobileRef.current?.value, mobile_number: rdmobileRef.current?.value,
}, },
}); });
setmodalRetailDistributors(res.data?.users); setmodalRetailDistributors(res.data?.Retaildistributor);
setModalTotalData(res.data?.totalUsers); setModalTotalData(res.data?.total_data);
} catch (err) { } catch (err) {
const msg = err?.response?.data?.message || "Something went wrong!"; const msg = err?.response?.data?.message || "Something went wrong!";
swal({ swal({
@ -174,12 +173,17 @@ const ViewRetailDistributorTM = () => {
}).then((value) => { }).then((value) => {
if (value === true) { if (value === true) {
axios axios
.patch(`/api/v1/unmap/${id}`, {}, { // Changed to PATCH and sent an empty body .patch(
headers: { `/api/unmap/${id}`,
"Access-Control-Allow-Origin": "*", { mappedTM: true },
Authorization: `Bearer ${token}`, {
}, // Changed to PATCH and sent an empty body
}) headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
},
}
)
.then((res) => { .then((res) => {
swal({ swal({
title: "Deleted", title: "Deleted",
@ -207,8 +211,8 @@ const ViewRetailDistributorTM = () => {
const handleAddRetailDistributor = async (rdid) => { const handleAddRetailDistributor = async (rdid) => {
try { try {
await axios.put( await axios.put(
`/api/v1/mappedtm/${rdid}`, `/api/mapped/${rdid}`,
{ mappedby: id }, { mappedTM: id },
{ {
headers: { headers: {
Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
@ -260,7 +264,7 @@ const ViewRetailDistributorTM = () => {
{/* Right Side with the Button */} {/* Right Side with the Button */}
<div className="page-title-right"> <div className="page-title-right">
{/* <Button <Button
variant="contained" variant="contained"
color="primary" color="primary"
style={{ style={{
@ -271,7 +275,7 @@ const ViewRetailDistributorTM = () => {
onClick={handleOpenModal} onClick={handleOpenModal}
> >
Add Retail Distributor Add Retail Distributor
</Button> */} </Button>
<Button <Button
variant="contained" variant="contained"
color="secondary" color="secondary"
@ -292,7 +296,7 @@ const ViewRetailDistributorTM = () => {
</Button> </Button>
</div> </div>
</div> </div>
{/* <Dialog <Dialog
open={openModal} open={openModal}
onClose={handleCloseModal} onClose={handleCloseModal}
maxWidth="md" maxWidth="md"
@ -300,96 +304,109 @@ const ViewRetailDistributorTM = () => {
> >
<DialogTitle>Search and Add Retail Distributor</DialogTitle> <DialogTitle>Search and Add Retail Distributor</DialogTitle>
<DialogContent> <DialogContent>
<div style={{ display: "flex", gap: "16px", marginBottom:"2rem",marginTop:"-1rem" }}> <div
<TextField style={{
label="Retail Distributor Trade Name" display: "flex",
placeholder="Retail Distributor Trade name" gap: "16px",
inputRef={rdnameRef} marginBottom: "2rem",
onChange={handlemodalSearchChange} marginTop: "-1rem",
disabled={loading} }}
style={{ flex: 1, marginRight: "16px" }} >
/> <TextField
<TextField label="Retail Distributor Trade Name"
style={{ flex: 1 }} placeholder="Retail Distributor Trade name"
label="Mobile Number" inputRef={rdnameRef}
placeholder="Mobile Number" onChange={handlemodalSearchChange}
inputRef={rdmobileRef} disabled={loading}
onChange={handlemodalSearchChange} style={{ flex: 1, marginRight: "16px" }}
disabled={loading} />
/> <TextField
</div> style={{ flex: 1 }}
<div className="table-responsive table-shoot mt-3"> label="Mobile Number"
<table className="table table-centered table-nowrap"> placeholder="Mobile Number"
<thead> inputRef={rdmobileRef}
<tr> onChange={handlemodalSearchChange}
<th>Trade Name</th> disabled={loading}
<th>Mobile</th> />
<th>Approved PD</th> </div>
<th>Action</th> <div className="table-responsive table-shoot mt-3">
</tr> <table className="table table-centered table-nowrap">
</thead> <thead>
<tbody> <tr>
{modalRetailDistributors.length > 0 ? ( <th>Trade Name</th>
modalRetailDistributors.map((RD) => ( <th>Mobile</th>
<tr key={RD._id}> <th>Email</th>
<td>{RD.trade_name}</td> <th>SC</th>
<td>{RD.mobile_number}</td> <th>TM</th>
<td>{RD.principal_distributer?.name}</td> <th>PD</th>
<td> <th>Action</th>
<Button </tr>
variant="contained" </thead>
color="primary" <tbody>
onClick={() => {modalRetailDistributors.length > 0 ? (
handleAddRetailDistributor(RD._id) modalRetailDistributors.map((RD) => (
} <tr key={RD._id}>
> <td>{RD.kycDetails.trade_name}</td>
Add <td>{RD.mobile_number}</td>
</Button> <td>{RD.email}</td>
</td> <td>{RD.mappedSCDetails?.name || "N/A"}</td>
</tr> <td>{RD.mappedTMDetails?.name || "N/A"}</td>
)) <td>{RD.principalDetails?.name || "N/A"}</td>
) : ( <td>
<tr> <Button
<td colSpan="6" className="text-center"> variant="contained"
No Retail Distributor found! color="primary"
onClick={() =>
handleAddRetailDistributor(RD._id)
}
>
Add
</Button>
</td> </td>
</tr> </tr>
)} ))
</tbody> ) : (
</table> <tr>
<td colSpan="6" className="text-center">
No Retail Distributor found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="d-flex justify-content-between">
<div>
Showing {modalRetailDistributors?.length} of{" "}
{modalTotalData} entries
</div> </div>
<div className="d-flex justify-content-between"> <div>
<div> <button
Showing {modalRetailDistributors?.length} of{" "} onClick={handlePreviousPage}
{modalTotalData} entries disabled={modalcurrentPage === 1 || loading}
</div> className="btn btn-primary"
<div> >
<button Previous
onClick={handlePreviousPage} </button>
disabled={modalcurrentPage === 1 || loading} <button
className="btn btn-primary" onClick={handleNextPage}
> disabled={
Previous modalRetailDistributors?.length < modalitemPerPage ||
</button> loading
<button }
onClick={handleNextPage} className="btn btn-primary ml-2"
disabled={ >
modalRetailDistributors?.length < Next
modalitemPerPage || loading </button>
}
className="btn btn-primary ml-2"
>
Next
</button>
</div>
</div> </div>
</div>
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={handleCloseModal} color="secondary"> <Button onClick={handleCloseModal} color="secondary">
Cancel Cancel
</Button> </Button>
</DialogActions> </DialogActions>
</Dialog> */} </Dialog>
</div> </div>
</div> </div>
@ -430,7 +447,7 @@ const ViewRetailDistributorTM = () => {
disabled={loading} disabled={loading}
/> />
</div> </div>
{/* <div className="col-lg-3"> <div className="col-lg-3">
<label>Mobile Number:</label> <label>Mobile Number:</label>
<input <input
type="text" type="text"
@ -440,7 +457,7 @@ const ViewRetailDistributorTM = () => {
onChange={handleSearchChange} onChange={handleSearchChange}
disabled={loading} disabled={loading}
/> />
</div> */} </div>
</div> </div>
<div className="table-responsive table-shoot mt-3"> <div className="table-responsive table-shoot mt-3">
@ -450,12 +467,12 @@ const ViewRetailDistributorTM = () => {
style={{ background: "#ecdddd" }} style={{ background: "#ecdddd" }}
> >
<tr> <tr>
<th className="text-start">ID</th> <th className="text-start">UniqueID</th>
<th className="text-start">Trade Name</th> <th className="text-start">Trade Name</th>
<th className="text-start">Approved PD</th>
<th className="text-start">Mobile</th> <th className="text-start">Mobile</th>
<th className="text-start">Email</th>
<th className="text-start">Created On</th> <th className="text-start">Created On</th>
{/* <th className="text-start">Action</th> */} <th className="text-start">Action</th>
</tr> </tr>
</thead> </thead>
@ -470,9 +487,10 @@ const ViewRetailDistributorTM = () => {
retaildistributorData?.map((RD, i) => { retaildistributorData?.map((RD, i) => {
return ( return (
<tr key={i}> <tr key={i}>
<td className="text-start">{RD?._id}</td> <td className="text-start">{RD?.uniqueId}</td>
<td className="text-start">{RD?.trade_name}</td> <td className="text-start">
<td className="text-start">{RD?.principal_distributer?.name}</td> {RD?.kycDetails?.trade_name}
</td>
<td className="text-start"> <td className="text-start">
{RD?.mobile_number ? ( {RD?.mobile_number ? (
RD?.mobile_number RD?.mobile_number
@ -482,18 +500,24 @@ const ViewRetailDistributorTM = () => {
</small> </small>
)} )}
</td> </td>
<td className="text-start"> {new Date(
RD.updatedAt <td className="text-start">{RD?.email}</td>
).toLocaleString("en-IN", { <td className="text-start">
weekday: "short", {" "}
month: "short", {new Date(RD.createdAt).toLocaleString(
day: "numeric", "en-IN",
year: "numeric", {
hour: "numeric", weekday: "short",
minute: "numeric", month: "short",
hour12: true, day: "numeric",
})}</td> year: "numeric",
{/* <td className="text-start"> hour: "numeric",
minute: "numeric",
hour12: true,
}
)}
</td>
<td className="text-start">
<button <button
type="button" type="button"
style={{ color: "white" }} style={{ color: "white" }}
@ -502,7 +526,7 @@ const ViewRetailDistributorTM = () => {
> >
Delete Delete
</button> </button>
</td> */} </td>
</tr> </tr>
); );
}) })
@ -532,8 +556,7 @@ const ViewRetailDistributorTM = () => {
<button <button
onClick={() => setCurrentPage(currentPage + 1)} onClick={() => setCurrentPage(currentPage + 1)}
disabled={ disabled={
retaildistributorData?.length < itemPerPage || retaildistributorData?.length < itemPerPage || loading
loading
} }
className="btn btn-primary ml-2" className="btn btn-primary ml-2"
> >

View File

@ -60,6 +60,7 @@ const ViewSalesCoOrdinatorTM = () => {
}, },
}) })
.then((res) => { .then((res) => {
// console.log(res.data.salesCoOrinators);
setSalesCoOrdinatorsData(res.data?.salesCoOrinators); setSalesCoOrdinatorsData(res.data?.salesCoOrinators);
setTotalData(res.data?.total_data); setTotalData(res.data?.total_data);
}) })
@ -289,7 +290,7 @@ const ViewSalesCoOrdinatorTM = () => {
</Button> </Button>
</div> </div>
</div> </div>
<Dialog open={openModal} onClose={handleCloseModal} fullWidth> <Dialog open={openModal} onClose={handleCloseModal} maxWidth="md" fullWidth>
<DialogTitle>Search and Add Sales Coordinator</DialogTitle> <DialogTitle>Search and Add Sales Coordinator</DialogTitle>
<DialogContent> <DialogContent>
<TextField <TextField
@ -315,6 +316,7 @@ const ViewSalesCoOrdinatorTM = () => {
<th>Id</th> <th>Id</th>
<th>Name</th> <th>Name</th>
<th>Mobile</th> <th>Mobile</th>
<th>TM</th>
<th>Action</th> <th>Action</th>
</tr> </tr>
</thead> </thead>
@ -324,6 +326,7 @@ const ViewSalesCoOrdinatorTM = () => {
<td>{coordinator.uniqueId}</td> <td>{coordinator.uniqueId}</td>
<td>{coordinator.name}</td> <td>{coordinator.name}</td>
<td>{coordinator.mobileNumber}</td> <td>{coordinator.mobileNumber}</td>
<td>{coordinator.mappedby?.name || "N/A"}</td>
<td> <td>
<Button <Button
variant="contained" variant="contained"

View File

@ -10,6 +10,7 @@ const Dashboard = () => {
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
const [salescoordinator, setSalescoordinator] = useState([]); const [salescoordinator, setSalescoordinator] = useState([]);
const [territorymanager, setTerritorymanager] = useState([]); const [territorymanager, setTerritorymanager] = useState([]);
const [retaildistributor, setRetaildistributor] = useState([]);
const token = isAutheticated(); const token = isAutheticated();
const getAllUsers = async () => { const getAllUsers = async () => {
@ -40,28 +41,47 @@ const Dashboard = () => {
// console.log(res.data) // console.log(res.data)
setTerritorymanager(res.data.total_data); setTerritorymanager(res.data.total_data);
}; };
// //2nd const getAllretaildistributor = async () => {
// const [category, setCategory] = useState([]); let res = await axios.get(`/api/getAllRD`, {
// const getAllCategory = async () => { headers: {
// let res = await axios.get(`/api/category/getCategories`, { Authorization: `Bearer ${token}`,
// headers: { },
// Authorization: `Bearer ${token}`, });
// }, // console.log(res.data)
// }); setRetaildistributor(res.data.total_data);
// // console.log(res.data); };
// setCategory(res?.data?.categories); //2nd
// }; const [category, setCategory] = useState(null);
const getAllCategory = async () => {
let res = await axios.get(`/api/category/getCategories`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setCategory(res?.data?.total_data);
};
// //3rd // //3rd
// const [product, setProduct] = useState([]); const [product, setProduct] = useState(null);
// const getAllProduct = async () => { const getAllProduct = async () => {
// let res = await axios.get(`/api/product/getAll/user/`, { let res = await axios.get(`/api/product/getAll/user/`, {
// headers: { headers: {
// Authorization: `Bearer ${token}`, Authorization: `Bearer ${token}`,
// }, },
// }); });
// // console.log(res.data); // console.log(res.data);
// setProduct(res?.data?.product); setProduct(res?.data?.total_data);
// }; };
const [Brand, setBrand] = useState(null);
const getAllBrands = async () => {
let res = await axios.get(`/api/brand/getBrands`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
// console.log(res.data);
setBrand(res?.data?.total_data);
};
// // 3rd // // 3rd
// const [Requests, setRequests] = useState([]); // const [Requests, setRequests] = useState([]);
// const getAllRequests = async () => { // const getAllRequests = async () => {
@ -141,8 +161,10 @@ const Dashboard = () => {
getAllUsers(); getAllUsers();
getAllsalescoordinator(); getAllsalescoordinator();
getAllterritorymanager(); getAllterritorymanager();
// getAllCategory(); getAllretaildistributor();
// getAllProduct(); getAllCategory();
getAllProduct();
getAllBrands();
// getAllRequests(); // getAllRequests();
}, [token]); }, [token]);
return ( return (
@ -151,9 +173,10 @@ const Dashboard = () => {
users={users} users={users}
salescoordinator={salescoordinator} salescoordinator={salescoordinator}
territorymanager={territorymanager} territorymanager={territorymanager}
// category={category} retaildistributor={retaildistributor}
// product={product} category={category}
// Requests={Requests} product={product}
Brand={Brand}
/> />
</> </>
); );

View File

@ -346,7 +346,7 @@ const CancelledOrders = () => {
searchText, searchText,
}, },
}); });
console.log(response); // console.log(response);
setOrders(response?.data?.cancelledOrders); setOrders(response?.data?.cancelledOrders);
setTotalOrders(response?.data?.totalOrders); setTotalOrders(response?.data?.totalOrders);
} catch (error) { } catch (error) {

View File

@ -346,7 +346,7 @@ const DeliveredOrders = () => {
searchText, searchText,
}, },
}); });
console.log(response); // console.log(response);
setOrders(response?.data?.deliveredOrders); setOrders(response?.data?.deliveredOrders);
setTotalOrders(response?.data?.totalOrders); setTotalOrders(response?.data?.totalOrders);
} catch (error) { } catch (error) {

View File

@ -348,7 +348,7 @@ const DispatchedOrders = () => {
searchText, searchText,
}, },
}); });
console.log(response); // console.log(response);
setOrders(response?.data?.dispatchedOrders); setOrders(response?.data?.dispatchedOrders);
setTotalOrders(response?.data?.totalOrders); setTotalOrders(response?.data?.totalOrders);
} catch (error) { } catch (error) {

View File

@ -696,7 +696,7 @@ const NewOrders = () => {
searchText, searchText,
}, },
}); });
console.log(response); // console.log(response);
setOrders(response?.data?.placedOrders); setOrders(response?.data?.placedOrders);
setTotalOrders(response?.data?.totalOrders); setTotalOrders(response?.data?.totalOrders);
} catch (error) { } catch (error) {

View File

@ -350,7 +350,7 @@ const ProcessingOrders = () => {
searchText, searchText,
}, },
}); });
console.log(response); // console.log(response);
setOrders(response?.data?.processingOrders); setOrders(response?.data?.processingOrders);
setTotalOrders(response?.data?.totalOrders); setTotalOrders(response?.data?.totalOrders);
} catch (error) { } catch (error) {

View File

@ -18,116 +18,125 @@ import axios from "axios";
{ {
/* <BeatLoader color="#36d7b7" /> */ /* <BeatLoader color="#36d7b7" /> */
} }
const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => { const WidgetsDropdown = ({
// const WidgetsDropdown = ({ users, category, product, Requests }) => { users,
// const token = isAutheticated(); salescoordinator,
// const [orders, setOrders] = useState([]); territorymanager,
// const [todayorders, setTodayOrders] = useState([]); retaildistributor,
// const [monthorders, setMonthOrders] = useState([]); Brand,
// const [yearorders, setYearOrders] = useState([]); product,
// const [lastyearorders, setLastYearOrders] = useState([]); category,
// const [processingorders, setProcessingOrders] = useState([]); }) => {
// const [dispatchedorders, setDispatchedOrders] = useState([]); // const WidgetsDropdown = ({ users, category, product, Requests }) => {
// const [deliveredorders, setDeliveredOrders] = useState([]); // const token = isAutheticated();
// const [cancelledorders, setCancelledOrders] = useState([]); // const [orders, setOrders] = useState([]);
// const getAllOrder = async () => { // const [todayorders, setTodayOrders] = useState([]);
// let res = await axios.get(`/api/order/getAll/`, { // const [monthorders, setMonthOrders] = useState([]);
// headers: { // const [yearorders, setYearOrders] = useState([]);
// Authorization: `Bearer ${token}`, // const [lastyearorders, setLastYearOrders] = useState([]);
// }, // const [processingorders, setProcessingOrders] = useState([]);
// }); // const [dispatchedorders, setDispatchedOrders] = useState([]);
// // console.log(res.data); // const [deliveredorders, setDeliveredOrders] = useState([]);
// setOrders(res?.data?.order); // const [cancelledorders, setCancelledOrders] = useState([]);
// setTodayOrders( // const getAllOrder = async () => {
// res?.data?.order?.filter((order) => { // let res = await axios.get(`/api/order/getAll/`, {
// return ( // headers: {
// new Date(order.createdAt).toDateString() === new Date().toDateString() // Authorization: `Bearer ${token}`,
// ); // },
// }) // });
// ); // // console.log(res.data);
// setMonthOrders( // setOrders(res?.data?.order);
// res?.data?.order?.filter((order) => { // setTodayOrders(
// return new Date(order.createdAt).getMonth() === new Date().getMonth(); // res?.data?.order?.filter((order) => {
// }) // return (
// ); // new Date(order.createdAt).toDateString() === new Date().toDateString()
// setYearOrders( // );
// res?.data?.order?.filter((order) => { // })
// return ( // );
// new Date(order.createdAt).getFullYear() === new Date().getFullYear() // setMonthOrders(
// ); // res?.data?.order?.filter((order) => {
// }) // return new Date(order.createdAt).getMonth() === new Date().getMonth();
// ); // })
// setLastYearOrders( // );
// res?.data?.order?.filter((order) => { // setYearOrders(
// return ( // res?.data?.order?.filter((order) => {
// new Date(order.createdAt).getFullYear() === // return (
// new Date().getFullYear() - 1 // new Date(order.createdAt).getFullYear() === new Date().getFullYear()
// ); // );
// }) // })
// ); // );
// }; // setLastYearOrders(
// const getProcessingOrder = async () => { // res?.data?.order?.filter((order) => {
// let res = await axios.get(`/api/order/getAll/processing`, { // return (
// headers: { // new Date(order.createdAt).getFullYear() ===
// Authorization: `Bearer ${token}`, // new Date().getFullYear() - 1
// }, // );
// }); // })
// // console.log(res.data); // );
// setProcessingOrders(res?.data?.order); // };
// }; // const getProcessingOrder = async () => {
// const getDispatchedOrder = async () => { // let res = await axios.get(`/api/order/getAll/processing`, {
// let res = await axios.get(`/api/order/getAll/dispatched`, { // headers: {
// headers: { // Authorization: `Bearer ${token}`,
// Authorization: `Bearer ${token}`, // },
// }, // });
// }); // // console.log(res.data);
// // console.log(res.data); // setProcessingOrders(res?.data?.order);
// setDispatchedOrders(res?.data?.order); // };
// }; // const getDispatchedOrder = async () => {
// const getDeliveredOrder = async () => { // let res = await axios.get(`/api/order/getAll/dispatched`, {
// let res = await axios.get(`/api/order/getAll/delivered`, { // headers: {
// headers: { // Authorization: `Bearer ${token}`,
// Authorization: `Bearer ${token}`, // },
// }, // });
// }); // // console.log(res.data);
// // console.log(res.data); // setDispatchedOrders(res?.data?.order);
// setDeliveredOrders(res?.data?.order); // };
// }; // const getDeliveredOrder = async () => {
// const getCancelledOrder = async () => { // let res = await axios.get(`/api/order/getAll/delivered`, {
// let res = await axios.get(`/api/order/getAll/cancelled`, { // headers: {
// headers: { // Authorization: `Bearer ${token}`,
// Authorization: `Bearer ${token}`, // },
// }, // });
// }); // // console.log(res.data);
// // console.log(res.data); // setDeliveredOrders(res?.data?.order);
// setCancelledOrders(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(() => { // useEffect(() => {
// getAllOrder(); // getAllOrder();
// getProcessingOrder(); // getProcessingOrder();
// getDispatchedOrder(); // getDispatchedOrder();
// getDeliveredOrder(); // getDeliveredOrder();
// getCancelledOrder(); // getCancelledOrder();
// }, [token]); // }, [token]);
// const date = new Date(); // const date = new Date();
// const day = date.getDate(); // const day = date.getDate();
// const suffix = // const suffix =
// day === 1 || day === 21 || day === 31 // day === 1 || day === 21 || day === 31
// ? "st" // ? "st"
// : day === 2 || day === 22 // : day === 2 || day === 22
// ? "nd" // ? "nd"
// : day === 3 || day === 23 // : day === 3 || day === 23
// ? "rd" // ? "rd"
// : "th"; // : "th";
// const month = date.toLocaleDateString("en-US", { month: "long" }); // const month = date.toLocaleDateString("en-US", { month: "long" });
// const formattedDate = `${day}${suffix} ${month}`; // const formattedDate = `${day}${suffix} ${month}`;
// // console.log(formattedDate); // // console.log(formattedDate);
// const year = date.toLocaleDateString("en-US", { year: "numeric" }); // const year = date.toLocaleDateString("en-US", { year: "numeric" });
// const formattedmonth = `${month} ${year}`; // const formattedmonth = `${month} ${year}`;
return ( return (
<> <>
<h4>Principal Distributor</h4> <h4>Users</h4>
{/* <h4>Principal Distributor</h4> */}
<CRow> <CRow>
<CCol sm={6} lg={3}> <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
@ -137,9 +146,20 @@ const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => {
title="Total Principal Distributor" title="Total Principal Distributor"
/> />
</CCol> </CCol>
</CRow> {/* </CRow> */}
<h4>Sales Coordinator</h4> {/* <h4>Retail Distributor</h4> */}
<CRow> {/* <CRow> */}
<CCol sm={6} lg={3}>
<CWidgetStatsA
className="mb-4"
color="primary"
value={<>{retaildistributor}</>}
title="Total Reatil Distributor"
/>
</CCol>
{/* </CRow> */}
{/* <h4>Sales Coordinator</h4> */}
{/* <CRow> */}
<CCol sm={6} lg={3}> <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
className="mb-4" className="mb-4"
@ -148,9 +168,9 @@ const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => {
title="Total Sales Coordinator" title="Total Sales Coordinator"
/> />
</CCol> </CCol>
</CRow> {/* </CRow> */}
<h4>Territory Manager</h4> {/* <h4>Territory Manager</h4> */}
<CRow> {/* <CRow> */}
<CCol sm={6} lg={3}> <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
className="mb-4" className="mb-4"
@ -159,8 +179,8 @@ const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => {
title="Total Territory Manager" title="Total Territory Manager"
/> />
</CCol> </CCol>
</CRow> </CRow>
{/* <CCol sm={6} lg={3}> {/* <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
className="mb-4" className="mb-4"
color="primary" color="primary"
@ -224,14 +244,22 @@ const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => {
/> */} /> */}
{/* </CCol> */} {/* </CCol> */}
{/* </CRow> {/* </CRow> */}
<h4>Products and Categories</h4> <h4>Products, Categories and Brands</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={<>{category.length}</>} value={<>{product}</>}
title="Total products"
/>
</CCol>
<CCol sm={6} lg={3}>
<CWidgetStatsA
className="mb-4"
color="primary"
value={<>{category}</>}
title="Total Categories" title="Total Categories"
/> />
</CCol> </CCol>
@ -239,12 +267,12 @@ const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => {
<CWidgetStatsA <CWidgetStatsA
className="mb-4" className="mb-4"
color="primary" color="primary"
value={<>{product.length}</>} value={<>{Brand}</>}
title="Total products" title="Total Brands"
/> />
</CCol> </CCol>
</CRow> </CRow>
<h4>Orders</h4> {/* <h4>Orders</h4>
<CRow> <CRow>
<CCol sm={6} lg={3}> <CCol sm={6} lg={3}>
<CWidgetStatsA <CWidgetStatsA
@ -318,7 +346,7 @@ const WidgetsDropdown = ({ users,salescoordinator,territorymanager }) => {
title="Orders - Cancelled" title="Orders - Cancelled"
/> />
</CCol> </CCol>
</CRow>*/} </CRow> */}
</> </>
); );
}; };