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
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "event-management-backend",
"version": "2.0.2",
"version": "2.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "event-management-backend",
"version": "2.0.2",
"version": "2.1.0",
"hasInstallScript": true,
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "event-management-backend",
"version": "2.0.2",
"version": "2.1.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
@@ -0,0 +1,3 @@
-- 2.1.0: how many times each person has been reminded about a feedback form (automatic and by hand).
ALTER TABLE "FeedbackInvite" ADD COLUMN "reminderCount" INTEGER NOT NULL DEFAULT 0;
UPDATE "FeedbackInvite" SET "reminderCount" = 1 WHERE "remindedAt" IS NOT NULL;
+2 -1
View File
@@ -1450,7 +1450,8 @@ model FeedbackInvite {
userId String
tokenHash String @unique
sentAt DateTime @default(now())
remindedAt DateTime?
remindedAt DateTime? // the last reminder (automatic or by hand)
reminderCount Int @default(0)
respondedAt DateTime?
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -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 };
}
@@ -19,6 +19,7 @@ const ACCESS_ACTIONS = {
kids_offline: 'Kids check-in list downloaded for offline use',
volunteer_roster: 'Volunteer roster opened',
ai_feedback: 'Feedback comments summarised by the AI helper',
feedback_responses: 'Feedback answers viewed (named form)',
ai_report: 'Report summarised by the AI helper (anonymised totals)',
};
+24 -6
View File
@@ -183,19 +183,37 @@ async function sendFeedbackInvites(formId) {
return people.length;
}
/** The single reminder: a fresh link for everyone who hasn't answered. */
async function sendFeedbackReminders(formId) {
/** A manual reminder isn't sent to the same person again within this long. */
const REMIND_GAP_MS = 24 * 3600e3;
/**
* A fresh link for everyone who hasn't answered. With no options it's the automatic reminder:
* only people never reminded. `userIds` limits it to those people; `minGapMs` skips anyone
* reminded more recently than that (the manual "Remind" button). Returns how many were sent.
*/
async function sendFeedbackReminders(formId, { userIds = null, minGapMs = null, now = new Date() } = {}) {
const form = await prisma.feedbackForm.findUnique({ where: { id: formId }, include: { event: true } });
if (!form) return 0;
// Manual: not if they were sent the form, or reminded, within minGapMs.
const since = minGapMs == null ? null : new Date(now.getTime() - minGapMs);
const recent = since == null ? { remindedAt: null } : { sentAt: { lt: since }, OR: [{ remindedAt: null }, { remindedAt: { lt: since } }] };
const invites = await prisma.feedbackInvite.findMany({
where: { formId, respondedAt: null, remindedAt: null },
where: { formId, respondedAt: null, ...recent, ...(userIds ? { userId: { in: userIds } } : {}) },
include: { user: { select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true } } },
});
let sent = 0;
for (const inv of invites) {
const token = newToken();
await prisma.feedbackInvite.update({ where: { id: inv.id }, data: { tokenHash: hashToken(token), remindedAt: new Date() } });
// Only if they still haven't answered (they may have while this ran).
const claimed = await prisma.feedbackInvite.updateMany({
where: { id: inv.id, respondedAt: null },
data: { tokenHash: hashToken(token), remindedAt: now, reminderCount: { increment: 1 } },
});
if (claimed.count !== 1) continue;
sent += 1;
await sendFeedbackMessage(inv.user, form.event, token, { reminder: true }).catch(e => console.warn('[feedback] reminder failed:', e?.message || e));
}
return invites.length;
return sent;
}
/** Background job: send forms whose time has come, and reminders 3 days after. */
@@ -224,7 +242,7 @@ async function findInviteByToken(token) {
}
module.exports = {
ANSWERABLE, ALL_TYPES, REMINDER_AFTER_MS, feedbackError, hashToken, feedbackLink,
ANSWERABLE, ALL_TYPES, REMINDER_AFTER_MS, REMIND_GAP_MS, feedbackError, hashToken, feedbackLink,
cleanFields, cleanAnswer, summarise,
feedbackRecipients, sendFeedbackInvites, sendFeedbackReminders, runFeedbackJob, findInviteByToken,
};
+1
View File
@@ -23,6 +23,7 @@ import './resources/adminPrivacy';
import './resources/checkin';
import './resources/auth';
import './resources/ai';
import './resources/feedback';
const pkg = require('../../package.json') as { version: string };
@@ -0,0 +1,85 @@
/**
* The Feedback page (2.1.0): see services/feedback.ts. Supervisors and admins; campus-scoped
* supervisors see their campuses' events. Setting a form up, "Send now" and the summary report
* stay in money.ts.
*/
import { z } from 'zod';
import { defineRoute } from '../route';
import { single } from '../paging';
import { id, idParams } from '../schemas';
import * as feedback from '../../services/feedback';
/* eslint-disable @typescript-eslint/no-explicit-any -- campus scope and the access log are JavaScript */
const cs = require('../../utils/campusScope') as {
scopeEvent(opts?: { need?: 'view' | 'manage' }): any;
scopeList: any;
listWhere(req: unknown, path?: string): Promise<object>;
};
const { logDataAccess } = require('../../utils/accessLog') as { logDataAccess(req: unknown, entry: { action: string; what?: string; eventId?: string; records?: number }): Promise<void> };
const event = z.object({ id, title: z.string(), startDate: z.coerce.date(), endDate: z.coerce.date() });
const status = z.enum(['sent', 'scheduled', 'not_scheduled']).describe('sent, scheduled (a send time is set) or not_scheduled');
const when = z.coerce.date().nullable();
const count = z.object({ label: z.string(), value: z.number().int() });
export const overview = defineRoute({
method: 'get', path: '/feedback', tag: 'Feedback', summary: 'Every event with a feedback form',
description: 'Newest event first, with how many were asked and answered, and the average star rating.',
access: 'supervisor', campusScope: 'scopeList (the handler filters by listWhere)', middleware: [cs.scopeList],
response: single(z.array(z.object({
event, status, sendAt: when, sentAt: when, anonymous: z.boolean(),
invited: z.number().int(), answered: z.number().int(), responseRate: z.number().nullable().describe('%'),
averageRating: z.number().nullable().describe('Every star rating on the form, 1–5'), lastReminderAt: when,
}))),
async handler({ req }) { return { data: await feedback.feedbackOverview(await cs.listWhere(req, 'event')) }; },
});
export const results = defineRoute({
method: 'get', path: '/events/:id/feedback/results', tag: 'Feedback', summary: 'An event\'s feedback: results, responses and who was asked',
description: 'On an anonymous form, responses have no name and `people` is null. Opening a named form\'s answers is recorded in the access log.',
access: 'supervisor', campusScope: 'scopeEvent(view)', middleware: [cs.scopeEvent()], params: idParams,
response: single(z.object({
event,
form: z.object({
status, sendAt: when, sentAt: when, audience: z.enum(['checked_in', 'all']), anonymous: z.boolean(), intro: z.string().nullable(),
autoReminderAt: when.describe('When the automatic reminder goes (3 days after sending)'), autoReminderSent: z.boolean(),
}),
counts: z.object({
invited: z.number().int(), answered: z.number().int(), notAnswered: z.number().int(), responseRate: z.number().nullable(),
canRemind: z.number().int().describe('Not answered, and not sent the form or a reminder in the last 24 hours'),
remindedRecently: z.number().int(),
waiting: z.number().int().describe('Would get the form but haven\'t been sent it yet (e.g. checked in after it went out)'),
}),
averageRating: z.number().nullable(),
questions: z.array(z.object({
fieldId: id, type: z.string(), label: z.string(), answered: z.number().int(),
average: z.number().nullable().optional(), distribution: z.array(count).optional(), counts: z.array(count).optional(),
texts: z.array(z.object({ value: z.string(), name: z.string().optional() })).optional(),
})),
fields: z.array(z.object({ id, type: z.string(), label: z.string() })),
responses: z.array(z.object({ id, createdAt: z.coerce.date(), name: z.string().nullable(), answers: z.record(z.string(), z.string()).describe('Question id → answer') })),
people: z.array(z.object({
userId: id, name: z.string(), email: z.string().nullable(), phoneNumber: z.string().nullable(),
sentAt: z.coerce.date(), remindedAt: when, reminderCount: z.number().int(), respondedAt: when, canRemind: z.boolean(),
})).nullable(),
})),
async handler({ params, req }) {
const data = await feedback.eventFeedback(params.id);
if (!data.form.anonymous && data.responses.length) {
await logDataAccess(req, { action: 'feedback_responses', what: `Feedback answers: ${data.event.title}`, eventId: data.event.id, records: data.responses.length });
}
return { data };
},
});
export const remind = defineRoute({
method: 'post', path: '/events/:id/feedback/remind', tag: 'Feedback', summary: 'Remind people who haven\'t answered',
description: 'A fresh link to everyone who hasn\'t answered, or to `userIds` (named forms only). Nobody is sent the form or a reminder twice within 24 hours. Without `userIds` it also sends the form to anyone who has become eligible since it went out.',
access: 'supervisor', campusScope: 'scopeEvent(manage)', middleware: [cs.scopeEvent({ need: 'manage' })], params: idParams,
body: z.object({ userIds: z.array(id).max(1000).nullish().describe('Only these people (named forms)') }),
response: single(z.object({ reminded: z.number().int(), newlyInvited: z.number().int(), skipped: z.number().int(), message: z.string() })),
async handler({ params, body }) {
const { title: _title, ...data } = await feedback.remindFeedback(params.id, { userIds: body.userIds });
return { data };
},
});
@@ -0,0 +1,182 @@
/**
* 2.1.0: the Feedback page (services/feedback.ts) — results per event, anonymous forms that stay
* anonymous, and "Remind" with its 24-hour rule (utils/feedback.js sendFeedbackReminders).
*/
const mockDb: any = {
feedbackForm: { findUnique: jest.fn(), findMany: jest.fn() },
feedbackInvite: { findMany: jest.fn(), updateMany: jest.fn(), count: jest.fn(), create: jest.fn(), groupBy: jest.fn() },
feedbackAnswer: { findMany: jest.fn() },
ticket: { findMany: jest.fn() },
registration: { findMany: jest.fn() },
user: { findMany: jest.fn() },
};
jest.mock('../src/config/db', () => mockDb);
const mockMail = jest.fn(async () => undefined);
jest.mock('../src/utils/email', () => ({ sendMail: (...a: unknown[]) => (mockMail as jest.Mock)(...a), emailWrapper: (h: string) => h, ctaButton: () => '', fallbackLink: () => '' }));
jest.mock('../src/utils/notify', () => ({ waTextAny: jest.fn(async () => undefined) }));
jest.mock('../src/utils/whatsapp', () => ({ isValidZAPhone: () => false }));
import * as feedback from '../src/services/feedback';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { sendFeedbackReminders } = require('../src/utils/feedback');
const NOW = new Date('2026-11-10T12:00:00Z');
const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3600e3);
const EVENT = { id: 'ev1', title: 'Men\'s Breakfast', startDate: new Date('2026-11-01T07:00:00Z'), endDate: new Date('2026-11-01T10:00:00Z') };
const FIELDS = [
{ id: 'f1', type: 'rating', label: 'Overall', options: null },
{ id: 'f2', type: 'text', label: 'What could be better?', options: null },
{ id: 'f0', type: 'statement', label: 'Thanks for coming', options: null },
];
const person = (id: string, name: string) => ({ id, name, email: `${id}@example.com`, phoneNumber: null });
function form(extra: object = {}) {
return {
id: 'form1', eventId: 'ev1', event: EVENT, anonymous: false, audience: 'checked_in', intro: null,
sendAt: hoursAgo(72), sentAt: hoursAgo(72), reminderSentAt: null, fields: FIELDS,
responses: [
{ id: 'r1', createdAt: hoursAgo(60), user: { name: 'Anna' }, answers: [{ fieldId: 'f1', value: '5' }, { fieldId: 'f2', value: 'Longer coffee break' }] },
{ id: 'r2', createdAt: hoursAgo(50), user: { name: 'Ben' }, answers: [{ fieldId: 'f1', value: '4' }] },
],
invites: [
{ userId: 'u1', user: person('u1', 'Anna'), sentAt: hoursAgo(72), remindedAt: null, reminderCount: 0, respondedAt: hoursAgo(60) },
{ userId: 'u2', user: person('u2', 'Ben'), sentAt: hoursAgo(72), remindedAt: null, reminderCount: 0, respondedAt: hoursAgo(50) },
{ userId: 'u3', user: person('u3', 'Cara'), sentAt: hoursAgo(72), remindedAt: hoursAgo(2), reminderCount: 1, respondedAt: null },
{ userId: 'u4', user: person('u4', 'Dumi'), sentAt: hoursAgo(72), remindedAt: null, reminderCount: 0, respondedAt: null },
{ userId: 'u5', user: person('u5', 'Eve'), sentAt: hoursAgo(1), remindedAt: null, reminderCount: 0, respondedAt: null },
],
...extra,
};
}
beforeEach(() => {
jest.clearAllMocks();
mockDb.ticket.findMany.mockResolvedValue([]);
mockDb.registration.findMany.mockResolvedValue([]);
mockDb.user.findMany.mockResolvedValue([]);
mockDb.feedbackInvite.updateMany.mockResolvedValue({ count: 1 });
});
describe('averageRating', () => {
test('averages every valid star rating, to one decimal', () => {
expect(feedback.averageRating(['5', '4', '4'])).toBe(4.3);
expect(feedback.averageRating(['x', '9', '0'])).toBeNull();
expect(feedback.averageRating([])).toBeNull();
});
});
describe('one event\'s feedback', () => {
test('a named form: names on answers, everyone asked, not answered first', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form());
const data = await feedback.eventFeedback('ev1', NOW);
expect(data.counts).toMatchObject({ invited: 5, answered: 2, notAnswered: 3, responseRate: 40 });
expect(data.averageRating).toBe(4.5);
expect(data.fields.map((f: any) => f.id)).toEqual(['f1', 'f2']); // statements aren't questions
expect(data.responses[0]).toMatchObject({ name: 'Anna', answers: { f1: '5', f2: 'Longer coffee break' } });
expect(data.people!.map((p: any) => p.name)).toEqual(['Cara', 'Dumi', 'Eve', 'Anna', 'Ben']);
});
test('nobody is remindable within 24 hours of the form or a reminder', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form());
const data = await feedback.eventFeedback('ev1', NOW);
const can = Object.fromEntries(data.people!.map((p: any) => [p.name, p.canRemind]));
expect(can).toEqual({ Cara: false, Dumi: true, Eve: false, Anna: false, Ben: false });
expect(data.counts).toMatchObject({ canRemind: 1, remindedRecently: 2 });
});
test('an anonymous form: no names anywhere, and no list of who has answered', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form({ anonymous: true }));
const data = await feedback.eventFeedback('ev1', NOW);
expect(data.people).toBeNull();
expect(data.responses.every((r: any) => r.name === null)).toBe(true);
expect(JSON.stringify(data)).not.toMatch(/Anna|Ben|Cara|u1@example/);
expect(data.counts.notAnswered).toBe(3);
});
test('an event without a form is a 404', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(null);
await expect(feedback.eventFeedback('ev1', NOW)).rejects.toMatchObject({ statusCode: 404 });
});
});
describe('Remind', () => {
test('not before the form has gone out', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form({ sentAt: null }));
await expect(feedback.remindFeedback('ev1')).rejects.toMatchObject({ statusCode: 409 });
});
test('not one by one on an anonymous form', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form({ anonymous: true }));
await expect(feedback.remindFeedback('ev1', { userIds: ['u4'] })).rejects.toMatchObject({ statusCode: 400 });
});
test('reminds those not reminded or sent the form in the last 24 hours, and says who was skipped', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue({ ...form(), invites: [{ userId: 'u3' }, { userId: 'u4' }, { userId: 'u5' }] });
mockDb.feedbackInvite.findMany.mockResolvedValue([{ id: 'i4', userId: 'u4', user: person('u4', 'Dumi') }]);
mockDb.feedbackInvite.count.mockResolvedValue(3);
const out = await feedback.remindFeedback('ev1');
expect(out).toMatchObject({ reminded: 1, newlyInvited: 0, skipped: 2 });
expect(out.message).toBe('Reminded 1 person. 2 people were sent the form or a reminder in the last 24 hours, so not again yet.');
const where = mockDb.feedbackInvite.findMany.mock.calls[0][0].where;
expect(where).toMatchObject({ formId: 'form1', respondedAt: null });
expect(where.sentAt.lt).toBeInstanceOf(Date);
expect(where.OR).toHaveLength(2);
expect(mockDb.feedbackInvite.updateMany.mock.calls[0][0].data.reminderCount).toEqual({ increment: 1 });
expect(mockMail).toHaveBeenCalledWith(expect.objectContaining({ to: 'u4@example.com', subject: 'Reminder: How was Men\'s Breakfast?' }));
});
test('one person on a named form', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form());
mockDb.feedbackInvite.findMany.mockResolvedValue([{ id: 'i4', userId: 'u4', user: person('u4', 'Dumi') }]);
mockDb.feedbackInvite.count.mockResolvedValue(1);
const out = await feedback.remindFeedback('ev1', { userIds: ['u4'] });
expect(out.message).toBe('Reminded 1 person.');
expect(mockDb.feedbackInvite.findMany.mock.calls[0][0].where.userId).toEqual({ in: ['u4'] });
expect(mockDb.feedbackInvite.create).not.toHaveBeenCalled(); // no new invites when reminding one person
});
test('everyone already reminded today', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue({ ...form(), invites: [] });
mockDb.feedbackInvite.findMany.mockResolvedValue([]);
mockDb.feedbackInvite.count.mockResolvedValue(2);
const out = await feedback.remindFeedback('ev1');
expect(out.message).toBe('Everyone who hasn\'t answered was sent the form or a reminder in the last 24 hours. Try again tomorrow.');
});
test('someone who answers while reminders go out isn\'t reminded', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue({ ...form(), invites: [] });
mockDb.feedbackInvite.findMany.mockResolvedValue([{ id: 'i4', userId: 'u4', user: person('u4', 'Dumi') }]);
mockDb.feedbackInvite.updateMany.mockResolvedValue({ count: 0 });
mockDb.feedbackInvite.count.mockResolvedValue(0);
expect((await feedback.remindFeedback('ev1')).reminded).toBe(0);
expect(mockMail).not.toHaveBeenCalled();
});
});
describe('the automatic reminder', () => {
test('still goes only to people never reminded, and counts it', async () => {
mockDb.feedbackForm.findUnique.mockResolvedValue(form());
mockDb.feedbackInvite.findMany.mockResolvedValue([{ id: 'i4', userId: 'u4', user: person('u4', 'Dumi') }]);
expect(await sendFeedbackReminders('form1')).toBe(1);
expect(mockDb.feedbackInvite.findMany.mock.calls[0][0].where).toEqual({ formId: 'form1', respondedAt: null, remindedAt: null });
expect(mockDb.feedbackInvite.updateMany.mock.calls[0][0].data.reminderCount).toEqual({ increment: 1 });
});
});
describe('overview', () => {
test('newest event first, with status, response rate, average rating and last reminder', async () => {
const older = { ...EVENT, id: 'ev0', title: 'Camp', startDate: new Date('2026-06-01T00:00:00Z') };
mockDb.feedbackForm.findMany.mockResolvedValue([
{ id: 'form0', event: older, sendAt: null, sentAt: null, anonymous: true, _count: { invites: 0, responses: 0 } },
{ id: 'form1', event: EVENT, sendAt: hoursAgo(72), sentAt: hoursAgo(72), anonymous: false, _count: { invites: 4, responses: 3 } },
]);
mockDb.feedbackAnswer.findMany.mockResolvedValue([{ value: '5', field: { formId: 'form1' } }, { value: '3', field: { formId: 'form1' } }]);
mockDb.feedbackInvite.groupBy.mockResolvedValue([{ formId: 'form1', _max: { remindedAt: hoursAgo(5) } }]);
const rows = await feedback.feedbackOverview({});
expect(rows.map((r: any) => [r.event.title, r.status, r.responseRate, r.averageRating])).toEqual([
['Men\'s Breakfast', 'sent', 75, 4],
['Camp', 'not_scheduled', null, null],
]);
expect(rows[0].lastReminderAt).toEqual(hoursAgo(5));
});
});