Archived
- Send now and Remind answer straight away with who they're going to and queue the feedback-send task; the Feedback page refreshes to show progress. - One-off background tasks (enqueueTask in src/jobs/index.js): pg-boss with retries, or in-process after the response when the queue is off. - Reminders are claimed with the 24-hour rule, so two tasks at once never remind the same person twice. - Tests: tests/tasks.test.js, tests/feedbackPage.test.ts, e2e/feedback.spec.ts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
183 lines
9.9 KiB
TypeScript
183 lines
9.9 KiB
TypeScript
/**
|
|
* The Feedback page (2.1.0): what supervisors and admins see of post-event feedback, and the
|
|
* "Remind" button. Forms, sending and the automatic reminder are in utils/feedback.js.
|
|
*
|
|
* Anonymous forms stay anonymous here: no names on answers, and no list of who has or hasn't
|
|
* answered (on a small event that would give the answers away) — only counts.
|
|
*/
|
|
import { prisma as typedPrisma } from '../v2/legacy';
|
|
import { fail } from './errors';
|
|
|
|
/* eslint-disable @typescript-eslint/no-explicit-any -- the records are Prisma's with includes */
|
|
const prisma = typedPrisma as any;
|
|
const fb = require('../utils/feedback') as {
|
|
ANSWERABLE: string[];
|
|
REMINDER_AFTER_MS: number;
|
|
REMIND_GAP_MS: number;
|
|
summarise(fields: any[], answers: any[]): any[];
|
|
feedbackRecipients(form: any): Promise<{ id: string }[]>;
|
|
sendFeedbackInvites(formId: string): Promise<number>;
|
|
sendFeedbackReminders(formId: string, opts?: { userIds?: string[] | null; minGapMs?: number | null; now?: Date }): Promise<number>;
|
|
};
|
|
const jobs = require('../jobs') as { enqueueTask(name: string, data: object): Promise<{ queued: boolean }> };
|
|
|
|
export type FormStatus = 'sent' | 'scheduled' | 'not_scheduled';
|
|
const statusOf = (form: { sentAt: Date | null; sendAt: Date | null }): FormStatus => (form.sentAt ? 'sent' : form.sendAt ? 'scheduled' : 'not_scheduled');
|
|
const rate = (answered: number, invited: number) => (invited ? Math.round((answered / invited) * 100) : null);
|
|
const round1 = (n: number) => Math.round(n * 10) / 10;
|
|
|
|
/** Average of every star rating on a form (all rating questions together), or null. Pure. */
|
|
export function averageRating(values: string[]): number | null {
|
|
const nums = values.map(Number).filter(n => Number.isInteger(n) && n >= 1 && n <= 5);
|
|
return nums.length ? round1(nums.reduce((s, n) => s + n, 0) / nums.length) : null;
|
|
}
|
|
|
|
/** Every event with a feedback form, newest event first. `where` is the campus scope (listWhere). */
|
|
export async function feedbackOverview(where: object = {}) {
|
|
const forms = await prisma.feedbackForm.findMany({
|
|
where,
|
|
include: {
|
|
event: { select: { id: true, title: true, startDate: true, endDate: true } },
|
|
_count: { select: { invites: true, responses: true } },
|
|
},
|
|
});
|
|
if (!forms.length) return [];
|
|
const ids = forms.map((f: any) => f.id);
|
|
const [ratings, reminders] = await Promise.all([
|
|
prisma.feedbackAnswer.findMany({ where: { field: { formId: { in: ids }, type: 'rating' } }, select: { value: true, field: { select: { formId: true } } } }),
|
|
prisma.feedbackInvite.groupBy({ by: ['formId'], where: { formId: { in: ids } }, _max: { remindedAt: true } }),
|
|
]);
|
|
const ratingsBy = new Map<string, string[]>();
|
|
for (const r of ratings) ratingsBy.set(r.field.formId, [...(ratingsBy.get(r.field.formId) || []), r.value]);
|
|
const remindedBy = new Map(reminders.map((r: any) => [r.formId, r._max.remindedAt]));
|
|
return forms
|
|
.map((f: any) => ({
|
|
event: f.event,
|
|
status: statusOf(f),
|
|
sendAt: f.sendAt,
|
|
sentAt: f.sentAt,
|
|
anonymous: f.anonymous,
|
|
invited: f._count.invites,
|
|
answered: f._count.responses,
|
|
responseRate: rate(f._count.responses, f._count.invites),
|
|
averageRating: averageRating(ratingsBy.get(f.id) || []),
|
|
lastReminderAt: remindedBy.get(f.id) || null,
|
|
}))
|
|
.sort((a: any, b: any) => new Date(b.event.startDate).getTime() - new Date(a.event.startDate).getTime());
|
|
}
|
|
|
|
async function formFor(eventId: string, include: object = {}) {
|
|
const form = await prisma.feedbackForm.findUnique({ where: { eventId }, include: { event: { select: { id: true, title: true, startDate: true, endDate: true } }, ...include } });
|
|
if (!form) fail(404, 'This event has no feedback form.', 'NO_FEEDBACK_FORM');
|
|
return form;
|
|
}
|
|
|
|
/** People who would get the form but haven't been sent it (not sent yet, or checked in later). */
|
|
async function waitingCount(form: any, invitedIds: Set<string>) {
|
|
return (await fb.feedbackRecipients(form)).filter(u => !invitedIds.has(u.id)).length;
|
|
}
|
|
|
|
/** One event's feedback: results per question, each response, and (named forms) who was asked. */
|
|
export async function eventFeedback(eventId: string, now = new Date()) {
|
|
const form = await formFor(eventId, {
|
|
fields: { orderBy: { order: 'asc' } },
|
|
responses: { orderBy: { createdAt: 'desc' }, include: { answers: true, user: { select: { name: true } } } },
|
|
invites: { include: { user: { select: { id: true, name: true, email: true, phoneNumber: true } } } },
|
|
});
|
|
const named = !form.anonymous;
|
|
const fields = form.fields.filter((f: any) => fb.ANSWERABLE.includes(f.type));
|
|
const answers = form.responses.flatMap((r: any) => r.answers.map((a: any) => ({ fieldId: a.fieldId, value: a.value, ...(named ? { name: r.user?.name || '' } : {}) })));
|
|
const invited = form.invites.length;
|
|
const answered = form.responses.length;
|
|
const gapFrom = now.getTime() - fb.REMIND_GAP_MS;
|
|
const notAnswered = form.invites.filter((i: any) => !i.respondedAt);
|
|
// Not sent the form or a reminder in the last 24 hours (as remindFeedback).
|
|
const remindable = (i: any) => !i.respondedAt && new Date(i.sentAt).getTime() < gapFrom && (!i.remindedAt || new Date(i.remindedAt).getTime() < gapFrom);
|
|
const canRemind = notAnswered.filter(remindable).length;
|
|
const waiting = await waitingCount(form, new Set(form.invites.map((i: any) => i.userId)));
|
|
const autoReminderAt = form.sentAt ? new Date(new Date(form.sentAt).getTime() + fb.REMINDER_AFTER_MS) : null;
|
|
|
|
return {
|
|
event: form.event,
|
|
form: {
|
|
status: statusOf(form),
|
|
sendAt: form.sendAt,
|
|
sentAt: form.sentAt,
|
|
audience: (form.audience === 'all' ? 'all' : 'checked_in') as 'all' | 'checked_in',
|
|
anonymous: form.anonymous,
|
|
intro: form.intro,
|
|
autoReminderAt,
|
|
autoReminderSent: !!form.reminderSentAt,
|
|
},
|
|
counts: {
|
|
invited,
|
|
answered,
|
|
notAnswered: notAnswered.length,
|
|
responseRate: rate(answered, invited),
|
|
canRemind,
|
|
remindedRecently: notAnswered.length - canRemind,
|
|
waiting,
|
|
},
|
|
averageRating: averageRating(answers.filter((a: any) => fields.some((f: any) => f.id === a.fieldId && f.type === 'rating')).map((a: any) => a.value)),
|
|
questions: fb.summarise(fields, answers),
|
|
fields: fields.map((f: any) => ({ id: f.id, type: f.type, label: f.label })),
|
|
responses: form.responses.map((r: any) => ({
|
|
id: r.id,
|
|
createdAt: r.createdAt,
|
|
name: named ? r.user?.name || 'Someone who has since been removed' : null,
|
|
answers: Object.fromEntries(r.answers.map((a: any) => [a.fieldId, a.value])),
|
|
})),
|
|
people: named
|
|
? form.invites
|
|
.map((i: any) => ({
|
|
userId: i.userId,
|
|
name: i.user?.name || '',
|
|
email: i.user?.email && !/@(guest\.local|deleted\.invalid)$/.test(i.user.email) ? i.user.email : null,
|
|
phoneNumber: i.user?.phoneNumber || null,
|
|
sentAt: i.sentAt,
|
|
remindedAt: i.remindedAt,
|
|
reminderCount: i.reminderCount,
|
|
respondedAt: i.respondedAt,
|
|
canRemind: remindable(i),
|
|
}))
|
|
.sort((a: any, b: any) => Number(!!a.respondedAt) - Number(!!b.respondedAt) || a.name.localeCompare(b.name))
|
|
: null,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* "Remind": a fresh link to everyone who hasn't answered (or the people in `userIds`, named
|
|
* forms only), skipping anyone sent the form or a reminder in the last 24 hours. Without `userIds` it also sends
|
|
* the form to people who became eligible after it went out (e.g. checked in later).
|
|
*
|
|
* 2.1.1: the emails go out in the background (jobs task `feedback-send`); this works out who
|
|
* they'll go to and answers straight away. The counts are what's being sent, not what was.
|
|
*/
|
|
export async function remindFeedback(eventId: string, { userIds }: { userIds?: string[] | null } = {}, now = new Date()) {
|
|
const form = await formFor(eventId);
|
|
if (!form.sentAt) fail(409, 'The feedback form hasn\'t gone out yet. Use "Send now" to send it.', 'FEEDBACK_NOT_SENT');
|
|
const only = userIds && userIds.length ? [...new Set(userIds)] : null;
|
|
if (only && form.anonymous) fail(400, 'This form is anonymous, so people can\'t be reminded one by one. Remind everyone who hasn\'t answered instead.', 'FEEDBACK_ANONYMOUS');
|
|
const since = new Date(now.getTime() - fb.REMIND_GAP_MS);
|
|
const mine = { formId: form.id, respondedAt: null, ...(only ? { userId: { in: only } } : {}) };
|
|
const [notAnswered, reminded, invitedIds] = await Promise.all([
|
|
prisma.feedbackInvite.count({ where: mine }),
|
|
// The same rule as sendFeedbackReminders with minGapMs.
|
|
prisma.feedbackInvite.count({ where: { ...mine, sentAt: { lt: since }, OR: [{ remindedAt: null }, { remindedAt: { lt: since } }] } }),
|
|
only ? Promise.resolve(null) : prisma.feedbackInvite.findMany({ where: { formId: form.id }, select: { userId: true } }),
|
|
]);
|
|
const newlyInvited = invitedIds ? await waitingCount(form, new Set(invitedIds.map((i: any) => i.userId))) : 0;
|
|
const skipped = Math.max(0, notAnswered - reminded);
|
|
if (reminded || newlyInvited) await jobs.enqueueTask('feedback-send', { formId: form.id, kind: 'remind', userIds: only });
|
|
|
|
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
|
|
const parts: string[] = [];
|
|
if (reminded) parts.push(`Reminding ${plural(reminded, 'person', 'people')}`);
|
|
if (newlyInvited) parts.push(`sending the form to ${plural(newlyInvited, 'person', 'people')} for the first time`);
|
|
let message = parts.length ? `${parts.join(' and ')}. It carries on in the background.` : 'Nobody to remind.';
|
|
if (!parts.length && skipped) message = 'Everyone who hasn\'t answered was sent the form or a reminder in the last 24 hours. Try again tomorrow.';
|
|
else if (parts.length && skipped) message += ` ${plural(skipped, 'person was', 'people were')} sent the form or a reminder in the last 24 hours, so not again yet.`;
|
|
message = message.charAt(0).toUpperCase() + message.slice(1);
|
|
return { reminded, newlyInvited, skipped, queued: !!(reminded || newlyInvited), message, title: form.event.title };
|
|
}
|