- {item.id} {item.isactive}
+ {item.id} {item.isActive}
{item.publisher.lastName}, {item.publisher.firstName}
@@ -133,19 +133,19 @@ export const getServerSideProps = async (context) => {
const role = session?.user.role;
console.log("server role: " + role);
- var queryUrl = process.env.NEXTAUTH_URL + "/api/data/availabilities?select=id,name,isactive,dayofweek,dayOfMonth,startTime,endTime,publisher.firstName,publisher.lastName,publisher.id";
+ var queryUrl = process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/availabilities?select=id,name,isActive,dayofweek,dayOfMonth,startTime,endTime,publisher.firstName,publisher.lastName,publisher.id";
if (role === UserRole.USER || context.query.my) {
queryUrl += `&where={"publisherId":"${session?.user.id}"}`;
} else if (role == UserRole.ADMIN) {
if (context.query.id) {
queryUrl += `&where={"publisherId":"${context.query.id}"}`;
} else {
- queryUrl += `&where={"isactive":true}`;
+ queryUrl += `&where={"isActive":true}`;
}
}
var resp = await axios.get(
queryUrl
- // process.env.NEXTAUTH_URL + "/api/data/availabilities?include=publisher",
+ // process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/availabilities?include=publisher",
, { decompress: true });
var items = resp.data;
console.log("got " + items.length + " availabilities");
diff --git a/pages/cart/availabilities/new.tsx b/pages/cart/availabilities/new.tsx
index f281459..06a91b7 100644
--- a/pages/cart/availabilities/new.tsx
+++ b/pages/cart/availabilities/new.tsx
@@ -31,7 +31,7 @@ export const getServerSideProps = async (context) => {
};
}
const { data: item } = await axios.get(
- process.env.NEXTAUTH_URL + "/api/data/availabilities/" + context.params.id
+ process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/availabilities/" + context.params.id
);
return {
diff --git a/pages/cart/calendar/index.tsx b/pages/cart/calendar/index.tsx
index a3f5746..5bb9269 100644
--- a/pages/cart/calendar/index.tsx
+++ b/pages/cart/calendar/index.tsx
@@ -57,6 +57,7 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
const [allShifts, setAllShifts] = useState(initialShifts);
+ const [isPublished, setIsPublished] = useState(() => initialShifts.some(shift => shift.isPublished));
const [value, onChange] = useState(new Date());
const [shifts, setShifts] = React.useState([]);
const [error, setError] = React.useState(null);
@@ -100,7 +101,7 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
console.log("Setting date to '" + date.toLocaleDateString() + "' from '" + selectedDate.toLocaleDateString() + "'. ISO: " + date.toISOString(), "locale ISO:", common.getISODateOnly(date));
if (isCheckboxChecked) {
console.log(`getting unassigned publishers for ${common.getMonthName(date.getMonth())} ${date.getFullYear()}`);
- const { data: availablePubsForDate } = await axiosInstance.get(`/api/?action=getUnassignedPublishers&date=${dateStr}&select=id,firstName,lastName,isactive,desiredShiftsPerMonth`);
+ const { data: availablePubsForDate } = await axiosInstance.get(`/api/?action=getUnassignedPublishers&date=${dateStr}&select=id,firstName,lastName,isActive,desiredShiftsPerMonth`);
setAvailablePubs(availablePubsForDate);
}
else {
@@ -108,7 +109,8 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
try {
const { data: shiftsForDate } = await axiosInstance.get(`/api/?action=getShiftsForDay&date=${dateStr}`);
setShifts(shiftsForDate);
- let { data: availablePubsForDate } = await axiosInstance.get(`/api/?action=filterPublishers&assignments=true&availabilities=true&date=${dateStr}&select=id,firstName,lastName,isactive,desiredShiftsPerMonth`);
+ setIsPublished(shiftsForDate.some(shift => shift.isPublished));
+ let { data: availablePubsForDate } = await axiosInstance.get(`/api/?action=filterPublishers&assignments=true&availabilities=true&date=${dateStr}&select=id,firstName,lastName,isActive,desiredShiftsPerMonth`);
availablePubsForDate.forEach(pub => {
pub.canTransport = pub.availabilities.some(av =>
@@ -172,8 +174,8 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
// currentMonthAssignments and previousMonthAssignments properties
// Sort publishers based on availability and then by assignment counts.
const sortedPubs = updatedPubs.sort((a, b) => {
- if (a.isactive !== b.isactive) {
- return a.isactive ? -1 : 1;
+ if (a.isActive !== b.isActive) {
+ return a.isActive ? -1 : 1;
}
// First, sort by isselected.
if (a.isSelected !== b.isSelected) {
@@ -355,7 +357,7 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
const newAssignment = {
publisher: { connect: { id: publisher.id } },
shift: { connect: { id: shiftId } },
- isactive: true,
+ isActive: true,
isConfirmed: true
};
const { data } = await axiosInstance.post("/api/data/assignments", newAssignment);
@@ -511,10 +513,26 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
}
}
+ const togglePublished = async () => {
+ try {
+ const publishState = !isPublished; // Toggle the state
+ const isPublishedParam = publishState ? 'true' : 'fasle';
+ await axiosInstance.get(`/api/?action=updateShifts&isPublished=${isPublishedParam}&date=${common.getISODateOnly(value)}`);
+ setIsPublished(publishState); // Update state based on the action
+
+ } catch (error) {
+ console.log(error);
+ }
+ }
+
const [isMenuOpen, setIsMenuOpen] = useState(false);
const [isConfirmModalOpen, setConfirmModalOpen] = useState(false);
+ async function copyOldAvailabilities(event: MouseEvent): Promise {
+ await axiosInstance.get(`/api/?action=copyOldAvailabilities&date=${common.getISODateOnly(value)}`);
+ }
+
return (
<>
@@ -550,6 +568,12 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
}}
message="Това ще изпрати имейли до всички участници за смените им през избрания месец. Сигурни ли сте?"
/>
+
+
+ {isPublished ? "Скрий" : "Публикувай"} графика (м.)
+
{isLoading('fetchShifts') ? ( ) : ( )} презареди
Генерирай статистика
+ Прехвърли предпочитанията
)}
@@ -669,7 +694,7 @@ export default function CalendarPage({ initialEvents, initialShifts }) {
// Determine border class if selected
const selectedBorderClass = pub.isSelected ? 'border-blue-400 border-b-4' : '';
// Determine opacity class
- const activeOpacityClass = pub.isactive ? '' : 'opacity-25';
+ const activeOpacityClass = pub.isActive ? '' : 'opacity-25';
return (
@@ -866,9 +891,9 @@ import axiosServer from '../../../src/axiosServer';
import { start } from 'repl';
export const getServerSideProps = async (context) => {
const axios = await axiosServer(context);
- const baseUrl = common.getBaseUrl();
- console.log('runtime BaseUrl: ' + baseUrl);
- console.log('runtime NEXTAUTH_URL: ' + process.env.NEXTAUTH_URL);
+ // const baseUrl = common.getBaseUrl();
+ // console.log('runtime BaseUrl: ' + baseUrl);
+ console.log('runtime NEXT_PUBLIC_PUBLIC_URL: ' + process.env.NEXT_PUBLIC_PUBLIC_URL);
console.log('Runtime Axios Base URL:', axios.defaults.baseURL);
const currentDate = new Date();
@@ -878,20 +903,20 @@ export const getServerSideProps = async (context) => {
const url = `/api/data/shifts?where={"startTime":{"$and":[{"$gte":"${common.getISODateOnly(firstDayOfMonth)}","$lt":"${common.getISODateOnly(lastDayOfMonth)}"}]}}`;
const prismaClient = common.getPrismaClient();
- // let events = await prismaClient.cartEvent.findMany({ where: { isactive: true } });
+ // let events = await prismaClient.cartEvent.findMany({ where: { isActive: true } });
// events = events.map(event => ({
// ...event,
// // Convert Date objects to ISO strings
// startTime: event.startTime.toISOString(),
// endTime: event.endTime.toISOString(),
// }));
- const { data: events } = await axios.get(`/api/data/cartevents?where={"isactive":true}`);
+ const { data: events } = await axios.get(`/api/data/cartevents?where={"isActive":true}`);
//const { data: shifts } = await axios.get(url);
// get all shifts for the month, including assigments
let shifts = await prismaClient.shift.findMany({
where: {
- isactive: true,
+ isActive: true,
startTime: {
gte: firstDayOfMonth,
//lt: lastDayOfMonth
diff --git a/pages/cart/cartevents/edit/[id].tsx b/pages/cart/cartevents/edit/[id].tsx
index 81fca35..689c487 100644
--- a/pages/cart/cartevents/edit/[id].tsx
+++ b/pages/cart/cartevents/edit/[id].tsx
@@ -7,9 +7,9 @@ export const getServerSideProps = async (context) => {
console.log("edit page getServerSideProps");
const axios = await axiosServer(context);
const { id } = context.query;
- const { data } = await axios.get(`${process.env.NEXTAUTH_URL}/api/data/cartevents/` + id);
+ const { data } = await axios.get(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/api/data/cartevents/` + id);
const locations = await axios
- .get(`${process.env.NEXTAUTH_URL}/api/data/locations?select=id,name`)
+ .get(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/api/data/locations?select=id,name`)
.then((res) => {
console.log("locations: " + JSON.stringify(res.data));
return res.data;
diff --git a/pages/cart/cartevents/index.tsx b/pages/cart/cartevents/index.tsx
index c5006c1..0396d9f 100644
--- a/pages/cart/cartevents/index.tsx
+++ b/pages/cart/cartevents/index.tsx
@@ -69,7 +69,7 @@ export default function CartEventPage({ items, locations }: ICartEventPageProps)
{item.shiftDuration}
- {item.isactive ? "Yes" : "No"}
+ {item.isActive ? "Yes" : "No"}
{
const axios = await axiosServer(context);
const locations = await axios
- .get(`${process.env.NEXTAUTH_URL}/api/data/locations?select=id,name`)
+ .get(`${process.env.NEXT_PUBLIC_PUBLIC_URL}/api/data/locations?select=id,name`)
.then((res) => {
console.log("locations: " + JSON.stringify(res.data));
return res.data;
@@ -41,7 +41,7 @@ export const getServerSideProps = async (context) => {
const { id } = context.query.id;
const { data: item } = await axiosInstance.get(
- process.env.NEXTAUTH_URL + "/api/data/cartevents/" + context.params.id
+ process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/cartevents/" + context.params.id
);
return {
diff --git a/pages/cart/locations/[id].tsx b/pages/cart/locations/[id].tsx
index f66a6bc..c66f338 100644
--- a/pages/cart/locations/[id].tsx
+++ b/pages/cart/locations/[id].tsx
@@ -99,11 +99,11 @@ export const getServerSideProps: GetServerSideProps = async (context) => {
const axios = await axiosServer(context);
const { data: location } = await axios.get(
- `${process.env.NEXTAUTH_URL}/api/data/locations/${context.params.id}`
+ `${process.env.NEXT_PUBLIC_PUBLIC_URL}/api/data/locations/${context.params.id}`
);
if (location.backupLocationId !== null) {
const { data: backupLocation } = await axios.get(
- process.env.NEXTAUTH_URL + "/api/data/locations/" + location.backupLocationId
+ process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/locations/" + location.backupLocationId
);
location.backupLocationName = backupLocation.name;
location.backupLocationContent = backupLocation ? backupLocation.content : "";
diff --git a/pages/cart/locations/edit/[id].tsx b/pages/cart/locations/edit/[id].tsx
index ef1b7b8..a48f89a 100644
--- a/pages/cart/locations/edit/[id].tsx
+++ b/pages/cart/locations/edit/[id].tsx
@@ -29,7 +29,7 @@ export const getServerSideProps = async (context) => {
};
}
const { data: item } = await axios.get(
- process.env.NEXTAUTH_URL + "/api/data/locations/" + context.params.id
+ process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/locations/" + context.params.id
);
console.log(item) //this is the location object
context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
diff --git a/pages/cart/locations/new.tsx b/pages/cart/locations/new.tsx
index be77ea0..a76cf0a 100644
--- a/pages/cart/locations/new.tsx
+++ b/pages/cart/locations/new.tsx
@@ -32,7 +32,7 @@ export const getServerSideProps = async (context) => {
}
const { data: loc } = await axios.get(
- `${process.env.NEXTAUTH_URL}api/data/locations/` + context.params.id
+ `${process.env.NEXT_PUBLIC_PUBLIC_URL}api/data/locations/` + context.params.id
);
console.log(location) //this is the location object
context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
diff --git a/pages/cart/publishers/edit/[id].tsx b/pages/cart/publishers/edit/[id].tsx
index 680fb41..0e93b9a 100644
--- a/pages/cart/publishers/edit/[id].tsx
+++ b/pages/cart/publishers/edit/[id].tsx
@@ -44,7 +44,7 @@ export const getServerSideProps = async (context) => {
props: {}
};
}
- var url = process.env.NEXTAUTH_URL + "/api/data/publishers/" + context.query.id + "?include=availabilities,assignments,assignments.shift";
+ var url = process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/publishers/" + context.query.id + "?include=availabilities,assignments,assignments.shift";
console.log("GET PUBLISHER FROM:" + url)
const { data: item } = await axios.get(url);
diff --git a/pages/cart/publishers/import.tsx b/pages/cart/publishers/import.tsx
index 02dc288..7e10eb7 100644
--- a/pages/cart/publishers/import.tsx
+++ b/pages/cart/publishers/import.tsx
@@ -136,6 +136,7 @@ export default function ImportPage() {
const handleSave = async () => {
try {
common.logger.debug("handleSave to: " + common.getBaseUrl());
+ console.log("handleSave to: " + common.getBaseUrl());
const header = rawData[mode.headerRow];
for (let i = mode.headerRow + 1; i < rawData.length; i++) { //fullData.length; each publisher
//update status.info with current publisher
@@ -194,7 +195,7 @@ export default function ImportPage() {
let personNames = names.join(' ');
try {
try {
- const select = "&select=id,firstName,lastName,phone,isTrained,desiredShiftsPerMonth,isactive,type,availabilities";
+ const select = "&select=id,firstName,lastName,phone,isTrained,desiredShiftsPerMonth,isActive,type,availabilities";
const responseByName = await axiosInstance.get(`/api/?action=findPublisher&filter=${names.join(' ')}${select}`);
let existingPublisher = responseByName.data[0];
if (!existingPublisher) {
@@ -248,7 +249,7 @@ export default function ImportPage() {
{ key: 'phone', value: phone },
{ key: 'desiredShiftsPerMonth', value: desiredShiftsPerMonth, parse: parseInt },
{ key: 'isTrained', value: isTrained },
- { key: 'isactive', value: isActive },
+ { key: 'isActive', value: isActive },
{ key: 'type', value: publisherType, parse: common.getPubTypeEnum }
];
@@ -286,7 +287,7 @@ export default function ImportPage() {
phone,
firstName: names[0],
lastName: names[1],
- isactive: isActive,
+ isActive: isActive,
isTrained,
desiredShiftsPerMonth,
});
@@ -301,7 +302,7 @@ export default function ImportPage() {
phone,
firstName: firstname,
lastName: names[names.length - 1],
- isactive: isActive,
+ isActive: isActive,
isTrained,
desiredShiftsPerMonth
});
@@ -530,7 +531,7 @@ export default function ImportPage() {
weekOfMonth: weekNr, // Add the missing 'weekOfMonth'
startTime,
endTime,
- isactive: true,
+ isActive: true,
type: AvailabilityType.OneTime,
isWithTransportIn: false, // Add the missing 'isWithTransport' property
isWithTransportOut: false, // Add the missing 'isWithTransport' property
diff --git a/pages/cart/publishers/index.tsx b/pages/cart/publishers/index.tsx
index 40bc324..e0b0c57 100644
--- a/pages/cart/publishers/index.tsx
+++ b/pages/cart/publishers/index.tsx
@@ -225,7 +225,7 @@ export default PublishersPage;
export const getServerSideProps = async (context) => {
const axios = await axiosServer(context);
//ToDo: refactor all axios calls to use axiosInstance and this URL
- const { data: publishers } = await axios.get('/api/data/publishers?select=id,firstName,lastName,email,isactive,isTrained,isImported,assignments.shift.startTime,availabilities.startTime&dev=fromuseefect');
+ const { data: publishers } = await axios.get('/api/data/publishers?select=id,firstName,lastName,email,isActive,isTrained,isImported,assignments.shift.startTime,availabilities.startTime&dev=fromuseefect');
return {
props: {
diff --git a/pages/cart/publishers/new.tsx b/pages/cart/publishers/new.tsx
index fb99ae4..c0b1988 100644
--- a/pages/cart/publishers/new.tsx
+++ b/pages/cart/publishers/new.tsx
@@ -47,7 +47,7 @@ export const getServerSideProps = async (context) => {
props: {}
};
}
- var url = process.env.NEXTAUTH_URL + "/api/data/publishers/" + context.query.id + "?include=availabilities,shifts";
+ var url = process.env.NEXT_PUBLIC_PUBLIC_URL + "/api/data/publishers/" + context.query.id + "?include=availabilities,shifts";
console.log("GET PUBLISHER FROM:" + url)
const { data } = await axios.get(url);
diff --git a/pages/cart/publishers/stats.tsx b/pages/cart/publishers/stats.tsx
index e69f47f..d881b1f 100644
--- a/pages/cart/publishers/stats.tsx
+++ b/pages/cart/publishers/stats.tsx
@@ -41,7 +41,7 @@ function ContactsPage({ publishers }) {
{filteredPublishers.map((pub) => (
- {pub.firstName} {pub.lastName}
+ {pub.firstName} {pub.lastName}
{pub.currentMonthAvailabilityDaysCount || 0} | {pub.currentMonthAvailabilityHoursCount || 0}
@@ -74,16 +74,23 @@ export default ContactsPage;
export const getServerSideProps = async (context) => {
const dateStr = new Date().toISOString().split('T')[0];
- let publishers = await filterPublishers('id,firstName,lastName,email,isactive,desiredShiftsPerMonth', "", new Date(), true, true, false);
+ let publishers = await filterPublishers('id,firstName,lastName,email,isActive,desiredShiftsPerMonth', "", new Date(), true, true, false);
// 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`);
+ // 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
+ // 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) {
@@ -100,8 +107,13 @@ export const getServerSideProps = async (context) => {
}
}
});
+ //remove availabilities that isFromPreviousAssignment
+ publisher.availabilities = publisher.availabilities.filter(availability => !availability.isFromPreviousAssignment);
+
});
+ //remove publishers without availabilities
+ publishers = publishers.filter(publisher => publisher.availabilities.length > 0);
return {
props: {
diff --git a/pages/cart/reports/experience.tsx b/pages/cart/reports/experience.tsx
index 5cb4db8..9e4df08 100644
--- a/pages/cart/reports/experience.tsx
+++ b/pages/cart/reports/experience.tsx
@@ -32,7 +32,7 @@ export const getServerSideProps = async (context) => {
// };
// }
// const { data: loc } = await axiosInstance.get(
- // `${process.env.NEXTAUTH_URL}api/data/locations/` + context.params.id
+ // `${process.env.NEXT_PUBLIC_PUBLIC_URL}api/data/locations/` + context.params.id
// );
// console.log(location) //this is the location object
diff --git a/pages/cart/reports/list.tsx b/pages/cart/reports/list.tsx
index 03c3d78..3675b55 100644
--- a/pages/cart/reports/list.tsx
+++ b/pages/cart/reports/list.tsx
@@ -74,6 +74,18 @@ export default function Reports() {
Добави нов отчет
+
+
+ Отчети
+
+
+
+ Случка
+
+
+
+ Отзиви
+
diff --git a/pages/cart/reports/report.tsx b/pages/cart/reports/report.tsx
index ef3b971..8c7bcff 100644
--- a/pages/cart/reports/report.tsx
+++ b/pages/cart/reports/report.tsx
@@ -33,7 +33,7 @@ export const getServerSideProps = async (context) => {
// }
// const { data: loc } = await axiosInstance.get(
- // `${process.env.NEXTAUTH_URL}api/data/locations/` + context.params.id
+ // `${process.env.NEXT_PUBLIC_PUBLIC_URL}api/data/locations/` + context.params.id
// );
// console.log(location) //this is the location object
// context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
diff --git a/pages/contactUs.tsx b/pages/contactUs.tsx
index a7cd1a8..6fb5088 100644
--- a/pages/contactUs.tsx
+++ b/pages/contactUs.tsx
@@ -24,7 +24,7 @@ const ContactsPage = () => {
*/
}
- {/*
+ {/*
Телеграм
*/}
diff --git a/pages/dash.tsx b/pages/dash.tsx
index c5f8ced..71718db 100644
--- a/pages/dash.tsx
+++ b/pages/dash.tsx
@@ -86,7 +86,7 @@ async function getAvailabilities(userId) {
select: {
id: true,
name: true,
- isactive: true,
+ isActive: true,
isFromPreviousAssignment: true,
dayofweek: true,
dayOfMonth: true,
@@ -121,7 +121,7 @@ async function getAvailabilities(userId) {
shiftId Int
publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
publisherId String
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
isConfirmed Boolean @default(false)
isWithTransport Boolean @default(false)
Report Report[]
@@ -133,7 +133,7 @@ async function getAvailabilities(userId) {
},
select: {
id: true,
- isTentative: true,
+ isBySystem: true,
isConfirmed: true,
isWithTransport: true,
shift: {
diff --git a/prisma/bl/subqueries.js b/prisma/bl/subqueries.js
index ab557e0..44f977f 100644
--- a/prisma/bl/subqueries.js
+++ b/prisma/bl/subqueries.js
@@ -13,7 +13,7 @@ export const publisherSelectWithAvCount = {
select: {
availability: {
where: {
- isactive: true
+ isActive: true
}
}
@@ -40,7 +40,7 @@ export const publisherSelect = {
// endTime: true,
// dayOfMonth: true,
// dayofweek: true,
-// isactive: true,
+// isActive: true,
// count: 'Availability_count'
// }
// }
\ No newline at end of file
diff --git a/prisma/migrations/20221130072538_updates/migration.sql b/prisma/migrations/20221130072538_updates/migration.sql
index 239a224..978530e 100644
--- a/prisma/migrations/20221130072538_updates/migration.sql
+++ b/prisma/migrations/20221130072538_updates/migration.sql
@@ -5,7 +5,7 @@ CREATE TABLE `Publisher` (
`lastName` VARCHAR(191) NOT NULL,
`email` VARCHAR(191) NOT NULL,
`phone` VARCHAR(191) NULL,
- `isactive` BOOLEAN NOT NULL DEFAULT true,
+ `isActive` BOOLEAN NOT NULL DEFAULT true,
`age` INTEGER NULL,
UNIQUE INDEX `Publisher_email_key`(`email`),
@@ -41,7 +41,7 @@ CREATE TABLE `Shift` (
`name` VARCHAR(191) NOT NULL,
`startTime` DATETIME(3) NOT NULL,
`endTime` DATETIME(3) NOT NULL,
- `isactive` BOOLEAN NOT NULL DEFAULT true,
+ `isActive` BOOLEAN NOT NULL DEFAULT true,
`requiresTransport` BOOLEAN NOT NULL DEFAULT false,
PRIMARY KEY (`id`)
@@ -52,7 +52,7 @@ CREATE TABLE `Location` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL,
`address` VARCHAR(191) NOT NULL,
- `isactive` BOOLEAN NOT NULL DEFAULT true,
+ `isActive` BOOLEAN NOT NULL DEFAULT true,
`dayofweek` ENUM('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') NOT NULL,
PRIMARY KEY (`id`)
diff --git a/prisma/migrations/20221201223336_/migration.sql b/prisma/migrations/20221201223336_/migration.sql
index 90fe9cb..446e110 100644
--- a/prisma/migrations/20221201223336_/migration.sql
+++ b/prisma/migrations/20221201223336_/migration.sql
@@ -6,10 +6,10 @@
*/
-- AlterTable
-ALTER TABLE `Availability` ADD COLUMN `isactive` BOOLEAN NOT NULL DEFAULT true;
+ALTER TABLE `Availability` ADD COLUMN `isActive` BOOLEAN NOT NULL DEFAULT true;
-- AlterTable
-ALTER TABLE `CartEvent` ADD COLUMN `isactive` BOOLEAN NOT NULL DEFAULT true,
+ALTER TABLE `CartEvent` ADD COLUMN `isActive` BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN `locationId` INTEGER NOT NULL,
ADD COLUMN `shiftDuration` INTEGER NOT NULL;
diff --git a/prisma/migrations/20221217221944_publisher_to_shift_renamed_assignment/migration.sql b/prisma/migrations/20221217221944_publisher_to_shift_renamed_assignment/migration.sql
index a466b86..cd87cb8 100644
--- a/prisma/migrations/20221217221944_publisher_to_shift_renamed_assignment/migration.sql
+++ b/prisma/migrations/20221217221944_publisher_to_shift_renamed_assignment/migration.sql
@@ -18,7 +18,7 @@ CREATE TABLE `Assignment` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`shiftId` INTEGER NOT NULL,
`publisherId` INTEGER NOT NULL,
- `isactive` BOOLEAN NOT NULL DEFAULT true,
+ `isActive` BOOLEAN NOT NULL DEFAULT true,
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
diff --git a/prisma/migrations/20240131113517_assignment_isactive_renamed_istetative/migration.sql b/prisma/migrations/20240131113517_assignment_isactive_renamed_istetative/migration.sql
index 0d0703e..55bc254 100644
--- a/prisma/migrations/20240131113517_assignment_isactive_renamed_istetative/migration.sql
+++ b/prisma/migrations/20240131113517_assignment_isactive_renamed_istetative/migration.sql
@@ -1,11 +1,11 @@
/*
Warnings:
- - You are about to drop the column `isactive` on the `assignment` table. All the data in the column will be lost.
+ - You are about to drop the column `isActive` on the `assignment` table. All the data in the column will be lost.
*/
-- AlterTable
-ALTER TABLE `Assignment` DROP COLUMN `isactive`,
+ALTER TABLE `Assignment` DROP COLUMN `isActive`,
ADD COLUMN `isTentative` BOOLEAN NOT NULL DEFAULT false;
-- AlterTable
diff --git a/prisma/migrations/20240325214807_misc_renames/migration.sql b/prisma/migrations/20240325214807_misc_renames/migration.sql
new file mode 100644
index 0000000..890be7a
--- /dev/null
+++ b/prisma/migrations/20240325214807_misc_renames/migration.sql
@@ -0,0 +1,21 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `isTentative` on the `Assignment` table. All the data in the column will be lost.
+
+*/
+
+-- AlterTable
+ALTER TABLE `Assignment`
+ ADD COLUMN `isBySystem` BOOLEAN NOT NULL DEFAULT FALSE;
+
+-- Depending on your DBMS, you might need to execute one statement at a time.
+-- Especially, the UPDATE statement should be run separately.
+UPDATE `Assignment` SET `isBySystem` = isTentative;
+
+-- Drop the isTentative column
+ALTER TABLE `Assignment` DROP COLUMN `isTentative`;
+
+-- AlterTable
+ALTER TABLE `Report`
+ ADD COLUMN `type` ENUM('ServiceReport', 'Experience', 'Feedback_Problem', 'Feedback_Suggestion', 'Feedback') NOT NULL DEFAULT 'ServiceReport';
diff --git a/prisma/migrations/20240328162213_add_availability_self_ref/migration.sql b/prisma/migrations/20240328162213_add_availability_self_ref/migration.sql
new file mode 100644
index 0000000..bd11572
--- /dev/null
+++ b/prisma/migrations/20240328162213_add_availability_self_ref/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE `Availability` ADD COLUMN `parentAvailabilityId` INTEGER NULL;
+
+-- AddForeignKey
+ALTER TABLE `Availability` ADD CONSTRAINT `Availability_parentAvailabilityId_fkey` FOREIGN KEY (`parentAvailabilityId`) REFERENCES `Availability`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/prisma/migrations/20240401231200_add_publisher_email_sbscription_options/migration.sql b/prisma/migrations/20240401231200_add_publisher_email_sbscription_options/migration.sql
new file mode 100644
index 0000000..e7f91bc
--- /dev/null
+++ b/prisma/migrations/20240401231200_add_publisher_email_sbscription_options/migration.sql
@@ -0,0 +1,3 @@
+-- AlterTable
+ALTER TABLE `Publisher` ADD COLUMN `isSubscribedToCoverMe` BOOLEAN NOT NULL DEFAULT false,
+ ADD COLUMN `isSubscribedToReminders` BOOLEAN NOT NULL DEFAULT false;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 2ea7b1f..1faea21 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -81,13 +81,21 @@ enum PublisherType {
SpecialPioneer_Missionary
}
+enum ReportType {
+ ServiceReport
+ Experience
+ Feedback_Problem
+ Feedback_Suggestion
+ Feedback
+}
+
model Publisher {
id String @id @default(cuid())
firstName String
lastName String
email String @unique
phone String?
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
isImported Boolean @default(false)
isTrained Boolean @default(false)
age Int?
@@ -98,20 +106,21 @@ model Publisher {
userId String? @unique
user User? @relation(fields: [userId], references: [id])
- role UserRole @default(USER)
- desiredShiftsPerMonth Int @default(4)
- isMale Boolean @default(true)
- isNameForeign Boolean @default(false)
-
- familyHeadId String? // Optional familyHeadId for each family member
- familyHead Publisher? @relation("FamilyMember", fields: [familyHeadId], references: [id])
- familyMembers Publisher[] @relation("FamilyMember")
- alwaysAsFamily Boolean? @default(false) //NEW v1.0.1 // New field to indicate if the publisher always wants to be assigned with the family
- type PublisherType @default(Publisher)
- town String?
- comments String?
- reports Report[]
- Message Message[]
+ role UserRole @default(USER)
+ desiredShiftsPerMonth Int @default(4)
+ isMale Boolean @default(true)
+ isNameForeign Boolean @default(false)
+ isSubscribedToCoverMe Boolean @default(false)
+ isSubscribedToReminders Boolean @default(false)
+ familyHeadId String? // Optional familyHeadId for each family member
+ familyHead Publisher? @relation("FamilyMember", fields: [familyHeadId], references: [id])
+ familyMembers Publisher[] @relation("FamilyMember")
+ alwaysAsFamily Boolean? @default(false) //NEW v1.0.1 // New field to indicate if the publisher always wants to be assigned with the family
+ type PublisherType @default(Publisher)
+ town String?
+ comments String?
+ reports Report[]
+ Message Message[]
}
model Availability {
@@ -124,7 +133,7 @@ model Availability {
weekOfMonth Int?
startTime DateTime
endTime DateTime
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
type AvailabilityType @default(Weekly)
isWithTransportIn Boolean @default(false)
isWithTransportOut Boolean @default(false)
@@ -133,7 +142,10 @@ model Availability {
repeatWeekly Boolean? // New field to indicate weekly repetition // until now dayofweek was used for repetition when dayOfMonth is null
repeatFrequency Int? // New field to indicate repetition frequency
endDate DateTime? // New field for the end date of repetition
- dateOfEntry DateTime? //NEW v1.0.1 trade storage for intuintivity
+ dateOfEntry DateTime? //NEW v1.0.1
+ parentAvailabilityId Int?
+ parentAvailability Availability? @relation("ParentAvailability", fields: [parentAvailabilityId], references: [id])
+ ChildAvailabilities Availability[] @relation("ParentAvailability")
}
model CartEvent {
@@ -143,7 +155,7 @@ model CartEvent {
shiftDuration Int
shifts Shift[]
dayofweek DayOfWeek
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
location Location @relation(fields: [locationId], references: [id])
locationId Int
eventType EventType @default(PW_Cart)
@@ -160,7 +172,7 @@ model Shift {
name String
startTime DateTime
endTime DateTime
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
requiresTransport Boolean @default(false)
notes String?
//date DateTime
@@ -177,7 +189,7 @@ model Assignment {
shiftId Int
publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
publisherId String
- isTentative Boolean @default(false) // if no availability for it, when importing previous schedules
+ isBySystem Boolean @default(false) // if no availability for it, when importing previous schedules
isConfirmed Boolean @default(false)
isWithTransport Boolean @default(false)
isMailSent Boolean @default(false)
@@ -190,7 +202,7 @@ model Location {
id Int @id @default(autoincrement())
name String
address String
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
content String? @db.LongText
cartEvents CartEvent[]
reports Report[]
@@ -219,7 +231,8 @@ model Report {
returnVisitInfoCount Int?
conversationCount Int?
- experienceInfo String? @db.LongText
+ experienceInfo String? @db.LongText
+ type ReportType @default(ServiceReport)
@@map("Report")
}
diff --git a/prisma/seed.sql b/prisma/seed.sql
index f64a4f5..6261a5c 100644
--- a/prisma/seed.sql
+++ b/prisma/seed.sql
@@ -30,7 +30,7 @@ INSERT INTO
`id`,
`name`,
`address`,
- `isactive`
+ `isActive`
)
VALUES (
1,
@@ -57,7 +57,7 @@ INSERT INTO
`startTime`,
`endTime`,
`dayofweek`,
- `isactive`,
+ `isActive`,
`locationId`,
`shiftDuration`,
`eventType`,
@@ -147,7 +147,7 @@ VALUES (
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */
;
--- INSERT INTO `cartevent` (`id`, `startTime`, `endTime`, `dayofweek`, `isactive`, `locationId`, `shiftDuration`, `eventType`, `numberOfPublishers`)
+-- INSERT INTO `cartevent` (`id`, `startTime`, `endTime`, `dayofweek`, `isActive`, `locationId`, `shiftDuration`, `eventType`, `numberOfPublishers`)
-- VALUES
-- (2, '2023-12-27 07:00:33.174', '2023-12-27 16:00:33.174', 'Tuesday', 1, 2, 90, 'PW_Cart', 4),
-- (3, '2023-12-28 07:00:33.174', '2023-12-28 16:00:33.174', 'Wednesday', 1, 3, 90, 'PW_Cart', 4),
diff --git a/process.d.ts b/process.d.ts
index b140ecb..b31f4de 100644
--- a/process.d.ts
+++ b/process.d.ts
@@ -1,6 +1,6 @@
declare namespace NodeJS {
export interface ProcessEnv {
- NEXTAUTH_URL: string
+ PUBLIC_URL: string
NEXTAUTH_SECRET: string
GITHUB_ID: string
GITHUB_SECRET: string
diff --git a/server.js b/server.js
index bfd1b44..8e3982c 100644
--- a/server.js
+++ b/server.js
@@ -28,22 +28,25 @@ let baseUrlGlobal;
// require('dotenv').config();
// }
-console.log("initial process.env.NODE_ENV = ", process.env.NODE_ENV);
+console.log("initial process.env.NODE_ENV = ", process.env.NODE_ENV); //NODE_ENV can be passed as docker param
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`
});
console.log("process.env.NODE_ENV = ", process.env.NODE_ENV);
-const PORT = process.env.NEXT_PUBLIC_PORT || 3000;
-const HOST = process.env.NEXT_PUBLIC_HOST;
+const PROTOCOL = process.env.PROTOCOL;
+const PORT = process.env.PORT || 3000;
+const HOST = process.env.HOST;
+
const dev = process.env.NODE_ENV !== "production";
-const PROTOCOL = process.env.NEXT_PUBLIC_PROTOCOL;
const nextApp = next({ dev });
const nextHandler = nextApp.getRequestHandler();
-console.log("process.env.SSL_ENABLED = ", process.env.SSL_ENABLED);
+console.log("process.env.PROTOCOL = ", process.env.PROTOCOL);
+process.env.NEXTAUTH_URL = process.env.NEXT_PUBLIC_PUBLIC_URL; //NEXTAUTH_URL mandatory for next-auth
+console.log("process.env.NEXT_PUBLIC_PUBLIC_URL = ", process.env.NEXT_PUBLIC_PUBLIC_URL);
console.log("process.env.NEXTAUTH_URL = ", process.env.NEXTAUTH_URL);
-console.log("process.env.NEXT_PUBLIC_PORT = ", process.env.NEXT_PUBLIC_PORT);
+console.log("process.env.PORT = ", process.env.PORT);
console.log("process.env.TELEGRAM_BOT = ", process.env.TELEGRAM_BOT);
//require('module-alias/register');
@@ -62,12 +65,37 @@ const uploadTmp = multer({ storage: storageMem });
const prisma = common.getPrismaClient();
+const server = express();
+//check if ssl is enabled
+if (process.env.PROTOCOL === 'https') {
+ console.log("SSL_ENABLED = true");
+ // Redirect from http to https
+ // server.use((req, res, next) => {
+ // if (req.headers['x-forwarded-proto'] !== 'https') {
+ // return res.redirect(`https://${req.headers.host}${req.url}`);
+ // }
+ // next();
+ // });
+ if (process.env.SSL_KEY && process.env.SSL_CERT) {
+ const options = {
+ key: fs.readFileSync(process.env.SSL_KEY),
+ cert: fs.readFileSync(process.env.SSL_CERT),
+ secureProtocol: 'TLSv1_2_method', // Example: Force TLS 1.2
+ };
+ https.createServer(options, server).listen(PORT);
+ }
+}
+else {
+ server.listen(PORT, (err) => {
+ if (err) throw err;
+ console.log(`> Ready on ${PROTOCOL}://${HOST}:${PORT}`);
+ });
+}
// handlers
nextApp
.prepare()
.then(() => {
- const server = express();
// Add the middleware to set 'x-forwarded-host' header
server.use((req, res, next) => {
@@ -84,6 +112,8 @@ nextApp
next();
});
server.use("/favicon.ico", express.static("styles/favicon_io/favicon.ico"));
+ // server.use("/robots.txt", express.static("styles/favicon_io/robots.txt"));
+ // server.use("/sitemap.xml", express.static("styles/favicon_io/sitemap.xml"));
server.get("/last_schedule_json", (req, res) => {
// var data = JSON.parse(fs.readFileSync("./content/sources/march_flat.json", "utf8"));
@@ -259,7 +289,7 @@ nextApp
var shifts = await prisma.shift.findMany({
where: {
- isactive: true,
+ isActive: true,
startTime: {
gte: fromDate,
lt: toDate,
@@ -410,7 +440,7 @@ nextApp
var publishers = await prisma.publisher.findMany({
where: {
- isactive: true,
+ isActive: true,
email: {
not: "",
},
@@ -556,31 +586,6 @@ nextApp
return nextHandler(req, res);
});
- //check if ssl is enabled
- if (process.env.SSL_ENABLED === "true") {
- console.log("SSL_ENABLED = true");
- // Redirect from http to https
- // server.use((req, res, next) => {
- // if (req.headers['x-forwarded-proto'] !== 'https') {
- // return res.redirect(`https://${req.headers.host}${req.url}`);
- // }
- // next();
- // });
- if (process.env.SSL_KEY && process.env.SSL_CERT) {
- const options = {
- key: fs.readFileSync(process.env.SSL_KEY),
- cert: fs.readFileSync(process.env.SSL_CERT),
- secureProtocol: 'TLSv1_2_method', // Example: Force TLS 1.2
- };
- https.createServer(options, server).listen(PORT);
- }
- }
- else {
- server.listen(PORT, (err) => {
- if (err) throw err;
- console.log(`> Ready on ${PROTOCOL}://${HOST}:${PORT}`);
- });
- }
})
.catch((ex) => {
console.warn(`Error starting server on ${HOST}:${PORT}`)
diff --git a/src/helpers/common.js b/src/helpers/common.js
index 4cc84e7..e580a4b 100644
--- a/src/helpers/common.js
+++ b/src/helpers/common.js
@@ -4,8 +4,9 @@
const levenshtein = require('fastest-levenshtein');
-const fs = require("fs");
-const path = require("path");
+const fs = typeof window === 'undefined' ? require('fs') : undefined;
+const path = typeof window === 'undefined' ? require('path') : undefined;
+
const { PrismaClient } = require('@prisma/client');
const DayOfWeek = require("@prisma/client").DayOfWeek;
@@ -75,43 +76,10 @@ exports.setBaseUrl = function (req) {
};
exports.getBaseUrl = function (relative = "", req = null) {
- const filePath = path.join(__dirname, 'baseUrl.txt');
-
- try {
- if (fs.existsSync(filePath)) {
- const baseUrl = fs.readFileSync(filePath, 'utf8').trim();
- const fullUrl = relative ? new URL(relative, baseUrl).toString() : baseUrl;
- return fullUrl;
- } else {
- if (req) {
- const baseUrl = exports.setBaseUrl(req); // Correctly reference setBaseUrl
- return `${baseUrl}/${relative.replace(/^\/|\/$/g, '')}`;
- }
- console.log('Base URL file does not exist.');
- return null;
- }
- } catch (error) {
- console.error('Error reading the base URL file:', error);
- return null;
- }
- // const host = process.env.NEXT_PUBLIC_HOST || '127.0.0.1';
- // const port = process.env.NEXT_PUBLIC_PORT ? `:${ process.env.NEXT_PUBLIC_PORT } ` : '';
- // const protocol = process.env.NEXT_PUBLIC_PROTOCOL || "https"
-
- // //const url = `${ protocol }://${host}${port}/${relative.replace(/^\/|\/$/g, '')}/`;
- // const isRelativeEmpty = !relative || relative.trim() === '';
- // const formattedRelative = !isRelativeEmpty ? '/' + relative.replace(/^\/|\/$/g, '') : '';
- // const url = `${protocol}://${host}${port}${formattedRelative}`;
-
-
- // logger.debug("NODE_ENV = ", process.env.NODE_ENV, "protocol:", protocol);
- // logger.debug("getBaseURL = ", url);
-
- // return url;
+ return process.env.NEXT_PUBLIC_PUBLIC_URL + relative;
};
-
let prisma;
exports.getPrismaClient = function getPrismaClient() {
if (!prisma) {
@@ -122,6 +90,8 @@ exports.getPrismaClient = function getPrismaClient() {
datasources: { db: { url: process.env.DATABASE_URL } },
});
}
+ logger.debug("getPrismaClient: process.env.DATABASE_URL = ", process.env.DATABASE_URL);
+
return prisma;
}
@@ -228,15 +198,52 @@ exports.getDayOfWeekDate = function (dayOfWeekName, date = new Date()) {
return date;
};
//common.getWeekOfMonth(date)
-// exports.getWeekOfMonth = function (date) {
-// // Copy date so don't modify original
-// date = new Date(date);
-// // Adjust to Monday of this week
-// date.setDate(date.getDate() + 3 - (date.getDayEuropean() + 6) % 7);
-// // Return week number
-// const weekNumber = Math.floor((date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000 / 7);
-// return weekNumber;
-// }
+exports.getWeekOfMonth = function (inputDate) {
+ let date = new Date(inputDate);
+ let firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
+ let firstMonday = new Date(firstDayOfMonth);
+
+ // Adjust firstDayOfMonth to the first Monday of the month
+ if (firstDayOfMonth.getDay() === 0) { // Sunday
+ firstMonday.setDate(2);
+ } else if (firstDayOfMonth.getDay() !== 1) { // Not Monday
+ firstMonday.setDate(9 - firstDayOfMonth.getDay());
+ }
+
+ // Calculate the difference in days
+ let diff = (date - firstMonday) / (1000 * 60 * 60 * 24);
+ // Calculate week number
+ let weekNumber = Math.ceil((diff + 1) / 7);
+
+ return weekNumber;
+};
+
+exports.getDateFromWeekNrAndDayOfWeek = function (firstMonday, weekNr, dayOfWeekEnum, startTime) {
+ firstMonday = new Date(firstMonday);
+ startTime = new Date(startTime);
+ if (!weekNr || weekNr < 1 || weekNr > 5) {
+ weekNr = this.getWeekOfMonth(startTime);
+ }
+ //get int from dayOfWeekEnum
+ let dayOfWeekNr = this.getDayOfWeekIndex(dayOfWeekEnum);
+ if (dayOfWeekNr < 0 || dayOfWeekNr > 6) {
+ dayOfWeekNr = 0;
+ }
+
+ // Calculate the day offset from the first Monday of the month
+ // Note: Assuming dayOfWeekEnum starts from 0 (Monday) to 6 (Sunday)
+ const daysFromFirstMonday = (weekNr - 1) * 7 + dayOfWeekNr;
+
+ // Calculate the new date
+ let newStart = new Date(firstMonday);
+ newStart.setDate(firstMonday.getDate() + daysFromFirstMonday);
+
+ // Extract time from startTime and apply it to newStart
+ const time = new Date(startTime);
+ newStart.setHours(time.getHours(), time.getMinutes(), time.getSeconds());
+
+ return newStart;
+}
exports.getMonthDatesInfo = function (date) {
// get first day of the month
@@ -275,6 +282,9 @@ exports.getMonthDatesInfo = function (date) {
// lastSunday.setDate(firstDayNextMonth.getDate() - firstDayNextMonth.getDay());
//logger.debug("Last Sunday: ", lastSunday);
+ const diffInDays = (lastSunday - firstMonday) / (1000 * 60 * 60 * 24);
+ // Calculate number of weeks, rounding up for partial weeks
+ const nrOfWeeks = Math.ceil((diffInDays + 1) / 7);
return {
firstDay: firstDay,
@@ -285,7 +295,7 @@ exports.getMonthDatesInfo = function (date) {
date: date,
monthName: monthName,
year: date.getFullYear(),
- nrOfWeeks: Math.ceil((lastMonday.getDate() - firstMonday.getDate()) / 7)
+ nrOfWeeks: nrOfWeeks
};
};
exports.getMonthInfo = exports.getMonthDatesInfo;
diff --git a/src/helpers/data.js b/src/helpers/data.js
index 7c0916b..dc39ff2 100644
--- a/src/helpers/data.js
+++ b/src/helpers/data.js
@@ -79,10 +79,7 @@ async function findPublisher(names, email, select, getAll = false) {
}
async function findPublisherAvailability(publisherId, date) {
-
const prisma = common.getPrismaClient();
- const dayOfWeek = common.getDayOfWeekNameEnEnum(date); // Assuming common.getDayOfWeekNameEnEnum returns the day of week
- //const weekOfMonth = common.getWeekOfMonth(date); // Assuming common.getWeekOfMonth returns the week of month
date = new Date(date); // Convert to date object if not already
const hours = date.getHours();
const minutes = date.getMinutes();
@@ -90,32 +87,24 @@ async function findPublisherAvailability(publisherId, date) {
const potentialAvailabilities = await prisma.availability.findMany({
where: {
publisherId: publisherId,
- OR: [
+ AND: [ // Ensure both conditions must be met
{
- // Exact date match
startTime: {
- gte: new Date(date.setHours(0, 0, 0, 0)),
- lt: new Date(date.setHours(23, 59, 59, 999))
- }
+ lte: new Date(date), // startTime is less than or equal to the date
+ },
},
{
- // Correct day of week and before the date, with endDate consideration
- dayofweek: dayOfWeek,
- OR: [
- {
- endDate: null
- },
- {
- endDate: {
- gt: date
- }
- }
- ]
- }
- ]
+ endTime: {
+ gte: new Date(date), // endTime is greater than or equal to the date
+ },
+ },
+ ],
}
});
+ if (potentialAvailabilities.length === 0) {
+ return null; // No availability found
+ }
// Filter the results based on time and other criteria when not exact date match
const availability = potentialAvailabilities.find(avail => {
const availStartHours = avail.startTime.getHours();
@@ -147,7 +136,7 @@ async function getAvailabilities(userId) {
select: {
id: true,
name: true,
- isactive: true,
+ isActive: true,
isFromPreviousAssignment: true,
dayofweek: true,
dayOfMonth: true,
@@ -182,7 +171,7 @@ async function getAvailabilities(userId) {
shiftId Int
publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
publisherId String
- isactive Boolean @default(true)
+ isActive Boolean @default(true)
isConfirmed Boolean @default(false)
isWithTransport Boolean @default(false)
Report Report[]
@@ -194,7 +183,7 @@ async function getAvailabilities(userId) {
},
select: {
id: true,
- isTentative: true,
+ isBySystem: true,
isConfirmed: true,
isWithTransport: true,
shift: {
diff --git a/src/helpers/excel.js b/src/helpers/excel.js
index 40f2f1c..4b18578 100644
--- a/src/helpers/excel.js
+++ b/src/helpers/excel.js
@@ -323,21 +323,21 @@ exports.processEvents = async function (events, year, monthNumber, progressCallb
}
var shifts = await prisma.shift.findMany({
where: {
- isactive: true,
+ isActive: true,
startTime: {
gte: monthDatesInfo.firstMonday,
lt: monthDatesInfo.lastSunday,
},
}
});
- var locations = await prisma.location.findMany({ where: { isactive: true, } });
+ var locations = await prisma.location.findMany({ where: { isActive: true, } });
- var cartEvents = await prisma.cartEvent.findMany({ where: { isactive: true, } });
+ var cartEvents = await prisma.cartEvent.findMany({ where: { isActive: true, } });
var publishers = await prisma.publisher.findMany({
- where: { isactive: true, },
+ where: { isActive: true, },
include: {
- availabilities: { where: { isactive: true, }, },
+ availabilities: { where: { isActive: true, }, },
assignments: { include: { shift: true, }, },
},
});
@@ -472,7 +472,7 @@ exports.processEvents = async function (events, year, monthNumber, progressCallb
email: name.toLowerCase().replace(/ /g, "."), // + "@gmail.com"
firstName: firstname,
lastName: lastname,
- isactive: true,
+ isActive: true,
isImported: true,
// role: "EXTERNAL",
};
@@ -486,18 +486,18 @@ exports.processEvents = async function (events, year, monthNumber, progressCallb
// const availability = await prisma.availability.create({
// data: {
// publisherId: publisher.id,
- // //date: date,
// dayofweek: dayofWeek,
// startTime: startTime,
// endTime: endTime,
- // name: `от предишен график, ${publisher.firstName} ${publisher.lastName}`,
+ // name: `от график, ${publisher.firstName} ${publisher.lastName}`,
// isFromPreviousAssignment: true,
- // isactive: true,
+ // isActive: true,
// },
// });
// console.log(`Created WEEKLY availability with ID ${availability.id} for date '${date.toDateString()}' and publisher '${publisher.firstName} ${publisher.lastName}'`);
// }
- // const personResponse = await axiosInstance.post("/publishers", manualPub);
+
+ const personResponse = await axiosInstance.post("/publishers", manualPub);
// let personId = personResponse.data.id;
} catch (e) {
@@ -533,6 +533,7 @@ exports.processEvents = async function (events, year, monthNumber, progressCallb
});
//ToDo: fix findPublisherAvailability and creation of availabilities
// check if there is an availability for this publisher on this date, and if not, create one
+ //ToDo: check if that works
// const availability = await data.findPublisherAvailability(publisher.id, start);
// if (!availability && createAvailabilities) {
// const dayofWeek = common.getDayOfWeekNameEnEnum(date);
@@ -546,9 +547,11 @@ exports.processEvents = async function (events, year, monthNumber, progressCallb
// endTime: end,
// name: `от предишен график, ${publisher.firstName} ${publisher.lastName}`,
// isFromPreviousAssignment: true,
+ // isWithTransportIn: isWithTransport && event.shiftNr == 1,
+ // isWithTransportOut: isWithTransport && event.shiftNr > 1,
// },
// });
- // console.log(`Created WEEKLY availability with ID ${availability.id} for date '${date.toDateString()}' and publisher '${publisher.firstName} ${publisher.lastName}'`);
+ // console.log(`Created SYSTEM availability with ID ${availability.id} for date '${date.toDateString()}' and publisher '${publisher.firstName} ${publisher.lastName}'`);
// }
console.log(`Created assignment with ID ${assignment.id} for date '${date.toDateString()}' and location '${event.placeOfEvent}'. publisher: ${publisher.firstName} ${publisher.lastName}}`);
diff --git a/src/helpers/imports.js b/src/helpers/imports.js
deleted file mode 100644
index a866ff6..0000000
--- a/src/helpers/imports.js
+++ /dev/null
@@ -1,4 +0,0 @@
-//??? can we consolidate all imports into one file?
-import ProtectedRoute from '../../../components/protectedRoute';
-import axiosInstance from '../../../src/axiosSecure';
-import Layout from "../../../components/layout";
\ No newline at end of file
diff --git a/src/sql/dev-test.sql b/src/sql/dev-test.sql
index d7fe46b..09a3621 100644
--- a/src/sql/dev-test.sql
+++ b/src/sql/dev-test.sql
@@ -11,7 +11,7 @@ SELECT DISTINCT Publisher.*
FROM Publisher
INNER JOIN Availability ON Availability.publisherId = Publisher.id
WHERE
- Availability.isactive = true
+ Availability.isActive = true
AND ( (
Availability.dayOfMonth IS NOT NULL
AND Availability.startTime <= '2023-03-30 13:00:00'
@@ -30,7 +30,7 @@ SELECT DISTINCT Publisher.*
FROM Publisher
INNER JOIN Availability ON Availability.publisherId = Publisher.id
WHERE
- Availability.isactive = true
+ Availability.isActive = true
AND (Availability.dayOfMonth = 5) clfuyo33e005aknvchf1wm3bu All publishers: 121;
(118) unique,