Archived
New report (Reports -> Other, or "Compare" on the Event series page): each event in a series side by side, oldest first - registrations, tickets, income (dashboard definition), people checked in (average per session on multi-session events) and attendance rate, with the change from the event before. Exports like the other reports; campus-scoped staff see only their campuses' events. GET /api/series/:id/compare. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
241 lines
12 KiB
JavaScript
241 lines
12 KiB
JavaScript
/**
|
|
* Event series (1.47.1): separate events grouped on one series page — every year's camp, the
|
|
* monthly men's breakfast. A series isn't tied to a campus, so it can have events at several.
|
|
* Each event page links to the next public event in its series, and people can follow a series:
|
|
* when a new event in it goes live they get one email, sent as News & announcements (so only to
|
|
* people who opted in to news, with an unsubscribe link).
|
|
*/
|
|
|
|
const prisma = require('../config/db');
|
|
const { slugify } = require('./campuses');
|
|
|
|
function seriesError(message, statusCode = 400) {
|
|
const err = new Error(message);
|
|
err.statusCode = statusCode;
|
|
return err;
|
|
}
|
|
|
|
/** Events anyone can see: active, not hidden and live. */
|
|
function publicEventWhere(now = new Date()) {
|
|
return { isActive: true, isHidden: false, goLiveAt: { lte: now } };
|
|
}
|
|
|
|
/** Name, slug, description and picture from a create/update body (`current` on update). */
|
|
function cleanSeriesInput(body = {}, current = null) {
|
|
const data = {};
|
|
if (body.name !== undefined || !current) {
|
|
const name = String(body.name || '').trim();
|
|
if (!name) throw seriesError('Give the series a name');
|
|
if (name.length > 120) throw seriesError('The name is too long');
|
|
data.name = name;
|
|
}
|
|
if (body.slug !== undefined || !current) {
|
|
const slug = slugify(body.slug || data.name || current?.name);
|
|
if (!slug) throw seriesError('The web address needs letters or numbers');
|
|
data.slug = slug;
|
|
}
|
|
if (body.description !== undefined) data.description = String(body.description || '').trim() || null;
|
|
if (body.picture !== undefined) data.picture = String(body.picture || '').trim() || null;
|
|
return data;
|
|
}
|
|
|
|
/** The series to save on an event from a body's `seriesId`: undefined = leave as is, null = none. */
|
|
async function seriesForEvent(seriesId, db = prisma) {
|
|
if (seriesId === undefined) return undefined;
|
|
if (!seriesId) return null;
|
|
const found = await db.eventSeries.findUnique({ where: { id: String(seriesId) }, select: { id: true } });
|
|
if (!found) throw seriesError('That series no longer exists');
|
|
return found.id;
|
|
}
|
|
|
|
const NEXT_SELECT = { id: true, title: true, startDate: true, endDate: true, location: true, redirectUrl: true };
|
|
|
|
/**
|
|
* The next public event in the same series after `event` (starting later, not over yet), or null.
|
|
*/
|
|
async function nextInSeries(event, db = prisma, now = new Date()) {
|
|
if (!event?.seriesId) return null;
|
|
return db.event.findFirst({
|
|
where: { ...publicEventWhere(now), seriesId: event.seriesId, id: { not: event.id }, startDate: { gt: event.startDate }, endDate: { gte: now } },
|
|
orderBy: { startDate: 'asc' },
|
|
select: NEXT_SELECT,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Splits a series' public events into upcoming (not over yet, soonest first) and past (latest
|
|
* first). Pure, for the series page.
|
|
*/
|
|
function splitEvents(events, now = new Date()) {
|
|
const upcoming = events.filter(e => new Date(e.endDate) >= now).sort((a, b) => new Date(a.startDate) - new Date(b.startDate));
|
|
const past = events.filter(e => new Date(e.endDate) < now).sort((a, b) => new Date(b.startDate) - new Date(a.startDate));
|
|
return { upcoming, past };
|
|
}
|
|
|
|
// ─── Following ───────────────────────────────────────────────────────────────
|
|
|
|
async function follow(seriesId, userId) {
|
|
const series = await prisma.eventSeries.findUnique({ where: { id: seriesId }, select: { id: true } });
|
|
if (!series) throw seriesError('Series not found', 404);
|
|
await prisma.seriesFollow.upsert({ where: { seriesId_userId: { seriesId, userId } }, create: { seriesId, userId }, update: {} });
|
|
}
|
|
|
|
async function unfollow(seriesId, userId) {
|
|
await prisma.seriesFollow.deleteMany({ where: { seriesId, userId } });
|
|
}
|
|
|
|
function frontendUrl() {
|
|
return String(process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
|
|
}
|
|
|
|
/**
|
|
* The `series` job: for each event in a series that is now public and hasn't started, email the
|
|
* series' followers once. The event is claimed first (seriesAnnouncedAt), so a slow run or two
|
|
* workers never send twice. An event made public after it started is never announced.
|
|
*/
|
|
async function runAnnounceJob(now = new Date()) {
|
|
const due = await prisma.event.findMany({
|
|
where: { ...publicEventWhere(now), seriesId: { not: null }, seriesAnnouncedAt: null, startDate: { gt: now } },
|
|
select: { id: true, title: true, startDate: true, location: true, redirectUrl: true, series: { select: { id: true, name: true, slug: true } } },
|
|
take: 50,
|
|
});
|
|
let announced = 0;
|
|
let sent = 0;
|
|
let skipped = 0;
|
|
for (const ev of due) {
|
|
const claimed = await prisma.event.updateMany({ where: { id: ev.id, seriesAnnouncedAt: null }, data: { seriesAnnouncedAt: now } });
|
|
if (!claimed.count) continue;
|
|
announced++;
|
|
const follows = await prisma.seriesFollow.findMany({
|
|
where: { seriesId: ev.series.id, user: { isActive: true } },
|
|
select: { user: { select: { id: true, name: true, email: true } } },
|
|
});
|
|
const { filterRecipients, bulkEmailFooter } = require('./privacy');
|
|
const { recipients, skipped: notNews } = await filterRecipients(
|
|
follows.filter(f => f.user.email).map(f => ({ email: f.user.email, name: f.user.name, userId: f.user.id })),
|
|
{ channel: 'email', kind: 'news' },
|
|
);
|
|
skipped += notNews;
|
|
const { sendMail } = require('./email');
|
|
for (const r of recipients) {
|
|
const footer = bulkEmailFooter({ kind: 'news', recipient: r });
|
|
const msg = announcementEmail({ name: r.name, event: ev, series: ev.series });
|
|
try {
|
|
await sendMail({ to: r.email, subject: msg.subject, html: msg.html + footer.html, text: msg.text + footer.text, headers: footer.headers });
|
|
sent++;
|
|
} catch (e) {
|
|
try { console.warn('[series] failed to email', r.email, e?.message || e); } catch {}
|
|
}
|
|
}
|
|
}
|
|
return { announced, sent, skipped };
|
|
}
|
|
|
|
function announcementEmail({ name, event, series }) {
|
|
const { emailWrapper, ctaButton } = require('./email');
|
|
const esc = s => String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
const when = new Date(event.startDate).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
|
|
const url = `${frontendUrl()}/events/${event.id}`;
|
|
const seriesUrl = `${frontendUrl()}/series/${series.slug}`;
|
|
const subject = `New in ${series.name}: ${event.title}`;
|
|
const body = `
|
|
<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 8px 0;letter-spacing:-0.3px">${esc(event.title)}</p>
|
|
<p style="color:#64748b;font-size:14px;margin:0 0 24px 0">New in ${esc(series.name)}</p>
|
|
<p style="margin:0 0 16px 0;color:#374151">Hi <strong>${esc(name || 'there')}</strong>,</p>
|
|
<p style="margin:0 0 16px 0;color:#374151">You follow <strong>${esc(series.name)}</strong>, and the next one is out: <strong>${esc(event.title)}</strong> on ${esc(when)}${event.location ? `, ${esc(event.location)}` : ''}.</p>
|
|
${ctaButton('See the event', url)}
|
|
<p style="margin:16px 0 0 0;font-size:13px;color:#64748b">To stop hearing about this series, unfollow it on <a href="${seriesUrl}" style="color:#64748b">its page</a>.</p>`;
|
|
const text = `Hi ${name || 'there'},\n\nYou follow ${series.name}, and the next one is out: ${event.title} on ${when}${event.location ? `, ${event.location}` : ''}.\n\nSee the event: ${url}\n\nTo stop hearing about this series, unfollow it on its page: ${seriesUrl}`;
|
|
return { subject, text, html: emailWrapper(body, { preheader: subject }) };
|
|
}
|
|
|
|
// ─── Year-on-year comparison (1.47.2) ────────────────────────────────────────
|
|
|
|
// The same "real income" as the dashboard's top events: everything except the legs that apply an
|
|
// earlier donation to an order (not new money). Refunds count, as negatives.
|
|
const EXCLUDE_DONATION_LEGS = {
|
|
NOT: { AND: [{ isDonation: false }, { originalPaymentId: { not: null } }, { amount: { gt: 0 } }] },
|
|
};
|
|
|
|
const pct = (now, before) => (before > 0 ? Math.round(((now - before) / before) * 100) : null);
|
|
|
|
/**
|
|
* Adds `change` to each row against the row before it (rows oldest first): the percentage up or
|
|
* down for registrations, tickets, income and checked in, null when there's nothing to compare.
|
|
* Pure, for tests.
|
|
*/
|
|
function withChanges(rows) {
|
|
return rows.map((r, i) => {
|
|
const prev = rows[i - 1];
|
|
return {
|
|
...r,
|
|
change: prev
|
|
? { registrations: pct(r.registrations, prev.registrations), tickets: pct(r.tickets, prev.tickets), income: pct(r.income, prev.income), checkedIn: pct(r.checkedIn, prev.checkedIn) }
|
|
: null,
|
|
};
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Registrations, tickets, income and attendance for each event in a series that the person may
|
|
* see (`scopeWhere`, from campusScope.eventWhere), oldest first, with the change from the one
|
|
* before. Checked in: check-ins on a single-date event; on a multi-session event, the average per
|
|
* session that wasn't cancelled.
|
|
*/
|
|
async function compareSeries(seriesId, { scopeWhere = {} } = {}, db = prisma) {
|
|
const series = await db.eventSeries.findUnique({ where: { id: seriesId }, select: { id: true, name: true, slug: true } });
|
|
if (!series) throw seriesError('Series not found', 404);
|
|
const events = await db.event.findMany({
|
|
where: { AND: [{ seriesId }, scopeWhere] },
|
|
orderBy: { startDate: 'asc' },
|
|
select: {
|
|
id: true, title: true, startDate: true, endDate: true, scheduleType: true, isActive: true,
|
|
campus: { select: { id: true, name: true, slug: true, colour: true } },
|
|
_count: { select: { sessions: { where: { cancelledAt: null } } } },
|
|
},
|
|
});
|
|
const ids = events.map(e => e.id);
|
|
const [regs, tickets, income, usages] = ids.length ? await Promise.all([
|
|
db.registration.groupBy({ by: ['eventId'], where: { eventId: { in: ids }, status: { not: 'cancelled' } }, _count: { _all: true } }),
|
|
db.ticket.groupBy({ by: ['eventId'], where: { eventId: { in: ids } }, _sum: { quantity: true } }),
|
|
db.payment.groupBy({ by: ['eventId'], where: { ...EXCLUDE_DONATION_LEGS, eventId: { in: ids } }, _sum: { amount: true } }),
|
|
// People checked in (a group scan can let several in at once), per event through the ticket.
|
|
Promise.all(ids.map(async eventId => ({ eventId, n: (await db.ticketUsage.aggregate({ where: { ticket: { eventId } }, _sum: { quantityRedeemed: true } }))._sum.quantityRedeemed || 0 }))),
|
|
]) : [[], [], [], []];
|
|
const map = (rows, pick) => new Map(rows.map(r => [r.eventId, pick(r)]));
|
|
const regBy = map(regs, r => r._count._all);
|
|
const ticketBy = map(tickets, r => r._sum.quantity || 0);
|
|
const incomeBy = map(income, r => r._sum.amount || 0);
|
|
const usageBy = map(usages, r => r.n);
|
|
|
|
const rows = events.map(e => {
|
|
const scans = usageBy.get(e.id) || 0;
|
|
const sessions = e.scheduleType === 'sessions' ? e._count.sessions : 0;
|
|
const t = ticketBy.get(e.id) || 0;
|
|
const checkedIn = sessions > 0 ? Math.round(scans / sessions) : scans;
|
|
return {
|
|
eventId: e.id, title: e.title, startDate: e.startDate, endDate: e.endDate, campus: e.campus, isActive: e.isActive,
|
|
sessions,
|
|
registrations: regBy.get(e.id) || 0,
|
|
tickets: t,
|
|
income: Math.round((incomeBy.get(e.id) || 0) * 100) / 100,
|
|
checkedIn,
|
|
attendanceRate: t > 0 ? Math.min(100, Math.round((checkedIn / t) * 100)) : null,
|
|
};
|
|
});
|
|
return { series, events: withChanges(rows) };
|
|
}
|
|
|
|
// ─── Privacy ─────────────────────────────────────────────────────────────────
|
|
|
|
/** Series someone follows, for "Download my data". */
|
|
async function exportFollows(userId, db = prisma) {
|
|
const rows = await db.seriesFollow.findMany({ where: { userId }, orderBy: { createdAt: 'asc' }, select: { createdAt: true, series: { select: { name: true } } } });
|
|
return rows.map(r => ({ series: r.series.name, since: r.createdAt }));
|
|
}
|
|
|
|
module.exports = {
|
|
publicEventWhere, cleanSeriesInput, seriesForEvent, nextInSeries, splitEvents,
|
|
follow, unfollow, runAnnounceJob, announcementEmail, exportFollows, seriesError, withChanges, compareSeries,
|
|
};
|