@aglyn/plugins-forms 1.0.0-beta.221 → 1.0.0-beta.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +1 -0
  2. package/package.json +14 -12
  3. package/src/lib/components/form-detail-card.js +166 -29
  4. package/src/lib/components/form-detail-card.js.map +1 -1
  5. package/src/lib/components/form-submissions-card.component.d.ts +12 -0
  6. package/src/lib/components/form-submissions-card.component.js +35 -2
  7. package/src/lib/components/form-submissions-card.component.js.map +1 -1
  8. package/src/lib/components/form.js +2 -1
  9. package/src/lib/components/form.js.map +1 -1
  10. package/src/lib/components/host-forms-card.component.d.ts +8 -0
  11. package/src/lib/components/host-forms-card.component.js +26 -1
  12. package/src/lib/components/host-forms-card.component.js.map +1 -1
  13. package/src/lib/components/site-package-form-preview.component.d.ts +13 -0
  14. package/src/lib/components/site-package-form-preview.component.js +57 -0
  15. package/src/lib/components/site-package-form-preview.component.js.map +1 -0
  16. package/src/lib/constants/site-package.d.ts +18 -0
  17. package/src/lib/constants/site-package.js +18 -0
  18. package/src/lib/constants/site-package.js.map +1 -0
  19. package/src/lib/declarations.console-server.d.ts +39 -0
  20. package/src/lib/declarations.console-server.js +68 -0
  21. package/src/lib/declarations.console-server.js.map +1 -0
  22. package/src/lib/declarations.server.js +22 -0
  23. package/src/lib/declarations.server.js.map +1 -1
  24. package/src/lib/model/form-door.d.ts +37 -0
  25. package/src/lib/model/form-door.js +50 -0
  26. package/src/lib/model/form-door.js.map +1 -0
  27. package/src/lib/model/form-submission-counts.d.ts +26 -0
  28. package/src/lib/model/form-submission-counts.js +35 -0
  29. package/src/lib/model/form-submission-counts.js.map +1 -0
  30. package/src/lib/model/form-submission-list.d.ts +40 -0
  31. package/src/lib/model/form-submission-list.js +66 -0
  32. package/src/lib/model/form-submission-list.js.map +1 -0
  33. package/src/lib/model/form-submission-record.d.ts +52 -0
  34. package/src/lib/model/form-submission-record.js +70 -0
  35. package/src/lib/model/form-submission-record.js.map +1 -0
  36. package/src/lib/model/form-unavailable.d.ts +83 -0
  37. package/src/lib/model/form-unavailable.js +88 -0
  38. package/src/lib/model/form-unavailable.js.map +1 -0
  39. package/src/lib/model/forms-record-lists.d.ts +31 -0
  40. package/src/lib/model/forms-record-lists.js +55 -0
  41. package/src/lib/model/forms-record-lists.js.map +1 -0
  42. package/src/lib/plan-entitlements.js +6 -6
  43. package/src/lib/plan-entitlements.js.map +1 -1
  44. package/src/lib/plugin.js +34 -0
  45. package/src/lib/plugin.js.map +1 -1
  46. package/src/lib/server/api-v1/form-submissions.d.ts +34 -0
  47. package/src/lib/server/api-v1/form-submissions.js +273 -0
  48. package/src/lib/server/api-v1/form-submissions.js.map +1 -0
  49. package/src/lib/server/api-v1/openapi.d.ts +26 -0
  50. package/src/lib/server/api-v1/openapi.js +133 -0
  51. package/src/lib/server/api-v1/openapi.js.map +1 -0
  52. package/src/lib/server/form-intake-gate.d.ts +34 -0
  53. package/src/lib/server/form-intake-gate.js +44 -0
  54. package/src/lib/server/form-intake-gate.js.map +1 -0
  55. package/src/lib/server/form-submission-index.d.ts +26 -0
  56. package/src/lib/server/form-submission-index.js +51 -0
  57. package/src/lib/server/form-submission-index.js.map +1 -0
  58. package/src/lib/server/form-submit.d.ts +43 -0
  59. package/src/lib/server/form-submit.js +850 -0
  60. package/src/lib/server/form-submit.js.map +1 -0
  61. package/src/lib/server/increment-form-stats.d.ts +70 -0
  62. package/src/lib/server/increment-form-stats.js +112 -0
  63. package/src/lib/server/increment-form-stats.js.map +1 -0
  64. package/src/lib/server.d.ts +10 -0
  65. package/src/lib/server.js +15 -0
  66. package/src/lib/server.js.map +1 -1
  67. package/src/lib/transfer/form-submissions-transfer-key.d.ts +37 -0
  68. package/src/lib/transfer/form-submissions-transfer-key.js +40 -0
  69. package/src/lib/transfer/form-submissions-transfer-key.js.map +1 -0
  70. package/src/lib/transfer/form-submissions-transfer.d.ts +98 -0
  71. package/src/lib/transfer/form-submissions-transfer.js +563 -0
  72. package/src/lib/transfer/form-submissions-transfer.js.map +1 -0
  73. package/src/lib/transfer/form-submissions-transfer.server.d.ts +26 -0
  74. package/src/lib/transfer/form-submissions-transfer.server.js +31 -0
  75. package/src/lib/transfer/form-submissions-transfer.server.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/components/form-detail-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n buildRoute,\n type FormFieldDecl,\n formFieldsCanYieldAnEmail,\n formFieldsCaptureConsent,\n PageHeaderActions,\n PageHeaderRecord,\n listConsoleWidgets,\n pluginDocsHelp,\n Route,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\n// The CRM's route builder by its leaf path, not the plugin barrel: the barrel\n// is the entry point the tenant's loader imports to activate the plugin's\n// site half, and a console page named there would ship to every published\n// page. The same import the Inbox makes for the same reason.\nimport { pluginRecordFilteredHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { ICON_VARIANT_BESIGNER } from '@aglyn/shared-data-enums'\nimport { AppLink, CardDisplay, GridItems, MdiIcon, useLoading } from '@aglyn/shared-ui-jsx'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n AlertTitle,\n Button,\n Chip,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useSiteContainerOptions,\n useHostVersionApi,\n} from '@aglyn/tenant-feature-instance'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { collection, doc, limit, query, updateDoc } from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useMemo, useState } from 'react'\nimport { FORM_CONTACT_FIELDS_ZONE } from './form-zones'\nimport { FORMS_DOCUMENT_SEGMENT } from '../constants/bundle-common'\nimport FormDesignPreview from './form-design-preview.component'\nimport FormMetricsCard from './form-metrics-card.component'\nimport FormSubmissionsCard from './form-submissions-card.component'\nimport useFormPromoteApi from './use-form-promote-api'\nimport useFormStatsRecountApi from './use-form-stats-recount-api'\n\nexport interface FormDetailCardProps {\n hostId: string\n formId: string\n /**\n * The Forms surface's own absolute console path.\n *\n * Only the not-found branch links it. The trail carries the way back on a\n * form that exists, so a link beside the heading would be the breadcrumb\n * written twice; a form that does NOT exist has no heading of its own for\n * the trail to end on, and the reader needs somewhere to go.\n */\n basePath?: string\n /** Whether this viewer's role on the site may make a version live. */\n canPublish?: boolean\n /** False while the role is still being read; see the disabled reasons. */\n hostRoleLoaded?: boolean\n}\n\n/**\n * One form — the component detail surface, for a document that is also a\n * contract.\n *\n * The split this enforces is the reason it exists rather than sending a row\n * straight into the besigner. A form has two halves:\n *\n * - the DESIGN, which is what an author draws, and which lives in the\n * besigner reached from here;\n * - the DECLARATION — where a submission is routed and which field carries\n * marketing consent — which is edited here.\n *\n * They are edited apart because the declaration is what the design is then\n * checked AGAINST. `checkFormContract` compares the two at publish, so a\n * surface that let an author change both in one motion would let them satisfy\n * the check by moving whichever side happened to be easier — which is how a\n * form ends up with lead routing pointed at a field nobody fills in.\n *\n * ## Promotion lives here, not only in the besigner\n *\n * A component's version history offers Publish on any version: promotion is\n * how you go back, not only how you go forward, and an author restoring last\n * week's design should not have to open a canvas to do it.\n *\n * It rides `/api/forms/promote` rather than an `updateDoc` here, because\n * a form's promotion has to run `checkFormContract` on the tree it is about to\n * write and REFUSE. A check in this component would be advice a determined\n * client could skip; the route reads the stored version itself, so nothing\n * about the design crosses the wire inbound and there is no version of this\n * surface that can publish a design the check has not seen.\n */\nexport function FormDetailCard(props: FormDetailCardProps) {\n const { hostId, formId, basePath, canPublish, hostRoleLoaded } = props\n const firestore = useFirestore()\n const ContactFieldsZone = useConsoleWidgetSlot()\n // Read at render, after the shell has loaded its plugins.\n const hasContactFieldsWidget =\n listConsoleWidgets(FORM_CONTACT_FIELDS_ZONE.id).length > 0\n /**\n * The write a widget in the contact-fields zone asks for. The declaration\n * is one array on the form document, and the document is this plugin's, so\n * the page writes what the widget decided.\n */\n const saveFields = useCallback(\n async (fields: FormFieldDecl[]) => {\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n fields,\n updatedAt: Timestamp.now(),\n })\n },\n [firestore, hostId, formId],\n )\n const { orgSlug, subdomain: host } = useConsoleHostRoute(hostId)\n const createHostVersion = useHostVersionApi()\n const promoteForm = useFormPromoteApi()\n const recountFormStats = useFormStatsRecountApi()\n const router = useRouter()\n const { enqueueSnackbar } = useSnackbar()\n const { queueLoading } = useLoading()\n\n const { data: form, status } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'forms', formId),\n [firestore, hostId, formId],\n { idField: '$id' },\n )\n // Three states, not two (AGL-706): loading and absent both arrive as\n // `undefined`, and an editable form over a mistyped id reads as data loss.\n const notFound = status !== 'loading' && !form\n\n /**\n * The published design, in BOTH stored forms (AGL-1151).\n *\n * The read above is converter-less, so `nodes` arrives exactly as stored —\n * msgpack for a design promoted since forms were compressed, a plain map\n * for everything older. Decoded once here because two surfaces below need\n * it and both fail silently on the raw value: `checkFormContract` reports\n * bogus violations against a tree it cannot walk, and the AGL-753 empty\n * guard passes on a `Bytes` because `Object.keys` counts the wrapper.\n */\n const formNodes = useMemo(\n () => Aglyn.decodeStoredNodes<Record<string, any>>(form?.nodes),\n [form?.nodes],\n )\n\n // No orderBy: the oldest version docs predate `createdAt`, and Firestore\n // drops documents missing the ordered field.\n const { data: versionDocs } = useFirestoreCollection<any>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'forms', formId, 'versions'),\n limit(100),\n ),\n [firestore, hostId, formId],\n { idField: '$id' },\n )\n const versions = [...(versionDocs ?? [])].sort(\n (a: any, b: any) =>\n (b.createdAt?.seconds ?? 0) - (a.createdAt?.seconds ?? 0),\n )\n const publishedVersionId = form?.versionId as string | undefined\n\n const [name, setName] = useState<string | null>(null)\n const [lead, setLead] = useState<boolean | null>(null)\n const [consentField, setConsentField] = useState<string | null>(null)\n /**\n * The campaigns picked on screen, or null while the stored value stands.\n *\n * Null and `[]` are different: null means \"not touched\", `[]` means \"take\n * this form out of every campaign\". Collapsing them would make clearing the\n * last campaign a no-op, which is the half of set-and-clear that is easy to\n * ship broken.\n */\n const [campaignIds, setCampaignIds] = useState<string[] | null>(null)\n const [opening, setOpening] = useState(false)\n const [promoting, setPromoting] = useState<string | null>(null)\n /**\n * What a REFUSED promotion said, kept on the surface rather than in a toast.\n *\n * A contract violation is a list of things to go and fix in the besigner,\n * and a snackbar is gone by the time the author has read the second one.\n * The besigner's own refusal persists for the same reason.\n */\n const [promoteRefusal, setPromoteRefusal] = useState<{\n message: string\n violations: Aglyn.FormContractViolation[]\n } | null>(null)\n\n /** The fields the PUBLISHED design draws, which is what a submission can carry. */\n const declaredFields: Aglyn.FormFieldDecl[] = useMemo(\n () => (Array.isArray(form?.fields) ? form.fields : []),\n [form],\n )\n\n const effectiveLead = lead ?? form?.routing?.lead === true\n const effectiveConsent = consentField ?? String(form?.consentFieldName ?? '')\n /*\n * Whether lead routing COULD work on this design — the two preconditions\n * `checkFormContract` applies at publish, asked here so the switch says so\n * before it is flipped rather than after (AGL-2612). Consent is read as\n * it is being edited: picking a field below is what satisfies it.\n */\n const hasEmailField = formFieldsCanYieldAnEmail(declaredFields)\n const capturesConsent = formFieldsCaptureConsent(declaredFields, effectiveConsent)\n /*\n * Where this form's people are: the contacts list narrowed to this form,\n * asked of the plugin that keeps people (`null`, and no link, without one). Built from the resolved org slug and\n * subdomain the besigner link already waits on, so the link appears when\n * they land and never points at a half-built address.\n */\n const contactsHref =\n orgSlug && host\n ? pluginRecordFilteredHref('contact', { orgSlug, host }, 'form', formId)\n : null\n /*\n * WHICH CAMPAIGNS THIS FORM IS PART OF.\n *\n * The site's campaigns are read while this page is open because the field\n * is DISPLAYED here as well as edited here: the document stores ids, and a\n * page that drew them until a button was pressed would be showing a\n * merchant raw storage. Bounded at the ceiling the campaigns table itself\n * draws, so it can offer nothing that list does not.\n */\n const siteCampaigns = useSiteContainerOptions('campaign', hostId, { enabled: Boolean(form) })\n const storedCampaigns = useMemo(\n () => Aglyn.readContainerIds(form as Record<string, unknown>, 'campaign'),\n [form],\n )\n const effectiveCampaigns = campaignIds ?? storedCampaigns\n\n /**\n * What the published design would break, judged against the declaration as\n * it is being edited here.\n *\n * Shown here as well as at publish because the two halves are edited in\n * different places: turning lead routing on for a form whose design has no\n * email field is a break the author causes HERE, on a design they are not\n * looking at, and the besigner would not tell them until they next opened\n * it.\n */\n const violations = useMemo(\n () =>\n form\n ? Aglyn.checkFormContract({\n form: {\n routing: { ...(form.routing ?? {}), lead: effectiveLead },\n ...(effectiveConsent\n ? { consentFieldName: effectiveConsent }\n : {}),\n },\n formId,\n nodes: formNodes as never,\n formNodeId: findFormNodeId(formNodes as never),\n })\n : [],\n [form, formId, effectiveLead, effectiveConsent],\n )\n\n const handleSave = useCallback(async () => {\n const dequeue = queueLoading()\n try {\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n // A rename carries the keys the Forms list searches by (AGL-3330), or\n // the form would be findable only by the name it used to have.\n ...(name != null\n ? {\n displayName: name.trim(),\n ...Aglyn.formListFields({\n id: formId,\n displayName: name.trim(),\n slug: form?.slug,\n }),\n }\n : {}),\n ...(lead != null ? { routing: { ...(form?.routing ?? {}), lead } } : {}),\n ...(consentField != null\n ? { consentFieldName: consentField.trim() }\n : {}),\n // An empty selection is stored as an empty array rather than removing\n // the field: one shape for \"in no campaign\", which is what keeps this\n // writer and the campaign's own detach agreeing. `inCampaign` rides\n // with it, the boolean the list's \"In a campaign\" filter asks\n // (AGL-3330).\n ...(campaignIds != null ? Aglyn.formCampaignFields(campaignIds) : {}),\n updatedAt: Timestamp.now(),\n })\n setName(null)\n setLead(null)\n setConsentField(null)\n setCampaignIds(null)\n enqueueSnackbar('Form saved', { variant: 'success', persist: false })\n /*\n * A form that routes leads holds `0` of them until its first, and one\n * that does not holds none (AGL-3330). The counters are the server's\n * to write, so the switch asks for them to be recounted.\n */\n if (lead != null && lead !== (form?.routing?.lead === true)) {\n void recountFormStats({ hostId, formIds: [formId] })\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n }, [\n firestore,\n hostId,\n formId,\n form,\n name,\n lead,\n consentField,\n campaignIds,\n queueLoading,\n enqueueSnackbar,\n recountFormStats,\n ])\n\n /**\n * Makes one version the version the live sites serve.\n *\n * The route decides, not this handler: it re-reads the stored version, runs\n * `checkFormContract` on the tree it is about to write, and answers 422 with\n * the violations when a publish would stop the submissions arriving. So the\n * only thing here is what to do with each answer — and a refusal is put on\n * the page rather than in a toast, because it is a list of things to fix.\n */\n const handlePromote = useCallback(\n (targetVersionId: string) => async () => {\n if (promoting) return\n setPromoting(targetVersionId)\n setPromoteRefusal(null)\n try {\n const result = await promoteForm({ hostId, formId, versionId: targetVersionId })\n if (!result.ok) {\n const message = result.message ?? 'Publish failed'\n setPromoteRefusal({\n message,\n violations: result.violations ?? [],\n })\n // `persist` because this is a refusal an author has to act on: an\n // auto-dismissed warning is how someone walks away believing the\n // form shipped.\n enqueueSnackbar(message, {\n variant: 'warning',\n allowDuplicate: true,\n persist: true,\n })\n return\n }\n enqueueSnackbar(\n 'Published. The live sites now serve this version, and the form’s ' +\n 'declared fields match it.',\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('Could not publish that version', {\n variant: 'error',\n allowDuplicate: true,\n persist: true,\n })\n } finally {\n setPromoting(null)\n }\n },\n [promoting, promoteForm, hostId, formId, enqueueSnackbar],\n )\n\n /**\n * Opens a version in the besigner, minting the first one when the form has\n * none.\n *\n * Forms adopted from a page carry a declared field list and a `nodes` map\n * seeded from the page they were adopted from — so the first version opens\n * on the form the site was ALREADY submitting rather than a blank canvas.\n */\n const handleOpen = useCallback(\n (targetVersionId?: string) => async () => {\n if (opening) return\n setOpening(true)\n try {\n let versionId = targetVersionId ?? publishedVersionId ?? versions[0]?.$id\n if (!versionId) {\n versionId = Aglyn.createResourceUid()\n // Rides /api/hosts/versions: rules deny the client create, and the\n // route allows a resource's FIRST version on every plan — which\n // this always is, since the form reached here with no `versionId`.\n await createHostVersion({\n hostId,\n kind: 'form',\n parentId: formId,\n id: versionId,\n data: {\n formId,\n hostId,\n displayName: 'Initial version',\n // Emptiness, not just absence: a form that holds no `nodes` and\n // `??` would pass an empty map straight through to a version\n // that opens uneditable (AGL-753). Measured on the DECODED\n // tree — `Object.keys` over a stored `Bytes` is non-empty, so\n // the raw value passes this guard and mints exactly the\n // uneditable version it exists to stop (AGL-1151).\n nodes: Object.keys(formNodes ?? {}).length\n ? formNodes\n : {\n [Aglyn.CANVAS_ROOT_ELEMENT_ID]: {\n $id: Aglyn.CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n nodes: [],\n },\n },\n ...(form?.rootId ? { rootId: form.rootId } : {}),\n },\n })\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n versionId,\n updatedAt: Timestamp.now(),\n })\n }\n // The editor's URL needs the resolved org slug and subdomain, which\n // `useConsoleHostRoute` reads. Until they land the button below is\n // disabled, so this branch cannot be reached without them.\n if (orgSlug && host) {\n router.push(\n buildRoute(Route.PLUGIN_DOCUMENT_BESIGNER, {\n orgSlug,\n host,\n documentSegment: FORMS_DOCUMENT_SEGMENT,\n docId: formId,\n versionId,\n }),\n )\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('Could not open the besigner', {\n variant: 'error',\n allowDuplicate: true,\n })\n setOpening(false)\n }\n },\n [\n opening,\n createHostVersion,\n publishedVersionId,\n versions,\n firestore,\n hostId,\n formId,\n form,\n router,\n orgSlug,\n host,\n enqueueSnackbar,\n ],\n )\n\n const dirty =\n name != null ||\n lead != null ||\n consentField != null ||\n (campaignIds != null &&\n !Aglyn.containerMembershipUnchanged(storedCampaigns, campaignIds))\n // Named before it is used on every row, so a role denial reads as a reason\n // rather than as a control that does nothing.\n const publishBlock = hostRoleLoaded\n ? 'Your role on this site can edit content but not publish it'\n : 'Checking what your role can do…'\n\n if (notFound) {\n return (\n <CardDisplay\n header=\"Form not found\"\n help={pluginDocsHelp('forms', {\n anchor: '#build-a-form',\n excerpt:\n 'A form is created from the Forms list and keeps the id every ' +\n 'submission is filed under.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Alert severity=\"info\">\n {`No form on this site has the id ${formId}. It may have been deleted, or the link may be from another site.`}\n </Alert>\n {basePath ? <AppLink href={basePath}>{'Back to forms'}</AppLink> : null}\n </Stack>\n </CardDisplay>\n )\n }\n\n /* The cards, named so the page chrome above them is a plain list of\n what this surface publishes upward. */\n const cards = (\n <GridItems\n spacing={3}\n items={[\n {\n size: { xs: 12, lg: 5 },\n children: (\n <CardDisplay\n header=\"Details\"\n help={pluginDocsHelp('forms', {\n anchor: '#build-a-form',\n excerpt:\n 'The id is what every submission is filed under, so ' +\n 'renaming a form never splits its history.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <TextField\n label=\"Display name\"\n size=\"small\"\n value={name ?? form?.displayName ?? ''}\n onChange={(event) => setName(event.target.value)}\n fullWidth\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`ID ${formId} — every submission is filed under this, so it never changes`}\n </Typography>\n {/*\n A FORM IS PART OF A CAMPAIGN, and may be part of several.\n The same signup form is placed by one push and re-placed by\n the next, so this is a multi-select — a single value would\n make filing it under this quarter's campaign silently\n un-file it from last quarter's.\n\n It is an assignment and nothing else: it does not decide who\n a campaign mails, and it does not credit a submission to\n one. Attribution is recorded from the link a visitor\n followed, on its own evidence, and it goes on saying what it\n says whatever is picked here.\n */}\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={effectiveCampaigns}\n onChange={setCampaignIds}\n helperText=\"The campaigns this form is part of. It does not change who a campaign mails.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n />\n <Stack direction=\"row\" spacing={1}>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n disabled={!dirty}\n onClick={handleSave}\n >\n {'Save'}\n </Button>\n </Stack>\n </Stack>\n </CardDisplay>\n ),\n },\n {\n size: { xs: 12, lg: 7 },\n children: (\n <CardDisplay\n header=\"CRM routing\"\n help={pluginDocsHelp('forms', {\n anchor: '#where-submissions-go',\n excerpt:\n 'Every submission reaches the Inbox and updates the ' +\n 'contact. Lead routing and the consent field decide ' +\n 'what else happens to it.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n {/*\n THE PART THAT IS NOT A SWITCH (AGL-2612). Every capture\n lands in Contacts whatever is set below; the switch decides\n only whether a LEAD is filed beside the contact. Said\n first, because the switch on its own read as the only way\n a submission reached the CRM.\n */}\n <Typography variant=\"body2\">\n {'Every submission with an email address updates the person ' +\n 'in Contacts at stage Lead — a new contact when the ' +\n 'address is new, an interaction on their timeline when it ' +\n 'is not. A customer stays a customer.'}\n </Typography>\n <Stack spacing={0.5}>\n <FormControlLabel\n control={\n <Switch\n checked={effectiveLead}\n onChange={(event) => setLead(event.target.checked)}\n />\n }\n label=\"Also create a lead from the address someone gives this form\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {!hasEmailField\n ? 'Needs an email field in the published design — a ' +\n 'submission without an address cannot key a lead, and ' +\n 'publishing with this on would be refused until one exists.'\n : !capturesConsent\n ? 'Needs a marketing consent field — a lead nobody opted ' +\n 'in with is one the team cannot email, and publishing ' +\n 'with this on would be refused until the field below ' +\n 'names one.'\n : 'Files a lead in CRM → Leads for the sales team to work, ' +\n 'carrying the opt-in the consent field records.'}\n </Typography>\n </Stack>\n <TextField\n select\n label=\"Marketing consent field\"\n size=\"small\"\n value={effectiveConsent}\n onChange={(event) => setConsentField(event.target.value)}\n fullWidth\n helperText=\"The one field that IS the opt-in. Submitting a form is never itself consent.\"\n >\n <MenuItem value=\"\">\n {'None — this form collects no opt-in'}\n </MenuItem>\n {declaredFields.map((field) => (\n <MenuItem key={field.fieldName} value={field.fieldName}>\n {field.label\n ? `${field.label} (${field.fieldName})`\n : field.fieldName}\n </MenuItem>\n ))}\n </TextField>\n {violations.length ? (\n <Alert severity=\"warning\">\n <AlertTitle>{'This form would stop collecting'}</AlertTitle>\n <Stack component=\"ul\" sx={{ pl: 2, m: 0 }}>\n {violations.map((violation) => (\n <Typography\n component=\"li\"\n variant=\"body2\"\n key={`${violation.code}:${violation.nodeId ?? violation.fieldName ?? ''}`}\n >\n {violation.message}\n </Typography>\n ))}\n </Stack>\n </Alert>\n ) : null}\n {/*\n The people this form captured, on the list that holds them.\n Withheld until the site's address resolves, for the reason\n the besigner button is.\n */}\n {contactsHref ? (\n <Typography variant=\"body2\">\n <AppLink href={contactsHref}>\n {'See the contacts this form captured in the CRM'}\n </AppLink>\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n ),\n },\n // Where each field saves on the person: another plugin's card, in a\n // zone this page hosts. No item at all where nothing fills it, so the\n // grid keeps no empty cell.\n ...(ContactFieldsZone && hasContactFieldsWidget\n ? [\n {\n size: { xs: 12 },\n children: (\n <ContactFieldsZone\n slot={FORM_CONTACT_FIELDS_ZONE.id}\n hostId={hostId}\n formId={formId}\n fields={declaredFields}\n loading={status === 'loading'}\n saveFields={saveFields}\n />\n ),\n },\n ]\n : []),\n {\n size: { xs: 12, lg: 5 },\n children: (\n <FormMetricsCard\n stats={form?.stats}\n fields={declaredFields}\n leadRouting={effectiveLead}\n loading={status === 'loading'}\n />\n ),\n },\n {\n size: { xs: 12, lg: 7 },\n children: (\n <CardDisplay\n header=\"Versions\"\n help={pluginDocsHelp('forms', {\n anchor: '#build-a-form',\n excerpt:\n 'Publishing a form version updates every page that ' +\n 'places it. Saving does not — a save is not a publish.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n {promoteRefusal ? (\n <Alert\n severity=\"warning\"\n onClose={() => setPromoteRefusal(null)}\n >\n <AlertTitle>{promoteRefusal.message}</AlertTitle>\n {promoteRefusal.violations.length ? (\n <Stack component=\"ul\" sx={{ pl: 2, m: 0 }}>\n {promoteRefusal.violations.map((violation) => (\n <Typography\n component=\"li\"\n variant=\"body2\"\n key={`${violation.code}:${violation.nodeId ?? violation.fieldName ?? ''}`}\n >\n {violation.message}\n </Typography>\n ))}\n </Stack>\n ) : null}\n </Alert>\n ) : null}\n {versions.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No versions yet — opening the besigner creates the first one.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Version'}</TableCell>\n <TableCell>{'Created'}</TableCell>\n <TableCell>{'Updated'}</TableCell>\n <TableCell align=\"right\">{'Actions'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {versions.map((version: any) => (\n <TableRow key={version.$id} hover>\n <TableCell>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Typography variant=\"body2\">\n {version.displayName ?? version.$id}\n </Typography>\n {version.$id === publishedVersionId ? (\n <Chip\n label=\"Current\"\n color=\"success\"\n size=\"small\"\n />\n ) : null}\n </Stack>\n </TableCell>\n <TableCell>\n {version.createdAt?.toDate?.().toLocaleString() ??\n '--'}\n </TableCell>\n <TableCell>\n {version.updatedAt?.toDate?.().toLocaleString() ??\n '--'}\n </TableCell>\n <TableCell align=\"right\">\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ justifyContent: 'flex-end' }}\n >\n <Button\n size=\"small\"\n disabled={opening || !orgSlug || !host}\n onClick={handleOpen(version.$id)}\n >\n {'Open'}\n </Button>\n {/*\n The version the sites already serve has nothing\n to promote to, so the control is disabled\n rather than absent — an absent control and an\n inapplicable one look identical, and only one\n of them is honest.\n */}\n <Button\n size=\"small\"\n variant=\"outlined\"\n title={canPublish ? undefined : publishBlock}\n disabled={\n !canPublish ||\n promoting !== null ||\n version.$id === publishedVersionId\n }\n onClick={handlePromote(version.$id)}\n >\n {promoting === version.$id\n ? 'Publishing…'\n : version.$id === publishedVersionId\n ? 'Published'\n : 'Publish'}\n </Button>\n </Stack>\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n </Stack>\n </CardDisplay>\n ),\n },\n {\n /*\n THE MESSAGES THEMSELVES, under the numbers that describe them.\n Full width because it is a table of people and what they wrote,\n and it sits below the metrics because those are read at a glance\n and this is read a row at a time.\n */\n size: { xs: 12 },\n children: <FormSubmissionsCard hostId={hostId} formId={formId} />,\n },\n {\n // Full width: the frame is a document, and a document in a\n // five-column card is a column of one-word lines.\n size: { xs: 12 },\n children: (\n <CardDisplay\n header=\"What a submission will carry\"\n help={pluginDocsHelp('forms', {\n anchor: '#field-types',\n excerpt:\n 'Each field arrives under its own name. Two fields ' +\n 'sharing one name arrive as a single answer.',\n })}\n contentGutterX\n contentGutterY\n >\n <FormDesignPreview\n formId={formId}\n nodes={form?.nodes}\n consentFieldName={\n effectiveConsent ? effectiveConsent : undefined\n }\n loading={status === 'loading'}\n />\n </CardDisplay>\n ),\n },\n ]}\n />\n )\n\n return (\n <>\n {/*\n The page chrome this surface cannot set for itself. The console shell\n owns the layout and builds its heading from the Forms nav item, so\n without these the page about one form is headed `Forms` and its trail\n stops on the list — the same on every row of it.\n */}\n <PageHeaderRecord\n title={form ? form.displayName || formId : undefined}\n />\n {/*\n The besigner is what this surface exists to reach, so it leads — in\n the PAGE header, which is where an action belongs on a surface with\n no section rail beneath it. Withheld when there is no form: it would\n mint a version document under an id that has none (AGL-706).\n */}\n <PageHeaderActions>\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={opening || !orgSlug || !host}\n title={\n orgSlug && host ? undefined : 'Resolving this site’s address…'\n }\n onClick={handleOpen()}\n startIcon={\n <MdiIcon color=\"inherit\" path={ICON_VARIANT_BESIGNER.path} />\n }\n >\n {opening ? 'Opening…' : 'Edit in besigner'}\n </Button>\n </PageHeaderActions>\n {cards}\n </>\n )\n}\nFormDetailCard.displayName = 'FormDetailCard'\n\n/**\n * The `form` node inside a published design.\n *\n * A form document's tree holds exactly one, because the document IS that\n * form — but the tree is a flat map with a synthetic root, so the node has to\n * be found rather than assumed to be the root itself.\n */\nfunction findFormNodeId(\n nodes: Record<string, { componentId?: string }> | undefined,\n): string | undefined {\n return Object.keys(nodes ?? {}).find(\n (id) => nodes?.[id]?.componentId === 'form',\n )\n}\n\nexport default FormDetailCard\n"],"names":["Aglyn","buildRoute","formFieldsCanYieldAnEmail","formFieldsCaptureConsent","PageHeaderActions","PageHeaderRecord","listConsoleWidgets","pluginDocsHelp","Route","useConsoleWidgetSlot","pluginRecordFilteredHref","ICON_VARIANT_BESIGNER","AppLink","CardDisplay","GridItems","MdiIcon","useLoading","ScrollTable","useSnackbar","Timestamp","Alert","AlertTitle","Button","Chip","FormControlLabel","MenuItem","Stack","Switch","TableBody","TableCell","TableHead","TableRow","TextField","Typography","useConsoleHostRoute","useFirestore","useFirestoreCollection","useFirestoreDoc","useSiteContainerOptions","useHostVersionApi","ContainerPicker","collection","doc","limit","query","updateDoc","useRouter","useCallback","useMemo","useState","FORM_CONTACT_FIELDS_ZONE","FORMS_DOCUMENT_SEGMENT","FormDesignPreview","FormMetricsCard","FormSubmissionsCard","useFormPromoteApi","useFormStatsRecountApi","FormDetailCard","props","name","form","hostId","formId","basePath","canPublish","hostRoleLoaded","firestore","ContactFieldsZone","hasContactFieldsWidget","id","length","saveFields","fields","updatedAt","now","orgSlug","subdomain","host","createHostVersion","promoteForm","recountFormStats","router","enqueueSnackbar","queueLoading","data","status","idField","notFound","formNodes","decodeStoredNodes","nodes","versionDocs","versions","sort","a","b","createdAt","seconds","publishedVersionId","versionId","setName","lead","setLead","consentField","setConsentField","campaignIds","setCampaignIds","opening","setOpening","promoting","setPromoting","promoteRefusal","setPromoteRefusal","declaredFields","Array","isArray","effectiveLead","routing","effectiveConsent","String","consentFieldName","hasEmailField","capturesConsent","contactsHref","siteCampaigns","enabled","Boolean","storedCampaigns","readContainerIds","effectiveCampaigns","violations","checkFormContract","formNodeId","findFormNodeId","handleSave","dequeue","displayName","trim","formListFields","slug","formCampaignFields","variant","persist","formIds","error","console","allowDuplicate","handlePromote","targetVersionId","result","ok","message","handleOpen","$id","createResourceUid","kind","parentId","Object","keys","CANVAS_ROOT_ELEMENT_ID","componentId","rootId","push","PLUGIN_DOCUMENT_BESIGNER","documentSegment","docId","dirty","containerMembershipUnchanged","publishBlock","header","help","anchor","excerpt","contentGutterX","contentGutterY","spacing","sx","alignItems","severity","href","cards","items","size","xs","lg","children","label","value","onChange","event","target","fullWidth","color","options","helperText","empty","ready","direction","disabled","onClick","control","checked","select","map","field","fieldName","component","pl","m","violation","code","nodeId","slot","loading","stats","leadRouting","onClose","align","version","hover","toDate","toLocaleString","justifyContent","title","undefined","startIcon","path","find"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SACEC,UAAU,EAEVC,yBAAyB,EACzBC,wBAAwB,EACxBC,iBAAiB,EACjBC,gBAAgB,EAChBC,kBAAkB,EAClBC,cAAc,EACdC,KAAK,QACA,eAAc;AACrB,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BAAQC,QAAQA;;YACzD;YACA;gBACE,2DAA2D;gBAC3D,kDAAkD;gBAClDwH,MAAM;oBAAEC,IAAI;gBAAG;gBACfE,wBACE,KAAC5K;oBACC4J,QAAO;oBACPC,MAAMnK,eAAe,SAAS;wBAC5BoK,QAAQ;wBACRC,SACE,uDACA;oBACJ;oBACAC,cAAc;oBACdC,cAAc;8BAEd,cAAA,KAAC1H;wBACCU,QAAQA;wBACR4B,KAAK,EAAE9B,wBAAAA,KAAM8B,KAAK;wBAClB8B,kBACEF,mBAAmBA,mBAAmB0G;wBAExCX,SAAShI,WAAW;;;YAI5B;SACD;;IAIL,qBACE;;0BAOE,KAAChF;gBACC0N,OAAOnK,OAAOA,KAAK4E,WAAW,IAAI1E,SAASkK;;0BAQ7C,KAAC5N;0BACC,cAAA,KAACkB;oBACCgK,MAAK;oBACLzC,SAAQ;oBACRyD,UAAU3F,WAAW,CAAChC,WAAW,CAACE;oBAClCkJ,OACEpJ,WAAWE,OAAOmJ,YAAY;oBAEhCzB,SAAS/C;oBACTyE,yBACE,KAAClN;wBAAQiL,OAAM;wBAAUkC,MAAMvN,sBAAsBuN,IAAI;;8BAG1DvH,UAAU,aAAa;;;YAG3ByE;;;AAGP;AACA3H,eAAe+E,WAAW,GAAG;AAE7B;;;;;;CAMC,GACD,SAASH,eACP3C,KAA2D;IAE3D,OAAOmE,OAAOC,IAAI,CAACpE,gBAAAA,QAAS,CAAC,GAAGyI,IAAI,CAClC,CAAC9J;YAAOqB;eAAAA,CAAAA,0BAAAA,YAAAA,KAAO,CAACrB,GAAG,qBAAXqB,UAAasE,WAAW,MAAK;;AAEzC;AAEA,eAAevG,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/components/form-detail-card.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport {\n buildRoute,\n type FormFieldDecl,\n formFieldsCanYieldAnEmail,\n formFieldsCaptureConsent,\n PageHeaderActions,\n PageHeaderRecord,\n listConsoleWidgets,\n pluginDocsHelp,\n Route,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\n// The CRM's route builder by its leaf path, not the plugin barrel: the barrel\n// is the entry point the tenant's loader imports to activate the plugin's\n// site half, and a console page named there would ship to every published\n// page. The same import the Inbox makes for the same reason.\nimport { pluginRecordFilteredHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { ICON_VARIANT_BESIGNER } from '@aglyn/shared-data-enums'\nimport {\n AppLink,\n CardDisplay,\n GridItems,\n MdiIcon,\n useConfirmationContext,\n useLoading,\n} from '@aglyn/shared-ui-jsx'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n AlertTitle,\n Button,\n Chip,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n useConsoleHostRoute,\n useFirestore,\n useFirestoreCollection,\n useFirestoreDoc,\n useSiteContainerOptions,\n useHostVersionApi,\n} from '@aglyn/tenant-feature-instance'\nimport ContainerPicker from '@aglyn/tenant-feature-instance/components/container-picker'\nimport { collection, doc, limit, query, updateDoc } from 'firebase/firestore'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { FORM_CONTACT_FIELDS_ZONE } from './form-zones'\nimport { FORMS_DOCUMENT_SEGMENT } from '../constants/bundle-common'\nimport FormDesignPreview from './form-design-preview.component'\nimport FormMetricsCard from './form-metrics-card.component'\nimport FormSubmissionsCard from './form-submissions-card.component'\nimport useFormPromoteApi from './use-form-promote-api'\nimport useFormStatsRecountApi from './use-form-stats-recount-api'\n\nexport interface FormDetailCardProps {\n hostId: string\n formId: string\n /**\n * The Forms surface's own absolute console path.\n *\n * Only the not-found branch links it. The trail carries the way back on a\n * form that exists, so a link beside the heading would be the breadcrumb\n * written twice; a form that does NOT exist has no heading of its own for\n * the trail to end on, and the reader needs somewhere to go.\n */\n basePath?: string\n /** Whether this viewer's role on the site may make a version live. */\n canPublish?: boolean\n /** False while the role is still being read; see the disabled reasons. */\n hostRoleLoaded?: boolean\n}\n\n/**\n * One form — the component detail surface, for a document that is also a\n * contract.\n *\n * The split this enforces is the reason it exists rather than sending a row\n * straight into the besigner. A form has two halves:\n *\n * - the DESIGN, which is what an author draws, and which lives in the\n * besigner reached from here;\n * - the DECLARATION — where a submission is routed and which field carries\n * marketing consent — which is edited here.\n *\n * They are edited apart because the declaration is what the design is then\n * checked AGAINST. `checkFormContract` compares the two at publish, so a\n * surface that let an author change both in one motion would let them satisfy\n * the check by moving whichever side happened to be easier — which is how a\n * form ends up with lead routing pointed at a field nobody fills in.\n *\n * ## Promotion lives here, not only in the besigner\n *\n * A component's version history offers Publish on any version: promotion is\n * how you go back, not only how you go forward, and an author restoring last\n * week's design should not have to open a canvas to do it.\n *\n * It rides `/api/forms/promote` rather than an `updateDoc` here, because\n * a form's promotion has to run `checkFormContract` on the tree it is about to\n * write and REFUSE. A check in this component would be advice a determined\n * client could skip; the route reads the stored version itself, so nothing\n * about the design crosses the wire inbound and there is no version of this\n * surface that can publish a design the check has not seen.\n */\nexport function FormDetailCard(props: FormDetailCardProps) {\n const { hostId, formId, basePath, canPublish, hostRoleLoaded } = props\n const firestore = useFirestore()\n const ContactFieldsZone = useConsoleWidgetSlot()\n // Read at render, after the shell has loaded its plugins.\n const hasContactFieldsWidget =\n listConsoleWidgets(FORM_CONTACT_FIELDS_ZONE.id).length > 0\n /**\n * The write a widget in the contact-fields zone asks for. The declaration\n * is one array on the form document, and the document is this plugin's, so\n * the page writes what the widget decided.\n */\n const saveFields = useCallback(\n async (fields: FormFieldDecl[]) => {\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n fields,\n updatedAt: Timestamp.now(),\n })\n },\n [firestore, hostId, formId],\n )\n const { orgSlug, subdomain: host } = useConsoleHostRoute(hostId)\n const createHostVersion = useHostVersionApi()\n const promoteForm = useFormPromoteApi()\n const recountFormStats = useFormStatsRecountApi()\n const router = useRouter()\n const { enqueueSnackbar } = useSnackbar()\n const { queueLoading } = useLoading()\n const { confirm } = useConfirmationContext()\n\n const { data: form, status } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'forms', formId),\n [firestore, hostId, formId],\n { idField: '$id' },\n )\n // Three states, not two (AGL-706): loading and absent both arrive as\n // `undefined`, and an editable form over a mistyped id reads as data loss.\n const notFound = status !== 'loading' && !form\n\n /**\n * The published design, in BOTH stored forms (AGL-1151).\n *\n * The read above is converter-less, so `nodes` arrives exactly as stored —\n * msgpack for a design promoted since forms were compressed, a plain map\n * for everything older. Decoded once here because two surfaces below need\n * it and both fail silently on the raw value: `checkFormContract` reports\n * bogus violations against a tree it cannot walk, and the AGL-753 empty\n * guard passes on a `Bytes` because `Object.keys` counts the wrapper.\n */\n const formNodes = useMemo(\n () => Aglyn.decodeStoredNodes<Record<string, any>>(form?.nodes),\n [form?.nodes],\n )\n\n // No orderBy: the oldest version docs predate `createdAt`, and Firestore\n // drops documents missing the ordered field.\n const { data: versionDocs } = useFirestoreCollection<any>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'forms', formId, 'versions'),\n limit(100),\n ),\n [firestore, hostId, formId],\n { idField: '$id' },\n )\n const versions = [...(versionDocs ?? [])].sort(\n (a: any, b: any) =>\n (b.createdAt?.seconds ?? 0) - (a.createdAt?.seconds ?? 0),\n )\n const publishedVersionId = form?.versionId as string | undefined\n\n const [name, setName] = useState<string | null>(null)\n const [lead, setLead] = useState<boolean | null>(null)\n const [consentField, setConsentField] = useState<string | null>(null)\n /**\n * The campaigns picked on screen, or null while the stored value stands.\n *\n * Null and `[]` are different: null means \"not touched\", `[]` means \"take\n * this form out of every campaign\". Collapsing them would make clearing the\n * last campaign a no-op, which is the half of set-and-clear that is easy to\n * ship broken.\n */\n const [campaignIds, setCampaignIds] = useState<string[] | null>(null)\n const [opening, setOpening] = useState(false)\n const [promoting, setPromoting] = useState<string | null>(null)\n /**\n * What a REFUSED promotion said, kept on the surface rather than in a toast.\n *\n * A contract violation is a list of things to go and fix in the besigner,\n * and a snackbar is gone by the time the author has read the second one.\n * The besigner's own refusal persists for the same reason.\n */\n const [promoteRefusal, setPromoteRefusal] = useState<{\n message: string\n violations: Aglyn.FormContractViolation[]\n } | null>(null)\n\n /** The fields the PUBLISHED design draws, which is what a submission can carry. */\n const declaredFields: Aglyn.FormFieldDecl[] = useMemo(\n () => (Array.isArray(form?.fields) ? form.fields : []),\n [form],\n )\n\n const effectiveLead = lead ?? form?.routing?.lead === true\n const effectiveConsent = consentField ?? String(form?.consentFieldName ?? '')\n /*\n * Whether lead routing COULD work on this design — the two preconditions\n * `checkFormContract` applies at publish, asked here so the switch says so\n * before it is flipped rather than after (AGL-2612). Consent is read as\n * it is being edited: picking a field below is what satisfies it.\n */\n const hasEmailField = formFieldsCanYieldAnEmail(declaredFields)\n const capturesConsent = formFieldsCaptureConsent(declaredFields, effectiveConsent)\n /*\n * Where this form's people are: the contacts list narrowed to this form,\n * asked of the plugin that keeps people (`null`, and no link, without one). Built from the resolved org slug and\n * subdomain the besigner link already waits on, so the link appears when\n * they land and never points at a half-built address.\n */\n const contactsHref =\n orgSlug && host\n ? pluginRecordFilteredHref('contact', { orgSlug, host }, 'form', formId)\n : null\n /*\n * WHICH CAMPAIGNS THIS FORM IS PART OF.\n *\n * The site's campaigns are read while this page is open because the field\n * is DISPLAYED here as well as edited here: the document stores ids, and a\n * page that drew them until a button was pressed would be showing a\n * merchant raw storage. Bounded at the ceiling the campaigns table itself\n * draws, so it can offer nothing that list does not.\n */\n const siteCampaigns = useSiteContainerOptions('campaign', hostId, { enabled: Boolean(form) })\n const storedCampaigns = useMemo(\n () => Aglyn.readContainerIds(form as Record<string, unknown>, 'campaign'),\n [form],\n )\n const effectiveCampaigns = campaignIds ?? storedCampaigns\n\n /**\n * What the published design would break, judged against the declaration as\n * it is being edited here.\n *\n * Shown here as well as at publish because the two halves are edited in\n * different places: turning lead routing on for a form whose design has no\n * email field is a break the author causes HERE, on a design they are not\n * looking at, and the besigner would not tell them until they next opened\n * it.\n */\n const violations = useMemo(\n () =>\n form\n ? Aglyn.checkFormContract({\n form: {\n routing: { ...(form.routing ?? {}), lead: effectiveLead },\n ...(effectiveConsent\n ? { consentFieldName: effectiveConsent }\n : {}),\n },\n formId,\n nodes: formNodes as never,\n formNodeId: findFormNodeId(formNodes as never),\n })\n : [],\n [form, formId, effectiveLead, effectiveConsent],\n )\n\n /**\n * WHICH CARD IS WRITING, or null.\n *\n * Each card saves what it shows and nothing else (AGL-3508). One handler\n * used to write the name, the campaigns, the lead switch and the consent\n * field together from a button in Details, so a routing change made in its\n * own card sat unsaved until somebody pressed Save somewhere else — and was\n * dropped without a word when they left instead.\n */\n const [saving, setSaving] = useState<FormDetailSection | null>(null)\n\n /**\n * Details: the name and the campaigns. Never `routing` or the consent\n * field, so saving a rename cannot also commit a half-made routing change.\n */\n const handleSaveDetails = useCallback(async () => {\n const dequeue = queueLoading()\n setSaving('details')\n try {\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n // A rename carries the keys the Forms list searches by (AGL-3330), or\n // the form would be findable only by the name it used to have.\n ...(name != null\n ? {\n displayName: name.trim(),\n ...Aglyn.formListFields({\n id: formId,\n displayName: name.trim(),\n slug: form?.slug,\n }),\n }\n : {}),\n // An empty selection is stored as an empty array rather than removing\n // the field: one shape for \"in no campaign\", which is what keeps this\n // writer and the campaign's own detach agreeing. `inCampaign` rides\n // with it, the boolean the list's \"In a campaign\" filter asks\n // (AGL-3330).\n ...(campaignIds != null ? Aglyn.formCampaignFields(campaignIds) : {}),\n updatedAt: Timestamp.now(),\n })\n setName(null)\n setCampaignIds(null)\n enqueueSnackbar('Details saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setSaving(null)\n dequeue()\n }\n }, [\n firestore,\n hostId,\n formId,\n form,\n name,\n campaignIds,\n queueLoading,\n enqueueSnackbar,\n ])\n\n /**\n * CRM routing: the lead switch and the consent field, together, because\n * the contract judges them together — a lead surface with no opt-in field\n * is one of the breaks the warning in this card names.\n */\n const handleSaveRouting = useCallback(async () => {\n const dequeue = queueLoading()\n setSaving('routing')\n try {\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n ...(lead != null ? { routing: { ...(form?.routing ?? {}), lead } } : {}),\n ...(consentField != null\n ? { consentFieldName: consentField.trim() }\n : {}),\n updatedAt: Timestamp.now(),\n })\n setLead(null)\n setConsentField(null)\n enqueueSnackbar('CRM routing saved', { variant: 'success', persist: false })\n /*\n * A form that routes leads holds `0` of them until its first, and one\n * that does not holds none (AGL-3330). The counters are the server's\n * to write, so the switch asks for them to be recounted.\n */\n if (lead != null && lead !== (form?.routing?.lead === true)) {\n void recountFormStats({ hostId, formIds: [formId] })\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n setSaving(null)\n dequeue()\n }\n }, [\n firestore,\n hostId,\n formId,\n form,\n lead,\n consentField,\n queueLoading,\n enqueueSnackbar,\n recountFormStats,\n ])\n\n /*\n * Whether each card holds a change, measured against what is stored rather\n * than against \"was touched\": flipping the switch and flipping it back is\n * no change, and a Save that writes nothing should not be offered.\n */\n const detailsDirty =\n (name != null && name.trim() !== String(form?.displayName ?? '')) ||\n (campaignIds != null &&\n !Aglyn.containerMembershipUnchanged(storedCampaigns, campaignIds))\n const routingDirty =\n (lead != null && lead !== (form?.routing?.lead === true)) ||\n (consentField != null &&\n consentField.trim() !== String(form?.consentFieldName ?? ''))\n const dirty = detailsDirty || routingDirty\n /**\n * Read from inside handlers that must not re-subscribe on every keystroke:\n * `beforeunload` and the besigner buttons need the CURRENT answer.\n */\n const dirtyRef = useRef(false)\n dirtyRef.current = dirty\n\n /**\n * The exits a router cannot mediate: reload, tab close, or a link out of\n * the console. Registered only while a card holds a change, so a clean page\n * never nags — the same guard a content entry's editor keeps. The App\n * Router has no navigation-blocking hook, so an in-console link is guarded\n * only where this surface makes the move itself (the besigner buttons,\n * below); everywhere else the enabled Save and Discard in each card's\n * header are what say a change is waiting.\n */\n useEffect(() => {\n if (!dirty) return\n const warn = (event: BeforeUnloadEvent) => {\n event.preventDefault()\n event.returnValue = ''\n }\n window.addEventListener('beforeunload', warn)\n return () => window.removeEventListener('beforeunload', warn)\n }, [dirty])\n\n /**\n * Asked before this surface navigates away on its own — opening the\n * besigner — while a card holds a change. `confirm` resolves with no value\n * and REJECTS on cancel.\n */\n const confirmLeave = useCallback(async () => {\n if (!dirtyRef.current) return true\n return confirm({\n title: 'Discard unsaved changes?',\n description:\n 'This form has changes that have not been saved yet. Opening the ' +\n 'besigner now discards them.',\n confirmationText: 'Discard and open',\n })\n .then(() => true)\n .catch(() => false)\n }, [confirm])\n\n /**\n * Makes one version the version the live sites serve.\n *\n * The route decides, not this handler: it re-reads the stored version, runs\n * `checkFormContract` on the tree it is about to write, and answers 422 with\n * the violations when a publish would stop the submissions arriving. So the\n * only thing here is what to do with each answer — and a refusal is put on\n * the page rather than in a toast, because it is a list of things to fix.\n */\n const handlePromote = useCallback(\n (targetVersionId: string) => async () => {\n if (promoting) return\n setPromoting(targetVersionId)\n setPromoteRefusal(null)\n try {\n const result = await promoteForm({ hostId, formId, versionId: targetVersionId })\n if (!result.ok) {\n const message = result.message ?? 'Publish failed'\n setPromoteRefusal({\n message,\n violations: result.violations ?? [],\n })\n // `persist` because this is a refusal an author has to act on: an\n // auto-dismissed warning is how someone walks away believing the\n // form shipped.\n enqueueSnackbar(message, {\n variant: 'warning',\n allowDuplicate: true,\n persist: true,\n })\n return\n }\n enqueueSnackbar(\n 'Published. The live sites now serve this version, and the form’s ' +\n 'declared fields match it.',\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('Could not publish that version', {\n variant: 'error',\n allowDuplicate: true,\n persist: true,\n })\n } finally {\n setPromoting(null)\n }\n },\n [promoting, promoteForm, hostId, formId, enqueueSnackbar],\n )\n\n /**\n * Opens a version in the besigner, minting the first one when the form has\n * none.\n *\n * Forms adopted from a page carry a declared field list and a `nodes` map\n * seeded from the page they were adopted from — so the first version opens\n * on the form the site was ALREADY submitting rather than a blank canvas.\n */\n const handleOpen = useCallback(\n (targetVersionId?: string) => async () => {\n if (opening) return\n if (!(await confirmLeave())) return\n setOpening(true)\n try {\n let versionId = targetVersionId ?? publishedVersionId ?? versions[0]?.$id\n if (!versionId) {\n versionId = Aglyn.createResourceUid()\n // Rides /api/hosts/versions: rules deny the client create, and the\n // route allows a resource's FIRST version on every plan — which\n // this always is, since the form reached here with no `versionId`.\n await createHostVersion({\n hostId,\n kind: 'form',\n parentId: formId,\n id: versionId,\n data: {\n formId,\n hostId,\n displayName: 'Initial version',\n // Emptiness, not just absence: a form that holds no `nodes` and\n // `??` would pass an empty map straight through to a version\n // that opens uneditable (AGL-753). Measured on the DECODED\n // tree — `Object.keys` over a stored `Bytes` is non-empty, so\n // the raw value passes this guard and mints exactly the\n // uneditable version it exists to stop (AGL-1151).\n nodes: Object.keys(formNodes ?? {}).length\n ? formNodes\n : {\n [Aglyn.CANVAS_ROOT_ELEMENT_ID]: {\n $id: Aglyn.CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n nodes: [],\n },\n },\n ...(form?.rootId ? { rootId: form.rootId } : {}),\n },\n })\n await updateDoc(doc(firestore, 'hosts', hostId, 'forms', formId), {\n versionId,\n updatedAt: Timestamp.now(),\n })\n }\n // The editor's URL needs the resolved org slug and subdomain, which\n // `useConsoleHostRoute` reads. Until they land the button below is\n // disabled, so this branch cannot be reached without them.\n if (orgSlug && host) {\n router.push(\n buildRoute(Route.PLUGIN_DOCUMENT_BESIGNER, {\n orgSlug,\n host,\n documentSegment: FORMS_DOCUMENT_SEGMENT,\n docId: formId,\n versionId,\n }),\n )\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('Could not open the besigner', {\n variant: 'error',\n allowDuplicate: true,\n })\n setOpening(false)\n }\n },\n [\n opening,\n confirmLeave,\n createHostVersion,\n publishedVersionId,\n versions,\n firestore,\n hostId,\n formId,\n form,\n router,\n orgSlug,\n host,\n enqueueSnackbar,\n ],\n )\n\n // Named before it is used on every row, so a role denial reads as a reason\n // rather than as a control that does nothing.\n const publishBlock = hostRoleLoaded\n ? 'Your role on this site can edit content but not publish it'\n : 'Checking what your role can do…'\n\n if (notFound) {\n return (\n <CardDisplay\n header=\"Form not found\"\n help={pluginDocsHelp('forms', {\n anchor: '#build-a-form',\n excerpt:\n 'A form is created from the Forms list and keeps the id every ' +\n 'submission is filed under.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Alert severity=\"info\">\n {`No form on this site has the id ${formId}. It may have been deleted, or the link may be from another site.`}\n </Alert>\n {basePath ? <AppLink href={basePath}>{'Back to forms'}</AppLink> : null}\n </Stack>\n </CardDisplay>\n )\n }\n\n /* The cards, named so the page chrome above them is a plain list of\n what this surface publishes upward. */\n const cards = (\n <GridItems\n spacing={3}\n items={[\n {\n size: { xs: 12, lg: 5 },\n children: (\n <CardDisplay\n header=\"Details\"\n help={pluginDocsHelp('forms', {\n anchor: '#build-a-form',\n excerpt:\n 'The id is what every submission is filed under, so ' +\n 'renaming a form never splits its history.',\n })}\n HeaderProps={{\n action: (\n <FormDetailCardActions\n section=\"details\"\n dirty={detailsDirty}\n saving={saving}\n onDiscard={() => {\n setName(null)\n setCampaignIds(null)\n }}\n onSave={handleSaveDetails}\n />\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <TextField\n label=\"Display name\"\n size=\"small\"\n value={name ?? form?.displayName ?? ''}\n onChange={(event) => setName(event.target.value)}\n fullWidth\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`ID ${formId} — every submission is filed under this, so it never changes`}\n </Typography>\n {/*\n A FORM IS PART OF A CAMPAIGN, and may be part of several.\n The same signup form is placed by one push and re-placed by\n the next, so this is a multi-select — a single value would\n make filing it under this quarter's campaign silently\n un-file it from last quarter's.\n\n It is an assignment and nothing else: it does not decide who\n a campaign mails, and it does not credit a submission to\n one. Attribution is recorded from the link a visitor\n followed, on its own evidence, and it goes on saying what it\n says whatever is picked here.\n */}\n <ContainerPicker\n kind=\"campaign\"\n options={siteCampaigns.options}\n value={effectiveCampaigns}\n onChange={setCampaignIds}\n helperText=\"The campaigns this form is part of. It does not change who a campaign mails.\"\n empty={siteCampaigns.ready && !siteCampaigns.options.length}\n />\n </Stack>\n </CardDisplay>\n ),\n },\n {\n size: { xs: 12, lg: 7 },\n children: (\n <CardDisplay\n header=\"CRM routing\"\n help={pluginDocsHelp('forms', {\n anchor: '#where-submissions-go',\n excerpt:\n 'Every submission reaches the Inbox and updates the ' +\n 'contact. Lead routing and the consent field decide ' +\n 'what else happens to it.',\n })}\n HeaderProps={{\n action: (\n <FormDetailCardActions\n section=\"routing\"\n dirty={routingDirty}\n saving={saving}\n onDiscard={() => {\n setLead(null)\n setConsentField(null)\n }}\n onSave={handleSaveRouting}\n />\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n {/*\n THE PART THAT IS NOT A SWITCH (AGL-2612). Every capture\n lands in Contacts whatever is set below; the switch decides\n only whether a LEAD is filed beside the contact. Said\n first, because the switch on its own read as the only way\n a submission reached the CRM.\n */}\n <Typography variant=\"body2\">\n {'Every submission with an email address updates the person ' +\n 'in Contacts at stage Lead — a new contact when the ' +\n 'address is new, an interaction on their timeline when it ' +\n 'is not. A customer stays a customer.'}\n </Typography>\n <Stack spacing={0.5}>\n <FormControlLabel\n control={\n <Switch\n checked={effectiveLead}\n onChange={(event) => setLead(event.target.checked)}\n />\n }\n label=\"Also create a lead from the address someone gives this form\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {!hasEmailField\n ? 'Needs an email field in the published design — a ' +\n 'submission without an address cannot key a lead, and ' +\n 'publishing with this on would be refused until one exists.'\n : !capturesConsent\n ? 'Needs a marketing consent field — a lead nobody opted ' +\n 'in with is one the team cannot email, and publishing ' +\n 'with this on would be refused until the field below ' +\n 'names one.'\n : 'Files a lead in CRM → Leads for the sales team to work, ' +\n 'carrying the opt-in the consent field records.'}\n </Typography>\n </Stack>\n <TextField\n select\n label=\"Marketing consent field\"\n size=\"small\"\n value={effectiveConsent}\n onChange={(event) => setConsentField(event.target.value)}\n fullWidth\n helperText=\"The one field that IS the opt-in. Submitting a form is never itself consent.\"\n >\n <MenuItem value=\"\">\n {'None — this form collects no opt-in'}\n </MenuItem>\n {declaredFields.map((field) => (\n <MenuItem key={field.fieldName} value={field.fieldName}>\n {field.label\n ? `${field.label} (${field.fieldName})`\n : field.fieldName}\n </MenuItem>\n ))}\n </TextField>\n {violations.length ? (\n <Alert severity=\"warning\">\n <AlertTitle>{'This form would stop collecting'}</AlertTitle>\n <Stack component=\"ul\" sx={{ pl: 2, m: 0 }}>\n {violations.map((violation) => (\n <Typography\n component=\"li\"\n variant=\"body2\"\n key={`${violation.code}:${violation.nodeId ?? violation.fieldName ?? ''}`}\n >\n {violation.message}\n </Typography>\n ))}\n </Stack>\n </Alert>\n ) : null}\n {/*\n The people this form captured, on the list that holds them.\n Withheld until the site's address resolves, for the reason\n the besigner button is.\n */}\n {contactsHref ? (\n <Typography variant=\"body2\">\n <AppLink href={contactsHref}>\n {'See the contacts this form captured in the CRM'}\n </AppLink>\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n ),\n },\n // Where each field saves on the person: another plugin's card, in a\n // zone this page hosts. No item at all where nothing fills it, so the\n // grid keeps no empty cell.\n ...(ContactFieldsZone && hasContactFieldsWidget\n ? [\n {\n size: { xs: 12 },\n children: (\n <ContactFieldsZone\n slot={FORM_CONTACT_FIELDS_ZONE.id}\n hostId={hostId}\n formId={formId}\n fields={declaredFields}\n loading={status === 'loading'}\n saveFields={saveFields}\n />\n ),\n },\n ]\n : []),\n {\n size: { xs: 12, lg: 5 },\n children: (\n <FormMetricsCard\n stats={form?.stats}\n fields={declaredFields}\n leadRouting={effectiveLead}\n loading={status === 'loading'}\n />\n ),\n },\n {\n size: { xs: 12, lg: 7 },\n children: (\n <CardDisplay\n header=\"Versions\"\n help={pluginDocsHelp('forms', {\n anchor: '#build-a-form',\n excerpt:\n 'Publishing a form version updates every page that ' +\n 'places it. Saving does not — a save is not a publish.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n {promoteRefusal ? (\n <Alert\n severity=\"warning\"\n onClose={() => setPromoteRefusal(null)}\n >\n <AlertTitle>{promoteRefusal.message}</AlertTitle>\n {promoteRefusal.violations.length ? (\n <Stack component=\"ul\" sx={{ pl: 2, m: 0 }}>\n {promoteRefusal.violations.map((violation) => (\n <Typography\n component=\"li\"\n variant=\"body2\"\n key={`${violation.code}:${violation.nodeId ?? violation.fieldName ?? ''}`}\n >\n {violation.message}\n </Typography>\n ))}\n </Stack>\n ) : null}\n </Alert>\n ) : null}\n {versions.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No versions yet — opening the besigner creates the first one.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Version'}</TableCell>\n <TableCell>{'Created'}</TableCell>\n <TableCell>{'Updated'}</TableCell>\n <TableCell align=\"right\">{'Actions'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {versions.map((version: any) => (\n <TableRow key={version.$id} hover>\n <TableCell>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Typography variant=\"body2\">\n {version.displayName ?? version.$id}\n </Typography>\n {version.$id === publishedVersionId ? (\n <Chip\n label=\"Current\"\n color=\"success\"\n size=\"small\"\n />\n ) : null}\n </Stack>\n </TableCell>\n <TableCell>\n {version.createdAt?.toDate?.().toLocaleString() ??\n '--'}\n </TableCell>\n <TableCell>\n {version.updatedAt?.toDate?.().toLocaleString() ??\n '--'}\n </TableCell>\n <TableCell align=\"right\">\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ justifyContent: 'flex-end' }}\n >\n <Button\n size=\"small\"\n disabled={opening || !orgSlug || !host}\n onClick={handleOpen(version.$id)}\n >\n {'Open'}\n </Button>\n {/*\n The version the sites already serve has nothing\n to promote to, so the control is disabled\n rather than absent — an absent control and an\n inapplicable one look identical, and only one\n of them is honest.\n */}\n <Button\n size=\"small\"\n variant=\"outlined\"\n title={canPublish ? undefined : publishBlock}\n disabled={\n !canPublish ||\n promoting !== null ||\n version.$id === publishedVersionId\n }\n onClick={handlePromote(version.$id)}\n >\n {promoting === version.$id\n ? 'Publishing…'\n : version.$id === publishedVersionId\n ? 'Published'\n : 'Publish'}\n </Button>\n </Stack>\n </TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n </Stack>\n </CardDisplay>\n ),\n },\n {\n /*\n THE MESSAGES THEMSELVES, under the numbers that describe them.\n Full width because it is a table of people and what they wrote,\n and it sits below the metrics because those are read at a glance\n and this is read a row at a time.\n */\n size: { xs: 12 },\n children: (\n <FormSubmissionsCard\n hostId={hostId}\n formId={formId}\n formName={form?.displayName}\n />\n ),\n },\n {\n // Full width: the frame is a document, and a document in a\n // five-column card is a column of one-word lines.\n size: { xs: 12 },\n children: (\n <CardDisplay\n header=\"What a submission will carry\"\n help={pluginDocsHelp('forms', {\n anchor: '#field-types',\n excerpt:\n 'Each field arrives under its own name. Two fields ' +\n 'sharing one name arrive as a single answer.',\n })}\n contentGutterX\n contentGutterY\n >\n <FormDesignPreview\n formId={formId}\n nodes={form?.nodes}\n consentFieldName={\n effectiveConsent ? effectiveConsent : undefined\n }\n loading={status === 'loading'}\n />\n </CardDisplay>\n ),\n },\n ]}\n />\n )\n\n return (\n <>\n {/*\n The page chrome this surface cannot set for itself. The console shell\n owns the layout and builds its heading from the Forms nav item, so\n without these the page about one form is headed `Forms` and its trail\n stops on the list — the same on every row of it.\n */}\n <PageHeaderRecord\n title={form ? form.displayName || formId : undefined}\n />\n {/*\n The besigner is what this surface exists to reach, so it leads — in\n the PAGE header, which is where an action belongs on a surface with\n no section rail beneath it. Withheld when there is no form: it would\n mint a version document under an id that has none (AGL-706).\n */}\n <PageHeaderActions>\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={opening || !orgSlug || !host}\n title={\n orgSlug && host ? undefined : 'Resolving this site’s address…'\n }\n onClick={handleOpen()}\n startIcon={\n <MdiIcon color=\"inherit\" path={ICON_VARIANT_BESIGNER.path} />\n }\n >\n {opening ? 'Opening…' : 'Edit in besigner'}\n </Button>\n </PageHeaderActions>\n {cards}\n </>\n )\n}\nFormDetailCard.displayName = 'FormDetailCard'\n\n/** The cards on this page that hold an edit of their own. */\ntype FormDetailSection = 'details' | 'routing'\n\n/**\n * One card's Discard and Save, in that card's header (AGL-3508).\n *\n * Each is disabled until its card holds a change, and both while either card\n * is writing: the two saves touch one document, and a second write landing\n * mid-flight would be judged against a form the first is still changing.\n */\nfunction FormDetailCardActions(props: {\n section: FormDetailSection\n dirty: boolean\n saving: FormDetailSection | null\n onDiscard(): void\n onSave(): void\n}) {\n const { section, dirty, saving, onDiscard, onSave } = props\n return (\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"text\"\n disabled={!dirty || saving !== null}\n onClick={onDiscard}\n >\n {'Discard changes'}\n </Button>\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!dirty || saving !== null}\n onClick={() => void onSave()}\n >\n {saving === section ? 'Saving…' : 'Save'}\n </Button>\n </Stack>\n )\n}\n\n/**\n * The `form` node inside a published design.\n *\n * A form document's tree holds exactly one, because the document IS that\n * form — but the tree is a flat map with a synthetic root, so the node has to\n * be found rather than assumed to be the root itself.\n */\nfunction findFormNodeId(\n nodes: Record<string, { componentId?: string }> | undefined,\n): string | undefined {\n return Object.keys(nodes ?? {}).find(\n (id) => nodes?.[id]?.componentId === 'form',\n )\n}\n\nexport default FormDetailCard\n"],"names":["Aglyn","buildRoute","formFieldsCanYieldAnEmail","formFieldsCaptureConsent","PageHeaderActions","PageHeaderRecord","listConsoleWidgets","pluginDocsHelp","Route","useConsoleWidgetSlot","pluginRecordFilteredHref","ICON_VARIANT_BESIGNER","AppLink","CardDisplay","GridItems","MdiIcon","useConfirmationContext","useLoading","ScrollTable","useSnackbar","Timestamp","Alert","AlertTitle","Button","Chip","FormControlLabel","MenuItem","Stack","Switch","TableBody","TableCell","TableHead","TableRow","TextField","Typography","useConsoleHostRoute","useFirestore","useFirestoreCollection","useFirestoreDoc","useSiteContainerOptions","useHostVersionApi","ContainerPicker","collection","doc","limit","query","updateDoc","useRouter","useCallback","useEffect","useMemo","useRef","useState","FORM_CONTACT_FIELDS_ZONE","FORMS_DOCUMENT_SEGMENT","FormDesignPreview","FormMetricsCard","FormSubmissionsCard","useFormPromoteApi","useFormStatsRecountApi","FormDetailCard","props","name","form","hostId","formId","basePath","canPublish","hostRoleLoaded","firestore","ContactFieldsZone","hasContactFieldsWidget","id","length","saveFields","fields","updatedAt","now","orgSlug","subdomain","host","createHostVersion","promoteForm","recountFormStats","router","enqueueSnackbar","queueLoading","confirm","data","status","idField","notFound","formNodes","decodeStoredNodes","nodes","versionDocs","versions","sort","a","b","createdAt","seconds","publishedVersionId","versionId","setName","lead","setLead","consentField","setConsentField","campaignIds","setCampaignIds","opening","setOpening","promoting","setPromoting","promoteRefusal","setPromoteRefusal","declaredFields","Array","isArray","effectiveLead","routing","effectiveConsent","String","consentFieldName","hasEmailField","capturesConsent","contactsHref","siteCampaigns","enabled","Boolean","storedCampaigns","readContainerIds","effectiveCampaigns","violations","checkFormContract","formNodeId","findFormNodeId","saving","setSaving","handleSaveDetails","dequeue","displayName","trim","formListFields","slug","formCampaignFields","variant","persist","error","console","allowDuplicate","handleSaveRouting","formIds","detailsDirty","containerMembershipUnchanged","routingDirty","dirty","dirtyRef","current","warn","event","preventDefault","returnValue","window","addEventListener","removeEventListener","confirmLeave","title","description","confirmationText","then","catch","handlePromote","targetVersionId","result","ok","message","handleOpen","$id","createResourceUid","kind","parentId","Object","keys","CANVAS_ROOT_ELEMENT_ID","componentId","rootId","push","PLUGIN_DOCUMENT_BESIGNER","documentSegment","docId","publishBlock","header","help","anchor","excerpt","contentGutterX","contentGutterY","spacing","sx","alignItems","severity","href","cards","items","size","xs","lg","children","HeaderProps","action","FormDetailCardActions","section","onDiscard","onSave","label","value","onChange","target","fullWidth","color","options","helperText","empty","ready","control","checked","select","map","field","fieldName","component","pl","m","violation","code","nodeId","slot","loading","stats","leadRouting","onClose","align","version","hover","direction","toDate","toLocaleString","justifyContent","disabled","onClick","undefined","formName","startIcon","path","find"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,SACEC,UAAU,EAEVC,yBAAyB,EACzBC,wBAAwB,EACxBC,iBAAiB,EACjBC,gBAAgB,EAChBC,kBAAkB,EAClBC,cAAc,EACdC,KAAK,QACA,eAAc;AACrB,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,8EAA8E;AAC9E,0EAA0E;AAC1E,0EAA0E;AAC1E,6DAA6D;AAC7D,SAASC,wBAAwB,QAAQ,mDAAkD;AAC3F,SAASC,qBAAqB,QAAQ,2BAA0B;AAChE,SACEC,OAAO,EACPC,WA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,EAAE4E,SAAS,EAAEC,MAAM,EAAE,GAAG1J;IACtD,qBACE,MAAClC;QAAM2N,WAAU;QAAM/C,SAAS;;0BAC9B,KAAChL;gBACCuL,MAAK;gBACL3D,SAAQ;gBACRuG,UAAU,CAAC7F,SAASnB,WAAW;gBAC/BiH,SAASrC;0BAER;;0BAEH,KAAC/L;gBACCuL,MAAK;gBACL3D,SAAQ;gBACR0E,OAAM;gBACN6B,UAAU,CAAC7F,SAASnB,WAAW;gBAC/BiH,SAAS,IAAM,KAAKpC;0BAEnB7E,WAAW2E,UAAU,YAAY;;;;AAI1C;AAEA;;;;;;CAMC,GACD,SAAS5E,eACP3C,KAA2D;IAE3D,OAAOyF,OAAOC,IAAI,CAAC1F,gBAAAA,QAAS,CAAC,GAAGkK,IAAI,CAClC,CAACxL;YAAOsB;eAAAA,CAAAA,0BAAAA,YAAAA,KAAO,CAACtB,GAAG,qBAAXsB,UAAa4F,WAAW,MAAK;;AAEzC;AAEA,eAAe9H,eAAc"}
@@ -1,6 +1,8 @@
1
1
  export interface FormSubmissionsCardProps {
2
2
  hostId: string;
3
3
  formId: string;
4
+ /** The form's name, for the export dialog's "Form: …" filter; the id stands in until it is read. */
5
+ formName?: string;
4
6
  }
5
7
  /**
6
8
  * THE SUBMISSIONS TO ONE FORM — behind an ask, not on mount.
@@ -32,6 +34,16 @@ export interface FormSubmissionsCardProps {
32
34
  *
33
35
  * A workspace with no such plugin loaded has nothing to read them with, and
34
36
  * the card says so rather than offering a button that opens an empty space.
37
+ *
38
+ * ## Export, in the header
39
+ *
40
+ * The console's export dialog, opened on this form's submissions
41
+ * (`forms.submissions`, filtered to `{ formId }`): the person picks this
42
+ * form's questions and the submission's details as columns. It needs no
43
+ * reader plugin — the export reads the collection on the server — so it is
44
+ * offered whether or not the Inbox is on. Export only: a submission is what a
45
+ * visitor sent, so there is no Import beside it. Outside the console shell
46
+ * there is no launcher and no button.
35
47
  */
36
48
  export declare function FormSubmissionsCard(props: FormSubmissionsCardProps): import("react").JSX.Element;
37
49
  export declare namespace FormSubmissionsCard {
@@ -15,11 +15,12 @@
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
17
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
18
- import { listConsoleWidgets, pluginDocsHelp } from "@aglyn/aglyn";
18
+ import { listConsoleWidgets, pluginDocsHelp, useTransferLauncher } from "@aglyn/aglyn";
19
19
  import { useConsoleWidgetSlot } from "@aglyn/aglyn/app-utils/console-widget-slot-context";
20
20
  import { CardDisplay } from "@aglyn/shared-ui-jsx";
21
21
  import { Button, Stack, Typography } from "@mui/material";
22
22
  import { useState } from "react";
23
+ import { FORM_SUBMISSIONS_TRANSFER_KEY } from "../transfer/form-submissions-transfer-key.js";
23
24
  import { FORM_SUBMISSIONS_ZONE } from "./form-zones.js";
24
25
  /**
25
26
  * THE SUBMISSIONS TO ONE FORM — behind an ask, not on mount.
@@ -51,9 +52,20 @@ import { FORM_SUBMISSIONS_ZONE } from "./form-zones.js";
51
52
  *
52
53
  * A workspace with no such plugin loaded has nothing to read them with, and
53
54
  * the card says so rather than offering a button that opens an empty space.
55
+ *
56
+ * ## Export, in the header
57
+ *
58
+ * The console's export dialog, opened on this form's submissions
59
+ * (`forms.submissions`, filtered to `{ formId }`): the person picks this
60
+ * form's questions and the submission's details as columns. It needs no
61
+ * reader plugin — the export reads the collection on the server — so it is
62
+ * offered whether or not the Inbox is on. Export only: a submission is what a
63
+ * visitor sent, so there is no Import beside it. Outside the console shell
64
+ * there is no launcher and no button.
54
65
  */ export function FormSubmissionsCard(props) {
55
- const { hostId, formId } = props;
66
+ const { hostId, formId, formName } = props;
56
67
  const [asked, setAsked] = useState(false);
68
+ const transfer = useTransferLauncher();
57
69
  const Zone = useConsoleWidgetSlot();
58
70
  // Read at render, after the shell has loaded its plugins: whether anything
59
71
  // in this workspace registered a reader for one form's submissions.
@@ -71,6 +83,27 @@ import { FORM_SUBMISSIONS_ZONE } from "./form-zones.js";
71
83
  anchor: '#one-forms-own-page',
72
84
  excerpt: 'The same table the Inbox shows, narrowed to this form, and loaded ' + 'when you ask rather than on every visit to this page.'
73
85
  }),
86
+ HeaderProps: (transfer == null ? void 0 : transfer.can('export', {
87
+ resource: FORM_SUBMISSIONS_TRANSFER_KEY,
88
+ scope: 'host',
89
+ hostId
90
+ })) ? {
91
+ action: /*#__PURE__*/ _jsx(Button, {
92
+ size: "small",
93
+ onClick: ()=>transfer == null ? void 0 : transfer.openExport({
94
+ resource: FORM_SUBMISSIONS_TRANSFER_KEY,
95
+ scope: 'host',
96
+ hostId,
97
+ filter: {
98
+ label: `Form: ${(formName == null ? void 0 : formName.trim()) || formId}`,
99
+ value: {
100
+ formId
101
+ }
102
+ }
103
+ }),
104
+ children: 'Export'
105
+ })
106
+ } : undefined,
74
107
  contentGutterX: true,
75
108
  contentGutterY: true,
76
109
  children: /*#__PURE__*/ _jsxs(Stack, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/components/form-submissions-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { listConsoleWidgets, pluginDocsHelp } from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Stack, Typography } from '@mui/material'\nimport { useState } from 'react'\nimport { FORM_SUBMISSIONS_ZONE } from './form-zones'\n\nexport interface FormSubmissionsCardProps {\n hostId: string\n formId: string\n}\n\n/**\n * THE SUBMISSIONS TO ONE FORM — behind an ask, not on mount.\n *\n * ## Why the reader has to press something\n *\n * `formSubmissions` is the collection that grows without bound and the one\n * the customer is billed on. Every other number on this page is a counter\n * that rode a write which was happening anyway, so opening a form costs the\n * form document and its versions and nothing else — a ceiling\n * `forms-console-read-cost.spec.tsx` asserts in documents.\n *\n * A table that mounted its own paged listener would put a page of that\n * collection on every visit to the surface, including the many visits that\n * are about renaming a form, checking where its submissions route, or\n * publishing a version. None of those asked to read anybody's messages. The\n * ask is one click and it buys a live, paged reader; not asking would buy the\n * same reader for every visit that did not want it.\n *\n * ## Why the reader is a zone, not a table written here\n *\n * The reader this page wants already exists: it walks the collection with\n * `orderBy('createdAt')` and a page window, opens a submission, marks it read,\n * deletes, replies and shows attribution. A second implementation would be a\n * second place for the unordered `limit()` defect to come back. It belongs to\n * the plugin that reads submissions, so this card hosts the\n * `formSubmissions` zone and that plugin draws its reader there, scoped to\n * this form. Neither plugin imports the other.\n *\n * A workspace with no such plugin loaded has nothing to read them with, and\n * the card says so rather than offering a button that opens an empty space.\n */\nexport function FormSubmissionsCard(props: FormSubmissionsCardProps) {\n const { hostId, formId } = props\n const [asked, setAsked] = useState(false)\n const Zone = useConsoleWidgetSlot()\n // Read at render, after the shell has loaded its plugins: whether anything\n // in this workspace registered a reader for one form's submissions.\n const hasReader =\n Zone !== null && listConsoleWidgets(FORM_SUBMISSIONS_ZONE.id).length > 0\n\n if (asked && Zone) {\n return (\n <Zone slot={FORM_SUBMISSIONS_ZONE.id} hostId={hostId} formId={formId} />\n )\n }\n\n return (\n <CardDisplay\n header=\"Submissions to this form\"\n help={pluginDocsHelp('forms', {\n anchor: '#one-forms-own-page',\n excerpt:\n 'The same table the Inbox shows, narrowed to this form, and loaded ' +\n 'when you ask rather than on every visit to this page.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The messages this form collected, newest first. Reading them is ' +\n 'a query over the submissions collection, so it runs when you ' +\n 'ask rather than on every visit to this page.'}\n </Typography>\n {hasReader ? (\n <Button variant=\"outlined\" size=\"small\" onClick={() => setAsked(true)}>\n {'Show submissions'}\n </Button>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Submissions are read in the Inbox, which is switched off for ' +\n 'this workspace or this site. They are still being collected.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nFormSubmissionsCard.displayName = 'FormSubmissionsCard'\n\nexport default FormSubmissionsCard\n"],"names":["listConsoleWidgets","pluginDocsHelp","useConsoleWidgetSlot","CardDisplay","Button","Stack","Typography","useState","FORM_SUBMISSIONS_ZONE","FormSubmissionsCard","props","hostId","formId","asked","setAsked","Zone","hasReader","id","length","slot","header","help","anchor","excerpt","contentGutterX","contentGutterY","spacing","sx","alignItems","variant","color","size","onClick","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,kBAAkB,EAAEC,cAAc,QAAQ,eAAc;AACjE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,MAAM,EAAEC,KAAK,EAAEC,UAAU,QAAQ,gBAAe;AACzD,SAASC,QAAQ,QAAQ,QAAO;AAChC,SAASC,qBAAqB,QAAQ,kBAAc;AAOpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GACD,OAAO,SAASC,oBAAoBC,KAA+B;IACjE,MAAM,EAAEC,MAAM,EAAEC,MAAM,EAAE,GAAGF;IAC3B,MAAM,CAACG,OAAOC,SAAS,GAAGP,SAAS;IACnC,MAAMQ,OAAOb;IACb,2EAA2E;IAC3E,oEAAoE;IACpE,MAAMc,YACJD,SAAS,QAAQf,mBAAmBQ,sBAAsBS,EAAE,EAAEC,MAAM,GAAG;IAEzE,IAAIL,SAASE,MAAM;QACjB,qBACE,KAACA;YAAKI,MAAMX,sBAAsBS,EAAE;YAAEN,QAAQA;YAAQC,QAAQA;;IAElE;IAEA,qBACE,KAACT;QACCiB,QAAO;QACPC,MAAMpB,eAAe,SAAS;YAC5BqB,QAAQ;YACRC,SACE,uEACA;QACJ;QACAC,cAAc;QACdC,cAAc;kBAEd,cAAA,MAACpB;YAAMqB,SAAS;YAAGC,IAAI;gBAAEC,YAAY;YAAa;;8BAChD,KAACtB;oBAAWuB,SAAQ;oBAAQC,OAAM;8BAC/B,qEACC,kEACA;;gBAEHd,0BACC,KAACZ;oBAAOyB,SAAQ;oBAAWE,MAAK;oBAAQC,SAAS,IAAMlB,SAAS;8BAC7D;mCAGH,KAACR;oBAAWuB,SAAQ;oBAAQC,OAAM;8BAC/B,kEACC;;;;;AAMd;AACArB,oBAAoBwB,WAAW,GAAG;AAElC,eAAexB,oBAAmB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/components/form-submissions-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { listConsoleWidgets, pluginDocsHelp, useTransferLauncher } from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { Button, Stack, Typography } from '@mui/material'\nimport { useState } from 'react'\nimport { FORM_SUBMISSIONS_TRANSFER_KEY } from '../transfer/form-submissions-transfer-key'\nimport { FORM_SUBMISSIONS_ZONE } from './form-zones'\n\nexport interface FormSubmissionsCardProps {\n hostId: string\n formId: string\n /** The form's name, for the export dialog's \"Form: …\" filter; the id stands in until it is read. */\n formName?: string\n}\n\n/**\n * THE SUBMISSIONS TO ONE FORM — behind an ask, not on mount.\n *\n * ## Why the reader has to press something\n *\n * `formSubmissions` is the collection that grows without bound and the one\n * the customer is billed on. Every other number on this page is a counter\n * that rode a write which was happening anyway, so opening a form costs the\n * form document and its versions and nothing else — a ceiling\n * `forms-console-read-cost.spec.tsx` asserts in documents.\n *\n * A table that mounted its own paged listener would put a page of that\n * collection on every visit to the surface, including the many visits that\n * are about renaming a form, checking where its submissions route, or\n * publishing a version. None of those asked to read anybody's messages. The\n * ask is one click and it buys a live, paged reader; not asking would buy the\n * same reader for every visit that did not want it.\n *\n * ## Why the reader is a zone, not a table written here\n *\n * The reader this page wants already exists: it walks the collection with\n * `orderBy('createdAt')` and a page window, opens a submission, marks it read,\n * deletes, replies and shows attribution. A second implementation would be a\n * second place for the unordered `limit()` defect to come back. It belongs to\n * the plugin that reads submissions, so this card hosts the\n * `formSubmissions` zone and that plugin draws its reader there, scoped to\n * this form. Neither plugin imports the other.\n *\n * A workspace with no such plugin loaded has nothing to read them with, and\n * the card says so rather than offering a button that opens an empty space.\n *\n * ## Export, in the header\n *\n * The console's export dialog, opened on this form's submissions\n * (`forms.submissions`, filtered to `{ formId }`): the person picks this\n * form's questions and the submission's details as columns. It needs no\n * reader plugin — the export reads the collection on the server — so it is\n * offered whether or not the Inbox is on. Export only: a submission is what a\n * visitor sent, so there is no Import beside it. Outside the console shell\n * there is no launcher and no button.\n */\nexport function FormSubmissionsCard(props: FormSubmissionsCardProps) {\n const { hostId, formId, formName } = props\n const [asked, setAsked] = useState(false)\n const transfer = useTransferLauncher()\n const Zone = useConsoleWidgetSlot()\n // Read at render, after the shell has loaded its plugins: whether anything\n // in this workspace registered a reader for one form's submissions.\n const hasReader =\n Zone !== null && listConsoleWidgets(FORM_SUBMISSIONS_ZONE.id).length > 0\n\n if (asked && Zone) {\n return (\n <Zone slot={FORM_SUBMISSIONS_ZONE.id} hostId={hostId} formId={formId} />\n )\n }\n\n return (\n <CardDisplay\n header=\"Submissions to this form\"\n help={pluginDocsHelp('forms', {\n anchor: '#one-forms-own-page',\n excerpt:\n 'The same table the Inbox shows, narrowed to this form, and loaded ' +\n 'when you ask rather than on every visit to this page.',\n })}\n HeaderProps={\n transfer?.can('export', { resource: FORM_SUBMISSIONS_TRANSFER_KEY, scope: 'host', hostId })\n ? {\n action: (\n <Button\n size=\"small\"\n onClick={() =>\n transfer?.openExport({\n resource: FORM_SUBMISSIONS_TRANSFER_KEY,\n scope: 'host',\n hostId,\n filter: { label: `Form: ${formName?.trim() || formId}`, value: { formId } },\n })\n }\n >\n {'Export'}\n </Button>\n ),\n }\n : undefined\n }\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'The messages this form collected, newest first. Reading them is ' +\n 'a query over the submissions collection, so it runs when you ' +\n 'ask rather than on every visit to this page.'}\n </Typography>\n {hasReader ? (\n <Button variant=\"outlined\" size=\"small\" onClick={() => setAsked(true)}>\n {'Show submissions'}\n </Button>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Submissions are read in the Inbox, which is switched off for ' +\n 'this workspace or this site. They are still being collected.'}\n </Typography>\n )}\n </Stack>\n </CardDisplay>\n )\n}\nFormSubmissionsCard.displayName = 'FormSubmissionsCard'\n\nexport default FormSubmissionsCard\n"],"names":["listConsoleWidgets","pluginDocsHelp","useTransferLauncher","useConsoleWidgetSlot","CardDisplay","Button","Stack","Typography","useState","FORM_SUBMISSIONS_TRANSFER_KEY","FORM_SUBMISSIONS_ZONE","FormSubmissionsCard","props","hostId","formId","formName","asked","setAsked","transfer","Zone","hasReader","id","length","slot","header","help","anchor","excerpt","HeaderProps","can","resource","scope","action","size","onClick","openExport","filter","label","trim","value","undefined","contentGutterX","contentGutterY","spacing","sx","alignItems","variant","color","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,kBAAkB,EA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QAENC,cAAc;QACdC,cAAc;kBAEd,cAAA,MAACpC;YAAMqC,SAAS;YAAGC,IAAI;gBAAEC,YAAY;YAAa;;8BAChD,KAACtC;oBAAWuC,SAAQ;oBAAQC,OAAM;8BAC/B,qEACC,kEACA;;gBAEH3B,0BACC,KAACf;oBAAOyC,SAAQ;oBAAWb,MAAK;oBAAQC,SAAS,IAAMjB,SAAS;8BAC7D;mCAGH,KAACV;oBAAWuC,SAAQ;oBAAQC,OAAM;8BAC/B,kEACC;;;;;AAMd;AACApC,oBAAoBqC,WAAW,GAAG;AAElC,eAAerC,oBAAmB"}
@@ -20,6 +20,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
20
20
  import { trackEventBeforeNavigation } from "@aglyn/aglyn/app-utils/analytics-events";
21
21
  import { utmTouchField } from "@aglyn/aglyn/app-utils/utm-touch";
22
22
  import * as Aglyn from "@aglyn/aglyn";
23
+ import { parseFormUnavailableRefusal } from "../model/form-unavailable.js";
23
24
  import { mdiEmailFastOutline, mdiEmailOutline, mdiFormTextbox } from "@aglyn/shared-data-mdi";
24
25
  import { isSameOriginPath } from "@aglyn/shared-util-http/safe-redirect";
25
26
  import Alert from "@mui/material/Alert";
@@ -388,7 +389,7 @@ const REVEAL_NODE_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
388
389
  // exactly that reason. A plan-wall 429 keeps falling through to
389
390
  // the generic branch below, which is right: it is the owner's
390
391
  // billing problem, and nothing about waiting fixes it.
391
- const notice = Aglyn.parseFormUnavailableRefusal(body);
392
+ const notice = parseFormUnavailableRefusal(body);
392
393
  if (notice) {
393
394
  setUnavailable(notice);
394
395
  setStatus('unavailable');