refactoring; logging; cleanup;

This commit is contained in:
Dobromir Popov
2024-04-27 16:34:58 +03:00
parent 224b729677
commit 8dd5d36d7a
3 changed files with 81 additions and 158 deletions

View File

@ -9,6 +9,7 @@ const emailHelper = require('../../src/helpers/email');
const { v4: uuidv4 } = require('uuid');
const CON = require("../../src/helpers/const");
import { EventLogType } from "@prisma/client";
const logger = require('../../src/logger');
import fs from 'fs';
import path from 'path';
@ -46,6 +47,7 @@ export default async function handler(req, res) {
});
// Update the user status to accepted
console.log("User: " + publisher.firstName + " " + publisher.lastName + " accepted the CoverMe request");
logger.info("" + publisher.firstName + " " + publisher.lastName + " accepted the CoverMe request for shift " + shiftId + " PID: " + req.query.assignmentPID + "");
let assignmentPID = req.query.assignmentPID;
if (!shiftId) {
@ -276,6 +278,9 @@ export default async function handler(req, res) {
true, false);
}
// use
//concat and remove duplicate emails
let pubsToSend = subscribedPublishers.concat(availablePublishers).
filter((item, index, self) =>
@ -285,7 +290,7 @@ export default async function handler(req, res) {
);
console.log("Sending CoverMe request to " + pubsToSend.length + " publishers");
await prisma.eventLog.create({
let eventLog = await prisma.eventLog.create({
data: {
date: new Date(),
publisher: { connect: { id: publisher.id } },
@ -295,6 +300,7 @@ export default async function handler(req, res) {
+ "до: " + pubsToSend.map(p => p.firstName + " " + p.lastName + "<" + p.email + ">").join(", "),
}
});
logger.info("User: " + publisher.email + " sent a 'CoverMe' request for his assignment " + assignmentId + " - " + assignment.shift.cartEvent.location.name + " " + assignment.shift.startTime.toISOString() + " to " + pubsToSend.length + " publishers");
//send email to all subscribed publishers
for (let i = 0; i < pubsToSend.length; i++) {

View File

@ -2,7 +2,7 @@ import { getToken } from "next-auth/jwt";
import { NextApiRequest, NextApiResponse } from 'next'
import { DayOfWeek, AvailabilityType } from '@prisma/client';
const common = require('../../src/helpers/common');
const data = require('../../src/helpers/data');
const dataHelper = require('../../src/helpers/data');
const subq = require('../../prisma/bl/subqueries');
import { addMinutes } from 'date-fns';
@ -172,7 +172,7 @@ export default async function handler(req, res) {
// find publisher by full name or email
case "findPublisher":
const getAll = common.parseBool(req.query.all) || false;
let publisher = await data.findPublisher(filter, req.query.email, req.query.select, getAll);
let publisher = await dataHelper.findPublisher(filter, req.query.email, req.query.select, getAll);
res.status(200).json(publisher);
break;
@ -351,68 +351,8 @@ export default async function handler(req, res) {
break;
case "getPossibleShiftPublisherEmails":
let subscribedPublishers = await prisma.publisher.findMany({
where: {
isSubscribedToCoverMe: true
},
select: {
id: true,
firstName: true,
lastName: true,
email: true
}
}).then(pubs => {
return pubs.map(pub => {
return {
id: pub.id,
name: pub.firstName + " " + pub.lastName,
email: pub.email
}
});
});
let shift = await prisma.shift.findUnique({
where: {
id: parseInt(req.query.shiftId)
},
include: {
assignments: {
include: {
publisher: {
select: {
id: true,
firstName: true,
lastName: true,
email: true
}
}
}
}
}
});
let availableIn = new Date(addMinutes(shift.startTime, 0))
let availablePublishers = await filterPublishersNew_Available("id,firstName,lastName,email", availableIn,
true, false, false);
//filter out publishers that are already assigned to the shift
availablePublishers = availablePublishers.filter(pub => {
return shift.assignments.findIndex(assignment => assignment.publisher.id == pub.id) == -1;
});
//subscribed list includes only publishers that are not already assigned to the shift
subscribedPublishers = subscribedPublishers.filter(pub => {
return availablePublishers.findIndex(availablePub => availablePub.id == pub.id) == -1
&& shift.assignments.findIndex(assignment => assignment.publisher.id == pub.id) == -1;
});
//return names and email info only
availablePublishers = availablePublishers.map(pub => {
return {
id: pub.id,
name: pub.firstName + " " + pub.lastName,
email: pub.email
}
});
res.status(200).json({ shift, availablePublishers: availablePublishers, subscribedPublishers });
let data = await dataHelper.getCoverMePublisherEmails(parseInt(req.query.shiftId));
res.status(200).json(data);
break;
default:
@ -492,7 +432,7 @@ export async function getMonthlyStatistics(selectFields, filterDate) {
export async function filterPublishersNew_Available(selectFields, filterDate, isExactTime = false, isForTheMonth = false, isWithStats = true, includeOldAvailabilities = false) {
return data.filterPublishersNew(selectFields, filterDate, isExactTime, isForTheMonth, false, isWithStats, includeOldAvailabilities);
return dataHelper.filterPublishersNew(selectFields, filterDate, isExactTime, isForTheMonth, false, isWithStats, includeOldAvailabilities);
}
// availabilites filter:

View File

@ -230,6 +230,7 @@ async function getAvailabilities(userId) {
async function filterPublishersNew(selectFields, filterDate, isExactTime = false, isForTheMonth = false, noEndDateFilter = false, isWithStats = true, includeOldAvailabilities = false) {
const prisma = common.getPrismaClient();
filterDate = new Date(filterDate); // Convert to date object if not already
// Only attempt to split if selectFields is a string; otherwise, use it as it is.
@ -264,96 +265,6 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false
let filterTimeTo = new Date(filterDate);
let isDayFilter = true;
let whereClause = {};
//if full day, match by date only
// if (!isExactTime) { // Check only by date without considering time ( Assignments on specific days without time)
// whereClause["availabilities"] = {
// some: {
// OR: [
// {
// dayOfMonth: { not: null },
// startTime: { gte: filterDate },
// // endTime: { lte: filterDateEnd },
// }
// ,
// // Check if dayOfMonth is null and match by day of week using the enum (Assigments every week)
// // This includes availabilities from previous assignments but not with preference
// {
// dayOfMonth: null, // includes monthly and weekly repeats
// dayofweek: dayOfWeekEnum,
// // ToDo: and weekOfMonth
// startTime: { lte: filterDate },
// AND: [
// {
// OR: [ // OR condition for repeatUntil to handle events that either end after filterDate or repeat forever
// { endDate: { gte: filterDate } },
// { endDate: null }
// ]
// }
// ]
// }
// ]
// }
// };
// }
// //if not full day, match by date and time
// else {
// //match exact time (should be same as data.findPublisherAvailability())
// whereClause["availabilities"] = {
// some: {
// OR: [
// // Check if dayOfMonth is set and filterDate is between start and end dates (Assignments on specific days AND time)
// {
// // dayOfMonth: filterDate.getDate(),
// startTime: { gte: filterDate },
// // endTime: { lte: filterDate }
// },
// // Check if dayOfMonth is null and match by day of week using the enum (Assigments every week)
// {
// dayOfMonth: null,
// dayofweek: dayOfWeekEnum,
// startTime: { gte: filterDate },
// AND: [
// {
// OR: [ // OR condition for repeatUntil to handle events that either end after filterDate or repeat forever
// { endDate: { gte: filterDate } },
// { endDate: null }
// ]
// }
// ]
// }
// ]
// }
// };
// }
// if (isForTheMonth) {
// // If no filter date, return all publishers's availabilities for currentMonthStart
// whereClause["availabilities"] = {
// some: {
// OR: [
// // Check if dayOfMonth is not null and startTime is after monthInfo.firstMonday (Assignments on specific days AND time)
// {
// dayOfMonth: { not: null },
// startTime: { gte: monthInfo.firstMonday },
// // endTime: { lte: monthInfo.lastSunday }
// },
// // Check if dayOfMonth is null and match by day of week using the enum (Assigments every week)
// {
// dayOfMonth: null,
// AND: [
// {
// OR: [ // OR condition for repeatUntil to handle events that either end after filterDate or repeat forever
// { endDate: { gte: filterDate } },
// { endDate: null }
// ]
// }
// ]
// }
// ]
// }
// };
// }
var monthInfo = common.getMonthDatesInfo(filterDate);
if (isForTheMonth) {
@ -430,7 +341,6 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false
console.log(`getting publishers for date: ${filterDate}, isExactTime: ${isExactTime}, isForTheMonth: ${isForTheMonth}`);
//include availabilities if flag is true
const prisma = common.getPrismaClient(); //why we need to get it again?
let publishers = await prisma.publisher.findMany({
where: whereClause,
select: {
@ -561,6 +471,72 @@ async function filterPublishersNew(selectFields, filterDate, isExactTime = false
}
// exports.getCoverMePublisherEmails = async function (shiftId) {
async function getCoverMePublisherEmails(shiftId) {
const prisma = common.getPrismaClient();
let subscribedPublishers = await prisma.publisher.findMany({
where: {
isSubscribedToCoverMe: true
},
select: {
id: true,
firstName: true,
lastName: true,
email: true
}
}).then(pubs => {
return pubs.map(pub => {
return {
id: pub.id,
name: pub.firstName + " " + pub.lastName,
email: pub.email
}
});
});
let shift = await prisma.shift.findUnique({
where: {
id: shiftId
},
include: {
assignments: {
include: {
publisher: {
select: {
id: true,
firstName: true,
lastName: true,
email: true
}
}
}
}
}
});
let availableIn = new Date(addMinutes(shift.startTime, 0))
let availablePublishers = await filterPublishersNew("id,firstName,lastName,email", availableIn,
true, false, false, false, false);
//filter out publishers that are already assigned to the shift
availablePublishers = availablePublishers.filter(pub => {
return shift.assignments.findIndex(assignment => assignment.publisher.id == pub.id) == -1;
});
//subscribed list includes only publishers that are not already assigned to the shift
subscribedPublishers = subscribedPublishers.filter(pub => {
return availablePublishers.findIndex(availablePub => availablePub.id == pub.id) == -1
&& shift.assignments.findIndex(assignment => assignment.publisher.id == pub.id) == -1;
});
//return names and email info only
availablePublishers = availablePublishers.map(pub => {
return {
id: pub.id,
name: pub.firstName + " " + pub.lastName,
email: pub.email
}
});
return { shift, availablePublishers: availablePublishers, subscribedPublishers };
}
// function matchesAvailability(avail, filterDate) {
// // Setting the start and end time of the filterDate
@ -602,5 +578,6 @@ module.exports = {
findPublisherAvailability,
runSqlFile,
getAvailabilities,
filterPublishersNew
filterPublishersNew,
getCoverMePublisherEmails
};