add statsFilters

This commit is contained in:
Dobromir Popov
2024-05-02 01:50:09 +03:00
parent 876b235e54
commit db17572ea6

View File

@ -1,62 +1,173 @@
import { useState } from 'react'; import { useState, useEffect, useRef } from 'react';
import Layout from "../../../components/layout"; import Layout from "../../../components/layout";
import ProtectedRoute from '../../../components/protectedRoute'; import ProtectedRoute from '../../../components/protectedRoute';
import { Prisma, UserRole } from '@prisma/client'; import { Prisma, UserRole, PublisherType } from '@prisma/client';
import axiosServer from '../../../src/axiosServer'; import axiosServer from '../../../src/axiosServer';
import common from '../../../src/helpers/common'; import common from '../../../src/helpers/common';
// import { filterPublishers, /* other functions */ } from '../../api/index'; // import { filterPublishers, /* other functions */ } from '../../api/index';
import data from '../../../src/helpers/data'; import data from '../../../src/helpers/data';
import axiosInstance from '../../../src/axiosSecure';
import { setFlagsFromString } from 'v8';
import { set } from 'date-fns';
// const data = require('../../src/helpers/data'); function ContactsPage({ allPublishers }) {
const currentMonth = new Date().getMonth();
const [selectedMonth, setSelectedMonth] = useState("");
const isMounted = useRef(false);
function ContactsPage({ publishers, allPublishers }) {
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [publisherType, setPublisherType] = useState('');
const [publishers, setPublishers] = useState(allPublishers);
const [pubWithAssignmentsCount, setPubWithAssignmentsCount] = useState(0);
const [filteredPublishers, setFilteredPublishers] = useState(allPublishers);
const filteredPublishers = allPublishers.filter((publisher) => const [sortField, setSortField] = useState('firstName');
publisher.firstName.toLowerCase().includes(searchQuery.toLowerCase()) || const [sortOrder, setSortOrder] = useState('asc');
publisher.lastName.toLowerCase().includes(searchQuery.toLowerCase()) ||
publisher.email.toLowerCase().includes(searchQuery.toLowerCase()) || const months = common.getMonthNames();
publisher.phone?.toLowerCase().includes(searchQuery.toLowerCase()) const subsetMonths = Array.from({ length: 7 }, (_, i) => {
); const monthIndex = (currentMonth - 3 + i + 12) % 12; // Adjust for year wrap-around
return {
name: months[monthIndex],
index: monthIndex + 1
};
});
const datesOn15th = Array.from({ length: 7 }, (_, i) => new Date(new Date().getFullYear(), new Date().getMonth() - 3 + i, 15))
.map(date => date.toISOString().split('T')[0]);
function handleSort(field) {
const order = sortField === field && sortOrder === 'asc' ? 'desc' : 'asc';
setSortField(field);
setSortOrder(order);
}
useEffect(() => {
let filtered = allPublishers.filter(publisher =>
(publisher.firstName.toLowerCase().includes(searchQuery.toLowerCase()) ||
publisher.lastName.toLowerCase().includes(searchQuery.toLowerCase()) ||
publisher.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
(publisher.phone?.toLowerCase().includes(searchQuery.toLowerCase()))) &&
(publisherType ? publisher.type === publisherType : true)
);
if (sortField) {
filtered.sort((a, b) => {
// Check for undefined or null values and treat them as "larger" when sorting ascending
const aValue = a[sortField] || 0; // Treat undefined, null as 0
const bValue = b[sortField] || 0; // Treat undefined, null as 0
if (aValue === 0 && bValue !== 0) return 1; // aValue is falsy, push it to end if asc
if (bValue === 0 && aValue !== 0) return -1; // bValue is falsy, push it to end if asc
if (aValue < bValue) return sortOrder === 'asc' ? -1 : 1;
if (aValue > bValue) return sortOrder === 'asc' ? 1 : -1;
return 0;
});
}
setFilteredPublishers(filtered);
}, [searchQuery, publisherType, sortField, sortOrder, allPublishers]);
useEffect(() => {
if (isMounted.current) {
const fetchData = async () => {
const month = parseInt(selectedMonth);
const filterDate = new Date(new Date().getFullYear(), month - 1, 15);
try {
const response = await axiosInstance.get(`/api/?action=getAllPublishersWithStatistics&date=${filterDate.toISOString()}`);
setPublishers(response.data);
setFilteredPublishers(response.data);
setPubWithAssignmentsCount(response.data.filter(publisher => publisher.currentMonthAvailabilityHoursCount && publisher.currentMonthAvailabilityHoursCount > 0).length);
} catch (error) {
console.error('Failed to fetch publishers data:', error);
// Optionally, handle errors more gracefully here
}
};
fetchData();
} else {
// Set the ref to true after the initial render
isMounted.current = true;
}
}, [selectedMonth]); // Dependency array includes only selectedMonth
function renderSortArrow(field) {
return sortField === field ? sortOrder === 'asc' ? ' ↑' : ' ↓' : '';
}
return ( return (
<Layout> <Layout>
<ProtectedRoute allowedRoles={[UserRole.ADMIN, UserRole.POWERUSER, UserRole.USER]}> <ProtectedRoute allowedRoles={[UserRole.ADMIN, UserRole.POWERUSER, UserRole.USER]}>
<div className="container mx-auto p-4"> <div className="container mx-auto p-4">
<h1 className="text-xl font-semibold mb-4">Статистика </h1> <h1 className="text-xl font-semibold mb-4">Статистика </h1>
<h5 className="text-lg font-semibold mb-4">{publishers.length} участника с предпочитания за месеца (от {allPublishers.length} )</h5> <h5 className="text-lg font-semibold mb-4">{pubWithAssignmentsCount} участника с предпочитания за месеца (от {allPublishers.length} )</h5>
<input <div className="mb-4 flex justify-between items-center">
type="text" <input
placeholder="Търси по име, имейл или телефон..." type="text"
value={searchQuery} placeholder="Търси по име, имейл или телефон..."
onChange={(e) => setSearchQuery(e.target.value)} value={searchQuery}
className="border border-gray-300 rounded-md px-2 py-2 mb-4 w-full text-base md:text-sm" onChange={(e) => setSearchQuery(e.target.value)}
/> className="border border-gray-300 rounded-md px-2 py-2 text-base md:text-sm flex-grow mr-2"
/>
{/* Month dropdown */}
<select
className="border border-gray-300 rounded-md px-2 py-2 text-base md:text-sm"
value={selectedMonth}
onChange={(e) => setSelectedMonth(e.target.value)}
>
<option value="">избери месец</option>
{subsetMonths.map((month) => (
<option key={month.index} value={month.index}>{month.name}</option>
))}
</select>
{/* Publisher type dropdown */}
<select
className="border border-gray-300 rounded-md px-2 py-2 text-base md:text-sm"
value={publisherType}
onChange={(e) => setPublisherType(e.target.value)}
>
<option value="">Всички типове</option>
{Object.keys(PublisherType).map((type) => (
<option key={type} value={PublisherType[type]}>{PublisherType[type]}</option>
))}
</select>
</div>
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full text-left border-collapse"> <table className="w-full text-left border-collapse">
<thead> <thead>
<tr> <tr>
<th className="border-b font-medium p-4 pl-8 pt-0 pb-3">Име</th> <th className="border-b font-medium p-4 pl-8 pt-0 pb-3 cursor-pointer" onClick={() => handleSort('firstName')}>
<th className="border-b font-medium p-4 pt-0 pb-3">Възможности</th> Име{renderSortArrow('firstName')}
<th className="border-b font-medium p-4 pt-0 pb-3">Участия</th> </th>
<th className="border-b font-medium p-4 pt-0 pb-3">Последно влизане</th> <th className="border-b font-medium p-4 pt-0 pb-3 cursor-pointer" onClick={() => handleSort('currentMonthAvailabilityDaysCount')}>
Възможности{renderSortArrow('currentMonthAvailabilityDaysCount')}
</th>
<th className="border-b font-medium p-4 pt-0 pb-3 cursor-pointer" onClick={() => handleSort('currentMonthAssignments')}>
Участия{renderSortArrow('currentMonthAssignments')}
</th>
<th className="border-b font-medium p-4 pt-0 pb-3 cursor-pointer" onClick={() => handleSort('lastLogin')}>
Последно влизане{renderSortArrow('lastLogin')}
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{filteredPublishers.map((allPub) => { {filteredPublishers.map((pub) => {
// Find the publisher in the publishers collection to access statistics // Find the publisher in the publishers collection to access statistics
const pub = publishers.find(publisher => publisher.id === allPub.id); //const pub = publishers.find(publisher => publisher.id === allPub.id);
return ( return (
<tr key={allPub.id}> <tr key={pub.id}>
<td className="border-b p-4 pl-8" title={allPub.lastUpdate}>{allPub.firstName} {allPub.lastName}</td> <td className="border-b p-4 pl-8" title={pub.lastUpdate}>{pub.firstName} {pub.lastName}</td>
{/* Display statistics if publisher is found */} {/* Display statistics if publisher is found */}
{pub ? ( {pub ? (
<> <>
<td className="border-b p-4"> <td className="border-b p-4">
<span title="Възможност: часове | дни" className={`badge py-1 px-2 rounded-md text-xs ${pub.currentMonthAvailabilityHoursCount || pub.currentMonthAvailabilityDaysCount ? 'bg-teal-500 text-white' : 'bg-teal-200 text-gray-300'} hover:underline`}> {pub.availabilities.length > 0 ? (
{pub.currentMonthAvailabilityDaysCount || 0} | {pub.currentMonthAvailabilityHoursCount || 0} <span title="Възможност: часове | дни" className={`badge py-1 px-2 rounded-md text-xs ${pub.currentMonthAvailabilityHoursCount || pub.currentMonthAvailabilityDaysCount ? 'bg-teal-500 text-white' : 'bg-teal-200 text-gray-300'} hover:underline`}>
</span> {pub.currentMonthAvailabilityDaysCount} | {pub.currentMonthAvailabilityHoursCount}
</span>
) : <span title="Няма възможности" className="badge py-1 px-2 rounded-md text-xs bg-gray-300 text-gray-500">0</span>}
</td> </td>
<td className="border-b p-4"> <td className="border-b p-4">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
@ -79,10 +190,10 @@ function ContactsPage({ publishers, allPublishers }) {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center"> <div className="flex items-center">
<span className="badge py-1 px-2 rounded-md text-xs bg-gray-300 text-gray-500" title="участия този месец"> <span className="badge py-1 px-2 rounded-md text-xs bg-gray-300 text-gray-500" title="участия този месец">
{allPub.currentMonthAssignments || 0} {pub.currentMonthAssignments}
</span> </span>
<span className="badge py-1 px-2 rounded-md text-xs bg-gray-300 text-gray-500" title="участия миналия месец"> <span className="badge py-1 px-2 rounded-md text-xs bg-gray-300 text-gray-500" title="участия миналия месец">
{allPub.previousMonthAssignments || 0} {pub.previousMonthAssignments}
</span> </span>
</div> </div>
</div> </div>
@ -106,132 +217,12 @@ function ContactsPage({ publishers, allPublishers }) {
export default ContactsPage; export default ContactsPage;
// Helper functions ToDo: move them to common and replace all implementations with the common ones
function countAssignments(assignments, startTime, endTime) {
return assignments.filter(assignment =>
assignment.shift.startTime >= startTime && assignment.shift.startTime <= endTime
).length;
}
function convertShiftDates(assignments) {
assignments.forEach(assignment => {
if (assignment.shift && assignment.shift.startTime) {
assignment.shift.startTime = new Date(assignment.shift.startTime).toISOString();
assignment.shift.endTime = new Date(assignment.shift.endTime).toISOString();
}
});
}
export const getServerSideProps = async (context) => { export const getServerSideProps = async (context) => {
const allPublishers = await data.getAllPublishersWithStatistics(new Date());
const prisma = common.getPrismaClient();
const dateStr = new Date().toISOString().split('T')[0];
let publishers = await data.filterPublishersNew('id,firstName,lastName,email,isActive,desiredShiftsPerMonth,lastLogin', dateStr, false, true, true, true, true);
// const axios = await axiosServer(context);
// const { data: publishers } = await axios.get(`api/?action=filterPublishers&assignments=true&availabilities=true&date=${dateStr}&select=id,firstName,lastName,isActive,desiredShiftsPerMonth`);
// api/index?action=filterPublishers&assignments=true&availabilities=true&date=2024-03-14&select=id%2CfirstName%2ClastName%2CisActive%2CdesiredShiftsPerMonth
publishers.forEach(publisher => {
publisher.desiredShiftsPerMonth = publisher.desiredShiftsPerMonth || 0;
publisher.assignments = publisher.assignments || [];
publisher.availabilities = publisher.availabilities || [];
publisher.lastUpdate = publisher.availabilities.reduce((acc, curr) => curr.dateOfEntry > acc ? curr.dateOfEntry : acc, null);
if (publisher.lastUpdate) {
publisher.lastUpdate = common.getDateFormated(publisher.lastUpdate);
}
else {
publisher.lastUpdate = "Няма данни";
}
//serialize dates in publisher.assignments and publisher.availabilities
publisher.assignments.forEach(assignment => {
if (assignment.shift && assignment.shift.startTime) {
assignment.shift.startTime = assignment.shift.startTime.toISOString();
assignment.shift.endTime = assignment.shift.endTime.toISOString();
}
});
publisher.availabilities.forEach(availability => {
if (availability.startTime) {
availability.startTime = availability.startTime.toISOString();
availability.endTime = availability.endTime.toISOString();
if (availability.dateOfEntry) {
availability.dateOfEntry = availability.dateOfEntry.toISOString();
}
}
});
publisher.lastLogin = publisher.lastLogin ? publisher.lastLogin.toISOString() : null;
//remove availabilities that isFromPreviousAssignment
publisher.availabilities = publisher.availabilities.filter(availability => !availability.isFromPreviousAssignment);
});
//remove publishers without availabilities
publishers = publishers.filter(publisher => publisher.availabilities.length > 0);
let allPublishers = await prisma.publisher.findMany({
select: {
id: true,
firstName: true,
lastName: true,
email: true,
phone: true,
isActive: true,
desiredShiftsPerMonth: true,
lastLogin: true,
assignments: {
select: {
id: true,
shift: {
select: {
startTime: true,
endTime: true,
},
},
},
},
},
});
let monthInfo,
currentMonthStart, currentMonthEnd,
previousMonthStart, previousMonthEnd;
monthInfo = common.getMonthDatesInfo(new Date());
currentMonthStart = monthInfo.firstMonday;
currentMonthEnd = monthInfo.lastSunday;
let prevMnt = new Date();
prevMnt.setMonth(prevMnt.getMonth() - 1);
monthInfo = common.getMonthDatesInfo(prevMnt);
previousMonthStart = monthInfo.firstMonday;
previousMonthEnd = monthInfo.lastSunday;
allPublishers.forEach(publisher => {
// Use helper functions to calculate and assign assignment counts
publisher.currentMonthAssignments = countAssignments(publisher.assignments, currentMonthStart, currentMonthEnd);
publisher.previousMonthAssignments = countAssignments(publisher.assignments, previousMonthStart, previousMonthEnd);
publisher.lastLogin = publisher.lastLogin ? publisher.lastLogin.toISOString() : null;
// Convert date formats within the same iteration
convertShiftDates(publisher.assignments);
});
// Optionally, if you need a transformed list or additional properties, map the publishers
allPublishers = allPublishers.map(publisher => ({
...publisher,
// Potentially add more computed properties or transformations here if needed
}));
allPublishers.sort((a, b) => a.firstName.localeCompare(b.firstName) || a.lastName.localeCompare(b.lastName));
return { return {
props: { props: {
publishers, allPublishers
allPublishers,
}, },
}; };
}; };