Skip to content

feat(email): render an authored form's answers in the contact email - #834

Merged
sydevs-bot merged 7 commits into
mainfrom
claude/feat-832-form-answers
Sep 22, 2026
Merged

sydevs-bot merged 7 commits into
mainfrom
claude/feat-832-form-answers

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • The contact email renders the named form's own answers, so a form whose textarea is not called message no longer delivers an empty body.
  • No Message section any more — every answer is a sibling row under its authored label, in authoring order.
  • Saving a form whose field is named locale, path, hostUrl, userAgent or error is refused, naming the field.

Changes

  • src/jobs/DeliverSubmissions/formAnswers.ts — new pure buildFormAnswers: the walk, the select-label resolution, the checkbox Yes/No, the blank-answer drop.
  • src/jobs/DeliverSubmissions/deliverContact.ts — recipientFor became formDelivery: one widened form read returning the recipient and the answers, at the submission's own locale.
  • src/emails/UserMessageEmail.tsx — loses the message prop, gains answers. UserMessageDetail is now UserMessageRow, 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_KEYS derives from it.
  • src/collections/Forms/hooks/validateFormAction.ts — refuses a field colliding with one of those five.

Preview

  • Forms list — add a field named path to a form and save, to see the refusal
  • Report an issue form — rename the textarea, then check what a delivered report carries
  • User submissions — the rows whose answers now reach the email

Email previews

No preview script covers UserMessageEmail — scripts/preview-*-emails.ts are 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 by tests/unit/email-templates.spec.ts instead. See Manual verification for why a real send is blocked regardless.

Test results

  • Lean gate: ✓ pnpm lint, pnpm typecheck, pnpm typecheck:tests, pnpm test:unit (2156 passed) — re-run after the review round
  • Targeted specs: ✓ 87 passed — atlas-report-issue-form, forms-action-type, user-submissions-create, screen-submissions, user-submissions-access. atlas-report-issue-form re-run after the review round (11 passed)
  • Build: N/A — Railway builds the preview

Every new assertion was watched failing against the defect at its own site:

Defect reintroduced Cases that went red
answersFor forced to the one-key fallback both delivery cases — a renamed textarea delivered { label: 'Message', value: '' }, the production failure exactly
locale dropped from the form read the localized-label case alone
the reserved-name check disabled all five refusals
the reserved set widened to BASE_SUBMISSION_KEYS 8, including the three names that must keep saving
the check hoisted out of the changed-save guard the legacy-form case, while its pre-existing sibling stayed green
select label / checkbox mapping / preview line 4 unit cases

Manual verification

  1. ⚠ A real send is blocked on the intake-scanning ticket, per the issue's Scanning review. validateFormAction requires an Email block on every form, and an authored email answer from a .com/.org/.net address trips URL_PATTERN, so the submission 400s before it is ever delivered. [email protected] passes, which is why the failure reads as random.
  2. Once that lands: submit from the Atlas widget against a form whose textarea is renamed and which also authors a select and a checkbox, then read the delivered mail in Mailpit.
  3. Author a label in a second locale on that form, submit with that locale, and confirm the delivered mail carries the translated label.

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_LOCALE always, on the grounds that the recipient manager may not read the visitor's language. The isValidLocale gate is not part of that choice: locale is 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 because buildPayloadLocales sets fallbackLocale: '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 Message fallback 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-privileging message to 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, which URL_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. recipientFor already did a findByID on forms selecting recipient; 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: no req, because a nested read joining the caller's transaction takes the whole operation down with it (src/collections/AGENTS.md), and disableErrors, so a manager deleted since must not strand the message. formDelivery and clientNameFor run in sequence. The first round overlapped them in a Promise.all, which saved one round trip in a job nobody waits on and cost four lines asserting that two reads with different req treatment share no state.

select: { recipient: true, fields: true } stays wide, deliberately. It pulls all nine form-builder block tables and their _locales siblings to use four keys. A blocks select is 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.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 in src/lib/registrations/questions.ts could never have fired here. parseOptIn already knows the four spellings. No renders rather than dropping, because 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. The block union is discriminated, so 'name' in block narrows it and no cast is needed. A field named message is 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_locales and forms_blocks_select_options_locales all carry label, while name and the option value stay 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 label inside it is — so the German save carries each block's own id, or Payload reads the list as a replacement and drops the English labels with the rows. Verified against src/migrations/20260918_172634_atlas_config_report_issue_form.json, where the _locales tables are visible. The reserved-name case's block ids are distinct from the existing updates suite's, because a block id is the blocks table's own key and is unique across every form a suite creates — reusing legacy-email reddened a pre-existing case.

Where CLIENT_CONTEXT_KEYS lives. It started in UserSubmissions/submissionData.ts and moved to src/lib/submissions/, because Forms importing it was a cross-collection internal import — which src/AGENTS.md rule 4 prohibits outright, and which lib-boundary.spec.ts cannot catch, since it only walks modules under src/lib. Two owners, so it passes the one-consumer check, and it is the home the intake's scan classifier will want.

Where buildFormAnswers lives, and why not src/lib/. Delivery is its only consumer, and a src/lib/ module whose only consumer sits outside src/lib/ fails lib-boundary.spec.ts. It sits beside submissionContext.ts in the job folder, which src/AGENTS.md names as the home for single-owner code. authoredFieldNames in prepareUserSubmission is 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 buildFormAnswers keeps 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. Folding buildFormAnswers into buildRegistrationAnswers: the shared part is a six-line loop, the sources are a fixed question list versus authored form blocks, and three of formatAnswer's branches are dead for form answers. Reusing proposedChanges.ts' optionLabel: it takes a FlattenedField — a collection config field — not a form's authored blocks.

Review tooling. /pr-review-toolkit:review-pr is not installed in this environment, so the pass ran as the four /simplify lenses over the branch diff. comment-lint.mjs reported 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 what main has committed — sy-atlas-translations' unverified_note description, from #830. Reverted out of this branch rather than carried; it is drift between main'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

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
@railway-app

railway-app Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-834 environment in sahajcloud

Service Status Web Updated
SahajCloud ✅ Success (View Logs) Web Sep 22, 2026 at 4:55 am UTC
1 service not affected by this PR
  • mailpit

@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-834 September 22, 2026 04:26 Destroyed
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 22, 2026
@sydevs-bot

sydevs-bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 04:48Z address-review · attempt 1 · session · done
  • 04:48Z address-review · attempt 1 · session
  • 04:38Z adversarial-review · attempt 1 · session · done
  • 04:38Z adversarial-review · attempt 1 · session

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧐 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-fix deliverContact.ts:24 — the Promise.all overlap was never asked for.
  • should-fix UserMessageEmail.tsx:26 — UserMessageDetail names two things now.
  • consider UserMessageEmail.tsx:131 — duplicate labels collide on the React key.
  • consider deliverContact.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

Comment thread src/emails/UserMessageEmail.tsx Resolved
Comment thread src/emails/UserMessageEmail.tsx Resolved
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Sep 22, 2026
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
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-834 September 22, 2026 04:52 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

All four adversarial-review threads adopted, one commit each. Pushed as 05a6a20.

Nothing rebutted, nothing asked. Lean gate green, plus atlas-report-issue-form (11 passed). The PR body's Promise.all note is corrected.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Sep 22, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review September 22, 2026 05:04
@sydevs-bot
sydevs-bot requested a review from Ardnived September 22, 2026 05:04
@sydevs-bot sydevs-bot moved this from Revising to Approved in SYDevelopers Technical Roadmap Sep 22, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Sep 22, 2026
Merged via the queue into main with commit ed93fbb Sep 22, 2026
35 of 41 checks passed

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-834 — 05a6a20b Deployed Sep 22, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

feat(email): render an authored form's answers in the contact email

3 participants