diff --git a/components/PwaManager.tsx b/components/PwaManager.tsx index 77b3333..7d3dfdd 100644 --- a/components/PwaManager.tsx +++ b/components/PwaManager.tsx @@ -242,7 +242,10 @@ function PwaManager({ subs }) { headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ subscription }) + //sends test notification to the current subscription + // body: JSON.stringify({ subscription }) + //sends test notification to all subscriptions of this user + body: JSON.stringify({ id: session.user.id, title: "Тестово уведомление", message: "Това е тестово уведомление" }) }); }; diff --git a/components/PwaManagerNotifications.tsx b/components/PwaManagerNotifications.tsx index fd5fc6f..653f66e 100644 --- a/components/PwaManagerNotifications.tsx +++ b/components/PwaManagerNotifications.tsx @@ -7,6 +7,7 @@ function PwaManagerNotifications() { const [isPermissionGranted, setIsPermissionGranted] = useState(false); const [subscription, setSubscription] = useState(null); const [registration, setRegistration] = useState(null); + const [isSubSaved, setIsSubSaved] = useState(false); const { data: session } = useSession(); // Check if all required APIs are supported @@ -53,6 +54,7 @@ function PwaManagerNotifications() { if (existingSubscription) { console.log('Already subscribed.'); setSubscription(existingSubscription); + sendSubscriptionToServer(existingSubscription); } else if (Notification.permission === "granted") { // Permission was already granted but no subscription exists, so subscribe now subscribeToNotifications(registration); @@ -90,6 +92,7 @@ function PwaManagerNotifications() { }; const sendSubscriptionToServer = async (sub) => { + if (isSubSaved) { return; } if (session.user?.id != null) { await fetch(`/api/notify`, { method: 'PUT', @@ -105,6 +108,7 @@ function PwaManagerNotifications() { console.log('Subscription data saved on server.'); const s = await response.json(); setSubscription(sub); + setIsSubSaved(true); console.log('Web push subscribed!'); } }); diff --git a/components/availability/AvailabilityForm.js b/components/availability/AvailabilityForm.js index 0197755..aa1f8a4 100644 --- a/components/availability/AvailabilityForm.js +++ b/components/availability/AvailabilityForm.js @@ -412,7 +412,7 @@ export default function AvailabilityForm({ publisherId, existingItems, inline, o

- {editMode ? "Редактирай" : "Нова"} възможност: {common.getDateFormatedShort(new Date(day))} + {editMode ? "Редактирай" : "Нова"} възможност: {common.getDateFormattedShort(new Date(day))}

diff --git a/components/calendar/avcalendar.tsx b/components/calendar/avcalendar.tsx index cfac429..27b66d9 100644 --- a/components/calendar/avcalendar.tsx +++ b/components/calendar/avcalendar.tsx @@ -239,7 +239,7 @@ const AvCalendar = ({ publisherId, events, selectedDate, cartEvents, lastPublish if (startdate < new Date() || end < new Date() || startdate > end) return; //or if schedule is published (lastPublishedDate) if (editLockedBefore && startdate < editLockedBefore) { - toast.error(`Не можете да променяте предпочитанията си за дати преди ${common.getDateFormatedShort(editLockedBefore)}.`, { autoClose: 5000 }); + toast.error(`Не можете да променяте предпочитанията си за дати преди ${common.getDateFormattedShort(editLockedBefore)}.`, { autoClose: 5000 }); return; } diff --git a/pages/api/index.ts b/pages/api/index.ts index 330c407..cfb3e00 100644 --- a/pages/api/index.ts +++ b/pages/api/index.ts @@ -362,7 +362,7 @@ export default async function handler(req, res) { break; case "getAllPublishersWithStatistics": let noEndDate = common.parseBool(req.query.noEndDate); - res.status(200).json(await dataHelper.getAllPublishersWithStatistics(day, noEndDate)); + res.status(200).json(await dataHelper.getAllPublishersWithStatisticsMonth(day, noEndDate)); default: res.status(200).json({ @@ -643,7 +643,7 @@ export async function filterPublishers(selectFields, searchText, filterDate, fet } //if not full day, match by date and time else { - //match exact time (should be same as data.findPublisherAvailability()) + //match exact time (should be same as data.FindPublisherAvailability()) whereClause["availabilities"] = { some: { OR: [ @@ -723,7 +723,7 @@ export async function filterPublishers(selectFields, searchText, filterDate, fet } }); - console.log(`publishers: ${publishers.length}, WhereClause: ${JSON.stringify(whereClause)}`); + //console.log(`publishers: ${publishers.length}, WhereClause: ${JSON.stringify(whereClause)}`); if (filterDate) { diff --git a/pages/api/notify.ts b/pages/api/notify.ts index 6577593..354fea5 100644 --- a/pages/api/notify.ts +++ b/pages/api/notify.ts @@ -56,15 +56,17 @@ const Notification = async (req, res) => { if (index !== -1) { subscriptions[index] = subscription; // Update existing subscription + console.log('Subscription for publisher', id, 'updated.') } else { subscriptions.push(subscription); // Add new subscription + console.log('Subscription for publisher', id, 'saved.') } await prisma.publisher.update({ where: { id }, data: { pushSubscription: subscriptions } }); - console.log('Subscription for publisher', id, 'updated:', subscription) + console.log('Subscription update successful', subscription.keys.auth, ". Total subscriptions:", subscriptions.length) res.send({ subs: subscriptions.length }) res.statusCode = 200 res.end() @@ -111,6 +113,7 @@ const Notification = async (req, res) => { return } else if (id) { + console.log('Sending push notification to publisher ', id) await sendPush(id, title, message.actions) res.statusCode = 200 res.end() @@ -148,22 +151,25 @@ export const sendPush = async (id, title, message, actions) => { const publisher = await prisma.publisher.findUnique({ where: { id } }) - if (!publisher.pushSubscription) { - console.log('No push subscription found for publisher', id) - return - } - await webPush - .sendNotification( - publisher.pushSubscription, - JSON.stringify({ title, message, actions }) - ) - .then(response => { - console.log('Push notification sent to publisher', id) - }) - .catch(err => { - console.error('Error sending push notification to publisher', id, ':', err) - }) + if (Array.isArray(publisher.pushSubscription) && publisher.pushSubscription.length) { + for (const subscription of publisher.pushSubscription) { + await webPush + .sendNotification( + subscription, + JSON.stringify({ title, message, actions }) + ) + .then(response => { + console.log('Push notification sent to publisher', id) + }) + .catch(err => { + console.error('Error sending push notification to publisher', id, ':', err) + }) + } + } else { + console.log('No valid subscriptions found for publisher', id) + + } } //export breoadcastNotification for use in other files export const broadcastPush = async (title, message, actions) => { diff --git a/pages/cart/calendar/schedule.tsx b/pages/cart/calendar/schedule.tsx index 63c99df..f7c952c 100644 --- a/pages/cart/calendar/schedule.tsx +++ b/pages/cart/calendar/schedule.tsx @@ -34,6 +34,12 @@ const SchedulePage = () => { fetchHtmlContent(); // Call the function to fetch HTML content }, []); // Empty dependency array means this effect runs once on component mount + // temporary alert for the users + useEffect(() => { + alert("Мили братя, искаме само да ви напомним да ни изпратите вашите предпочитания за юни до 25-то число като използвате меню 'Възможности'. Ако имате проблем, моля пишете ни на 'specialnosvidetelstvanesofia@gmail.com'"); + }, []); + + return ( diff --git a/pages/cart/publishers/myschedule.tsx b/pages/cart/publishers/myschedule.tsx index bda1015..6669695 100644 --- a/pages/cart/publishers/myschedule.tsx +++ b/pages/cart/publishers/myschedule.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import Layout from "../../../components/layout"; import ProtectedRoute from '../../../components/protectedRoute'; import { UserRole } from '@prisma/client'; @@ -29,6 +29,11 @@ export default function MySchedulePage({ assignments }) { if (status === "loading") { return
Loading...
; } + // temporary alert for the users + useEffect(() => { + alert("Мили братя, искаме само да ви напомним да ни изпратите вашите предпочитания за юни до 25-то число като използвате меню 'Възможности'. Ако имате проблем, моля пишете ни на 'specialnosvidetelstvanesofia@gmail.com'"); + }, []); + const handleReplaceInAssignment = () => { // Add publisher as assignment logic diff --git a/pages/cart/publishers/stats.tsx b/pages/cart/publishers/stats.tsx index 813a40b..69e33f6 100644 --- a/pages/cart/publishers/stats.tsx +++ b/pages/cart/publishers/stats.tsx @@ -323,7 +323,7 @@ export default ContactsPage; export const getServerSideProps = async (context) => { - const allPublishers = await data.getAllPublishersWithStatistics(new Date()); + const allPublishers = await data.getAllPublishersWithStatisticsMonth(new Date()); //merge first and last name allPublishers.forEach(publisher => { publisher.name = `${publisher.firstName} ${publisher.lastName}`; diff --git a/pages/dash.tsx b/pages/dash.tsx index 9802a3f..1852128 100644 --- a/pages/dash.tsx +++ b/pages/dash.tsx @@ -54,7 +54,8 @@ export default function DashboardPage({ initialItems, initialUserId, cartEvents, //const [notificationsVisible, setNotificationsVisible] = useState(false); useEffect(() => { - if (newLogin === 'true') { + //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