Feedback page: results, responses, who hasn't answered, reminders (2.1.0)

- Supervisor -> Feedback (supervisors and admins, campus-scoped): every
  event's form with answered of asked, response rate, average rating and
  last reminder; per event the results per question (with the AI summary),
  each response, and on named forms who was asked and who has answered.
- Remind those who haven't answered (or one person on a named form): a
  fresh link, plus the form to anyone eligible who hasn't had it; nobody gets
  the form or a reminder twice within 24 hours. The 3-day job is unchanged.
- Anonymous forms show no names and no list of who has answered.
- FeedbackInvite.reminderCount (migration 20261103120000_feedback_reminders);
  access log action feedback_responses; help page; dashboard and Ctrl+K links.
- Roadmap: the AI helpers on the privacy pages are dropped; 2.1.0 is the
  feedback page.
- Tests: tests/feedbackPage.test.ts, e2e/feedback.spec.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-03 13:03:05 +02:00
co-authored by Claude Opus 5.5
parent c018772ded
commit 9dda0d1851
31 changed files with 2184 additions and 52 deletions
@@ -0,0 +1,170 @@
/**
* 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>;
};
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).
*/
export async function remindFeedback(eventId: string, { userIds }: { userIds?: string[] | null } = {}) {
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 newlyInvited = only ? 0 : await fb.sendFeedbackInvites(form.id);
const reminded = await fb.sendFeedbackReminders(form.id, { userIds: only, minGapMs: fb.REMIND_GAP_MS });
const stillWaiting = await prisma.feedbackInvite.count({ where: { formId: form.id, respondedAt: null, ...(only ? { userId: { in: only } } : {}) } });
const skipped = Math.max(0, stillWaiting - reminded - newlyInvited);
const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
const parts: string[] = [];
if (reminded) parts.push(`Reminded ${plural(reminded, 'person', 'people')}`);
if (newlyInvited) parts.push(`sent the form to ${plural(newlyInvited, 'person', 'people')} for the first time`);
let message = parts.length ? `${parts.join(' and ')}.` : '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 (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, message, title: form.event.title };
}