import React from "react";
import api from "../api.js";
import {useState, useEffect} from "react";
export default function ReportsModule() {
const username = localStorage.getItem('username');
const [reports, setReports] = useState([]);
const [month, setMonth] = useState("");
const [year, setYear] = useState("");
const [account, setAccount] = useState("");
const [accounts, setAccounts] = useState([]);
const [loading, setLoading] = useState(false);
const [rates, setRates] = useState({});
const [loadingRates, setLoadingRates] = useState(false);
const [grandTotal, setGrandTotal] = useState(0);
useEffect(() => {
const fetchAccounts = async () => {
setLoading(true);
try {
const response = await api.get('/accounts/');
if (response.status === 200) {
const sortedAccounts = [...response.data].sort((a, b) => a.store - b.store);
setAccounts(sortedAccounts);
}
} catch (error) {
alert(error);
} finally {
setLoading(false);
}
};
fetchAccounts();
}, []);
const fetchServiceVisits = async () => {
if (month !== "" && year !== "" && account !== "") {
setLoading(true);
try {
const response = await api.get(
`visits/?username=${username}&month=${month}&year=${year}&account=${account}`
);
if (response.status === 200) {
const sortedVisits = [...response.data].sort((a, b) => {
if (a.short_name < b.short_name) return -1;
if (a.short_name > b.short_name) return 1;
if (a.date < b.date) return -1;
if (a.date > b.date) return 1;
return 0;
});
setReports(sortedVisits);
setGrandTotal(null); // Reset to null when fetching
setRates({}); // Reset rates
}
} catch (error) {
alert(error);
} finally {
setLoading(false);
}
} else {
alert("All fields are required!!")
}
};
const fetchRate = async (account) => {
setLoading(true);
try {
const response = await api.post('/accounts/rate/', {'account': account});
if (response.status === 200) {
return response.data['rate'];
}
} catch (error) {
alert(error);
} finally {
setLoading(false);
}
}
useEffect(() => {
const fetchAndSetRates = async () => {
if (reports.length > 0) {
setLoadingRates(true);
try {
const uniqueAccounts = [...new Set(reports.map(report => report.short_name))];
const ratePromises = uniqueAccounts.map(account => fetchRate(account));
const fetchedRates = await Promise.all(ratePromises);
const ratesObject = {};
uniqueAccounts.forEach((account, index) => {
ratesObject[account] = fetchedRates[index];
});
setRates(ratesObject);
} catch (error) {
alert(error); // Handle errors appropriately
} finally {
setLoadingRates(false);
}
}
};
fetchAndSetRates();
}, [reports]);
useEffect(() => {
if (!loadingRates && Object.keys(rates).length > 0) {
const closedVisitsData = reports.reduce((count, visit) => {
if (visit.status === "Closed") {
count[visit.short_name] = {
closedVisits: (count[visit.short_name]?.closedVisits || 0) + 1,
fullName: visit.full_name,
};
}
return count;
}, {});
let totalByAccount = 0;
for (let key in closedVisitsData) {
if (rates[key] && rates[key] !== "N/A") {
totalByAccount += closedVisitsData[key].closedVisits * rates[key];
}
}
setGrandTotal(totalByAccount);
} else if (!loadingRates && reports.length === 0) {
setGrandTotal(0);
}
}, [reports, rates, loadingRates]);
const handleYear = (e) => {
setYear(e.target.value)
}
const handleMonth = (e) => {
setMonth(e.target.value)
}
const handleAccount = (e) => {
setAccount(e.target.value)
}
// Generate year options dynamically
const currentYear = new Date().getFullYear();
const yearOptions = [];
for (let y = 2024; y <= currentYear + 1; y++) {
yearOptions.push(y);
}
return (
Reports Module
{loading ?
: (
Closed Visits Detail
| Account |
Visits |
Rate |
Total |
{Object.entries(
reports.reduce(
(count, visit) => {
if (visit.status === "Closed") {
count[visit.short_name] = {
closedVisits: (count[visit.short_name]?.closedVisits || 0) + 1,
fullName: visit.full_name
}
}
return count;
}, {})
).map(
([short_name, count]) => (
| {count.fullName} |
{count.closedVisits} |
{loadingRates ? "Loading..." : (rates[short_name] || "N/A")} |
{loadingRates ? "Loading..." : rates[short_name] !== "N/A" ? count.closedVisits * rates[short_name] : "N/A"} |
)
)}
| Grand Total: |
{grandTotal} |
Open Visits Detail
| Account |
Date |
Notes |
{reports.filter(report => report.status !== 'Closed').map(report => (
{/* Assuming you have an 'id' field */}
| {report.full_name} |
{report.date} |
{report.notes ? report.notes : null} |
))}
)}
)
}