Repository navigation
feat(email): render an authored form's answers in the contact email - #834
Conversation
Delivery built the whole email body from one key. `deliverContact` read `readSubmissionValue(submissionData, 'message')`, so every answer to an authored question reached the `user-submissions` row and stopped there. An operator who named their textarea anything else — or added a select, a checkbox, a second text field — got an email with an empty body while the sender was shown a thank-you screen. Nothing on either side pinned the name `message`, and the form builder lets an author call a field anything. sydevs/SahajAtlasWeb#219 removed its own `reportMessage` workaround on the reviewer's instruction, so that is the live failure this closes. The email now renders the named form's own blocks. There is no `Message` section any more — the answers are the body, each a sibling row in the shape `EventRegistrationEmail` already uses for forwarded answers. `buildFormAnswers` walks `form.fields` in authoring order. Three block types store something other than what a reader should see, and each was read off `src/payload-types.ts` rather than assumed: - a `select` stores the chosen option's `value`, which is operator-authored and may be a slug, so the option's `label` is resolved, falling back to the raw value for an option deleted since; - a `checkbox` arrives as the string `'true'`/`'false'`, never a boolean, because `checkSubmissionData` refuses a non-string value — so `formatAnswer`'s boolean branch could never have fired. `parseOptIn` already knows the four spellings. `No` renders rather than dropping: the widget sends `'false'` deliberately, and an unticked consent box is an answer; - a `message` *block* carries no `name` at all, so no stored pair can match it. A field *named* `message` is an ordinary question. One form read, widened rather than doubled: `recipientFor` became `formDelivery` and selects `fields` beside `recipient`, keeping both existing properties — no `req`, so a nested read cannot take the caller's transaction down with it, and `disableErrors` so a deleted manager does not strand the message. That read now chooses a locale, because the forms plugin localizes `label` and a select option's `label` (`forms_blocks_*_locales` carry them — nothing in this repo declares it). It passes the submission's own locale, so the manager reads the question as the visitor was asked it and the resolved option label means what the visitor clicked. Gated through `isValidLocale`: the pair is submitter-chosen text, exempt from the URL scan, and it reaches the database layer as a query parameter. `UserMessageEmail` loses a prop rather than gaining one — `message` is gone, `answers` replaces it, and `previewText` slices the first answer, which is why a submission carrying no `message` key now has a preview line at all. Where the form no longer resolves, `deliverContact` synthesizes one `Message` row rather than making the template branch on which body it got. That covers only a form deleted after the row was written: a `contact` row is required to name one, and the other three types never reach this file. Answers reach a renderer for the first time, which `URL_EXEMPT_KEYS`' docblock anticipated. A client write is URL-scanned at intake; a manager-written row is not. Every value renders as an escaped React child and never inside a `<Link>`, asserted rather than left as a note. Each new assertion was watched failing against the defect at its own site: forcing the one-key fallback reds both delivery cases, dropping `locale` from the read reds the localized one alone, and disabling the select, checkbox and preview paths reds four unit cases. Refs #832 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01L5xHNXdaF3Wk1tiVXnDKSR
A submission carries the client's own context — `locale`, `path`, `hostUrl`, `userAgent`, `error` — in the same flat `submissionData` pairs as the answers, and sydevs/SahajAtlasWeb#219 appends it after them. So a field sharing one of those names has the visitor's typed answer silently replaced by the widget's value, and the form's author is the only person who could notice. Refused when the form is saved, not at intake. Same argument as the missing-field rules beside it: a form that collects an answer it then overwrites fails one visitor at a time with the author never present, and the save is the one moment they are. ⚠ The reserved set is deliberately not `BASE_SUBMISSION_KEYS`. Reserving all six would brick the form this work exists for — the production Contact Form authors both `name` and `message`, and both are legitimate: an authored `name` feeds `upsertUserByEmail` and an authored `subject` feeds `composeSubject`. Those are the intake *reading* an answer, not overwriting one. Only the five the client writes for itself are collisions with a loser. Those five were already enumerated as `URL_EXEMPT_KEYS`, so `CLIENT_CONTEXT_KEYS` names the set once and the exemption derives from it rather than keeping a second copy that can drift. The check sits inside the hook's existing "only judge a changed save" guard. Without that, an existing form carrying a colliding name would become unsaveable in the admin for good — the exact failure that guard was written for. Deleting the check reds the five refusals. Widening the set to all of `BASE_SUBMISSION_KEYS` reds eight cases, the three names that must keep saving among them — so the narrowing is covered in both directions. Refs #832 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01L5xHNXdaF3Wk1tiVXnDKSR
From the review pass. Three real defects and two placement corrections. **The inbox preview line was the sender's own address.** `previewText` took `answers[0]`, and a form's first block is almost always its Email field — so every report previewed as `[email protected]`, which is already the `Reply-To` and already two lines into the body. Position was the wrong question; length is what separates the prose from a select or a checkbox. The spec now names the preview element and asserts the email is *not* in it, so a positional choice cannot pass it again. **`CLIENT_CONTEXT_KEYS` was a cross-collection internal import.** `Forms` reached into `UserSubmissions/submissionData.ts`, which `src/AGENTS.md` rule 4 prohibits outright — and `lib-boundary.spec.ts` only walks modules under `src/lib`, so owner-to-owner reach-in is unenforced and would have been copied. The list has two owners and belongs to neither, so it moves to `src/lib/submissions/clientContext.ts`, which is also the home the intake's scan classifier will want. **The two form reads ran sequentially.** `formDelivery` and `clientNameFor` share nothing, so the second round trip was pure latency on every delivery. Their differing `req` treatment is what makes the overlap safe, and the comment says so, because the next reader would otherwise re-serialize it. Also: the block union is discriminated, so `'name' in block` narrows it and the three `as { name?: unknown }` casts, the `optionsOf` helper and four runtime type guards all go — `block.options?.find(…)?.label ?? value` is the whole select branch. `deliverContact` returns `{ to, answers }` rather than encoding "no form" as `undefined` vs `[]` for a second function to decode, which deletes `answersFor` and the sentinel with it. The module docblock moved above the imports, where TS attaches it to the module rather than to the type alias below. `select: { recipient: true, fields: true }` stays wide, deliberately. A blocks `select` is keyed per block *slug*, so the narrow form enumerates all nine and a block type added upstream would be dropped silently — losing its answers, which is the failure this whole change exists to fix. Three review findings were rejected, each after checking the source: - **Extract a shared answer row into `EmailLayout`.** The three templates' style pairs are three deliberate visual treatments (14/14, 14/14, 12/14 with different colours and margins), not copies. One component would either flatten them or take a style prop, which is most of the duplication back. The unexplained 1px divergence this branch added is gone instead — `answerValue` now matches `EventRegistrationEmail` exactly, which is what the comment beside it claims. - **Fold `buildFormAnswers` into `buildRegistrationAnswers`.** The shared part is a six-line loop; the sources are a fixed question list versus authored form blocks, and `formatAnswer`'s boolean, number and array branches are all dead for form answers. - **Delete the new guard case as a duplicate.** It is not one. Hoisting the collision check out of the "only judge a changed save" guard reds `lets an unrelated edit through on a form already carrying a reserved name` while the pre-existing sibling stays green — its legacy form carries no reserved name, so it cannot see the distinction. Refs #832 Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01L5xHNXdaF3Wk1tiVXnDKSR
|
🚅 Deployed to the SahajCloud-pr-834 environment in sahajcloud
1 service not affected by this PR
|
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 Adversarial review
Holistic. The diff is the size of #832 and carries nothing the ticket did not ask for: one widened read, one pure walk, one prop swap, one reserved-name check. Both new homes check out against src/AGENTS.md rule 4. The body's open question is decided correctly — see the locale thread. No API shape moves, so sydevs/SahajAtlasWeb#219 needs only the merge.
Findings
should-fixdeliverContact.ts:24— thePromise.alloverlap was never asked for.should-fixUserMessageEmail.tsx:26—UserMessageDetailnames two things now.considerUserMessageEmail.tsx:131— duplicate labels collide on the React key.considerdeliverContact.ts:118— no case covers an untranslated label.
Checked. Read whole: formAnswers.ts, deliverContact.ts, UserMessageEmail.tsx, validateFormAction.ts. Verified at source: fallbackLocale: 'en' on every non-English locale; rule 4 and lib-boundary's one-consumer list. Grepped every migration and seed for a reserved field name — none, so no stored form turns unsaveable.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
The Promise.all overlap was never asked for. It saved one round trip in a queued job nobody waits on, and cost four lines asserting that two Payload reads with different `req` treatment share no state — a claim about pool behaviour every later reader has to re-verify. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FjdixEHZJRwSTCdJwfVFaA
The type names two things since answers got their own section: a row under `Answers`, and a row in the details block it was named for. The props `answers` and `details` already say which section a row belongs to. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FjdixEHZJRwSTCdJwfVFaA
An author can label two blocks the same question, and the `|| block.name` fallback can collide too, so React warned and the rows stopped being stably keyed. `buildFormAnswers` drops the block name, so position is the honest key. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FjdixEHZJRwSTCdJwfVFaA
Reading the form at the visitor's locale is safe only because buildPayloadLocales sets fallbackLocale: 'en' on every non-English locale. Nothing in this file said so, and no case exercises the untranslated path. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01FjdixEHZJRwSTCdJwfVFaA
|
All four adversarial-review threads adopted, one commit each. Pushed as
Nothing rebutted, nothing asked. Lean gate green, plus 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
messageno longer delivers an empty body.Messagesection any more — every answer is a sibling row under its authored label, in authoring order.locale,path,hostUrl,userAgentorerroris refused, naming the field.Changes
src/jobs/DeliverSubmissions/formAnswers.ts— new purebuildFormAnswers: the walk, the select-label resolution, the checkboxYes/No, the blank-answer drop.src/jobs/DeliverSubmissions/deliverContact.ts—recipientForbecameformDelivery: one widened form read returning the recipient and the answers, at the submission's own locale.src/emails/UserMessageEmail.tsx— loses themessageprop, gainsanswers.UserMessageDetailis nowUserMessageRow, since a row is an answer or a detail.src/lib/submissions/clientContext.ts—CLIENT_CONTEXT_KEYS, the five keys the client writes for itself.URL_EXEMPT_KEYSderives from it.src/collections/Forms/hooks/validateFormAction.ts— refuses a field colliding with one of those five.Preview
pathto a form and save, to see the refusalEmail previews
No preview script covers
UserMessageEmail—scripts/preview-*-emails.tsare registration, notification, reminder and event only. Adding one needs a Payload boot plus a named form fixture, which is its own change; the render is pinned bytests/unit/email-templates.spec.tsinstead. See Manual verification for why a real send is blocked regardless.Test results
pnpm lint,pnpm typecheck,pnpm typecheck:tests,pnpm test:unit(2156 passed) — re-run after the review roundatlas-report-issue-form,forms-action-type,user-submissions-create,screen-submissions,user-submissions-access.atlas-report-issue-formre-run after the review round (11 passed)Every new assertion was watched failing against the defect at its own site:
answersForforced to the one-key fallback{ label: 'Message', value: '' }, the production failure exactlylocaledropped from the form readBASE_SUBMISSION_KEYSManual verification
validateFormActionrequires an Email block on every form, and an authoredemailanswer from a.com/.org/.netaddress tripsURL_PATTERN, so the submission 400s before it is ever delivered.[email protected]passes, which is why the failure reads as random.Notes for reviewer
The one open question, decided. The issue left "which locale the recipient reads" unresolved and recommended the submission's own locale. That is what this implements, and it is the judgement worth checking — the alternative is
DEFAULT_LOCALEalways, on the grounds that the recipient manager may not read the visitor's language. TheisValidLocalegate is not part of that choice:localeis submitter-chosen text, exempt from the URL scan, and it reaches the database layer as a query parameter either way. The choice is safe only becausebuildPayloadLocalessetsfallbackLocale: 'en'on every non-English locale, so a label the author never translated arrives in English rather than as a raw field name —submissionLocale's docblock names that dependency, since no case exercises the path.An empty answer set delivers an empty body, by design. The one-row
Messagefallback covers only a form deleted after the row was written. A form that resolves but whose fields carry no stored answer delivers the context block and no body — which is what "an absent or blank answer contributes no row" means. The case that could bite is a queued row whose form was renamed between submission and delivery; re-privilegingmessageto cover it would undo the point of the change, so it is left as specified.The body is read from the live form at delivery time, not from what was asked. A reviewer flagged this as the deeper fix, and it is: snapshotting the labelled pairs onto the row at intake — where the form is already read for
allowedSubmissionKeys— would need no forms read at delivery, no locale choice and no deleted-form fallback. It is a schema change and a migration, so it is out of this ticket's scope rather than dismissed. Worth a follow-up if the drift matters.No security review. The diff matches none of
securityReview.triggerPattern. But answers reach a renderer for the first time, whichURL_EXEMPT_KEYS' docblock anticipated, so the escaping is asserted rather than noted: a value carrying<script>and a bare domain renders as text, never as an anchor.No migration. Nothing in the diff changes a collection's field config.
Detail
Why one widened read rather than a second query.
recipientForalready did afindByIDonformsselectingrecipient; the field list comes off the same document, so the select widened rather than a query being added. Both of that read's existing properties are kept deliberately: noreq, because a nested read joining the caller's transaction takes the whole operation down with it (src/collections/AGENTS.md), anddisableErrors, so a manager deleted since must not strand the message.formDeliveryandclientNameForrun in sequence. The first round overlapped them in aPromise.all, which saved one round trip in a job nobody waits on and cost four lines asserting that two reads with differentreqtreatment share no state.select: { recipient: true, fields: true }stays wide, deliberately. It pulls all nine form-builder block tables and their_localessiblings to use four keys. A blocksselectis keyed per block slug, so the narrow form enumerates all nine — and a block type added upstream would then be dropped silently, losing its answers. That is the failure this change exists to fix, so the extra columns are the cheaper cost.What the three awkward block types actually store, each read off
src/payload-types.tsrather than assumed:selectstores the chosen option'svalue, which is operator-authored and may be a slug, so the option'slabelis resolved — falling back to the raw value for an option deleted since;checkboxarrives as the string'true'/'false', never a boolean, becausecheckSubmissionDatarefuses a non-string value. SoformatAnswer's boolean branch insrc/lib/registrations/questions.tscould never have fired here.parseOptInalready knows the four spellings.Norenders rather than dropping, because the widget sends'false'deliberately and an unticked consent box is an answer;messageblock carries nonameat all, so no stored pair can match it. The block union is discriminated, so'name' in blocknarrows it and no cast is needed. A field namedmessageis an ordinary question.Labels are localized, and nothing in this repo says so. The schema is the only evidence:
forms_blocks_textarea_locales,forms_blocks_select_localesandforms_blocks_select_options_localesall carrylabel, whilenameand the optionvaluestay on the unlocalized table (src/migrations/20260918_172634_atlas_config_report_issue_form.json). The forms plugin declares them.Fixture pre-mortem. The localized integration case assumes the blocks array itself is not localized while
labelinside it is — so the German save carries each block's ownid, or Payload reads the list as a replacement and drops the English labels with the rows. Verified againstsrc/migrations/20260918_172634_atlas_config_report_issue_form.json, where the_localestables are visible. The reserved-name case's block ids are distinct from the existingupdatessuite's, because a blockidis the blocks table's own key and is unique across every form a suite creates — reusinglegacy-emailreddened a pre-existing case.Where
CLIENT_CONTEXT_KEYSlives. It started inUserSubmissions/submissionData.tsand moved tosrc/lib/submissions/, becauseFormsimporting it was a cross-collection internal import — whichsrc/AGENTS.mdrule 4 prohibits outright, and whichlib-boundary.spec.tscannot catch, since it only walks modules undersrc/lib. Two owners, so it passes the one-consumer check, and it is the home the intake's scan classifier will want.Where
buildFormAnswerslives, and why notsrc/lib/. Delivery is its only consumer, and asrc/lib/module whose only consumer sits outsidesrc/lib/failslib-boundary.spec.ts. It sits besidesubmissionContext.tsin the job folder, whichsrc/AGENTS.mdnames as the home for single-owner code.authoredFieldNamesinprepareUserSubmissionis deliberately left alone: widening it to{ name, blockType }buys this PR nothing, and the shared home it would need is the one the scanning ticket creates.Where the reserved-name check sits. Inside the hook's existing "only judge a changed save" guard. Without that, an existing form carrying a colliding name would become unsaveable in the admin for good — the exact failure that guard was written for. Hoisting it out reds the new legacy-form case, which is how that placement is pinned.
The answer rows key on position, the details rows on their label. An author can ask two blocks the same question, and
buildFormAnswerskeeps no field name to break the tie with. The details labels are a fixed set this file writes, so they stay as they were.Review findings rejected, each after checking the source. Extracting a shared answer row into
EmailLayout: the three templates' style pairs are three deliberate visual treatments (14/14, 14/14, 12/14 with different colours and margins), not copies — one component would flatten them or take a style prop, which is most of the duplication back. The unexplained 1px divergence this branch had added is gone instead. FoldingbuildFormAnswersintobuildRegistrationAnswers: the shared part is a six-line loop, the sources are a fixed question list versus authored form blocks, and three offormatAnswer's branches are dead for form answers. ReusingproposedChanges.ts'optionLabel: it takes aFlattenedField— a collection config field — not a form's authored blocks.Review tooling.
/pr-review-toolkit:review-pris not installed in this environment, so the pass ran as the four/simplifylenses over the branch diff.comment-lint.mjsreported no banned comment across the 12 changed files.One unrelated thing left alone. Booting Payload for the integration lane regenerates
src/payload-types.ts, and it comes back one JSDoc line different from whatmainhas committed —sy-atlas-translations'unverified_notedescription, from #830. Reverted out of this branch rather than carried; it is drift betweenmain's generated file and the live global config, not this change.Closes #832
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code