Merge branch 'main' into production
This commit is contained in:
@ -19,7 +19,7 @@ const fetchConfig = async () => {
|
|||||||
return config.default;
|
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 router = useRouter();
|
||||||
const urls = {
|
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"
|
className="form-checkbox h-5 w-5 text-gray-600 mx-2"
|
||||||
checked={slot.isWithTransport}
|
checked={slot.isWithTransport}
|
||||||
disabled={!slot.isChecked}
|
disabled={!slot.isChecked}
|
||||||
|
// disabled={!slot.isChecked && slot.isFirst}
|
||||||
onChange={() => handleTransportChange(slot)} />
|
onChange={() => handleTransportChange(slot)} />
|
||||||
{slot.isFirst ? 'Вземане' : 'Връщане'}
|
{slot.isFirst ? 'Вземане' : 'Връщане'}
|
||||||
<span className="checkmark"></span>
|
<span className="checkmark"></span>
|
||||||
@ -428,15 +429,15 @@ export default function AvailabilityForm({ publisherId, existingItems, inline, o
|
|||||||
<ToastContainer></ToastContainer>
|
<ToastContainer></ToastContainer>
|
||||||
<form id="formAv" className="form p-5 bg-white shadow-md rounded-lg" onSubmit={handleSubmit}>
|
<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">
|
<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>
|
</h3>
|
||||||
|
|
||||||
<LocalizationProvider dateAdapter={AdapterDateFns} localeText={bgBG} adapterLocale={bg}>
|
<LocalizationProvider dateAdapter={AdapterDateFns} localeText={bgBG} adapterLocale={bg}>
|
||||||
{/* <div className="mb-2">
|
{datePicker && (
|
||||||
<DatePicker label="Изберете дата" value={day} onChange={(value) => setDay({ value })} />
|
<div className="mb-2">
|
||||||
</div> */}
|
<DatePicker label="Изберете дата" value={day} onChange={setDay} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div className="mb-2">
|
<div className="mb-2">
|
||||||
<label className="checkbox-container">
|
<label className="checkbox-container">
|
||||||
<input type="checkbox" checked={doRepeat} className="form-checkbox h-5 w-5 text-gray-600 mx-2"
|
<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}
|
inline={true}
|
||||||
existingItems={selectedItem ? [selectedItem] : []}
|
existingItems={selectedItem ? [selectedItem] : []}
|
||||||
date={selectedItem ? new Date(selectedItem.startTime) : new Date()}
|
date={selectedItem ? new Date(selectedItem.startTime) : new Date()}
|
||||||
|
datePicker={true}
|
||||||
onDone={(item) => {
|
onDone={(item) => {
|
||||||
toggleAv();
|
toggleAv();
|
||||||
setSelectedItem(null);
|
setSelectedItem(null);
|
||||||
|
@ -5,9 +5,9 @@
|
|||||||
"greeting": "Здравей",
|
"greeting": "Здравей",
|
||||||
"farewell": "Довиждане",
|
"farewell": "Довиждане",
|
||||||
"changeTo": "",
|
"changeTo": "",
|
||||||
"BG": "Български",
|
"BG": "български",
|
||||||
"EN": "Английски",
|
"EN": "английски",
|
||||||
"RU": "Руски",
|
"RU": "руски",
|
||||||
"login": "Вход",
|
"login": "Вход",
|
||||||
"logout": "Изход"
|
"logout": "Изход"
|
||||||
},
|
},
|
||||||
@ -23,7 +23,7 @@
|
|||||||
"contactAll": "Участници",
|
"contactAll": "Участници",
|
||||||
"feedback": "Отзиви",
|
"feedback": "Отзиви",
|
||||||
"contactUs": "За връзка",
|
"contactUs": "За връзка",
|
||||||
"admin": "Админ",
|
"admin": "Администрация",
|
||||||
"cart-places": "Места",
|
"cart-places": "Места",
|
||||||
"cart-publishers": "Вестители",
|
"cart-publishers": "Вестители",
|
||||||
"cart-events": "План",
|
"cart-events": "План",
|
||||||
|
@ -10,6 +10,25 @@
|
|||||||
"logout": "logout"
|
"logout": "logout"
|
||||||
},
|
},
|
||||||
"menu": {
|
"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: { locale, messages, session, ...pageProps }, }: AppProps<{ session: Session }>) {
|
||||||
function SmwsApp({ Component, pageProps, session, locale, messages }) {
|
function SmwsApp({ Component, pageProps, session, locale, messages }) {
|
||||||
// dynamic locale loading using our API endpoint
|
// dynamic locale loading using our API endpoint
|
||||||
// const [locale, setLocale] = useState(router.locale || 'bg');
|
// const [locale, setLocale] = useState(_locale);
|
||||||
// const [messages, setMessages] = useState({});
|
// const [messages, setMessages] = useState(_messages);
|
||||||
// useEffect(() => {
|
// useEffect(() => {
|
||||||
// async function loadLocaleData() {
|
// async function loadLocaleData() {
|
||||||
// const res = await fetch(`/api/translations/${locale}`);
|
// const res = await fetch(`/api/translations/${locale}`);
|
||||||
|
@ -137,7 +137,7 @@ export default async function handler(req, res) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case "getCalendarEvents":
|
case "getCalendarEvents":
|
||||||
let events = await getCalendarEvents(req.query.publisherId, day);
|
let events = await dataHelper.getCalendarEvents(req.query.publisherId, day);
|
||||||
res.status(200).json(events);
|
res.status(200).json(events);
|
||||||
|
|
||||||
case "getPublisherInfo":
|
case "getPublisherInfo":
|
||||||
@ -354,6 +354,8 @@ export default async function handler(req, res) {
|
|||||||
let data = await dataHelper.getCoverMePublisherEmails(parseInt(req.query.shiftId));
|
let data = await dataHelper.getCoverMePublisherEmails(parseInt(req.query.shiftId));
|
||||||
res.status(200).json(data);
|
res.status(200).json(data);
|
||||||
break;
|
break;
|
||||||
|
case "getAllPublishersWithStatistics":
|
||||||
|
res.status(200).json(await dataHelper.getAllPublishersWithStatistics(day));
|
||||||
|
|
||||||
default:
|
default:
|
||||||
res.status(200).json({
|
res.status(200).json({
|
||||||
@ -803,86 +805,6 @@ function matchesAvailability(avail, filterDate) {
|
|||||||
return avail.startTime >= filterDate && avail.startTime <= filterDateEnd;
|
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) {
|
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 ProtectedRoute, { serverSideAuth } from "../components/protectedRoute";
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import axiosInstance from '../src/axiosSecure';
|
import axiosInstance from '../src/axiosSecure';
|
||||||
|
// const dataHelper = require('../../src/helpers/data');
|
||||||
|
import dataHelper from '../src/helpers/data';
|
||||||
|
|
||||||
import { authOptions } from './api/auth/[...nextauth]'
|
import { authOptions } from './api/auth/[...nextauth]'
|
||||||
import { getServerSession } from "next-auth/next"
|
import { getServerSession } from "next-auth/next"
|
||||||
@ -85,106 +87,107 @@ export default function IndexPage({ initialItems, initialUserId }: IProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function getAvailabilities(userId) {
|
// async function getAvailabilities(userId) {
|
||||||
const prismaClient = common.getPrismaClient();
|
// const prismaClient = common.getPrismaClient();
|
||||||
const items = await prismaClient.availability.findMany({
|
// const items = await prismaClient.availability.findMany({
|
||||||
where: {
|
// where: {
|
||||||
publisherId: userId,
|
// publisherId: userId,
|
||||||
},
|
// },
|
||||||
select: {
|
// select: {
|
||||||
id: true,
|
// id: true,
|
||||||
name: true,
|
// name: true,
|
||||||
isActive: true,
|
// isActive: true,
|
||||||
isFromPreviousAssignment: true,
|
// isFromPreviousAssignment: true,
|
||||||
isFromPreviousMonth: true,
|
// isFromPreviousMonth: true,
|
||||||
dayofweek: true,
|
// dayofweek: true,
|
||||||
dayOfMonth: true,
|
// dayOfMonth: true,
|
||||||
startTime: true,
|
// startTime: true,
|
||||||
endTime: true,
|
// endTime: true,
|
||||||
repeatWeekly: true,
|
// repeatWeekly: true,
|
||||||
endDate: true,
|
// endDate: true,
|
||||||
publisher: {
|
// publisher: {
|
||||||
select: {
|
// select: {
|
||||||
firstName: true,
|
// firstName: true,
|
||||||
lastName: true,
|
// lastName: true,
|
||||||
id: true,
|
// id: true,
|
||||||
},
|
// },
|
||||||
},
|
// },
|
||||||
},
|
// },
|
||||||
});
|
// });
|
||||||
// Convert Date objects to ISO strings
|
// // Convert Date objects to ISO strings
|
||||||
const serializableItems = items.map(item => ({
|
// const serializableItems = items.map(item => ({
|
||||||
...item,
|
// ...item,
|
||||||
startTime: item.startTime.toISOString(),
|
// startTime: item.startTime.toISOString(),
|
||||||
endTime: item.endTime.toISOString(),
|
// endTime: item.endTime.toISOString(),
|
||||||
name: common.getTimeFomatted(item.startTime) + "-" + common.getTimeFomatted(item.endTime),
|
// name: common.getTimeFomatted(item.startTime) + "-" + common.getTimeFomatted(item.endTime),
|
||||||
//endDate can be null
|
// //endDate can be null
|
||||||
endDate: item.endDate ? item.endDate.toISOString() : null,
|
// endDate: item.endDate ? item.endDate.toISOString() : null,
|
||||||
type: 'availability',
|
// type: 'availability',
|
||||||
// Convert other Date fields similarly if they exist
|
// // Convert other Date fields similarly if they exist
|
||||||
}));
|
// }));
|
||||||
|
|
||||||
/*model Assignment {
|
// /*model Assignment {
|
||||||
id Int @id @default(autoincrement())
|
// id Int @id @default(autoincrement())
|
||||||
shift Shift @relation(fields: [shiftId], references: [id], onDelete: Cascade)
|
// shift Shift @relation(fields: [shiftId], references: [id], onDelete: Cascade)
|
||||||
shiftId Int
|
// shiftId Int
|
||||||
publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
|
// publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
|
||||||
publisherId String
|
// publisherId String
|
||||||
isActive Boolean @default(true)
|
// isActive Boolean @default(true)
|
||||||
isConfirmed Boolean @default(false)
|
// isConfirmed Boolean @default(false)
|
||||||
isWithTransport Boolean @default(false)
|
// isWithTransport Boolean @default(false)
|
||||||
Report Report[]
|
// Report Report[]
|
||||||
}*/
|
// }*/
|
||||||
//get assignments for this user
|
// //get assignments for this user
|
||||||
const assignments = await prismaClient.assignment.findMany({
|
// const assignments = await prismaClient.assignment.findMany({
|
||||||
where: {
|
// where: {
|
||||||
publisherId: userId,
|
// publisherId: userId,
|
||||||
},
|
// },
|
||||||
select: {
|
// select: {
|
||||||
id: true,
|
// id: true,
|
||||||
isBySystem: true,
|
// isBySystem: true,
|
||||||
isConfirmed: true,
|
// isConfirmed: true,
|
||||||
isWithTransport: true,
|
// isWithTransport: true,
|
||||||
shift: {
|
// shift: {
|
||||||
select: {
|
// select: {
|
||||||
id: true,
|
// id: true,
|
||||||
name: true,
|
// name: true,
|
||||||
startTime: true,
|
// startTime: true,
|
||||||
endTime: true,
|
// endTime: true,
|
||||||
//select all assigned publishers names as name - comma separated
|
// //select all assigned publishers names as name - comma separated
|
||||||
assignments: {
|
// assignments: {
|
||||||
select: {
|
// select: {
|
||||||
publisher: {
|
// publisher: {
|
||||||
select: {
|
// select: {
|
||||||
firstName: true,
|
// firstName: true,
|
||||||
lastName: true,
|
// lastName: true,
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
});
|
// });
|
||||||
|
|
||||||
const serializableAssignments = assignments.map(item => ({
|
// const serializableAssignments = assignments.map(item => ({
|
||||||
...item,
|
// ...item,
|
||||||
startTime: item.shift.startTime.toISOString(),
|
// startTime: item.shift.startTime.toISOString(),
|
||||||
endTime: item.shift.endTime.toISOString(),
|
// endTime: item.shift.endTime.toISOString(),
|
||||||
// name: item.shift.publishers.map(p => p.firstName + " " + p.lastName).join(", "),
|
// // 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: 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)),
|
// name: common.getTimeFomatted(new Date(item.shift.startTime)) + "-" + common.getTimeFomatted(new Date(item.shift.endTime)),
|
||||||
type: 'assignment',
|
// type: 'assignment',
|
||||||
//delete shift object
|
// //delete shift object
|
||||||
shift: null,
|
// shift: null,
|
||||||
publisher: { id: userId }
|
// publisher: { id: userId }
|
||||||
}));
|
// }));
|
||||||
|
|
||||||
serializableItems.push(...serializableAssignments);
|
// serializableItems.push(...serializableAssignments);
|
||||||
|
|
||||||
return serializableItems;
|
// return serializableItems;
|
||||||
|
|
||||||
|
// }
|
||||||
|
|
||||||
}
|
|
||||||
export const getServerSideProps = async (context) => {
|
export const getServerSideProps = async (context) => {
|
||||||
const auth = await serverSideAuth({
|
const auth = await serverSideAuth({
|
||||||
req: context.req,
|
req: context.req,
|
||||||
@ -198,7 +201,16 @@ export const getServerSideProps = async (context) => {
|
|||||||
console.log("server role: " + role);
|
console.log("server role: " + role);
|
||||||
const userId = session?.user.id;
|
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 {
|
return {
|
||||||
props: {
|
props: {
|
||||||
|
@ -101,16 +101,18 @@ Date.prototype.getDayEuropean = function () {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Helper function to convert month name to 0-based index
|
// Helper function to convert month name to 0-based index
|
||||||
|
exports.getMonthNames = function () {
|
||||||
|
return ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"];
|
||||||
|
}
|
||||||
exports.getMonthIndex = function (monthName) {
|
exports.getMonthIndex = function (monthName) {
|
||||||
const monthNames = ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"];
|
return exports.getMonthNames().indexOf(monthName.toLowerCase());
|
||||||
return monthNames.indexOf(monthName.toLowerCase());
|
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.getMonthName = function (monthIndex) {
|
exports.getMonthName = function (monthIndex) {
|
||||||
const monthNames = ["януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември"];
|
return exports.getMonthNames()[monthIndex];
|
||||||
return monthNames[monthIndex];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
exports.getMonthNameEn = function (monthIndex) {
|
exports.getMonthNameEn = function (monthIndex) {
|
||||||
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||||
return monthNames[monthIndex];
|
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)
|
// 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: [
|
AND: [
|
||||||
|
{ dayOfMonth: null },
|
||||||
|
{ startTime: { lte: filterTimeTo } }, // startTime included
|
||||||
{
|
{
|
||||||
OR: [ // OR condition for repeatUntil to handle events that either end after filterDate or repeat forever
|
OR: [ // OR condition for repeatUntil to handle events that either end after filterDate or repeat forever
|
||||||
{ endDate: { gte: filterTimeFrom } }, // endDate included
|
{ 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(`getting publishers for date: ${filterDate}, isExactTime: ${isExactTime}, isForTheMonth: ${isForTheMonth}`);
|
||||||
|
console.log`whereClause: ${JSON.stringify(whereClause)}`
|
||||||
//include availabilities if flag is true
|
//include availabilities if flag is true
|
||||||
let publishers = await prisma.publisher.findMany({
|
let publishers = await prisma.publisher.findMany({
|
||||||
where: whereClause,
|
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.dayOfMonth != null && avail.startTime >= currentMonthStart && avail.startTime <= monthInfo.lastSunday;
|
||||||
return avail.startTime >= monthInfo.firstMonday && (noEndDateFilter || 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 => {
|
// pub.currentMonthAvailabilityDaysCount += pub.availabilities.filter(avail => {
|
||||||
// return avail.dayOfMonth == null;
|
// return avail.dayOfMonth == null;
|
||||||
// }).length;
|
// }).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) {
|
// exports.getCoverMePublisherEmails = async function (shiftId) {
|
||||||
async function getCoverMePublisherEmails(shiftId) {
|
async function getCoverMePublisherEmails(shiftId) {
|
||||||
const prisma = common.getPrismaClient();
|
const prisma = common.getPrismaClient();
|
||||||
@ -579,5 +813,7 @@ module.exports = {
|
|||||||
runSqlFile,
|
runSqlFile,
|
||||||
getAvailabilities,
|
getAvailabilities,
|
||||||
filterPublishersNew,
|
filterPublishersNew,
|
||||||
getCoverMePublisherEmails
|
getCoverMePublisherEmails,
|
||||||
|
getAllPublishersWithStatistics,
|
||||||
|
getCalendarEvents
|
||||||
};
|
};
|
Reference in New Issue
Block a user