admin/src/views/TerritoryManager/ViewPrincipalDistributorTM.js
2024-12-13 15:44:15 +05:30

555 lines
20 KiB
JavaScript

import React, { useState, useEffect, useRef, useCallback } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";
import { Button } from "@mui/material";
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 ViewPrincipalDistributorTM = () => {
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/territorymanager/getOne/${id}`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => setData(response.data.data))
.catch((error) => console.error("Error fetching TM data:", error));
}, [id, token]);
// Fetch Principal Distributors data
const getTMsprincipaldistributorData = async () => {
setLoading(true);
axios
.get(`/api/v1/getbyTmId/${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(() => {
getTMsprincipaldistributorData();
}, [success, itemPerPage, currentPage]);
// Debounced search for Principal Distributors
const debouncedSearch = useCallback(
debounce(() => {
setCurrentPage(1);
getTMsprincipaldistributorData();
}, 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,
},
});
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/unmap/${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/mappedtm/${pdid}`,
{ mappedby: 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"
style={{
fontWeight: "bold",
marginBottom: "1rem",
textTransform: "capitalize",
}}
sx={{
backgroundColor: "white",
color: "black",
"&:hover": {
backgroundColor: "#0B0689",
color: "white",
},
}}
onClick={handleOpenModal}
>
Add Principal Distributor
</Button>
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
marginBottom: "1rem",
marginLeft: "1rem",
textTransform: "capitalize",
}}
onClick={() => navigate("/territorymanagers")}
>
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 ViewPrincipalDistributorTM;