diff --git a/components/reports/ReportForm.js b/components/reports/ReportForm.js
index 998a236..3672487 100644
--- a/components/reports/ReportForm.js
+++ b/components/reports/ReportForm.js
@@ -81,6 +81,7 @@ export default function ReportForm({ shiftId, existingItem, onDone }) {
};
fetchData();
}, [item.date, existingItem]);
+
const handleChange = ({ target }) => {
setItem({ ...item, [target.name]: target.value });
};
diff --git a/components/survey/SurveyForm.js b/components/survey/SurveyForm.js
new file mode 100644
index 0000000..4ed75be
--- /dev/null
+++ b/components/survey/SurveyForm.js
@@ -0,0 +1,169 @@
+import axiosInstance from '../../src/axiosSecure';
+import { useEffect, useState } from "react";
+import { toast } from "react-hot-toast";
+import { useRouter } from "next/router";
+import Link from "next/link";
+import { useSession } from "next-auth/react"
+import { MessageType, Message, Survey } from "@prisma/client";
+// import { content } from 'googleapis/build/src/apis/content';
+import { DatePicker } from '@mui/x-date-pickers/DatePicker';
+// import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFnsV3';
+// import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
+import dayjs from 'dayjs';
+
+const common = require('src/helpers/common');
+
+
+// ------------------ ------------------
+// This component is used to create and edit
+/* location model:
+
+model Survey {
+ id Int @id @default(autoincrement())
+ content String
+ answers Json?
+ messages Message[]
+ publicFrom DateTime?
+ publicUntil DateTime?
+}
+
+model Message {
+ id Int @id @default(autoincrement())
+ publisher Publisher @relation(fields: [publisherId], references: [id])
+ publisherId String
+ date DateTime
+ content String
+ isRead Boolean @default(false)
+ isPublic Boolean @default(false)
+ type MessageType @default(Email)
+ publicUntil DateTime?
+ shownDate DateTime?
+ answer String?
+ answerDate DateTime?
+
+ Survey Survey? @relation(fields: [surveyId], references: [id])
+ surveyId Int?
+}
+*/
+
+export default function SurveyForm({ existingItem }) {
+
+ const router = useRouter();
+ const [editMode, setEditMode] = useState(existingItem ? true : false);
+ const [item, setItem] = useState(existingItem || {
+ content: "Нова анкета",
+ answers: [],
+ publicFrom: new Date().toISOString(),
+ publicUntil: new Date().toISOString(),
+ });
+
+ useState(() => setEditMode(existingItem ? true : false), [existingItem]);
+
+
+ const handleChange = ({ target }) => {
+ setItem({ ...item, [target.name]: target.value });
+ };
+
+ const handleDateChange = (fieldName, newDate) => {
+ setItem((prevItem) => ({
+ ...prevItem,
+ [fieldName]: newDate
+ }));
+ };
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ try {
+ //get all publisherIds and create a message for each
+ const pubs = await axiosInstance.get("/api/data/publishers");
+ const messages = pubs.data.map(pub => {
+ return {
+ publisherId: pub.id,
+ content: JSON.stringify({ message: item.content, options: item.answers }),
+ date: new Date(),
+ isPublic: false,
+ type: MessageType.InApp,
+ publicUntil: item.publicUntil,
+ }
+ });
+ item.messages = { create: messages };
+ const { data } = await axiosInstance.post("/api/data/surveys", item);
+ toast.success("Анкетата е създадена успешно");
+ router.push("/cart/surveys");
+ } catch (error) {
+ toast.error("Възникна грешка при създаването на анкетата");
+ console.error("Error creating survey:", error);
+ }
+ }
+
+ const handleDelete = async (e) => {
+ e.preventDefault();
+ if (!editMode) return;
+ try {
+ await axiosInstance.delete(`/api/data/surveys/${existingItem.id}`);
+
+ toast.success("Записът изтрит", {
+ position: "bottom-center",
+ });
+
+ } catch (error) {
+ //alert("Нещо се обърка при изтриването. Моля, опитайте отново или се свържете с нас");
+ console.log(JSON.stringify(error));
+ toast.error(error.response?.data?.message || "Нещо се обърка при изтриването. Моля, опитай отново и се свържете с нас ако проблема продължи.");
+ }
+ };
+ return (
+
+ < form className="bg-white dark:bg-gray-800 shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit} >
+
+
Анкета {existingItem?.id}
+
+
+ handleDateChange('publicFrom', newDate)} value={dayjs(item.publicFrom)} />
+
+
+
+ handleDateChange('publicUntil', newDate)} value={dayjs(item.publicUntil)} />
+
+
+
+
+
+
+
+
+
+ {/* show count of each answer and the total answered/unanswered messages */}
+ {/* {item.answers.map((answer) => (
+
+
+ {item.messages.filter((message) => message.answer === answer).length}
+
+
+ ))} */}
+
+
+ {editMode && (
+ <>>
+ )}
+
+
+
+
+
+ );
+}
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 29825c8..4319f9d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -49,6 +49,7 @@
"jsonwebtoken": "^9.0.2",
"jszip": "^3.10.1",
"levenshtein-edit-distance": "^3.0.1",
+ "lodash": "^4.17.21",
"luxon": "^3.4.4",
"mailtrap": "^3.3.0",
"module-alias": "^2.2.3",
diff --git a/package.json b/package.json
index 64dcddb..5b7de75 100644
--- a/package.json
+++ b/package.json
@@ -67,6 +67,7 @@
"jsonwebtoken": "^9.0.2",
"jszip": "^3.10.1",
"levenshtein-edit-distance": "^3.0.1",
+ "lodash": "^4.17.21",
"luxon": "^3.4.4",
"mailtrap": "^3.3.0",
"module-alias": "^2.2.3",
diff --git a/pages/cart/surveys/index.tsx b/pages/cart/surveys/index.tsx
new file mode 100644
index 0000000..8bbd1b2
--- /dev/null
+++ b/pages/cart/surveys/index.tsx
@@ -0,0 +1,73 @@
+import React, { useState, useEffect } from 'react';
+import Layout from "../../../components/layout";
+import { GetServerSideProps } from 'next';
+import { Location, UserRole } from "@prisma/client";
+import axiosServer from '../../../src/axiosServer';
+const common = require('../../../src/helpers/common');
+// import * as common from '../../../src/helpers/common';
+import SurveyForm from '../../../components/survey/SurveyForm';
+import _ from 'lodash';
+
+const SurveyPage = ({ serverSurveys }) => {
+ const [selectedSurvey, setSelectedSurvey] = useState(null);
+
+ return (
+
+
+
Survey Page
+
+
+
+
+
Surveys
+
+
+
+
+
Selected Survey
+ {selectedSurvey && (
+
+
{selectedSurvey.title}
+
{selectedSurvey.description}
+
+ )}
+
+
+
+
+ );
+};
+
+export default SurveyPage;
+
+export const getServerSideProps: GetServerSideProps = async (context) => {
+ const prisma = common.getPrismaClient();
+ let serverSurveys = await prisma.survey.findMany({
+ where: {
+ },
+ include: {
+ messages: true,
+ },
+ });
+ serverSurveys = common.convertDatesToISOStrings(serverSurveys);
+
+ context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
+ return {
+ props: {
+ serverSurveys: serverSurveys
+ },
+ };
+};
+
diff --git a/pages/dash.tsx b/pages/dash.tsx
index 4e2fbd3..3f5c1ca 100644
--- a/pages/dash.tsx
+++ b/pages/dash.tsx
@@ -287,10 +287,11 @@ export const getServerSideProps = async (context) => {
key: "AvailabilityBlockDate"
}
});
- if (blockedDate)
- blockedDate.value = new Date(blockedDate.value);
- lastPublishedDate = lastPublishedDate > blockedDate.value ? lastPublishedDate : blockedDate.value;
+ if (blockedDate) {
+ blockedDate.value = new Date(blockedDate.value);
+ lastPublishedDate = lastPublishedDate > blockedDate.value ? lastPublishedDate : blockedDate.value;
+ }
return {
props: {
diff --git a/prisma/migrations/20240617043350_cascade_delete_messages/migration.sql b/prisma/migrations/20240617043350_cascade_delete_messages/migration.sql
new file mode 100644
index 0000000..a3c140e
--- /dev/null
+++ b/prisma/migrations/20240617043350_cascade_delete_messages/migration.sql
@@ -0,0 +1,5 @@
+-- DropForeignKey
+ALTER TABLE `message` DROP FOREIGN KEY `Message_surveyId_fkey`;
+
+-- AddForeignKey
+ALTER TABLE `Message` ADD CONSTRAINT `Message_surveyId_fkey` FOREIGN KEY (`surveyId`) REFERENCES `Survey`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 0ecb8b8..35996b6 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -287,7 +287,7 @@ model Message {
answer String?
answerDate DateTime?
- Survey Survey? @relation(fields: [surveyId], references: [id])
+ Survey Survey? @relation(fields: [surveyId], references: [id], onDelete: Cascade)
surveyId Int?
}