53 lines
1.8 KiB
JavaScript
53 lines
1.8 KiB
JavaScript
const { addJob } = require('../utils/scheduledEmails');
|
|
const { v4: uuidv4 } = require('uuid');
|
|
|
|
// @desc Schedule multiple automation emails for an event
|
|
// @route POST /api/automations/schedule
|
|
// @access Private/Supervisor or Admin
|
|
async function scheduleAutomations(req, res) {
|
|
try {
|
|
const { eventId, jobs } = req.body || {};
|
|
if (!eventId || typeof eventId !== 'string') {
|
|
return res.status(400).json({ message: 'eventId is required' });
|
|
}
|
|
if (!Array.isArray(jobs) || jobs.length === 0) {
|
|
return res.status(400).json({ message: 'jobs must be a non-empty array' });
|
|
}
|
|
|
|
const created = [];
|
|
for (const j of jobs) {
|
|
if (!j || !j.scheduledAt || !j.subject || !(j.html || j.text)) continue;
|
|
const when = new Date(j.scheduledAt);
|
|
if (isNaN(when.getTime())) continue;
|
|
const payload = {
|
|
subject: String(j.subject),
|
|
html: j.html ? String(j.html) : undefined,
|
|
text: (!j.html && j.text) ? String(j.text) : (j.text ? String(j.text) : undefined),
|
|
template: 'custom',
|
|
filter: { status: undefined, attendeeIds: undefined },
|
|
};
|
|
if (j.promoEventId && typeof j.promoEventId === 'string') {
|
|
payload.promoEventId = j.promoEventId;
|
|
}
|
|
const rec = addJob({
|
|
id: uuidv4(),
|
|
eventId,
|
|
createdById: req.user?.id || null,
|
|
scheduledAt: when.toISOString(),
|
|
payload,
|
|
});
|
|
created.push(rec);
|
|
}
|
|
|
|
if (created.length === 0) {
|
|
return res.status(400).json({ message: 'No valid jobs to schedule' });
|
|
}
|
|
|
|
return res.status(201).json({ message: `Scheduled ${created.length} automation job(s)`, jobs: created });
|
|
} catch (error) {
|
|
return res.status(400).json({ message: error?.message || String(error) });
|
|
}
|
|
}
|
|
|
|
module.exports = { scheduleAutomations };
|