1
0
Fork 0
polaris-task-force/src/lib/surveys/formBuilderConfig.ts
Z8MB1E 20b65d08fc feat(surveys): add survey system with audience targeting on plugin-form-builder
- forms collection: targeting group (all/users/roles/qualifications), activeFrom/activeUntil window, radio/date field blocks enabled
- form-submissions: server-side user attribution, expiry and audience gates, one attempt per user
- forms/submissions permissions in the Surveys registry group + admin role seed grants
- frontend /surveys list and /surveys/[id] take page with client block renderer
- register the pending role permission enum values migration
2026-09-23 18:17:29 -04:00

285 lines
10 KiB
TypeScript

/**
* Survey system built on top of the Payload Form Builder plugin.
*
* The plugin injects two collections: `forms` (survey definitions, authored in
* the admin panel with the block-based field builder) and `form-submissions`
* (one response per take). The plugin provides the field blocks and submission
* plumbing but no audience targeting, expiry, or attribution, so this module
* augments both collections via the plugin's override API:
*
* - audience targeting group (all / specific users / by role / by qualification)
* - activeFrom / activeUntil availability window
* - server-side attribution: submissions are stamped with the logged-in user
* - server-side gates on create: expiry, audience eligibility, one attempt
* per user per survey
*
* Admin-page visibility follows the repo-wide rule (read + admin:<slug>:manage)
* via requireAdminPageAccess; REST reads fall back to logged-in (forms) or
* staff (form-submissions). Authoring is gated by forms:* permissions.
*
* The frontend renders forms with a client-side block renderer and POSTs to
* /api/form-submissions. Payment and upload fields are disabled; the plugin's
* email step is a silent no-op because no form has emails configured.
*/
import type { Field } from "payload";
import { APIError } from "payload";
import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
import {
hasPermission,
requireAdminPageAccess,
requirePermission,
} from "@/utils/access-control/hasPermission";
type PluginOptions = Parameters<typeof formBuilderPlugin>[0];
const audienceOptions = [
{ label: "All users", value: "all" },
{ label: "Specific users", value: "users" },
{ label: "By role", value: "roles" },
{ label: "By qualification", value: "qualifications" },
];
/** Sibling-first fallback (BankAccounts pattern) for group-nested conditions. */
const whenAudience = (
audience: string,
data: { targeting?: { audience?: string } | null } | undefined,
siblingData: { audience?: string | null } | undefined,
) => (siblingData?.audience ?? data?.targeting?.audience) === audience;
const targetingFields: Field[] = [
{
name: "audience",
type: "select",
required: true,
defaultValue: "all",
options: audienceOptions,
admin: { description: "Who is allowed to see and take this survey?" },
},
{
name: "users",
type: "relationship",
relationTo: "users",
hasMany: true,
admin: { condition: (data, siblingData) => whenAudience("users", data, siblingData) },
},
{
name: "roles",
type: "relationship",
relationTo: "roles",
hasMany: true,
admin: { condition: (data, siblingData) => whenAudience("roles", data, siblingData) },
},
{
name: "qualifications",
type: "relationship",
relationTo: "qualifications",
hasMany: true,
admin: {
condition: (data, siblingData) => whenAudience("qualifications", data, siblingData),
},
},
];
/** Normalize a relationship value (id or hydrated doc) to its id. */
function relationId(value: unknown): number | undefined {
if (typeof value === "number") return value;
if (typeof value === "object" && value !== null && "id" in value) {
return (value as { id: number }).id;
}
return undefined;
}
export function surveyFormBuilderConfig(): PluginOptions {
return {
fields: {
// The plugin's default field map does not register the radio or date
// blocks; enable them explicitly for survey questions.
radio: true,
date: true,
payment: false,
upload: false,
},
formOverrides: {
slug: "forms",
access: {
// REST/API reads: any logged-in user (frontend list + detail pages).
// Admin panel: needs forms:read AND admin:forms:manage.
read: requireAdminPageAccess("forms", ({ req }) => Boolean(req.user)),
create: requirePermission("forms:create"),
update: requirePermission("forms:update"),
delete: requirePermission("forms:delete"),
},
admin: {
group: "Surveys",
useAsTitle: "title",
enableRichTextRelationship: false,
},
fields: ({ defaultFields }) => [
...defaultFields,
{
name: "activeFrom",
type: "date",
label: "Active From",
admin: {
description: "Optional. The survey cannot be taken before this moment.",
},
},
{
name: "activeUntil",
type: "date",
label: "Active Until",
admin: {
description: "Optional. The survey can no longer be taken after this moment.",
},
},
{
name: "targeting",
type: "group",
label: "Targeting",
fields: targetingFields,
},
],
},
formSubmissionOverrides: {
slug: "form-submissions",
access: {
// Any logged-in user may submit; the hooks below enforce eligibility.
create: ({ req }) => Boolean(req.user),
// Responses are sensitive: REST reads need form-submissions:read;
// admin panel additionally needs admin:form-submissions:manage.
read: requireAdminPageAccess("form-submissions", ({ req }) =>
hasPermission(req.payload, req.user, "form-submissions:read"),
),
update: () => false,
delete: requirePermission("form-submissions:delete"),
},
admin: {
group: "Surveys",
defaultColumns: ["form", "user", "createdAt"],
},
fields: ({ defaultFields }) => [
...defaultFields,
{
// Set server-side in beforeChange; hidden everywhere in the UI.
// Not `required` because required validation runs before hooks.
name: "user",
type: "relationship",
relationTo: "users",
admin: { condition: () => false },
},
],
hooks: {
beforeChange: [
// 1. Attribute the submission to the logged-in user.
({ data, req }) => {
if (!data.user && req.user) {
data.user = req.user.id;
}
},
// 2. Expiry gate: the survey must be inside its availability window.
async ({ data, req }) => {
if (!req.user) throw new APIError("You must be logged in.", 403);
const form = await req.payload.findByID({
collection: "forms",
id: data.form as number,
req,
depth: 0,
});
const now = Date.now();
if (form.activeFrom && new Date(form.activeFrom as string).getTime() > now) {
throw new APIError("This survey is not open yet.", 403);
}
if (form.activeUntil && new Date(form.activeUntil as string).getTime() <= now) {
throw new APIError("This survey has closed.", 403);
}
},
// 3. Audience gate: the submitter must match the survey's targeting.
async ({ data, req }) => {
if (!req.user || req.user.collection !== "users") {
throw new APIError("You must be logged in.", 403);
}
const user = req.user;
const form = await req.payload.findByID({
collection: "forms",
id: data.form as number,
req,
depth: 0,
});
const targeting = form.targeting;
const audience = targeting?.audience ?? "all";
if (audience === "all") return;
const ineligible = () => new APIError("You are not eligible for this survey.", 403);
if (audience === "users") {
const ids = (targeting?.users ?? []).map(relationId).filter((v) => v !== undefined);
if (!ids.includes(user.id)) throw ineligible();
return;
}
if (audience === "roles") {
const roleIds = (user.roleDocs ?? []).map(relationId).filter((v) => v !== undefined);
const ids = (targeting?.roles ?? []).map(relationId).filter((v) => v !== undefined);
if (!ids.some((id) => roleIds.includes(id))) throw ineligible();
return;
}
if (audience === "qualifications") {
// Targeting stores Qualifications collection ids; the user's
// qualifications live on their Profile, so resolve names.
const qualIds = (targeting?.qualifications ?? [])
.map(relationId)
.filter((v) => v !== undefined);
if (qualIds.length === 0) throw ineligible();
const qualDocs = await req.payload.find({
collection: "qualifications",
where: { id: { in: qualIds } },
limit: qualIds.length,
depth: 0,
overrideAccess: true,
});
const names = qualDocs.docs.map((q) => q.name.toLowerCase());
const profileRes = await req.payload.find({
collection: "profiles",
where: { user: { equals: user.id } },
limit: 1,
depth: 1,
overrideAccess: true,
});
const held = profileRes.docs[0]?.progression?.qualifications ?? [];
const hasMatch = held.some((q) => {
if (typeof q === "number") return qualIds.includes(q);
if (typeof q === "object" && q !== null && "name" in q) {
return names.includes((q.name as string).toLowerCase());
}
return false;
});
if (!hasMatch) throw ineligible();
}
},
// 4. One attempt per user per survey.
async ({ data, req }) => {
if (!req.user) throw new APIError("You must be logged in.", 403);
const { totalDocs } = await req.payload.count({
collection: "form-submissions",
where: {
and: [{ form: { equals: data.form } }, { user: { equals: req.user.id } }],
},
});
if (totalDocs > 0) {
throw new APIError("You have already submitted this survey.", 409);
}
},
],
},
},
};
}