- {key}: {items.length}
+
+
+
Списък
+
-
+
+
+ ))}
+
+
+
+
+
Детайли
+
+
+ {/*
+
Selected Survey
+ {selectedSurvey ? (
+
+
{selectedSurvey.title}
+
{selectedSurvey.description}
+
+ ) : (
+
No survey selected.
+ )}
+
*/}
-
-
Selected Survey
- {selectedSurvey && (
-
-
{selectedSurvey.title}
-
{selectedSurvey.description}
-
- )}
+
-
);
};
diff --git a/pages/dash.tsx b/pages/dash.tsx
index 3f5c1ca..01e4ae8 100644
--- a/pages/dash.tsx
+++ b/pages/dash.tsx
@@ -2,6 +2,7 @@ import { useSession } from "next-auth/react"
import { useRouter } from 'next/router';
import React, { useState, useEffect } from 'react';
import Layout from "../components/layout"
+import { toast } from 'react-toastify';
import AvCalendar from '../components/calendar/avcalendar';
import { getSession } from "next-auth/react";
@@ -25,9 +26,9 @@ interface IProps {
initialUserId: string;
cartEvents: any;
lastPublishedDate: Date;
+ messages: any;
}
-export default function DashboardPage({ initialItems, initialUserId, cartEvents, lastPublishedDate }: IProps) {
-
+export default function DashboardPage({ initialItems, initialUserId, cartEvents, lastPublishedDate, messages }: IProps) {
const router = useRouter();
const { newLogin } = router.query;
const { data: session } = useSession();
@@ -51,17 +52,132 @@ export default function DashboardPage({ initialItems, initialUserId, cartEvents,
}, [session]);
+
+ // MESSAGES
//const [notificationsVisible, setNotificationsVisible] = useState(false);
- useEffect(() => {
- //if (newLogin === 'true')
- {
- // alert("Мили братя, искаме само да ви напомним да ни изпратите вашите предпочитания за юни до 25-то число като използвате меню 'Възможности'. Ако имате проблем, моля пишете ни на 'specialnosvidetelstvanesofia@gmail.com'");
- const currentPath = router.pathname;
- router.replace(currentPath, undefined, { shallow: true }); // Removes the query without affecting the history
- }
- }, []);// show the message every time we load the page
+ // useEffect(() => {
+ // //if (newLogin === 'true')
+ // {
+ // // alert("Мили братя, искаме само да ви напомним да ни изпратите вашите предпочитания за юни до 25-то число като използвате меню 'Възможности'. Ако имате проблем, моля пишете ни на 'specialnosvidetelstvanesofia@gmail.com'");
+ // const currentPath = router.pathname;
+ // router.replace(currentPath, undefined, { shallow: true }); // Removes the query without affecting the history
+ // }
+ // }, []);// show the message every time we load the page
+ useEffect(() => {
+ if (messages.length > 0) {
+ showMessageToasts(messages);
+ }
+ }, [messages]);
+
+ const showMessageToasts = (messages, handleMessageOptionAnswer) => {
+ const handleOptionClick = async (messageId, option, toastId) => {
+ try {
+ await axiosInstance.put(`/api/data/messages/${messageId}`, { answer: option });
+ toast.dismiss(toastId);
+ } catch (error) {
+ console.error("Error updating message:", error);
+ toast.error("Error updating message. Please try again.");
+ }
+ };
+
+ const handleClose = (toastId) => {
+ toast.dismiss(toastId);
+ };
+
+ messages.forEach((message, messageIndex) => {
+ const toastId = `message-${messageIndex}`;
+ const content = (
+
+
{message.content.message}
+
+ {message.content.options?.map((option, index) => (
+
+ ))}
+
+
+ );
+
+ toast(content, {
+ toastId,
+ autoClose: false, // Keep the toast open until manually closed
+ closeButton: true,
+ onClose: () => handleClose(toastId),
+ });
+ });
+ };
+
+ const showMessageToastNewModal = (messages, handleMessageOptionAnswer) => {
+ let currentMessageIndex = 0;
+
+ const showModal = () => {
+ if (currentMessageIndex >= messages.length) {
+ return; // All messages have been shown
+ }
+
+ const message = messages[currentMessageIndex];
+ const content = (
+
+
+
+
+
+
{message.content.message}
+
+ {message.content.options?.map((option, index) => (
+
+ ))}
+
+
+
+ );
+
+ toast(content, {
+ autoClose: false, // Keep the toast open until manually closed
+ closeButton: false,
+ onClose: handleClose,
+ //className: 'custom-toast', // Optional custom class for additional styling
+ });
+ };
+
+ const handleOptionClick = async (messageId, option) => {
+ try {
+ await axiosInstance.put(`/api/data/messages/${messageId}`, { answer: option });
+ toast.dismiss();
+ currentMessageIndex++;
+ showModal();
+ } catch (error) {
+ console.error("Error updating message:", error);
+ toast.error("Error updating message. Please try again.");
+ }
+ };
+
+ const handleClose = () => {
+ toast.dismiss();
+ };
+
+ showModal();
+ };
+
+ // FOR ADMINS ONLY
const handleUserSelection = async (publisher) => {
if (!publisher || publisher.id === undefined) return;
console.log("selecting publisher", publisher.id);
@@ -107,107 +223,6 @@ export default function DashboardPage({ initialItems, initialUserId, cartEvents,
}
-// 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.getTimeFormatted(item.startTime) + "-" + common.getTimeFormatted(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,
-// }
-// }
-// }
-// }
-// }
-// }
-// }
-// });
-
-// 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.getTimeFormatted(new Date(item.shift.startTime)) + "-" + common.getTimeFormatted(new Date(item.shift.endTime)),
-// type: 'assignment',
-// //delete shift object
-// shift: null,
-// publisher: { id: userId }
-// }));
-
-// serializableItems.push(...serializableAssignments);
-
-// return serializableItems;
-
-// }
-
export const getServerSideProps = async (context) => {
const auth = await serverSideAuth({
req: context.req,
@@ -293,13 +308,38 @@ export const getServerSideProps = async (context) => {
lastPublishedDate = lastPublishedDate > blockedDate.value ? lastPublishedDate : blockedDate.value;
}
+ let messages = await prisma.message.findMany({
+ where: {
+ publisherId: userId,
+ isPublic: false,
+ answer: null,
+ },
+ include: {
+ Survey: true,
+ }
+ });
+
+ messages = messages.filter((message) => {
+ return (!message.Survey.publicFrom || message.Survey.publicFrom >= common.getStartOfDay(new Date()))
+ && (!message.Survey.publicUntil || message.Survey.publicUntil <= common.getEndOfDay(new Date()))
+ });
+ messages = common.convertDatesToISOStrings(messages);
+ messages = messages.map(message => {
+ if (message.content) {
+ message.content = JSON.parse(message.content);
+ message.content.options = message.content.options?.split(",");
+
+ }
+ return message;
+ });
+
return {
props: {
initialItems: items,
userId: sessionServer?.user.id,
cartEvents: cartEvents,
lastPublishedDate: lastPublishedDate.toISOString(),
- // messages: (await import(`../content/i18n/${context.locale}.json`)).default
+ messages: messages
},
};
}
diff --git a/tsconfig.json b/tsconfig.json
index e903954..ed853ff 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -32,7 +32,8 @@
"components/location/LocationForm.js",
"pages/cart/locations/[id].tsx.old",
"components/publisher/ShiftsList.js",
- "src/helpers/data.js"
+ "src/helpers/data.js",
+ "components/survey/SurveyForm.js"
],
"exclude": [
"node_modules"