Merge branch 'main' into production
This commit is contained in:
@ -19,7 +19,7 @@ const fetchConfig = async () => {
|
||||
return config.default;
|
||||
};
|
||||
|
||||
export default function AvailabilityForm({ publisherId, existingItems, inline, onDone, date }) {
|
||||
export default function AvailabilityForm({ publisherId, existingItems, inline, onDone, date, datePicker = false }) {
|
||||
|
||||
const router = useRouter();
|
||||
const urls = {
|
||||
@ -411,6 +411,7 @@ export default function AvailabilityForm({ publisherId, existingItems, inline, o
|
||||
className="form-checkbox h-5 w-5 text-gray-600 mx-2"
|
||||
checked={slot.isWithTransport}
|
||||
disabled={!slot.isChecked}
|
||||
// disabled={!slot.isChecked && slot.isFirst}
|
||||
onChange={() => handleTransportChange(slot)} />
|
||||
{slot.isFirst ? 'Вземане' : 'Връщане'}
|
||||
<span className="checkmark"></span>
|
||||
@ -428,15 +429,15 @@ export default function AvailabilityForm({ publisherId, existingItems, inline, o
|
||||
<ToastContainer></ToastContainer>
|
||||
<form id="formAv" className="form p-5 bg-white shadow-md rounded-lg" onSubmit={handleSubmit}>
|
||||
<h3 className="text-xl font-semibold mb-5 text-gray-800 border-b pb-2">
|
||||
{editMode ? "Редактирай" : "Нова"} възможност: {common.getDateFormatedShort(day)}
|
||||
{editMode ? "Редактирай" : "Нова"} възможност: {common.getDateFormatedShort(new Date(day))}
|
||||
</h3>
|
||||
|
||||
<LocalizationProvider dateAdapter={AdapterDateFns} localeText={bgBG} adapterLocale={bg}>
|
||||
{/* <div className="mb-2">
|
||||
<DatePicker label="Изберете дата" value={day} onChange={(value) => setDay({ value })} />
|
||||
</div> */}
|
||||
|
||||
|
||||
{datePicker && (
|
||||
<div className="mb-2">
|
||||
<DatePicker label="Изберете дата" value={day} onChange={setDay} />
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-2">
|
||||
<label className="checkbox-container">
|
||||
<input type="checkbox" checked={doRepeat} className="form-checkbox h-5 w-5 text-gray-600 mx-2"
|
||||
|
@ -101,6 +101,7 @@ export default function AvailabilityList({ publisher, showNew }) {
|
||||
inline={true}
|
||||
existingItems={selectedItem ? [selectedItem] : []}
|
||||
date={selectedItem ? new Date(selectedItem.startTime) : new Date()}
|
||||
datePicker={true}
|
||||
onDone={(item) => {
|
||||
toggleAv();
|
||||
setSelectedItem(null);
|
||||
|
@ -5,9 +5,9 @@
|
||||
"greeting": "Здравей",
|
||||
"farewell": "Довиждане",
|
||||
"changeTo": "",
|
||||
"BG": "Български",
|
||||
"EN": "Английски",
|
||||
"RU": "Руски",
|
||||
"BG": "български",
|
||||
"EN": "английски",
|
||||
"RU": "руски",
|
||||
"login": "Вход",
|
||||
"logout": "Изход"
|
||||
},
|
||||
@ -23,7 +23,7 @@
|
||||
"contactAll": "Участници",
|
||||
"feedback": "Отзиви",
|
||||
"contactUs": "За връзка",
|
||||
"admin": "Админ",
|
||||
"admin": "Администрация",
|
||||
"cart-places": "Места",
|
||||
"cart-publishers": "Вестители",
|
||||
"cart-events": "План",
|
||||
|
@ -10,6 +10,25 @@
|
||||
"logout": "logout"
|
||||
},
|
||||
"menu": {
|
||||
"dashboard": "Dashboard"
|
||||
"dashboard": "Dashboard",
|
||||
"shedule": "Schedule",
|
||||
"myshedule": "My Schedule",
|
||||
"locations": "Cart Locations",
|
||||
"cart-report": "Report",
|
||||
"cart-experience": "Experience",
|
||||
"guidelines": "Guidelines",
|
||||
"permits": "Permits",
|
||||
"contactAll": "Contacts",
|
||||
"feedback": "Feedback",
|
||||
"contactUs": "Contact Us",
|
||||
"admin": "Administration",
|
||||
"cart-places": "Places",
|
||||
"cart-publishers": "Publishers",
|
||||
"cart-events": "Events",
|
||||
"cart-calendar": "Scheduler",
|
||||
"cart-reports": "View Reports",
|
||||
"statistics": "View Statistics",
|
||||
"coverMeLogs": "View CoverMe logs",
|
||||
"translations": "Translation"
|
||||
}
|
||||
}
|
@ -30,8 +30,8 @@ import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
|
||||
//function SmwsApp({ Component, pageProps: { locale, messages, session, ...pageProps }, }: AppProps<{ session: Session }>) {
|
||||
function SmwsApp({ Component, pageProps, session, locale, messages }) {
|
||||
// dynamic locale loading using our API endpoint
|
||||
// const [locale, setLocale] = useState(router.locale || 'bg');
|
||||
// const [messages, setMessages] = useState({});
|
||||
// const [locale, setLocale] = useState(_locale);
|
||||
// const [messages, setMessages] = useState(_messages);
|
||||
// useEffect(() => {
|
||||
// async function loadLocaleData() {
|
||||
// const res = await fetch(`/api/translations/${locale}`);
|
||||
|
@ -137,7 +137,7 @@ export default async function handler(req, res) {
|
||||
break;
|
||||
|
||||
case "getCalendarEvents":
|
||||
let events = await getCalendarEvents(req.query.publisherId, day);
|
||||
let events = await dataHelper.getCalendarEvents(req.query.publisherId, day);
|
||||
res.status(200).json(events);
|
||||
|
||||
case "getPublisherInfo":
|
||||
@ -354,6 +354,8 @@ export default async function handler(req, res) {
|
||||
let data = await dataHelper.getCoverMePublisherEmails(parseInt(req.query.shiftId));
|
||||
res.status(200).json(data);
|
||||
break;
|
||||
case "getAllPublishersWithStatistics":
|
||||
res.status(200).json(await dataHelper.getAllPublishersWithStatistics(day));
|
||||
|
||||
default:
|
||||
res.status(200).json({
|
||||
@ -803,86 +805,6 @@ function matchesAvailability(avail, filterDate) {
|
||||
return avail.startTime >= filterDate && avail.startTime <= filterDateEnd;
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
},
|
||||
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,
|
||||
});
|
||||
});
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
async function replaceInAssignment(oldPublisherId, newPublisherId, shiftId) {
|
||||
|
204
pages/dash.tsx
204
pages/dash.tsx
@ -7,6 +7,8 @@ import { Availability, UserRole } from "@prisma/client";
|
||||
import ProtectedRoute, { serverSideAuth } from "../components/protectedRoute";
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axiosInstance from '../src/axiosSecure';
|
||||
// const dataHelper = require('../../src/helpers/data');
|
||||
import dataHelper from '../src/helpers/data';
|
||||
|
||||
import { authOptions } from './api/auth/[...nextauth]'
|
||||
import { getServerSession } from "next-auth/next"
|
||||
@ -85,106 +87,107 @@ export default function IndexPage({ initialItems, initialUserId }: IProps) {
|
||||
}
|
||||
|
||||
|
||||
async function getAvailabilities(userId) {
|
||||
const prismaClient = common.getPrismaClient();
|
||||
const items = await prismaClient.availability.findMany({
|
||||
where: {
|
||||
publisherId: userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
isActive: true,
|
||||
isFromPreviousAssignment: true,
|
||||
isFromPreviousMonth: true,
|
||||
dayofweek: true,
|
||||
dayOfMonth: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
repeatWeekly: true,
|
||||
endDate: true,
|
||||
publisher: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
// Convert Date objects to ISO strings
|
||||
const serializableItems = items.map(item => ({
|
||||
...item,
|
||||
startTime: item.startTime.toISOString(),
|
||||
endTime: item.endTime.toISOString(),
|
||||
name: common.getTimeFomatted(item.startTime) + "-" + common.getTimeFomatted(item.endTime),
|
||||
//endDate can be null
|
||||
endDate: item.endDate ? item.endDate.toISOString() : null,
|
||||
type: 'availability',
|
||||
// Convert other Date fields similarly if they exist
|
||||
}));
|
||||
// async function getAvailabilities(userId) {
|
||||
// const prismaClient = common.getPrismaClient();
|
||||
// const items = await prismaClient.availability.findMany({
|
||||
// where: {
|
||||
// publisherId: userId,
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// name: true,
|
||||
// isActive: true,
|
||||
// isFromPreviousAssignment: true,
|
||||
// isFromPreviousMonth: true,
|
||||
// dayofweek: true,
|
||||
// dayOfMonth: true,
|
||||
// startTime: true,
|
||||
// endTime: true,
|
||||
// repeatWeekly: true,
|
||||
// endDate: true,
|
||||
// publisher: {
|
||||
// select: {
|
||||
// firstName: true,
|
||||
// lastName: true,
|
||||
// id: true,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// });
|
||||
// // Convert Date objects to ISO strings
|
||||
// const serializableItems = items.map(item => ({
|
||||
// ...item,
|
||||
// startTime: item.startTime.toISOString(),
|
||||
// endTime: item.endTime.toISOString(),
|
||||
// name: common.getTimeFomatted(item.startTime) + "-" + common.getTimeFomatted(item.endTime),
|
||||
// //endDate can be null
|
||||
// endDate: item.endDate ? item.endDate.toISOString() : null,
|
||||
// type: 'availability',
|
||||
// // Convert other Date fields similarly if they exist
|
||||
// }));
|
||||
|
||||
/*model Assignment {
|
||||
id Int @id @default(autoincrement())
|
||||
shift Shift @relation(fields: [shiftId], references: [id], onDelete: Cascade)
|
||||
shiftId Int
|
||||
publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
|
||||
publisherId String
|
||||
isActive Boolean @default(true)
|
||||
isConfirmed Boolean @default(false)
|
||||
isWithTransport Boolean @default(false)
|
||||
Report Report[]
|
||||
}*/
|
||||
//get assignments for this user
|
||||
const assignments = await prismaClient.assignment.findMany({
|
||||
where: {
|
||||
publisherId: userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
isBySystem: true,
|
||||
isConfirmed: true,
|
||||
isWithTransport: true,
|
||||
shift: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
//select all assigned publishers names as name - comma separated
|
||||
assignments: {
|
||||
select: {
|
||||
publisher: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// /*model Assignment {
|
||||
// id Int @id @default(autoincrement())
|
||||
// shift Shift @relation(fields: [shiftId], references: [id], onDelete: Cascade)
|
||||
// shiftId Int
|
||||
// publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
|
||||
// publisherId String
|
||||
// isActive Boolean @default(true)
|
||||
// isConfirmed Boolean @default(false)
|
||||
// isWithTransport Boolean @default(false)
|
||||
// Report Report[]
|
||||
// }*/
|
||||
// //get assignments for this user
|
||||
// const assignments = await prismaClient.assignment.findMany({
|
||||
// where: {
|
||||
// publisherId: userId,
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// isBySystem: true,
|
||||
// isConfirmed: true,
|
||||
// isWithTransport: true,
|
||||
// shift: {
|
||||
// select: {
|
||||
// id: true,
|
||||
// name: true,
|
||||
// startTime: true,
|
||||
// endTime: true,
|
||||
// //select all assigned publishers names as name - comma separated
|
||||
// assignments: {
|
||||
// select: {
|
||||
// publisher: {
|
||||
// select: {
|
||||
// firstName: true,
|
||||
// lastName: true,
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// });
|
||||
|
||||
const serializableAssignments = assignments.map(item => ({
|
||||
...item,
|
||||
startTime: item.shift.startTime.toISOString(),
|
||||
endTime: item.shift.endTime.toISOString(),
|
||||
// name: item.shift.publishers.map(p => p.firstName + " " + p.lastName).join(", "),
|
||||
//name: item.shift.assignments.map(a => a.publisher.firstName[0] + " " + a.publisher.lastName).join(", "),
|
||||
name: common.getTimeFomatted(new Date(item.shift.startTime)) + "-" + common.getTimeFomatted(new Date(item.shift.endTime)),
|
||||
type: 'assignment',
|
||||
//delete shift object
|
||||
shift: null,
|
||||
publisher: { id: userId }
|
||||
}));
|
||||
// const serializableAssignments = assignments.map(item => ({
|
||||
// ...item,
|
||||
// startTime: item.shift.startTime.toISOString(),
|
||||
// endTime: item.shift.endTime.toISOString(),
|
||||
// // name: item.shift.publishers.map(p => p.firstName + " " + p.lastName).join(", "),
|
||||
// //name: item.shift.assignments.map(a => a.publisher.firstName[0] + " " + a.publisher.lastName).join(", "),
|
||||
// name: common.getTimeFomatted(new Date(item.shift.startTime)) + "-" + common.getTimeFomatted(new Date(item.shift.endTime)),
|
||||
// type: 'assignment',
|
||||
// //delete shift object
|
||||
// shift: null,
|
||||
// publisher: { id: userId }
|
||||
// }));
|
||||
|
||||
serializableItems.push(...serializableAssignments);
|
||||
// serializableItems.push(...serializableAssignments);
|
||||
|
||||
return serializableItems;
|
||||
// return serializableItems;
|
||||
|
||||
// }
|
||||
|
||||
}
|
||||
export const getServerSideProps = async (context) => {
|
||||
const auth = await serverSideAuth({
|
||||
req: context.req,
|
||||
@ -198,7 +201,16 @@ export const getServerSideProps = async (context) => {
|
||||
console.log("server role: " + role);
|
||||
const userId = session?.user.id;
|
||||
|
||||
var items = await getAvailabilities(session.user.id);
|
||||
var items = await dataHelper.getCalendarEvents(session.user.id);
|
||||
// common.convertDatesToISOStrings(items);
|
||||
//serializable dates
|
||||
items = items.map(item => ({
|
||||
...item,
|
||||
startTime: item.startTime.toISOString(),
|
||||
endTime: item.endTime.toISOString(),
|
||||
date: item.date.toISOString(),
|
||||
}));
|
||||
|
||||
|
||||
return {
|
||||
props: {
|
||||
|
@ -101,16 +101,18 @@ Date.prototype.getDayEuropean = function () {
|
||||
};
|
||||
|
||||
// Helper function to convert month name to 0-based index
|
||||
exports.getMonthNames = function () {
|
||||
return ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"];
|
||||
}
|
||||
exports.getMonthIndex = function (monthName) {
|
||||
const monthNames = ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"];
|
||||
return monthNames.indexOf(monthName.toLowerCase());
|
||||
return exports.getMonthNames().indexOf(monthName.toLowerCase());
|
||||
};
|
||||
|
||||
exports.getMonthName = function (monthIndex) {
|
||||
const monthNames = ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"];
|
||||
return monthNames[monthIndex];
|
||||
return exports.getMonthNames()[monthIndex];
|
||||
};
|
||||
|
||||
|
||||
exports.getMonthNameEn = function (monthIndex) {
|
||||
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||
return monthNames[monthIndex];
|
||||
|
@ -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
|
||||
};
|
Reference in New Issue
Block a user