diff --git a/src/helpers/data.js b/src/helpers/data.js index f01565f..c344a39 100644 --- a/src/helpers/data.js +++ b/src/helpers/data.js @@ -300,8 +300,11 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false }, // Check if dayOfMonth is null and match by day of week using the enum (Assigments every week) { - dayOfMonth: null, + // dayOfMonth: null, + // startTime: { gte: filterTimeFrom }, AND: [ + { dayOfMonth: null }, + { startTime: { lte: filterTimeTo } }, // startTime included { OR: [ // OR condition for repeatUntil to handle events that either end after filterDate or repeat forever { endDate: { gte: filterTimeFrom } }, // endDate included @@ -345,6 +348,7 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false console.log(`getting publishers for date: ${filterDate}, isExactTime: ${isExactTime}, isForTheMonth: ${isForTheMonth}`); + console.log`whereClause: ${JSON.stringify(whereClause)}` //include availabilities if flag is true let publishers = await prisma.publisher.findMany({ where: whereClause, @@ -418,7 +422,7 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false // return avail.dayOfMonth != null && avail.startTime >= currentMonthStart && avail.startTime <= monthInfo.lastSunday; return avail.startTime >= monthInfo.firstMonday && (noEndDateFilter || avail.startTime <= monthInfo.lastSunday); }) - pub.currentMonthAvailabilityDaysCount = pub.currentMonthAvailability.length || 0; + pub.currentMonthAvailabilityDaysCount = pub.currentMonthAvailability.length; // pub.currentMonthAvailabilityDaysCount += pub.availabilities.filter(avail => { // return avail.dayOfMonth == null; // }).length; @@ -467,6 +471,236 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false } +//ToDo: refactor this function +async function getAllPublishersWithStatistics(filterDate) { + + const prisma = common.getPrismaClient(); + const monthInfo = common.getMonthDatesInfo(new Date(filterDate)); + const dateStr = new Date(monthInfo.firstMonday).toISOString().split('T')[0]; + + let publishers = await filterPublishersNew('id,firstName,lastName,email,isActive,desiredShiftsPerMonth,lastLogin,type', 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, + type: true, + assignments: { + select: { + id: true, + shift: { + select: { + startTime: true, + endTime: true, + }, + }, + }, + }, + availabilities: { + select: { + startTime: true, + endTime: true, + dateOfEntry: true, + isFromPreviousAssignment: true, + }, + // where: { + // startTime: { + // gte: new Date(monthInfo.firstMonday), + // }, + // }, + + }, + }, + }); + + + let prevMnt = new Date(); + prevMnt.setMonth(prevMnt.getMonth() - 1); + let prevMonthInfo = common.getMonthDatesInfo(prevMnt); + + + allPublishers.forEach(publisher => { + // Use helper functions to calculate and assign assignment counts + publisher.currentMonthAssignments = countAssignments(publisher.assignments, monthInfo.firstMonday, monthInfo.lastSunday); + publisher.previousMonthAssignments = countAssignments(publisher.assignments, prevMonthInfo.firstMonday, prevMonthInfo.lastSunday); + + publisher.lastLogin = publisher.lastLogin ? publisher.lastLogin.toISOString() : null; + // Convert date formats within the same iteration + convertShiftDates(publisher.assignments); + convertAvailabilityDates(publisher.availabilities); + // common.convertDatesToISOStrings(publisher.availabilities); //ToDo fix the function to work with this sctucture and use it + }); + + + //merge allPublishers with publishers + allPublishers = allPublishers.map(pub => { + const found = publishers.find(publisher => publisher.id === pub.id); + if (found) { + return { ...pub, ...found }; + } + return pub; + }); + + return allPublishers; +} + + +// 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 convertAvailabilityDates(availabilities) { + availabilities.forEach(av => { + av.startTime = new Date(av.startTime).toISOString(); + av.endTime = new Date(av.endTime).toISOString(); + av.dateOfEntry = new Date(av.dateOfEntry).toISOString() + }); +} +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(); + } + }); +} + + +async function getCalendarEvents(publisherId, date, availabilities = true, assignments = true) { + const result = []; + // let pubs = await filterPublishers("id,firstName,lastName,email".split(","), "", date, assignments, availabilities, date ? true : false, publisherId); + + const prisma = common.getPrismaClient(); + let publisher = await prisma.publisher.findUnique({ + where: { + id: publisherId + }, + select: { + id: true, + firstName: true, + lastName: true, + email: true, + availabilities: { + select: { + id: true, + dayOfMonth: true, + dayofweek: true, + weekOfMonth: true, + startTime: true, + endTime: true, + name: true, + isFromPreviousAssignment: true, + isFromPreviousMonth: true, + repeatWeekly: true, + isWithTransportIn: true, + isWithTransportOut: true, + } + }, + assignments: { + select: { + id: true, + shift: { + select: { + id: true, + startTime: true, + endTime: true, + isPublished: true + } + } + } + } + } + }); + + if (publisher) { + if (availabilities) { + publisher.availabilities?.forEach(item => { + result.push({ + ...item, + title: common.getTimeFomatted(new Date(item.startTime)) + "-" + common.getTimeFomatted(new Date(item.endTime)), //item.name, + date: new Date(item.startTime), + startTime: new Date(item.startTime), + endTime: new Date(item.endTime), + publisherId: publisher.id, + type: "availability", + isFromPreviousAssignment: item.isFromPreviousAssignment, + isWithTransportIn: item.isWithTransportIn, + isWithTransportOut: item.isWithTransportOut, + }); + }); + } + if (assignments) { + //only published shifts + + publisher.assignments?.filter( + assignment => assignment.shift.isPublished + ).forEach(item => { + result.push({ + ...item, + title: common.getTimeFomatted(new Date(item.shift.startTime)) + "-" + common.getTimeFomatted(new Date(item.shift.endTime)), + date: new Date(item.shift.startTime), + startTime: new Date(item.shift.startTime), + endTime: new Date(item.shift.endTime), + publisherId: item.publisherid, + type: "assignment", + }); + }); + + } + } + + + return result; +} + // exports.getCoverMePublisherEmails = async function (shiftId) { async function getCoverMePublisherEmails(shiftId) { const prisma = common.getPrismaClient(); @@ -579,5 +813,7 @@ module.exports = { runSqlFile, getAvailabilities, filterPublishersNew, - getCoverMePublisherEmails + getCoverMePublisherEmails, + getAllPublishersWithStatistics, + getCalendarEvents }; \ No newline at end of file