187 lines
7.1 KiB
TypeScript
187 lines
7.1 KiB
TypeScript
// pages/api/shifts.ts
|
|
|
|
import axiosServer from '../../src/axiosServer';
|
|
import { getToken } from "next-auth/jwt";
|
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
import { Prisma, PrismaClient, DayOfWeek, Publisher, Shift } from "@prisma/client";
|
|
import { levenshteinEditDistance } from "levenshtein-edit-distance";
|
|
import { filterPublishers, /* other functions */ } from './index';
|
|
|
|
import CAL from "../../src/helpers/calendar";
|
|
//const common = require("@common");
|
|
import common from "../../src/helpers/common";
|
|
import { Axios } from 'axios';
|
|
const path = require("path");
|
|
const fs = require("fs");
|
|
|
|
const generateTemplateFile = async (data, templateSrc) => {
|
|
const handlebars = require("handlebars");
|
|
const htmlDocx = require("html-docx-js");
|
|
|
|
// Compile the Handlebars template
|
|
const template = handlebars.compile(templateSrc);
|
|
|
|
// Generate the HTML output using the template and the events data
|
|
const html = template(data);
|
|
return html;
|
|
}
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
console.log(req.url);
|
|
console.log(req.query);
|
|
const prisma = common.getPrismaClient();
|
|
|
|
// If you don't have the NEXTAUTH_SECRET environment variable set,
|
|
// you will have to pass your secret as `secret` to `getToken`
|
|
const axios = await axiosServer({ req: req, res: res });
|
|
const token = await getToken({ req: req });
|
|
if (!token) {
|
|
// If no token or invalid token, return unauthorized status
|
|
return res.status(401).json({ message: "Unauthorized" });
|
|
}
|
|
|
|
|
|
if (req.method === 'GET') {
|
|
const { year, month } = req.query;
|
|
|
|
let monthIndex = parseInt(month as string) - 1;
|
|
const monthInfo = common.getMonthDatesInfo(new Date(year, month, 1));
|
|
let fromDate = monthInfo.firstMonday;
|
|
const toDate = monthInfo.lastSunday;
|
|
|
|
// Ensure fromDate is not in the past
|
|
const today = new Date();
|
|
today.setHours(0, 0, 0, 0); // Set time to midnight for accurate comparison
|
|
|
|
if (fromDate < today) {
|
|
fromDate = today;
|
|
}
|
|
|
|
|
|
try {
|
|
|
|
const shifts = await prisma.shift.findMany({
|
|
where: {
|
|
isactive: true,
|
|
startTime: {
|
|
gte: fromDate,
|
|
lt: toDate,
|
|
},
|
|
},
|
|
include: {
|
|
assignments: {
|
|
where: {},
|
|
include: {
|
|
publisher: true,
|
|
},
|
|
},
|
|
cartEvent: {
|
|
include: {
|
|
location: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
let json = JSON.stringify(shifts);
|
|
const groupedShifts = {};
|
|
const startDate = new Date(shifts[0].startTime);
|
|
const monthName = common.getMonthName(shifts[0].startTime.getMonth());
|
|
let i = 0;
|
|
try {
|
|
for (const shift of shifts) {
|
|
i++;
|
|
const date = new Date(shift.startTime);
|
|
const day = common.getISODateOnly(date)
|
|
const time = common.getTimeRange(shift.startTime, shift.endTime); //common.getLocalTime(date);
|
|
if (!groupedShifts[day]) {
|
|
groupedShifts[day] = {};
|
|
}
|
|
if (!groupedShifts[day][time]) {
|
|
groupedShifts[day][time] = [];
|
|
}
|
|
let shiftSchedule = {
|
|
date: date,
|
|
placeOfEvent: shift.cartEvent.location.name,
|
|
time: time,
|
|
//bold the text after - in the notes
|
|
notes: shift.notes?.substring(0, shift.notes.indexOf("-") + 1),
|
|
notes_bold: shift.notes?.substring(shift.notes.indexOf("-") + 1),
|
|
names: shift.assignments
|
|
.map((assignment) => {
|
|
return (
|
|
assignment.publisher.firstName +
|
|
" " +
|
|
assignment.publisher.lastName
|
|
);
|
|
})
|
|
.join(", "),
|
|
};
|
|
|
|
groupedShifts[day][time].push(shiftSchedule);
|
|
}
|
|
} catch (err) {
|
|
console.log(err + " " + JSON.stringify(shifts[i]));
|
|
}
|
|
|
|
// Create the output object in the format of the second JSON file
|
|
const monthlySchedule = {
|
|
month: monthName,
|
|
year: startDate.getFullYear(),
|
|
events: [],
|
|
};
|
|
|
|
for (const day in groupedShifts) {
|
|
var dayEvent = null;
|
|
|
|
for (const time in groupedShifts[day]) {
|
|
if (dayEvent == null) {
|
|
const shift = groupedShifts[day][time][0];
|
|
if (!shift) {
|
|
console.log("shift is null");
|
|
continue;
|
|
}
|
|
let weekday = common.getDayOfWeekName(shift.date);
|
|
weekday = weekday.charAt(0).toUpperCase() + weekday.slice(1);
|
|
let weekNr = common.getWeekNumber(shift.date);
|
|
console.log("weekday = " + weekday, " weekNr = " + weekNr);
|
|
dayEvent = {
|
|
week: weekNr,
|
|
dayOfWeek: weekday,
|
|
dayOfMonth: shift.date.getDate(),
|
|
placeOfEvent: shift.placeOfEvent,
|
|
shifts: [],
|
|
//transport: shift.notes,
|
|
};
|
|
}
|
|
|
|
dayEvent.shifts.push(...groupedShifts[day][time]);
|
|
}
|
|
|
|
monthlySchedule.events.push(dayEvent);
|
|
}
|
|
|
|
const outputPath = path.join(process.cwd(), 'public', 'content', 'output');
|
|
if (!fs.existsSync(outputPath)) {
|
|
fs.mkdirSync(outputPath, { recursive: true });
|
|
}
|
|
|
|
fs.writeFileSync(path.join(outputPath, `shifts ${year}.${month}.json`), JSON.stringify(monthlySchedule), 'utf8');
|
|
// Load the Handlebars template from a file
|
|
const template = fs.readFileSync("./src/templates/schedule.hbs", "utf8");
|
|
generateTemplateFile(monthlySchedule, template).then((result) => {
|
|
const filename = path.join(outputPath, `schedule ${year}.${month}.html`)
|
|
//fs.writeFileSync(filename, result, "utf8");
|
|
res.end(result);
|
|
}
|
|
);
|
|
}
|
|
catch (error) {
|
|
res.status(500).json({ error: "Internal Server Error" });
|
|
}
|
|
} else {
|
|
res.setHeader('Allow', ['GET']);
|
|
res.status(405).end(`Method ${req.method} Not Allowed`);
|
|
}
|
|
} |