Files
mwitnessing/pages/api/email.ts
2024-04-06 11:09:22 +03:00

234 lines
9.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// API endpoint to process email user actions - urls we send in emails to users
import { getToken } from "next-auth/jwt";
import type { NextApiRequest, NextApiResponse } from 'next';
import { createRouter, expressWrapper } from "next-connect";
const common = require('../../src/helpers/common');
const emailHelper = require('../../src/helpers/email');
const { v4: uuidv4 } = require('uuid');
import fs from 'fs';
import path from 'path';
const handlebars = require("handlebars");
const router = createRouter<NextApiRequest, NextApiResponse>();
//action to accept coverme request from email
/**
*
* @param req import { NextApiRequest, NextApiResponse } from 'next'
* @param res import { NextApiRequest, NextApiResponse } from 'next'
*/
export default async function handler(req, res) {
const prisma = common.getPrismaClient();
const action = req.query.action;
const emailaction = req.query.emailaction;
// Retrieve and validate the JWT token
//response is a special action that does not require a token
if (action == "email_response") {
switch (emailaction) {
case "coverMeAccept":
//validate shiftId and assignmentId
let shiftId = req.query.shiftId;
let userId = req.query.userId;
let user = await prisma.publisher.findUnique({
where: {
id: userId
}
});
// Update the user status to accepted
console.log("User: " + user.firstName + " " + user.lastName + " accepted the CoverMe request");
let assignmentPID = req.query.assignmentPID;
if (!shiftId) {
return res.status(400).json({ message: "Shift ID is not provided" });
}
if (!assignmentPID) {
return res.status(400).json({ message: "Assignment PID is not provided" });
}
//check if the assignment request is still open
const assignment = await prisma.assignment.findFirst({
where: {
publicGuid: assignmentPID,
shiftId: parseInt(shiftId),
isConfirmed: false
},
include: {
shift: {
include: {
cartEvent: {
include: {
location: true
}
}
}
}
}
});
if (!assignment) {
const messagePageUrl = `/message?message=${encodeURIComponent('Някой друг вече е отговорил на рази заявка за заместване')}&type=info&caption=${encodeURIComponent('Заявката е вече обработена')}`;
res.redirect(messagePageUrl);
return;
}
emailHelper.SendEmail_NewShifts(user, [assignment.shift]);
// await prisma.user.update({
// where: {
// id: parseInt(userId)
// },
// data: {
// status: "accepted",
// acceptedAt: date
// }
// });
break;
//POST
case "send_report": //we can send report form in the emails to the user. process the POSTED data here
// Send report form to the user
//get from POST data: locationId, date, placementCount, videoCount, returnVisitInfoCount, conversationCount
let locationId = req.body.locationId;
let date = req.body.date;
let placementCount = req.body.placementCount;
let videoCount = req.body.videoCount;
let returnVisitInfoCount = req.body.returnVisitInfoCount;
let conversationCount = req.body.conversationCount;
console.log("User: " + user.email + " sent a report: " +
locationId + " " + date + " " +
placementCount + " " + videoCount + " " +
returnVisitInfoCount + " " + conversationCount);
//save the report in the database
await prisma.report.create({
data: {
userId: parseInt(userId),
locationId: parseInt(locationId),
date: date,
placementCount: parseInt(placementCount),
videoCount: parseInt(videoCount),
returnVisitInfoCount: parseInt(returnVisitInfoCount),
conversationCount: parseInt(conversationCount)
}
});
break;
}
// //send email response to the user
// const emailResponse = await common.sendEmail(user.email, "Email Action Processed",
// "Your email action was processed successfully");
}
else {
const token = await getToken({ req: req });
if (!token) {
// If no token or invalid token, return unauthorized status
return res.status(401).json({ message: "Unauthorized to call this API endpoint" });
}
const user = await prisma.publisher.findUnique({
where: {
email: token.email
}
});
switch (action) {
case "sendCoverMeRequestByEmail":
// Send CoverMe request to the user
//get from POST data: shiftId, assignmentId, date
//let shiftId = req.body.shiftId;
let assignmentId = req.body.assignmentId;
let date = req.body.date;
console.log("User: " + user.email + " sent a 'CoverMe' request for his assignment " + assignmentId + " " + date);
let assignment = await prisma.assignment.findUnique({
where: {
id: parseInt(assignmentId)
},
include: {
shift: {
include: {
cartEvent: {
include: {
location: true
}
}
}
}
}
});
// update the assignment. generate new publicGuid, isConfirmed to false
let newPublicGuid = uuidv4();
await prisma.assignment.update({
where: {
id: parseInt(assignmentId)
},
data: {
publicGuid: newPublicGuid, // if this exists, we consider the request open
isConfirmed: false
}
});
//get all subscribed publisers
const subscribedPublishers = await prisma.publisher.findMany({
where: {
isSubscribedToCoverMe: true
}
});
//send email to all subscribed publishers
for (let i = 0; i < subscribedPublishers.length; i++) {
if (subscribedPublishers[i].id == user.id) {
continue;
}
//send email to subscribed publisher
let acceptUrl = process.env.NEXTAUTH_URL + "/api/email?action=email_response&emailaction=coverMeAccept&userId=" + subscribedPublishers[i].id + "&shiftId=" + assignment.shiftId + "&assignmentPID=" + newPublicGuid;
let model = {
user: user,
shiftId: assignment.shiftId,
acceptUrl: acceptUrl,
prefix: user.isMale ? "Брат" : "Сестра",
firstName: subscribedPublishers[i].firstName,
lastName: subscribedPublishers[i].lastName,
placeName: assignment.shift.cartEvent.location.name,
dateStr: common.getDateFormated(assignment.shift.startTime),
time: common.formatTimeHHmm(assignment.shift.startTime),
sentDate: common.getDateFormated(new Date())
};
let results = emailHelper.SendEmailHandlebars(
{
name: subscribedPublishers[i].firstName + " " + subscribedPublishers[i].lastName,
email: subscribedPublishers[i].email
}, "coverMe", model);
// if (results) {
// console.log("Error sending email: " + error);
// return res.status(500).json({ message: "Error sending email:" + error });
//}
if (results) {
console.log("Email sent to: " + subscribedPublishers[i].email);
}
}
break;
default:
return res.status(400).json({ message: "Invalid action" });
}
return res.status(200).json({ message: "User action processed" });
}
}
router.use(expressWrapper(handler));