admin/src/views/RetailDistributors/RetailDistributor.js
2025-01-11 16:39:32 +05:30

515 lines
20 KiB
JavaScript

import React, { useState, useEffect, useCallback, useRef } from "react";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { Button } from "@mui/material";
import { isAutheticated } from "src/auth";
import swal from "sweetalert";
import debounce from "lodash.debounce";
import { toast } from "react-hot-toast";
const RetailDistributor = () => {
const token = isAutheticated();
const Navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [allRetailDistributorsData, setAllRetailDistributorsData] = useState(
[]
);
const nameRef = useRef();
const principalDistributorRef = useRef();
const [totalPages, setTotalPages] = useState(1);
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10);
const [totalData, setTotalData] = useState(0);
const getRetailDistributorsData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/getAllRDandorder`, {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
page: currentPage,
show: itemPerPage,
tradename: nameRef.current.value,
principaldistributor: principalDistributorRef.current.value,
},
});
// console.log(res.data);
setAllRetailDistributorsData(res.data?.Retaildistributor);
setTotalData(res.data?.total_data);
setTotalPages(res.data?.total_pages);
} 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(() => {
getRetailDistributorsData();
}, [itemPerPage, currentPage]);
const debouncedSearch = useCallback(
debounce(() => {
setCurrentPage(1);
getRetailDistributorsData();
}, 500),
[]
);
const handleSearchChange = () => {
debouncedSearch();
};
const handleDownloadReport = async () => {
try {
const response = await axios.get(
`/api/retaildistributor/download-report`,
{
headers: {
Authorization: `Bearer ${token}`,
},
responseType: "arraybuffer",
}
);
// console.log(response);
// Check if the request was successful
if (response.status === 200) {
// Convert response data into a Blob for download
const url = window.URL.createObjectURL(
new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
})
);
// Create a temporary download link and trigger the download
const link = document.createElement("a");
link.href = url;
link.download = "RetailerReport.xlsx";
document.body.appendChild(link);
link.click();
// Cleanup
document.body.removeChild(link);
window.URL.revokeObjectURL(url); // Release Blob URL memory
// Show success message
toast.success("Report downloaded successfully!");
} else {
// If the response status is not 200, display an error message
throw new Error("Failed to download report");
}
} catch (err) {
// Display a user-friendly error message
const msg = err?.response?.data?.message || "Something went wrong!";
swal({
title: "Error",
text: msg,
icon: "error",
button: "Retry",
dangerMode: true,
});
}
};
const handleReset = async (id) => {
try {
const response = await axios.put(
`/api/rd/reset-password/${id}`,
{}, // No body content required for this request
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (response.data.success) {
toast.success(
"Password reset successfully! Email sent to Retailer."
);
}
} catch (error) {
toast.error(
error.response?.data?.message ||
"Failed to reset the password. Please try again."
);
}
};
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 align-items-center justify-content-between">
<div style={{ fontSize: "22px" }} className="fw-bold">
Retailers
</div>
<div className="page-title-right">
<Button
variant="contained"
style={{
fontWeight: "bold",
marginBottom: "0.5rem",
textTransform: "capitalize",
marginRight: "0.5rem",
}}
sx={{
backgroundColor: "white",
color: "black",
"&:hover": {
backgroundColor: "#0B0689",
color: "white",
},
}}
onClick={() => {
Navigate("/retaildistributor/add");
}}
>
Add Retailer
</Button>
<Button
variant="contained"
style={{
fontWeight: "bold",
marginBottom: "0.5rem",
textTransform: "capitalize",
}}
sx={{
backgroundColor: "white",
color: "black",
"&:hover": {
backgroundColor: "#0B0689",
color: "white",
},
}}
onClick={() =>
Navigate("/add-retail-distributor/multiple", {
replace: true,
})
}
>
Upload Spreadsheet
</Button>
</div>
</div>
</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-2 col-md-2">
<div className="dataTables_length">
<label className="w-100">
Show
<select
onChange={(e) => {
setItemPerPage(Number(e.target.value));
setCurrentPage(1); // Reset to first page when changing items per page
}}
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 col-md-4">
<label>Trade Name:</label>
<input
type="text"
name="searchTerm"
placeholder="Trade name"
className="form-control"
ref={nameRef}
onChange={handleSearchChange}
disabled={loading}
/>
</div>
<div className="col-lg-3 col-md-6">
<label>Principal Distributor Name:</label>
<input
type="text"
name="searchPrincipalDistributor"
placeholder="Principal Distributor name"
className="form-control"
onChange={handleSearchChange}
disabled={loading}
ref={principalDistributorRef}
/>
</div>
<div className="col-lg-3 d-flex justify-content-start mt-lg-0 mb-lg-0 mt-1 mb-1 align-items-center">
<Button
variant="contained"
color="primary"
size="small"
onClick={handleDownloadReport}
disabled={loading}
>
Download Report
</Button>
</div>
</div>
<div className="table-responsive table-shoot">
<table className="table table-centered table-nowrap">
<thead
className="thead-light"
style={{ background: "#ecdddd" }}
>
<tr>
<th style={{ width: "10%" }}>ID</th>
<th style={{ width: "12%" }}>Trade Name</th>
<th style={{ width: "10%" }}>Created On</th>
<th style={{ width: "14%" }}>
Principal Distributor
</th>
<th style={{ width: "14%" }}>Territory Manager</th>
<th style={{ width: "14%" }}>Sales Coordinator</th>
<th style={{ width: "6%" }}>Orders</th>
<th style={{ width: "6%" }}>Mapping</th>
<th style={{ width: "11%" }}>Action</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td className="text-center" colSpan="9">
Loading...
</td>
</tr>
) : allRetailDistributorsData.length > 0 ? (
allRetailDistributorsData.map((retailDistributor) => (
<tr key={retailDistributor._id}>
<td className="text-start">
{retailDistributor.uniqueId}
</td>
<td className="text-start">
{retailDistributor.kycDetails.trade_name}
</td>
<td className="text-start">
{new Date(
retailDistributor.createdAt
).toLocaleString("en-IN", {
// weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
// hour: "numeric",
// minute: "numeric",
// hour12: true,
})}
</td>
<td className="text-start">
{retailDistributor?.principalDetails?.name ||
"N/A"}
</td>
<td className="text-start">
{retailDistributor?.mappedTMDetails?.name ||
"N/A"}
</td>
<td className="text-start">
{retailDistributor?.mappedSCDetails?.name ||
"N/A"}
</td>
<td className="text-center">
<Link
to={`/retailerdistributor/orders/${retailDistributor._id}`}
>
<button
style={{
color: "black",
marginRight: "1rem",
}}
type="button"
className="btn btn-warning btn-sm waves-effect waves-light btn-table ml-2"
>
{retailDistributor?.totalOrders}
</button>
</Link>
</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">
{/* On large screens: View and Stock buttons in one row */}
<div className="d-flex flex-lg-row flex-column align-items-start">
<Link
to={`/retaildistributor/view/${retailDistributor._id}`}
>
<button
type="button"
className="btn btn-info btn-sm waves-effect waves-light btn-table"
>
View
</button>
</Link>
<Link
to={`/retailerdistributor/stocks/${retailDistributor?._id}`}
>
<button
style={{ color: "white" }}
type="button"
className="btn btn-info btn-sm waves-effect waves-light btn-table ml-lg-1 ml-0 mt-1 mt-lg-0"
>
Stock
</button>
</Link>
</div>
{/* On large screens: OI and Edit buttons in one row */}
<div className="d-flex flex-lg-row flex-column align-items-start">
<Link
to={`/retaildistributor/opening-inventory/${retailDistributor?._id}`}
>
<button
type="button"
className="btn btn-info btn-sm waves-effect waves-light btn-table mt-1"
>
OI
</button>
</Link>
<Link
to={`/retaildistributor/edit/${retailDistributor._id}`}
>
<button
type="button"
className="btn btn-info btn-sm waves-effect waves-light btn-table mt-1 ml-0 ml-lg-1"
>
Edit
</button>
</Link>
<button
type="button"
className="btn btn-info btn-sm waves-effect waves-light btn-table mt-1 ml-0 ml-lg-1"
onClick={() =>
handleReset(retailDistributor._id)
}
>
Reset
</button>
</div>
</td>
</tr>
))
) : (
<tr>
<td className="text-center" colSpan="9">
No Retailer found!
</td>
</tr>
)}
</tbody>
</table>
</div>
<div className="row mt-20">
<div className="col-sm-12 col-md-6 mb-20">
<div
className="dataTables_info"
id="datatable_info"
role="status"
aria-live="polite"
>
Showing {allRetailDistributorsData?.length} of{" "}
{totalData} entries
</div>
</div>
<div className="col-sm-12 col-md-6">
<div className="dataTables_paginate paging_simple_numbers">
<ul className="pagination">
<li
className={`paginate_button page-item previous ${
currentPage === 1 ? "disabled" : ""
}`}
>
<a
className="page-link"
onClick={() =>
setCurrentPage((prev) => Math.max(prev - 1, 1))
}
aria-controls="datatable"
>
Previous
</a>
</li>
{Array.from({ length: totalPages }, (_, index) => (
<li
key={index}
className={`paginate_button page-item ${
currentPage === index + 1 ? "active" : ""
}`}
>
<a
className="page-link"
onClick={() => setCurrentPage(index + 1)}
aria-controls="datatable"
>
{index + 1}
</a>
</li>
))}
<li
className={`paginate_button page-item next ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<a
className="page-link"
onClick={() =>
setCurrentPage((prev) =>
Math.min(prev + 1, totalPages)
)
}
aria-controls="datatable"
>
Next
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default RetailDistributor;