Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add number, dropdown and radio button fields
Claude7d600477681a
diff --git a/db/migrations/20261114130000_more_field_types.sql b/db/migrations/20261114130000_more_field_types.sqlnew file mode 100644index 0000000..0893eec--- /dev/null+++ b/db/migrations/20261114130000_more_field_types.sql@@ -0,0 +1,48 @@+-- Three more kinds of field: a number, a dropdown and a radio button.+--+-- A dropdown carries its list of choices in `options`. Radio buttons are+-- placed one by one, each its own row, and the buttons that belong together+-- share a `group_id`; the signer picks one button in each group. The name+-- of a radio button is its `label`.++alter table public.fields+ drop constraint if exists fields_type_check;++alter table public.fields+ add constraint fields_type_check check (+ type in (+ 'signature',+ 'initials',+ 'date',+ 'text',+ 'checkbox',+ 'number',+ 'dropdown',+ 'radio'+ )+ );++alter table public.fields+ add column if not exists options jsonb,+ add column if not exists group_id text;++alter table public.fields+ drop constraint if exists fields_options_only_on_dropdowns;++alter table public.fields+ add constraint fields_options_only_on_dropdowns check (+ options is null+ or (type = 'dropdown' and jsonb_typeof(options) = 'array')+ );++alter table public.fields+ drop constraint if exists fields_group_only_on_radios;++alter table public.fields+ add constraint fields_group_only_on_radios check (+ (type = 'radio') = (group_id is not null)+ );++create index if not exists idx_fields_envelope_group+ on public.fields(envelope_id, group_id)+ where group_id is not null;diff --git a/src/components/envelopes/interactive-placed-field.tsx b/src/components/envelopes/interactive-placed-field.tsxindex 2ef9e21..70abb50 100644--- a/src/components/envelopes/interactive-placed-field.tsx+++ b/src/components/envelopes/interactive-placed-field.tsx@@ -83,7 +83,8 @@ export function InteractivePlacedField({}: InteractivePlacedFieldProps) {const gestureRef = useRef<PointerGesture | null>(null);const percentMultiplier = 100 / coordinateScale;- const isCheckbox = field.type === "checkbox";+ const isRadio = field.type === "radio";+ const isCheckbox = field.type === "checkbox" || isRadio;const showInlineLabel =!isCheckbox &&field.width >= compactFieldWidthThreshold &&@@ -209,7 +210,7 @@ export function InteractivePlacedField({isSelected? "ring-4 ring-[rgba(28,29,43,0.10)]": "hover:ring-2 hover:ring-[rgba(28,29,43,0.08)]"- } cursor-grab ${isCheckbox ? "rounded-[0.25rem] p-0" : "rounded-[0.375rem] px-2 py-1"}`}+ } cursor-grab ${isRadio ? "rounded-full p-0" : isCheckbox ? "rounded-[0.25rem] p-0" : "rounded-[0.375rem] px-2 py-1"}`}onKeyDown={handleKeyboardSelect}onPointerCancel={endGesture}onPointerDown={(event) => beginGesture(event, "move")}diff --git a/src/components/envelopes/prepare-live-shell.tsx b/src/components/envelopes/prepare-live-shell.tsxindex b3114a9..c8cb08d 100644--- a/src/components/envelopes/prepare-live-shell.tsx+++ b/src/components/envelopes/prepare-live-shell.tsx@@ -3,13 +3,17 @@import {CalendarIcon,CaseSensitiveIcon,+ CircleDotIcon,+ HashIcon,SignatureIcon,SquareCheckIcon,+ SquareChevronDownIcon,TypeIcon,type LucideIcon,} from "lucide-react";import {useEffect,+ useId,useRef,useState,type Dispatch,@@ -20,6 +24,14 @@ import {} from "react";import { type PrepareEnvelopeData } from "@/lib/envelopes";+import {+ describeChoiceFieldProblem,+ findChoiceFieldProblem,+ MAX_FIELD_OPTIONS,+ MAX_FIELD_OPTION_LENGTH,+ MAX_RADIO_GROUP_BUTTONS,+ parseOptionLines,+} from "@/lib/field-choices";import {type FieldPlacement,type ReplaceFieldsResponse,@@ -64,9 +76,11 @@ type PrepareField = FieldPlacement & {};type LiveFieldSource = Array<{+ groupId?: string;height: number;id: string;label?: string;+ options?: string[];page: number;required: boolean;signerId: string;@@ -111,7 +125,12 @@ type FieldToolButtonProps = {type FieldEditorProps = {field: PrepareField;+ /** How many radio buttons share this field's group, itself included. */+ groupSize: number;+ onAddRadioButton: () => void;onDelete: () => void;+ onSetLabel: (label: string | undefined) => void;+ onSetOptions: (options: string[]) => void;onSetRequired: (required: boolean) => void;onSignerChange: (signerId: string) => void;signers: readonly PrepareShellSigner[];@@ -168,8 +187,67 @@ const fieldTools: readonly FieldTool[] = [placeholderLabel: "Checkbox",type: "checkbox",},+ {+ defaultHeight: 0.045,+ defaultWidth: 0.16,+ label: "Number",+ minHeight: 0.0045,+ minWidth: 0.006,+ placeholderLabel: "Number",+ type: "number",+ },+ {+ defaultHeight: 0.045,+ defaultWidth: 0.22,+ label: "Dropdown",+ minHeight: 0.0045,+ minWidth: 0.006,+ placeholderLabel: "Dropdown",+ type: "dropdown",+ },+ {+ defaultHeight: 0.023,+ defaultWidth: 0.03,+ label: "Radio button",+ minHeight: 0.0045,+ minWidth: 0.006,+ placeholderLabel: "Radio button",+ type: "radio",+ },] as const;+// Fields the sender may leave optional. A signature, initials and the date+// are always needed.+function canBeOptional(type: PrepareFieldType) {+ return (+ type === "text" ||+ type === "checkbox" ||+ type === "number" ||+ type === "dropdown" ||+ type === "radio"+ );+}++/** The fields that change together with this one: its radio group, or itself. */+function isSameChoice(field: PrepareField, other: PrepareField) {+ return (+ field.id === other.id ||+ (field.type === "radio" &&+ other.type === "radio" &&+ field.groupId !== undefined &&+ field.groupId === other.groupId)+ );+}++/** An id for a radio group, or for a button added to one. */+function newLocalId() {+ return typeof window !== "undefined" &&+ "crypto" in window &&+ typeof window.crypto.randomUUID === "function"+ ? window.crypto.randomUUID()+ : `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+}+const genericSubmitError = "Something went wrong. Please try again.";const autosaveDelayMs = 450;@@ -192,9 +270,11 @@ function buildLiveFields(fields: LiveFieldSource | PrepareEnvelopeData["fields"],) {return fields.map((field, index) => ({+ groupId: field.groupId,height: field.height,id: field.id ?? `field-${index + 1}`,label: field.label,+ options: field.options ? [...field.options] : undefined,page: field.page,required: field.required,signerId: field.signerId,@@ -249,9 +329,11 @@ function clearSelectedFieldFromViewportClick(function buildFieldRequest(fields: readonly PrepareField[]) {return {fields: fields.map((field) => ({+ groupId: field.type === "radio" ? field.groupId : undefined,height: roundNormalized(field.height),id: field.id,label: field.label,+ options: field.type === "dropdown" ? (field.options ?? []) : undefined,page: field.page,required: field.required,signerId: field.signerId,@@ -398,7 +480,38 @@ function PrepareLiveShellContent({(field) => field.signerId === signer.id && field.type === "signature",),);- const canContinue = missingSignatureSigner == null;+ // A dropdown without choices, or a radio button on its own, can be saved+ // in a draft but not sent.+ const choiceProblem = findChoiceFieldProblem(fields);+ const choiceProblemMessage = choiceProblem+ ? describeChoiceFieldProblem(+ choiceProblem,+ signers.find((signer) => signer.id === choiceProblem.signerId)?.name ??+ "a signer",+ )+ : null;+ const canContinue = missingSignatureSigner == null && choiceProblem == null;+ const selectedGroupSize = selectedField+ ? fields.filter((field) => isSameChoice(selectedField, field)).length+ : 0;+ const fieldEditorActions = selectedField+ ? {+ onAddRadioButton: () =>+ addRadioButton(selectedField.id, setFields, setSelectedFieldId),+ onDelete: () =>+ deleteField(selectedField.id, setFields, setSelectedFieldId),+ onSetLabel: (label: string | undefined) =>+ updateField(selectedField.id, { label }, setFields),+ onSetOptions: (options: string[]) =>+ updateField(selectedField.id, { options }, setFields),+ onSetRequired: (required: boolean) =>+ setFieldRequired(selectedField.id, required, setFields),+ onSignerChange: (signerId: string) => {+ setSelectedSignerId(signerId);+ reassignField(selectedField.id, signerId, setFields);+ },+ }+ : null;useEffect(() => {let isActive = true;@@ -806,6 +919,13 @@ function PrepareLiveShellContent({</div></div>+ {/* Not a status region: the page has one, for "Saved". */}+ {choiceProblemMessage ? (+ <p aria-live="polite" className="notice notice-warning">+ {choiceProblemMessage}+ </p>+ ) : null}+<div className="panel overflow-hidden rounded-[1.25rem]"><divclassName={`relative overflow-auto p-3 sm:p-6 ${@@ -900,7 +1020,11 @@ function PrepareLiveShellContent({field={field}isSelected={selectedField?.id === field.id}key={field.id}- label={getFieldTool(field.type).placeholderLabel}+ label={+ field.type === "radio" && field.label+ ? `Radio button: ${field.label}`+ : getFieldTool(field.type).placeholderLabel+ }onInteractionChange={setIsFieldInteracting}onMove={(deltaX, deltaY) =>moveField(field.id, deltaX, deltaY, setFields)@@ -948,20 +1072,13 @@ function PrepareLiveShellContent({</div></div>- {selectedField ? (+ {selectedField && fieldEditorActions ? (<div className="panel rounded-[1.25rem] p-4 lg:hidden"><FieldEditor+ {...fieldEditorActions}field={selectedField}- onDelete={() =>- deleteField(selectedField.id, setFields, setSelectedFieldId)- }- onSetRequired={(required) =>- setFieldRequired(selectedField.id, required, setFields)- }- onSignerChange={(signerId) => {- setSelectedSignerId(signerId);- reassignField(selectedField.id, signerId, setFields);- }}+ groupSize={selectedGroupSize}+ key={selectedField.id}signers={signers}/></div>@@ -980,23 +1097,12 @@ function PrepareLiveShellContent({<section className="panel space-y-3 rounded-[1.25rem] p-4"><p className="section-eyebrow px-1">Inspector</p><div>- {selectedField ? (+ {selectedField && fieldEditorActions ? (<FieldEditor+ {...fieldEditorActions}field={selectedField}- onDelete={() =>- deleteField(- selectedField.id,- setFields,- setSelectedFieldId,- )- }- onSetRequired={(required) =>- setFieldRequired(selectedField.id, required, setFields)- }- onSignerChange={(signerId) => {- setSelectedSignerId(signerId);- reassignField(selectedField.id, signerId, setFields);- }}+ groupSize={selectedGroupSize}+ key={selectedField.id}signers={signers}/>) : (@@ -1069,7 +1175,10 @@ function PrepareLiveShellContent({const fieldToolIcons: Record<PrepareFieldType, LucideIcon> = {checkbox: SquareCheckIcon,date: CalendarIcon,+ dropdown: SquareChevronDownIcon,initials: CaseSensitiveIcon,+ number: HashIcon,+ radio: CircleDotIcon,signature: SignatureIcon,text: TypeIcon,};@@ -1295,13 +1404,31 @@ function SaveStatusIndicator({function FieldEditor({field,+ groupSize,+ onAddRadioButton,onDelete,+ onSetLabel,+ onSetOptions,onSetRequired,onSignerChange,signers,}: FieldEditorProps) {const tool = getFieldTool(field.type);- const isOptionalField = field.type === "text" || field.type === "checkbox";+ const isOptionalField = canBeOptional(field.type);+ // What is being typed, kept as typed. The field itself holds the tidied+ // value, and saving hands that back; without a copy of its own the box+ // would lose a trailing space or an empty line in mid-thought. The editor+ // is keyed by field, so these start again for each one.+ const [labelDraft, setLabelDraft] = useState(field.label ?? "");+ const [optionsDraft, setOptionsDraft] = useState(+ (field.options ?? []).join("\n"),+ );+ const optionCount = field.options?.length ?? 0;+ // The editor is on the page twice, once for narrow screens and once in+ // the side panel, so its inputs cannot share fixed ids.+ const editorId = useId();+ const optionsId = `${editorId}-options`;+ const labelId = `${editorId}-label`;return (<section aria-label="Field settings" role="region">@@ -1345,10 +1472,88 @@ function FieldEditor({</div></div>+ {field.type === "dropdown" ? (+ <div>+ <label+ className="block px-1 text-[0.8125rem] font-semibold text-(--secondary)"+ htmlFor={optionsId}+ >+ Choices+ </label>+ <textarea+ aria-describedby={`${optionsId}-help`}+ className="field-input mt-2 min-h-32 resize-y leading-6"+ id={optionsId}+ onChange={(event) => {+ setOptionsDraft(event.target.value);+ onSetOptions(parseOptionLines(event.target.value));+ }}+ placeholder={"Yes\nNo\nNot sure"}+ spellCheck={false}+ value={optionsDraft}+ />+ <p+ className={`mt-1.5 px-1 text-xs leading-5 ${+ optionCount < 2+ ? "font-semibold text-(--warning)"+ : "text-(--tertiary)"+ }`}+ id={`${optionsId}-help`}+ >+ {optionCount < 2+ ? "One choice per line. Add at least two."+ : `One choice per line. ${String(optionCount)} of up to ${String(MAX_FIELD_OPTIONS)}. The signer picks one.`}+ </p>+ </div>+ ) : null}++ {field.type === "radio" ? (+ <div>+ <label+ className="block px-1 text-[0.8125rem] font-semibold text-(--secondary)"+ htmlFor={labelId}+ >+ What this button means+ </label>+ <input+ aria-describedby={`${labelId}-help`}+ className="field-input mt-2"+ id={labelId}+ maxLength={MAX_FIELD_OPTION_LENGTH}+ onChange={(event) => {+ setLabelDraft(event.target.value);+ onSetLabel(event.target.value.trim() || undefined);+ }}+ placeholder="Yes"+ value={labelDraft}+ />+ <p+ className={`mt-1.5 px-1 text-xs leading-5 ${+ groupSize < 2+ ? "font-semibold text-(--warning)"+ : "text-(--tertiary)"+ }`}+ id={`${labelId}-help`}+ >+ {groupSize < 2+ ? "A radio button needs at least one more in its group."+ : `${String(groupSize)} buttons in this group. The signer picks one.`}+ </p>+ <button+ className="btn-quiet mt-2 w-full"+ disabled={groupSize >= MAX_RADIO_GROUP_BUTTONS}+ onClick={onAddRadioButton}+ type="button"+ >+ + Add a button to this group+ </button>+ </div>+ ) : null}+{isOptionalField ? (<div><p className="px-1 text-[0.8125rem] font-semibold text-(--secondary)">- Required+ {field.type === "radio" ? "Required (whole group)" : "Required"}</p><div className="segmented mt-2 flex w-full">{[@@ -1423,13 +1628,22 @@ function placeField(fieldCounterRef.current += 1;const nextField: PrepareField = {...nextRect,+ // A radio button starts a group of its own; more are added from the+ // inspector.+ groupId: tool.type === "radio" ? newLocalId() : undefined,id:typeof window !== "undefined" && "crypto" in window? window.crypto.randomUUID(): `field-${fieldCounterRef.current}`,- label: undefined,+ label: tool.type === "radio" ? "Option 1" : undefined,+ options: tool.type === "dropdown" ? [] : undefined,page: activePage,- required: tool.type === "text" || tool.type === "checkbox" ? false : true,+ // Text, number and checkbox fields start optional; a dropdown or a+ // group of radio buttons is usually a question that needs an answer.+ required:+ tool.type === "text" || tool.type === "number" || tool.type === "checkbox"+ ? false+ : true,signerId: selectedSignerId,type: tool.type,};@@ -1443,14 +1657,72 @@ function reassignField(fieldId: string,signerId: string,setFields: Dispatch<SetStateAction<PrepareField[]>>,+) {+ setFields((currentFields) => {+ const target = currentFields.find((field) => field.id === fieldId);++ // The buttons of a radio group are answered by one person.+ return currentFields.map((field) =>+ target && isSameChoice(target, field) ? { ...field, signerId } : field,+ );+ });+}++function updateField(+ fieldId: string,+ patch: Pick<Partial<PrepareField>, "label" | "options">,+ setFields: Dispatch<SetStateAction<PrepareField[]>>,) {setFields((currentFields) =>currentFields.map((field) =>- field.id === fieldId ? { ...field, signerId } : field,+ field.id === fieldId ? { ...field, ...patch } : field,),);}+/** Adds a radio button just below this one, in the same group. */+function addRadioButton(+ fieldId: string,+ setFields: Dispatch<SetStateAction<PrepareField[]>>,+ setSelectedFieldId: Dispatch<SetStateAction<string | null>>,+) {+ const nextId = newLocalId();++ setFields((currentFields) => {+ const source = currentFields.find((field) => field.id === fieldId);++ if (!source || source.type !== "radio" || !source.groupId) {+ return currentFields;+ }++ const group = currentFields.filter((field) => isSameChoice(source, field));++ if (+ group.length >= MAX_RADIO_GROUP_BUTTONS ||+ currentFields.some((field) => field.id === nextId)+ ) {+ return currentFields;+ }++ // Below the lowest button of the group on this page, or as low as the+ // page allows.+ const lowest = group+ .filter((field) => field.page === source.page)+ .reduce((bottom, field) => Math.max(bottom, field.y), source.y);++ return [+ ...currentFields,+ {+ ...source,+ id: nextId,+ label: `Option ${String(group.length + 1)}`,+ y: Math.min(1 - source.height, lowest + source.height * 1.6),+ },+ ];+ });+ setSelectedFieldId(nextId);+}+function moveField(fieldId: string,deltaX: number,@@ -1518,20 +1790,18 @@ function setFieldRequired(setFields: Dispatch<SetStateAction<PrepareField[]>>,) {setFields((currentFields) =>- currentFields.map((field) => {- if (field.id !== fieldId) {- return field;- }+ {+ const target = currentFields.find((field) => field.id === fieldId);- if (field.type !== "text" && field.type !== "checkbox") {- return field;+ if (!target || !canBeOptional(target.type)) {+ return currentFields;}- return {- ...field,- required,- };- }),+ // A radio group is required or optional as a whole.+ return currentFields.map((field) =>+ isSameChoice(target, field) ? { ...field, required } : field,+ );+ },);}diff --git a/src/components/envelopes/review-shell.tsx b/src/components/envelopes/review-shell.tsxindex 92ee3bc..8982011 100644--- a/src/components/envelopes/review-shell.tsx+++ b/src/components/envelopes/review-shell.tsx@@ -46,7 +46,14 @@ type ReviewRecordView = {};type ReviewFieldSummaryLabel =- "Checkbox" | "Date" | "Initials" | "Signature" | "Text";+ | "Dropdown"+ | "Number"+ | "Radio group"+ | "Checkbox"+ | "Date"+ | "Initials"+ | "Signature"+ | "Text";type ReviewSigner = {color?: string;diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsxindex 88f614f..48b8b96 100644--- a/src/components/signing/signing-live-shell.tsx+++ b/src/components/signing/signing-live-shell.tsx@@ -47,6 +47,11 @@ import {type SigningVisibleField,} from "@/lib/schemas/signing";import { type SigningSubmission } from "@/lib/schemas/field";+import {+ countAnswerableFields,+ isNumberEntry,+ NUMBER_ENTRY_MESSAGE,+} from "@/lib/field-choices";const typedSignatureFont ='"Snell Roundhand", "Brush Script MT", "Segoe Script", cursive';@@ -134,6 +139,12 @@ function getCanvasFieldLabel(return "Text";case "checkbox":return "Checkbox";+ case "number":+ return "Number";+ case "dropdown":+ return "Choose";+ case "radio":+ return "Option";default:return "Field";}@@ -167,11 +178,49 @@ function getFieldLabel(return "Enter text";case "checkbox":return "Checkbox";+ case "number":+ return "Enter a number";+ case "dropdown":+ return "Choose one";+ case "radio":+ return "Option";default:return "Field";}}+/** The values the signer has entered so far, by field. */+type EnteredValues = {+ /** Checkboxes and radio buttons. */+ checkboxValues: Record<string, boolean>;+ signatureValues: Record<string, SignatureEntry>;+ /** Text, number and dropdown fields. */+ textValues: Record<string, string>;+};++/** The radio buttons that are answered together with this one. */+function getRadioGroup(+ field: SigningCurrentField,+ fields: readonly SigningCurrentField[],+) {+ return fields.filter(+ (other) =>+ other.type === "radio" &&+ (other.id === field.id ||+ (field.groupId !== undefined && other.groupId === field.groupId)),+ );+}++/** A number field holding something that is not a number. */+function hasInvalidNumber(+ field: SigningCurrentField,+ textValues: Record<string, string>,+) {+ const value = (textValues[field.id] ?? "").trim();++ return field.type === "number" && value.length > 0 && !isNumberEntry(value);+}+function getSummaryLabel(field: SigningCurrentField) {switch (field.type) {case "signature":@@ -184,6 +233,12 @@ function getSummaryLabel(field: SigningCurrentField) {return "Text input";case "checkbox":return "Checkbox";+ case "number":+ return "Number";+ case "dropdown":+ return "Dropdown";+ case "radio":+ return "Choice";default:return "Field";}@@ -194,11 +249,15 @@ function isActionSummaryField(field: SigningCurrentField) {return true;}- if (field.type === "text") {+ if (+ field.type === "text" ||+ field.type === "number" ||+ field.type === "dropdown"+ ) {return true;}- if (field.type === "checkbox") {+ if (field.type === "checkbox" || field.type === "radio") {return field.required;}@@ -207,17 +266,13 @@ function isActionSummaryField(field: SigningCurrentField) {function getCompletionValue(field: SigningCurrentField,+ fields: readonly SigningCurrentField[],{checkboxValues,localDateLabel,signatureValues,textValues,- }: {- checkboxValues: Record<string, boolean>;- localDateLabel: string;- signatureValues: Record<string, SignatureEntry>;- textValues: Record<string, string>;- },+ }: EnteredValues & { localDateLabel: string },) {if (field.type === "signature" || field.type === "initials") {return signatureValues[field.id]?.value ?? "Tap to sign";@@ -227,30 +282,49 @@ function getCompletionValue(return textValues[field.id]?.trim() || "Enter text";}+ if (field.type === "number") {+ return hasInvalidNumber(field, textValues)+ ? "Not a number"+ : textValues[field.id]?.trim() || "Enter a number";+ }++ if (field.type === "dropdown") {+ return textValues[field.id]?.trim() || "Choose one";+ }+if (field.type === "checkbox") {return checkboxValues[field.id] ? "Checked" : "Optional";}+ if (field.type === "radio") {+ const chosen = getRadioGroup(field, fields).find(+ (button) => checkboxValues[button.id],+ );++ return chosen ? getFieldLabel(chosen) : "Choose one";+ }+return localDateLabel;}function isFieldComplete(field: SigningCurrentField,- {- checkboxValues,- signatureValues,- textValues,- }: {- checkboxValues: Record<string, boolean>;- signatureValues: Record<string, SignatureEntry>;- textValues: Record<string, string>;- },+ fields: readonly SigningCurrentField[],+ { checkboxValues, signatureValues, textValues }: EnteredValues,) {if (field.type === "signature" || field.type === "initials") {return Boolean(signatureValues[field.id]?.value);}- if (field.type === "text") {+ if (field.type === "number" && hasInvalidNumber(field, textValues)) {+ return false;+ }++ if (+ field.type === "text" ||+ field.type === "number" ||+ field.type === "dropdown"+ ) {if (!field.required) {return true;}@@ -266,11 +340,22 @@ function isFieldComplete(return Boolean(checkboxValues[field.id]);}+ if (field.type === "radio") {+ if (!field.required) {+ return true;+ }++ // One chosen button answers for the whole group.+ return getRadioGroup(field, fields).some(+ (button) => checkboxValues[button.id],+ );+ }+return true;}function getVisibleFieldValue(field: SigningVisibleField) {- if (field.type === "checkbox") {+ if (field.type === "checkbox" || field.type === "radio") {return field.checked ? "Checked" : "Unchecked";}@@ -279,15 +364,7 @@ function getVisibleFieldValue(field: SigningVisibleField) {function buildSigningSubmissionPayload(record: SigningPayload,- {- checkboxValues,- signatureValues,- textValues,- }: {- checkboxValues: Record<string, boolean>;- signatureValues: Record<string, SignatureEntry>;- textValues: Record<string, string>;- },+ { checkboxValues, signatureValues, textValues }: EnteredValues,): SigningSubmission {const fields: SigningSubmission["fields"] = [];@@ -318,13 +395,17 @@ function buildSigningSubmissionPayload(continue;}- if (field.type === "text") {+ if (+ field.type === "text" ||+ field.type === "number" ||+ field.type === "dropdown"+ ) {const value = textValues[field.id]?.trim();if (value) {fields.push({fieldId: field.id,- type: "text",+ type: field.type,value,});}@@ -332,11 +413,11 @@ function buildSigningSubmissionPayload(continue;}- if (field.type === "checkbox") {+ if (field.type === "checkbox" || field.type === "radio") {fields.push({checked: Boolean(checkboxValues[field.id]),fieldId: field.id,- type: "checkbox",+ type: field.type,});}}@@ -403,21 +484,46 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {const pageVisibleFields = record.visibleFields.filter((field) => field.page === activePage,);- const actionSummaryFields =- record.currentSignerFields.filter(isActionSummaryField);- const remainingFields = record.currentSignerFields.filter(+ const enteredValues: EnteredValues = {+ checkboxValues,+ signatureValues,+ textValues,+ };+ // A group of radio buttons is one question: it is listed and counted once.+ const seenRadioGroups = new Set<string>();+ const actionSummaryFields = record.currentSignerFields.filter((field) => {+ if (!isActionSummaryField(field)) {+ return false;+ }++ if (field.type !== "radio" || field.groupId === undefined) {+ return true;+ }++ if (seenRadioGroups.has(field.groupId)) {+ return false;+ }++ seenRadioGroups.add(field.groupId);++ return true;+ });+ const remainingFields = countAnswerableFields(+ record.currentSignerFields,(field) =>field.required &&- !isFieldComplete(field, {- checkboxValues,- signatureValues,- textValues,- }),+ !isFieldComplete(field, record.currentSignerFields, enteredValues),+ );+ // An optional number field may be left empty, but not filled with+ // something that is not a number.+ const invalidNumberCount = record.currentSignerFields.filter((field) =>+ hasInvalidNumber(field, textValues),).length;- const canFinish = remainingFields === 0;- const requiredFieldCount = record.currentSignerFields.filter(+ const canFinish = remainingFields === 0 && invalidNumberCount === 0;+ const requiredFieldCount = countAnswerableFields(+ record.currentSignerFields,(field) => field.required,- ).length;+ );const completionPercent =requiredFieldCount === 0? 100@@ -477,11 +583,7 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {try {const response = await fetch(record.submitUrl, {body: JSON.stringify(- buildSigningSubmissionPayload(record, {- checkboxValues,- signatureValues,- textValues,- }),+ buildSigningSubmissionPayload(record, enteredValues),),headers: {"content-type": "application/json",@@ -775,12 +877,30 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {field={field}key={field.id}localDateLabel={localDateLabel}+ isInvalid={hasInvalidNumber(field, textValues)}onCheckboxChange={(checked) => {setSubmitError(null);- setCheckboxValues((current) => ({- ...current,- [field.id]: checked,- }));+ setCheckboxValues((current) => {+ const next = {+ ...current,+ [field.id]: checked,+ };++ // Choosing one radio button lets go of+ // the others in its group.+ if (field.type === "radio" && checked) {+ for (const button of getRadioGroup(+ field,+ record.currentSignerFields,+ )) {+ if (button.id !== field.id) {+ next[button.id] = false;+ }+ }+ }++ return next;+ });}}onSignatureClick={() =>handleSignatureFieldClick(field)@@ -844,6 +964,15 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {? "All required fields complete": `${remainingFields} required field${remainingFields === 1 ? "" : "s"} remaining`}</p>+ {invalidNumberCount > 0 ? (+ <p+ className="mt-1.5 text-[0.8125rem] font-semibold leading-5 text-(--danger)"+ role="alert"+ >+ A number field marked in red does not hold a number.{" "}+ {NUMBER_ENTRY_MESSAGE}+ </p>+ ) : null}<divaria-hidden="true"className="mt-3 h-2 overflow-hidden rounded-full bg-(--surface-strong)"@@ -885,19 +1014,19 @@ export function SigningLiveShell({ record }: { record: SigningPayload }) {<div className="mt-3 space-y-2">{actionSummaryFields.map((field) => (<FieldStatusRow- isComplete={isFieldComplete(field, {- checkboxValues,- signatureValues,- textValues,- })}+ isComplete={isFieldComplete(+ field,+ record.currentSignerFields,+ enteredValues,+ )}+ isInvalid={hasInvalidNumber(field, textValues)}key={field.id}label={`${getSummaryLabel(field)} · Page ${field.page}`}- value={getCompletionValue(field, {- checkboxValues,- localDateLabel,- signatureValues,- textValues,- })}+ value={getCompletionValue(+ field,+ record.currentSignerFields,+ { ...enteredValues, localDateLabel },+ )}/>))}</div>@@ -1153,6 +1282,7 @@ function SigningToolbarStatus({function CurrentSignerField({checkboxValue,field,+ isInvalid,localDateLabel,onCheckboxChange,onSignatureClick,@@ -1162,6 +1292,8 @@ function CurrentSignerField({}: {checkboxValue: boolean;field: SigningCurrentField;+ /** True for a number field holding something that is not a number. */+ isInvalid: boolean;localDateLabel: string;onCheckboxChange: (checked: boolean) => void;onSignatureClick: () => void;@@ -1261,6 +1393,92 @@ function CurrentSignerField({);}+ if (field.type === "number") {+ return (+ <div+ className={`absolute z-2 overflow-hidden rounded-[0.375rem] border-2 focus-within:bg-white ${+ isInvalid+ ? "border-(--danger) bg-(--danger-soft)"+ : "border-(--accent) bg-[rgb(var(--accent-rgb)/0.07)]"+ }`}+ data-signing-field="true"+ style={frame}+ title={isInvalid ? NUMBER_ENTRY_MESSAGE : undefined}+ >+ <input+ aria-invalid={isInvalid ? true : undefined}+ aria-label={getFieldLabel(field)}+ autoComplete="off"+ className="h-full w-full border-none bg-transparent px-2 text-sm text-(--fg) outline-none placeholder:text-(--placeholder)"+ id={`signing-field-${field.id}`}+ inputMode="decimal"+ name={`signing-field-${field.id}`}+ onChange={(event) => onTextChange(event.target.value)}+ placeholder={showInlineLabel ? "Number" : ""}+ value={textValue}+ />+ </div>+ );+ }++ if (field.type === "dropdown") {+ return (+ <div+ className="absolute z-2 overflow-hidden rounded-[0.375rem] border-2 border-(--accent) bg-[rgb(var(--accent-rgb)/0.07)] focus-within:bg-white"+ data-signing-field="true"+ style={frame}+ >+ <select+ aria-label={getFieldLabel(field)}+ className={`h-full w-full cursor-pointer border-none bg-transparent px-1.5 text-sm outline-none ${+ textValue ? "text-(--fg)" : "text-(--secondary)"+ }`}+ id={`signing-field-${field.id}`}+ name={`signing-field-${field.id}`}+ onChange={(event) => onTextChange(event.target.value)}+ value={textValue}+ >+ <option value="">+ {field.required ? "Choose one" : "No answer"}+ </option>+ {(field.options ?? []).map((option) => (+ <option key={option} value={option}>+ {option}+ </option>+ ))}+ </select>+ </div>+ );+ }++ if (field.type === "radio") {+ return (+ <button+ aria-checked={checkboxValue}+ aria-label={getFieldLabel(field)}+ className={`absolute z-2 flex items-center justify-center rounded-full border-2 border-(--accent) text-(--accent-ink) transition ${+ checkboxValue+ ? "bg-[rgb(var(--accent-rgb)/0.14)]"+ : "bg-white hover:bg-[rgb(var(--accent-rgb)/0.10)]"+ }`}+ data-signing-field="true"+ // An answer that is needed can be changed but not taken back; one+ // that is optional can be cleared by choosing it again.+ onClick={() => onCheckboxChange(field.required ? true : !checkboxValue)}+ role="radio"+ style={frame}+ type="button"+ >+ {checkboxValue ? (+ <span+ aria-hidden="true"+ className="block size-[52%] max-h-3 max-w-3 rounded-full bg-current"+ />+ ) : null}+ </button>+ );+ }+return (<buttonaria-label={getFieldLabel(field)}@@ -1300,6 +1518,23 @@ function VisibleFieldStamp({ field }: { field: SigningVisibleField }) {const showInlineLabel = shouldShowInlineFieldLabel(field);const showInlineValue = shouldShowInlineFieldValue(field);+ if (field.type === "radio") {+ return (+ <div+ className="pointer-events-none absolute z-1 flex items-center justify-center rounded-full border border-(--border-strong) bg-[rgba(28,29,43,0.03)]"+ data-signing-field="true"+ style={frame}+ >+ {field.checked ? (+ <span+ aria-hidden="true"+ className="block size-[52%] max-h-3 max-w-3 rounded-full bg-(--secondary)"+ />+ ) : null}+ </div>+ );+ }+if (field.type === "checkbox") {return (<div@@ -1783,10 +2018,13 @@ function DialogFrame({function FieldStatusRow({isComplete,+ isInvalid,label,value,}: {isComplete: boolean;+ /** Filled in, but with something the field cannot take. */+ isInvalid: boolean;label: string;value: string;}) {@@ -1799,9 +2037,15 @@ function FieldStatusRow({</p></div><span- className={`pill shrink-0 ${isComplete ? "pill-success" : "pill-accent"}`}+ className={`pill shrink-0 ${+ isInvalid+ ? "pill-danger"+ : isComplete+ ? "pill-success"+ : "pill-accent"+ }`}>- {isComplete ? "Complete" : "Required"}+ {isInvalid ? "Fix this" : isComplete ? "Complete" : "Required"}</span></div>);diff --git a/src/lib/choice-fields.dbtest.ts b/src/lib/choice-fields.dbtest.tsnew file mode 100644index 0000000..fbf1c3e--- /dev/null+++ b/src/lib/choice-fields.dbtest.ts@@ -0,0 +1,290 @@+import assert from "node:assert/strict";+import { randomUUID } from "node:crypto";+import { after, before, test } from "node:test";++import type pg from "pg";+import { ZodError } from "zod";++import { openTestDatabase } from "./db/test-database.ts";+import {+ EnvelopeMutationError,+ getEnvelopeDetailDataForUser,+ getPrepareEnvelopeDataForUser,+ getReviewEnvelopeDataForUser,+ replaceDraftEnvelopeFields,+ replaceDraftEnvelopeSigners,+ sendDraftEnvelope,+} from "./envelopes.ts";++// Number, dropdown and radio fields against a real Postgres: a draft may+// hold them half-finished, and an envelope cannot be sent until they can+// be answered. Run with `npm run test:db`.++let database: pg.Pool;+const createdUsers: string[] = [];++before(async () => {+ database = await openTestDatabase();+});++after(async () => {+ await database.query(`delete from public."user" where id = any($1)`, [+ createdUsers,+ ]);+ await database.end();+});++async function createDraft() {+ const userId = randomUUID();+ const envelopeId = randomUUID();++ createdUsers.push(userId);+ await database.query(+ `insert into public."user" (id, name, email, role) values ($1, 'Sam Sender', $2, 'user')`,+ [userId, `${userId}@example.test`],+ );+ await database.query(+ `+ insert into envelopes (+ id, user_id, title, status, source_pdf_key, source_pdf_filename,+ source_pdf_size_bytes, page_count, source_pdf_hash+ ) values ($1, $2, 'Survey', 'draft', $3, 'survey.pdf', 10, 1, $4)+ `,+ [envelopeId, userId, `test/${envelopeId}.pdf`, "a".repeat(64)],+ );+ await database.query(+ `+ insert into envelope_pages (id, envelope_id, page_number, width_pt, height_pt)+ values ($1, $2, 1, 612, 792)+ `,+ [randomUUID(), envelopeId],+ );++ const saved = await replaceDraftEnvelopeSigners(+ userId,+ envelopeId,+ {+ signers: [+ { email: "[email protected]", name: "Riley Recipient" },+ { email: "[email protected]", name: "Casey Second" },+ ],+ },+ database,+ );+ const [riley, casey] = saved.signers.map((signer) => signer.id);++ return { casey: casey!, envelopeId, riley: riley!, userId };+}++function field(+ signerId: string,+ type: string,+ y: number,+ extra: Record<string, unknown> = {},+) {+ return {+ height: 0.03,+ page: 1,+ required: true,+ signerId,+ type,+ width: 0.2,+ x: 0.1,+ y,+ ...extra,+ };+}++test("a draft keeps half-finished choices, and sending waits until they can be answered", async () => {+ const { casey, envelopeId, riley, userId } = await createDraft();+ const groupId = randomUUID();+ const signatures = [+ field(riley, "signature", 0.1),+ field(casey, "signature", 0.15),+ ];+ const save = (fields: unknown[]) =>+ replaceDraftEnvelopeFields(userId, envelopeId, { fields }, database);+ const review = () =>+ getReviewEnvelopeDataForUser(userId, envelopeId, database);++ // As the editor saves it the moment the fields are placed: a dropdown+ // with no choices yet and one radio button on its own.+ await save([+ ...signatures,+ field(riley, "number", 0.2, { required: false }),+ field(riley, "dropdown", 0.25, { options: [] }),+ field(casey, "radio", 0.3, { groupId, label: "Option 1" }),+ ]);++ let reviewed = await review();++ assert.equal(reviewed?.canSend, false);+ assert.match(+ reviewed?.disabledReason ?? "",+ /dropdown for Riley Recipient needs at least two choices/,+ );+ await assert.rejects(+ sendDraftEnvelope(+ userId,+ envelopeId,+ { senderEmail: "[email protected]", senderName: "Sam Sender" },+ { database },+ ),+ (error: unknown) =>+ error instanceof EnvelopeMutationError &&+ error.statusCode === 400 &&+ /dropdown/.test(error.message),+ );++ // With the dropdown filled in, the lone radio button is what is left.+ await save([+ ...signatures,+ field(riley, "number", 0.2, { required: false }),+ field(riley, "dropdown", 0.25, { options: ["Yes", "No", "Not sure"] }),+ field(casey, "radio", 0.3, { groupId, label: "Option 1" }),+ ]);+ reviewed = await review();+ assert.equal(reviewed?.canSend, false);+ assert.match(+ reviewed?.disabledReason ?? "",+ /radio button for Casey Second is on its own/,+ );++ await save([+ ...signatures,+ field(riley, "number", 0.2, { required: false }),+ field(riley, "dropdown", 0.25, { options: ["Yes", "No", "Not sure"] }),+ field(casey, "radio", 0.3, { groupId, label: "Agree" }),+ field(casey, "radio", 0.35, { groupId, label: "Disagree" }),+ field(casey, "radio", 0.4, { groupId, label: "Abstain" }),+ ]);+ reviewed = await review();+ assert.equal(reviewed?.canSend, true);+ assert.equal(reviewed?.disabledReason, null);++ // The three buttons are one thing to do, on the review page and on the+ // envelope page alike.+ assert.deepEqual(+ reviewed?.signers.map((signer) => signer.fieldSummaries),+ [+ ["Signature", "Number", "Dropdown"],+ ["Signature", "Radio group"],+ ],+ );++ const detail = await getEnvelopeDetailDataForUser(+ userId,+ envelopeId,+ database,+ );++ assert.deepEqual(+ detail?.signers.map((signer) => signer.metaLabel),+ ["3 fields assigned", "2 fields assigned"],+ );++ // What was saved comes back to the editor as it was.+ const prepared = await getPrepareEnvelopeDataForUser(userId, envelopeId, {+ database,+ });+ const dropdown = prepared?.fields.find((entry) => entry.type === "dropdown");+ const radios = prepared?.fields.filter((entry) => entry.type === "radio");++ assert.deepEqual(dropdown?.options, ["Yes", "No", "Not sure"]);+ assert.equal(dropdown?.groupId, undefined);+ assert.deepEqual(+ radios?.map((entry) => [entry.label, entry.groupId, entry.options]),+ [+ ["Agree", groupId, undefined],+ ["Disagree", groupId, undefined],+ ["Abstain", groupId, undefined],+ ],+ );+});++test("choices only belong on dropdowns, groups only on radio buttons, and a group holds together", async () => {+ const { casey, envelopeId, riley, userId } = await createDraft();+ const groupId = randomUUID();+ const refused: unknown[][] = [+ // Choices on a field that is not a dropdown.+ [field(riley, "text", 0.2, { options: ["Yes", "No"] })],+ // The same choice twice.+ [field(riley, "dropdown", 0.2, { options: ["Yes", "Yes"] })],+ // More choices than a dropdown holds.+ [+ field(riley, "dropdown", 0.2, {+ options: Array.from({ length: 21 }, (_, index) => `Choice ${index}`),+ }),+ ],+ // A radio button with no group, and a group on something else.+ [field(riley, "radio", 0.2)],+ [field(riley, "checkbox", 0.2, { groupId })],+ // One group answered by two people.+ [+ field(riley, "radio", 0.2, { groupId }),+ field(casey, "radio", 0.25, { groupId }),+ ],+ // One group that is both required and optional.+ [+ field(riley, "radio", 0.2, { groupId }),+ field(riley, "radio", 0.25, { groupId, required: false }),+ ],+ // A type that does not exist.+ [field(riley, "slider", 0.2)],+ ];++ for (const fields of refused) {+ await assert.rejects(+ replaceDraftEnvelopeFields(userId, envelopeId, { fields }, database),+ ZodError,+ JSON.stringify(fields),+ );+ }++ const stored = await database.query(+ "select 1 from fields where envelope_id = $1",+ [envelopeId],+ );++ assert.equal(stored.rowCount, 0);+});++test("the database itself keeps choices and groups where they belong", async () => {+ const { envelopeId, riley } = await createDraft();+ const insert = (+ type: string,+ options: string | null,+ groupId: string | null,+ ) =>+ database.query(+ `+ insert into fields (+ id, envelope_id, signer_id, type, page, x, y, width, height,+ options, group_id+ ) values ($1, $2, $3, $4, 1, 0.1, 0.1, 0.1, 0.1, $5::jsonb, $6)+ `,+ [randomUUID(), envelopeId, riley, type, options, groupId],+ );++ await assert.rejects(+ insert("text", '["Yes"]', null),+ /fields_options_only_on_dropdowns/,+ );+ await assert.rejects(+ insert("dropdown", '{"not":"a list"}', null),+ /fields_options_only_on_dropdowns/,+ );+ await assert.rejects(+ insert("radio", null, null),+ /fields_group_only_on_radios/,+ );+ await assert.rejects(+ insert("checkbox", null, "group-1"),+ /fields_group_only_on_radios/,+ );+ await assert.rejects(insert("slider", null, null), /fields_type_check/);++ await insert("dropdown", '["Yes","No"]', null);+ await insert("radio", null, "group-1");+ await insert("number", null, null);+});diff --git a/src/lib/downloads.ts b/src/lib/downloads.tsindex d0dfe74..733b633 100644--- a/src/lib/downloads.ts+++ b/src/lib/downloads.ts@@ -85,11 +85,13 @@ type FieldRow = {checked: boolean | null;createdAt: number;envelopeId: string;+ groupId: string | null;height: number;id: string;imageKey: string | null;inputMethod: FieldRecord["inputMethod"] | null;label: string | null;+ options: string[] | null;page: number;required: boolean;signerId: string;@@ -165,11 +167,13 @@ function mapFieldRow(row: FieldRow): FieldRecord {checked: row.checked,createdAt: row.createdAt,envelopeId: row.envelopeId,+ groupId: row.groupId ?? undefined,height: row.height,id: row.id,imageKey: row.imageKey,inputMethod: row.inputMethod,label: row.label ?? undefined,+ options: row.options ?? undefined,page: row.page,required: row.required,signerId: row.signerId,@@ -467,6 +471,8 @@ async function listFieldsForEnvelope(value,image_key AS "imageKey",checked,+ options,+ group_id AS "groupId",submitted_at AS "submittedAt",created_at AS "createdAt",updated_at AS "updatedAt"diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 063c53e..fed9a8f 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -14,6 +14,11 @@ import {formatDeadline,isEnvelopeExpired,} from "./envelope-deadline.ts";+import {+ countAnswerableFields,+ describeChoiceFieldProblem,+ findChoiceFieldProblem,+} from "./field-choices.ts";import {changeDeadlineResponseSchema,changeRemindersResponseSchema,@@ -174,11 +179,13 @@ type FieldRow = {checked: boolean | null;createdAt: number;envelopeId: string;+ groupId: string | null;height: number;id: string;imageKey: string | null;inputMethod: FieldRecord["inputMethod"] | null;label: string | null;+ options: string[] | null;page: number;required: boolean;signerId: string;@@ -198,11 +205,15 @@ function shouldCountFieldForSignerSummary(return true;}- if (field.type === "text") {+ if (+ field.type === "text" ||+ field.type === "number" ||+ field.type === "dropdown"+ ) {return true;}- if (field.type === "checkbox") {+ if (field.type === "checkbox" || field.type === "radio") {return field.required;}@@ -243,7 +254,14 @@ export type DashboardEnvelopeListItem = {};type ReviewFieldSummary =- "Checkbox" | "Date" | "Initials" | "Signature" | "Text";+ | "Checkbox"+ | "Date"+ | "Dropdown"+ | "Initials"+ | "Number"+ | "Radio group"+ | "Signature"+ | "Text";export type ReviewSignerSummary = {email: string;@@ -389,15 +407,21 @@ const FIELD_TYPE_SUMMARY_LABELS: Record<> = {checkbox: "Checkbox",date: "Date",+ dropdown: "Dropdown",initials: "Initials",+ number: "Number",+ radio: "Radio group",signature: "Signature",text: "Text",};const FIELD_TYPE_SORT_ORDER: Record<FieldRecord["type"], number> = {- checkbox: 4,+ checkbox: 6,date: 2,+ dropdown: 5,initials: 1,+ number: 4,+ radio: 7,signature: 0,text: 3,};@@ -619,11 +643,13 @@ function mapFieldRow(row: FieldRow): PersistedFieldRecord {checked: row.checked,createdAt: row.createdAt,envelopeId: row.envelopeId,+ groupId: row.groupId ?? undefined,height: row.height,id: row.id,imageKey: row.imageKey,inputMethod: row.inputMethod,label: row.label ?? undefined,+ options: row.options ?? undefined,page: row.page,required: row.required,signerId: row.signerId,@@ -910,6 +936,8 @@ async function listFieldsForEnvelopeIds(value,image_key AS "imageKey",checked,+ options,+ group_id AS "groupId",submitted_at AS "submittedAt",created_at AS "createdAt",updated_at AS "updatedAt"@@ -1017,6 +1045,46 @@ function buildFieldsBySigner(}, new Map());}+/**+ * What is unfinished about a dropdown or a radio group, in words for the+ * sender, or null when every one of them can be answered.+ */+function describeChoiceProblem(+ signers: readonly PersistedSignerRecord[],+ fields: readonly FieldRecord[],+): string | null {+ const problem = findChoiceFieldProblem(fields);++ if (!problem) {+ return null;+ }++ return describeChoiceFieldProblem(+ problem,+ signers.find((signer) => signer.id === problem.signerId)?.name ??+ "a signer",+ );+}++/** The fields with each group of radio buttons counted once. */+function withRadioGroupsOnce(fields: readonly FieldRecord[]): FieldRecord[] {+ const seenGroups = new Set<string>();++ return fields.filter((field) => {+ if (field.type !== "radio" || !field.groupId) {+ return true;+ }++ if (seenGroups.has(field.groupId)) {+ return false;+ }++ seenGroups.add(field.groupId);++ return true;+ });+}+function getMissingSignatureSigner(signers: readonly PersistedSignerRecord[],fieldsBySigner: ReadonlyMap<string, readonly FieldRecord[]>,@@ -1309,16 +1377,14 @@ export async function getEnvelopeDetailDataForUser(]);const signers = signersByEnvelope.get(envelopeId) ?? [];const fields = fieldsByEnvelope.get(envelopeId) ?? [];- const fieldCountsBySigner = fields.reduce<Map<string, number>>(- (counts, field) => {- if (!shouldCountFieldForSignerSummary(field)) {- return counts;- }-- counts.set(field.signerId, (counts.get(field.signerId) ?? 0) + 1);- return counts;- },- new Map(),+ const fieldCountsBySigner = new Map(+ [...buildFieldsBySigner(fields)].map(+ ([signerId, signerFields]) =>+ [+ signerId,+ countAnswerableFields(signerFields, shouldCountFieldForSignerSummary),+ ] as const,+ ),);const timeline = auditEvents.map((event) => ({description: buildTimelineDescription(event),@@ -1629,21 +1695,21 @@ export async function getReviewEnvelopeDataForUser(fieldsBySigner,);const isEmpty = signers.length === 0 || fields.length === 0;+ const choiceProblem = describeChoiceProblem(signers, fields);return {- canSend: !isEmpty && !missingSignatureSigner,+ canSend: !isEmpty && !missingSignatureSigner && !choiceProblem,copyRecipients,disabledReason: missingSignatureSigner? `Every signer must have at least one Signature field before sending. ${missingSignatureSigner.name} is missing one.`- : null,+ : choiceProblem,envelopeId,filename: envelope.sourcePdfFilename,isEmpty,pageCount: envelope.pageCount,signers: signers.map((signer) => ({email: signer.email,- fieldSummaries: (fieldsBySigner.get(signer.id) ?? [])- .slice()+ fieldSummaries: withRadioGroupsOnce(fieldsBySigner.get(signer.id) ?? []).sort((left, right) =>FIELD_TYPE_SORT_ORDER[left.type] -@@ -1709,6 +1775,12 @@ export async function sendDraftEnvelope();}+ const choiceProblem = describeChoiceProblem(signers, fields);++ if (choiceProblem) {+ throw new EnvelopeMutationError(choiceProblem, 400);+ }+const firstSigner = signers[0];if (!firstSigner) {@@ -2437,9 +2509,11 @@ export async function replaceDraftEnvelopeFields(checked,submitted_at,created_at,- updated_at+ updated_at,+ options,+ group_id) VALUES (- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NULL, NULL, NULL, NULL, NULL, $12, $13+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NULL, NULL, NULL, NULL, NULL, $12, $13, $14::jsonb, $15)`,[@@ -2456,6 +2530,10 @@ export async function replaceDraftEnvelopeFields(field.label ?? null,field.createdAt,field.updatedAt,+ field.type === "dropdown"+ ? JSON.stringify(field.options ?? [])+ : null,+ field.groupId ?? null,],);}diff --git a/src/lib/field-choices.test.ts b/src/lib/field-choices.test.tsnew file mode 100644index 0000000..9683029--- /dev/null+++ b/src/lib/field-choices.test.ts@@ -0,0 +1,178 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ countAnswerableFields,+ describeChoiceFieldProblem,+ describeEntryProblem,+ DROPDOWN_ENTRY_MESSAGE,+ findChoiceFieldProblem,+ isNumberEntry,+ judgeRadioGroups,+ MAX_FIELD_OPTIONS,+ NUMBER_ENTRY_MESSAGE,+ parseOptionLines,+} from "./field-choices.ts";++test("a number field takes plain and comma-grouped numbers and nothing else", () => {+ for (const entry of [+ "0",+ "1250",+ "12.5",+ "-3",+ "+7.25",+ " 42 ",+ "1,250",+ "1,250,000.75",+ "-12,000",+ ]) {+ assert.equal(isNumberEntry(entry), true, entry);+ }++ for (const entry of [+ "",+ "abc",+ "12,5",+ "1,25",+ "1.2.3",+ "12.",+ ".5",+ "1e5",+ "1 250",+ "12,5000",+ "٣",+ "12%",+ "$12",+ "--1",+ "1".repeat(19),+ ]) {+ assert.equal(isNumberEntry(entry), false, entry);+ }+});++test("choices are read one per line, without blanks or repeats", () => {+ assert.deepEqual(parseOptionLines(" Yes \n\nNo\r\nYes\n Maybe"), [+ "Yes",+ "No",+ "Maybe",+ ]);+ assert.deepEqual(parseOptionLines(""), []);+ assert.equal(+ parseOptionLines(+ Array.from({ length: 40 }, (_, index) => `Choice ${index}`).join("\n"),+ ).length,+ MAX_FIELD_OPTIONS,+ );+ assert.equal(parseOptionLines("x".repeat(200))[0].length, 80);+});++test("a dropdown needs two choices and a radio button needs company", () => {+ const signerId = "signer-1";++ assert.equal(findChoiceFieldProblem([]), null);+ assert.equal(+ findChoiceFieldProblem([+ { options: ["Yes", "No"], required: true, signerId, type: "dropdown" },+ { groupId: "g1", required: true, signerId, type: "radio" },+ { groupId: "g1", required: true, signerId, type: "radio" },+ { required: true, signerId, type: "signature" },+ ]),+ null,+ );++ for (const options of [undefined, null, [], ["Only"]]) {+ assert.deepEqual(+ findChoiceFieldProblem([+ { options, required: false, signerId, type: "dropdown" },+ ]),+ { kind: "dropdown_options", signerId },+ );+ }++ const lonely = findChoiceFieldProblem([+ { groupId: "g1", required: true, signerId, type: "radio" },+ { groupId: "g1", required: true, signerId, type: "radio" },+ { groupId: "g2", required: true, signerId: "signer-2", type: "radio" },+ ]);++ assert.deepEqual(lonely, { kind: "radio_group_size", signerId: "signer-2" });+ assert.match(describeChoiceFieldProblem(lonely!, "Ada"), /Ada/);+});++test("a group of radio buttons counts as one thing to do", () => {+ const signerId = "signer-1";++ assert.equal(+ countAnswerableFields(+ [+ { required: true, signerId, type: "signature" },+ { groupId: "g1", required: true, signerId, type: "radio" },+ { groupId: "g1", required: true, signerId, type: "radio" },+ { groupId: "g1", required: true, signerId, type: "radio" },+ { groupId: "g2", required: true, signerId, type: "radio" },+ { groupId: "g2", required: true, signerId, type: "radio" },+ { required: false, signerId, type: "checkbox" },+ ],+ (field) => field.required,+ ),+ 3,+ );+});++test("what a signer enters must be a number, or one of the choices offered", () => {+ assert.equal(describeEntryProblem({ type: "number" }, "12.5"), null);+ assert.equal(+ describeEntryProblem({ type: "number" }, "twelve"),+ NUMBER_ENTRY_MESSAGE,+ );+ assert.equal(+ describeEntryProblem({ options: ["Yes", "No"], type: "dropdown" }, "Yes"),+ null,+ );++ for (const [options, value] of [+ [["Yes", "No"], "Maybe"],+ [["Yes", "No"], "yes"],+ [[], "Yes"],+ [undefined, "Yes"],+ ] as const) {+ assert.equal(+ describeEntryProblem({ options, type: "dropdown" }, value),+ DROPDOWN_ENTRY_MESSAGE,+ );+ }++ // Free text has no rule of this kind.+ assert.equal(describeEntryProblem({ type: "text" }, "anything"), null);+});++test("radio buttons are judged a group at a time", () => {+ const signerId = "signer-1";+ const button = (id: string, groupId: string, required: boolean) => ({+ groupId,+ id,+ required,+ signerId,+ type: "radio",+ });+ const fields = [+ button("a1", "a", true),+ button("a2", "a", true),+ button("b1", "b", false),+ button("b2", "b", false),+ { id: "sig", required: true, signerId, type: "signature" },+ ];+ const judge = (...chosen: string[]) =>+ judgeRadioGroups(fields, (field) => chosen.includes(field.id));++ assert.equal(judge("a1"), "ok");+ assert.equal(judge("a2", "b1"), "ok");+ // The required group has no answer.+ assert.equal(judge(), "missing");+ assert.equal(judge("b2"), "missing");+ // Two answers in one group, required or not.+ assert.equal(judge("a1", "a2"), "too_many");+ assert.equal(judge("a1", "b1", "b2"), "too_many");+ // Too many wins over missing: it is the one that cannot be a mistake.+ assert.equal(judge("b1", "b2"), "too_many");+});diff --git a/src/lib/field-choices.ts b/src/lib/field-choices.tsnew file mode 100644index 0000000..5001bf4--- /dev/null+++ b/src/lib/field-choices.ts@@ -0,0 +1,205 @@+// The rules for the fields a signer answers by choosing or by typing a+// number: dropdowns, radio buttons and number fields. Shared by the field+// editor, the signing page and the server, so all three agree.++export const MAX_FIELD_OPTIONS = 20;+export const MAX_FIELD_OPTION_LENGTH = 80;+export const MIN_FIELD_OPTIONS = 2;+export const MAX_RADIO_GROUP_BUTTONS = 20;+export const MAX_NUMBER_ENTRY_LENGTH = 40;++export const NUMBER_ENTRY_MESSAGE = "Enter a number, such as 1250 or 12.5.";++// Plain digits with an optional sign and decimal part, or the same with a+// comma between every three digits. A comma used as a decimal mark ("12,5")+// is refused rather than guessed at: read one way it is twelve and a half,+// read the other it is one hundred and twenty-five.+const PLAIN_NUMBER = /^[+-]?\d{1,18}(\.\d{1,10})?$/;+const GROUPED_NUMBER = /^[+-]?\d{1,3}(,\d{3}){1,5}(\.\d{1,10})?$/;++/** True for what a signer may leave in a number field. */+export function isNumberEntry(value: string): boolean {+ const trimmed = value.trim();++ return (+ trimmed.length <= MAX_NUMBER_ENTRY_LENGTH &&+ (PLAIN_NUMBER.test(trimmed) || GROUPED_NUMBER.test(trimmed))+ );+}++/**+ * The choices typed into the editor, one per line: trimmed, with empty+ * lines and repeats dropped, and no more than a dropdown can hold.+ */+export function parseOptionLines(text: string): string[] {+ const options: string[] = [];++ for (const line of text.split(/\r?\n/)) {+ const option = line.trim().slice(0, MAX_FIELD_OPTION_LENGTH).trim();++ if (option && !options.includes(option)) {+ options.push(option);+ }++ if (options.length === MAX_FIELD_OPTIONS) {+ break;+ }+ }++ return options;+}++type ChoiceField = {+ groupId?: string | null;+ options?: readonly string[] | null;+ required: boolean;+ signerId: string;+ type: string;+};++export type ChoiceFieldProblem = {+ kind: "dropdown_options" | "radio_group_size";+ signerId: string;+};++/**+ * What still has to be fixed before an envelope can be sent: a dropdown+ * with fewer than two choices, or a radio button on its own. A draft may be+ * saved in either state, because the editor saves as the sender works.+ */+export function findChoiceFieldProblem(+ fields: readonly ChoiceField[],+): ChoiceFieldProblem | null {+ const groupSizes = new Map<string, { count: number; signerId: string }>();++ for (const field of fields) {+ if (+ field.type === "dropdown" &&+ (field.options?.length ?? 0) < MIN_FIELD_OPTIONS+ ) {+ return { kind: "dropdown_options", signerId: field.signerId };+ }++ if (field.type === "radio" && field.groupId) {+ const group = groupSizes.get(field.groupId);++ if (group) {+ group.count += 1;+ } else {+ groupSizes.set(field.groupId, { count: 1, signerId: field.signerId });+ }+ }+ }++ for (const group of groupSizes.values()) {+ if (group.count < MIN_FIELD_OPTIONS) {+ return { kind: "radio_group_size", signerId: group.signerId };+ }+ }++ return null;+}++export function describeChoiceFieldProblem(+ problem: ChoiceFieldProblem,+ signerName: string,+): string {+ return problem.kind === "dropdown_options"+ ? `A dropdown for ${signerName} needs at least two choices. Select it and add them.`+ : `A radio button for ${signerName} is on its own. Add another button to its group, or remove it.`;+}++/**+ * How many things a signer is asked to do, counting a group of radio+ * buttons as one.+ */+export function countAnswerableFields<Field extends ChoiceField>(+ fields: readonly Field[],+ counts: (field: Field) => boolean,+): number {+ const seenGroups = new Set<string>();+ let total = 0;++ for (const field of fields) {+ if (!counts(field)) {+ continue;+ }++ if (field.type === "radio" && field.groupId) {+ if (seenGroups.has(field.groupId)) {+ continue;+ }++ seenGroups.add(field.groupId);+ }++ total += 1;+ }++ return total;+}++export const DROPDOWN_ENTRY_MESSAGE =+ "Choose one of the listed options in each dropdown.";++/**+ * What is wrong with what a signer entered in a number or dropdown field,+ * or null when it can go on the document as it is.+ */+export function describeEntryProblem(+ field: Pick<ChoiceField, "options" | "type">,+ value: string,+): string | null {+ if (field.type === "number" && !isNumberEntry(value)) {+ return NUMBER_ENTRY_MESSAGE;+ }++ if (field.type === "dropdown" && !(field.options ?? []).includes(value)) {+ return DROPDOWN_ENTRY_MESSAGE;+ }++ return null;+}++export type RadioGroupVerdict = "missing" | "ok" | "too_many";++/**+ * Judges the radio buttons group by group: never more than one chosen, and+ * exactly one where the group is required.+ */+export function judgeRadioGroups<Field extends ChoiceField>(+ fields: readonly Field[],+ isChosen: (field: Field) => boolean,+): RadioGroupVerdict {+ const groups = new Map<string, { chosen: number; required: boolean }>();++ for (const field of fields) {+ if (field.type !== "radio" || !field.groupId) {+ continue;+ }++ const group = groups.get(field.groupId) ?? { chosen: 0, required: false };++ group.required ||= field.required;++ if (isChosen(field)) {+ group.chosen += 1;+ }++ groups.set(field.groupId, group);+ }++ let verdict: RadioGroupVerdict = "ok";++ for (const group of groups.values()) {+ if (group.chosen > 1) {+ return "too_many";+ }++ if (group.required && group.chosen === 0) {+ verdict = "missing";+ }+ }++ return verdict;+}diff --git a/src/lib/schemas/field.ts b/src/lib/schemas/field.tsindex a57a74a..50cdc18 100644--- a/src/lib/schemas/field.ts+++ b/src/lib/schemas/field.ts@@ -1,5 +1,11 @@import { z } from "zod";+import {+ MAX_FIELD_OPTION_LENGTH,+ MAX_FIELD_OPTIONS,+ MAX_NUMBER_ENTRY_LENGTH,+ MAX_RADIO_GROUP_BUTTONS,+} from "../field-choices.ts";import { fieldInputMethods, fieldTypes } from "../types/domain.ts";import {idSchema,@@ -30,8 +36,46 @@ export const fieldPlacementSchema = zheight: normalizedSizeSchema,required: z.boolean().default(true),label: optionalTrimmedString(120),+ // The choices of a dropdown. A draft may hold fewer than two while the+ // sender is still typing them; sending checks for that.+ options: z+ .array(z.string().trim().min(1).max(MAX_FIELD_OPTION_LENGTH))+ .max(MAX_FIELD_OPTIONS)+ .optional(),+ // The group a radio button belongs to. The signer picks one per group.+ groupId: z.string().trim().min(1).max(64).optional(),}).superRefine((field, ctx) => {+ if (field.options !== undefined && field.type !== "dropdown") {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Only dropdown fields have choices",+ path: ["options"],+ });+ }++ if (+ field.options !== undefined &&+ new Set(field.options).size !== field.options.length+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Each choice in a dropdown must be different",+ path: ["options"],+ });+ }++ if ((field.type === "radio") !== (field.groupId !== undefined)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ field.type === "radio"+ ? "A radio button must belong to a group"+ : "Only radio buttons belong to a group",+ path: ["groupId"],+ });+ }+if (field.x + field.width > 1.000001) {ctx.addIssue({code: z.ZodIssueCode.custom,@@ -62,7 +106,55 @@ export const fieldPlacementSchema = z}});-export const fieldPlacementListSchema = z.array(fieldPlacementSchema);+// The buttons of one radio group are answered together, so they must agree+// on who answers them and on whether an answer is needed.+export const fieldPlacementListSchema = z+ .array(fieldPlacementSchema)+ .superRefine((fields, ctx) => {+ const groups = new Map<+ string,+ { count: number; required: boolean; signerId: string }+ >();++ fields.forEach((field, index) => {+ if (field.type !== "radio" || field.groupId === undefined) {+ return;+ }++ const group = groups.get(field.groupId);++ if (!group) {+ groups.set(field.groupId, {+ count: 1,+ required: field.required,+ signerId: field.signerId,+ });+ return;+ }++ group.count += 1;++ if (+ group.signerId !== field.signerId ||+ group.required !== field.required+ ) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ "The buttons in a radio group must have the same signer and be required or optional together",+ path: [index, "groupId"],+ });+ }++ if (group.count === MAX_RADIO_GROUP_BUTTONS + 1) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `A radio group can have at most ${String(MAX_RADIO_GROUP_BUTTONS)} buttons`,+ path: [index, "groupId"],+ });+ }+ });+ });export const replaceFieldsSchema = z.object({fields: fieldPlacementListSchema,@@ -122,11 +214,34 @@ const checkboxSubmissionSchema = z.object({checked: z.boolean(),});+// Whether what was typed is a number, and whether what was chosen is one of+// the field's choices, is checked against the field when it is submitted.+const numberSubmissionSchema = z.object({+ fieldId: idSchema,+ type: z.literal("number"),+ value: z.string().trim().min(1).max(MAX_NUMBER_ENTRY_LENGTH),+});++const dropdownSubmissionSchema = z.object({+ fieldId: idSchema,+ type: z.literal("dropdown"),+ value: z.string().trim().min(1).max(MAX_FIELD_OPTION_LENGTH),+});++const radioSubmissionSchema = z.object({+ fieldId: idSchema,+ type: z.literal("radio"),+ checked: z.boolean(),+});+export const signingFieldSubmissionSchema = z.union([typedSignatureSubmissionSchema,drawnSignatureSubmissionSchema,textSubmissionSchema,checkboxSubmissionSchema,+ numberSubmissionSchema,+ dropdownSubmissionSchema,+ radioSubmissionSchema,]);export const signingSubmissionSchema = z.object({diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.tsindex 4386259..129667f 100644--- a/src/lib/schemas/signing.ts+++ b/src/lib/schemas/signing.ts@@ -21,9 +21,13 @@ export const signingUnavailableStateSchema = z.enum([]);const signingFieldBaseSchema = z.object({+ /** The group a radio button belongs to. */+ groupId: z.string().trim().min(1).optional(),height: normalizedSizeSchema,id: idSchema,label: optionalTrimmedString(120),+ /** The choices of a dropdown. */+ options: z.array(z.string().trim().min(1)).optional(),page: z.number().int().positive(),required: z.boolean(),signerId: idSchema,diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.tsindex d92560f..12ba2af 100644--- a/src/lib/services/pdf-finalize.test.ts+++ b/src/lib/services/pdf-finalize.test.ts@@ -263,3 +263,95 @@ test("the certificate names the people who were sent a copy", async () => {assert.ok(!(await extractText(without)).includes("Copy recipients"));});++test("numbers and dropdown choices are stamped as text, radio buttons as rings", async () => {+ const fixture = await makeFixture();+ const base = {+ createdAt: 1_800_000_000,+ envelopeId: fixture.envelope.id,+ height: 0.03,+ page: 1,+ required: true,+ signerId: "signer-1",+ submittedAt: 1_800_000_000,+ updatedAt: 1_800_000_000,+ width: 0.3,+ x: 0.1,+ };+ const choiceFields: FieldRecord[] = [+ { ...base, id: "number-1", type: "number", value: "1,250.75", y: 0.5 },+ {+ ...base,+ id: "dropdown-1",+ options: ["Tak", "Nie", "Nie wiem"],+ type: "dropdown",+ value: "Nie wiem",+ y: 0.55,+ },+ // An optional dropdown that was left alone: nothing to stamp.+ {+ ...base,+ id: "dropdown-2",+ options: ["One", "Two"],+ required: false,+ submittedAt: null,+ type: "dropdown",+ value: null,+ y: 0.6,+ },+ {+ ...base,+ checked: true,+ groupId: "group-1",+ id: "radio-1",+ label: "Yes",+ type: "radio",+ width: 0.03,+ y: 0.65,+ },+ {+ ...base,+ checked: false,+ groupId: "group-1",+ id: "radio-2",+ label: "No",+ type: "radio",+ width: 0.03,+ y: 0.7,+ },+ ];+ const render = (fields: FieldRecord[]) =>+ renderFinalizedEnvelopePdf(+ {+ auditEvents: fixture.auditEvents,+ completedAt: fixture.envelope.completedAt!,+ envelope: fixture.envelope,+ fields,+ signers: fixture.signers,+ sourcePdfKey: fixture.envelope.sourcePdfKey,+ },+ { seal: saveUnsealed, storageService: fixture.storageService },+ );+ const pdfBytes = await render([...fixture.fields, ...choiceFields]);+ const text = (await extractText(pdfBytes)).replace(/\s+/g, " ");++ assert.ok(text.includes("1,250.75"));+ assert.ok(text.includes("Nie wiem"));+ // The choices that were not picked are not on the document.+ assert.ok(!text.includes("Tak"));+ assert.ok(!text.includes("One"));++ // The two radio buttons add drawing to the page: two rings and one dot.+ // Without them the same document is smaller.+ const withoutRadios = await render([+ ...fixture.fields,+ ...choiceFields.filter((field) => field.type !== "radio"),+ ]);+ const chosenOnly = await render([+ ...fixture.fields,+ ...choiceFields.filter((field) => field.id !== "radio-2"),+ ]);++ assert.ok(pdfBytes.byteLength > chosenOnly.byteLength);+ assert.ok(chosenOnly.byteLength > withoutRadios.byteLength);+});diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 8ce4341..30b8053 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -240,7 +240,7 @@ function getFieldPadding(widthPt: number, heightPt: number): number {}function shouldStampField(field: FieldRecord): boolean {- if (field.type === "checkbox") {+ if (field.type === "checkbox" || field.type === "radio") {return typeof field.checked === "boolean";}@@ -435,7 +435,9 @@ async function stampFieldValue(return;}case "date":- case "text": {+ case "text":+ case "number":+ case "dropdown": {const textValue = field.value?.trim();if (!textValue) {@@ -492,6 +494,31 @@ async function stampFieldValue(return;}+ case "radio": {+ // A ring for every button, and a dot in the one that was chosen.+ const diameter = Math.min(rect.widthPt, rect.heightPt, 14);+ const center = {+ x: rect.xPt + padding / 2 + diameter / 2,+ y: rect.yPt + rect.heightPt / 2,+ };++ page.drawCircle({+ borderColor: rgb(0.18, 0.18, 0.18),+ borderWidth: 1.1,+ size: diameter / 2,+ ...center,+ });++ if (field.checked) {+ page.drawCircle({+ color: rgb(0.08, 0.08, 0.08),+ size: diameter * 0.24,+ ...center,+ });+ }++ return;+ }default:return;}diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex aaa7d7a..2fbbaa2 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -76,10 +76,14 @@ import {type StorageService,} from "./services/storage.ts";import { requireConfigValue } from "./services/service-config.ts";-import { RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS } from "./types/domain.ts";+import {+ RECIPIENT_DOWNLOAD_LINK_TTL_SECONDS,+ type FieldType,+} from "./types/domain.ts";import { getEnv } from "./utils/env.ts";import { escapeHtml } from "./utils/html.ts";import { isEnvelopeExpired } from "./envelope-deadline.ts";+import { describeEntryProblem, judgeRadioGroups } from "./field-choices.ts";import {buildElectronicRecordsDisclosure,CONSENT_STATEMENT,@@ -157,16 +161,18 @@ type SigningFieldRow = {checked: boolean | null;createdAt: number;envelopeId: string;+ groupId: string | null;height: number;id: string;imageKey: string | null;inputMethod: "auto" | "drawn" | "typed" | null;label: string | null;+ options: string[] | null;page: number;required: boolean;signerId: string;submittedAt: number | null;- type: "checkbox" | "date" | "initials" | "signature" | "text";+ type: FieldType;updatedAt: number;value: string | null;width: number;@@ -445,11 +451,13 @@ function mapFieldRow(row: SigningFieldRow) {checked: row.checked,createdAt: row.createdAt,envelopeId: row.envelopeId,+ groupId: row.groupId ?? undefined,height: row.height,id: row.id,imageKey: row.imageKey,inputMethod: row.inputMethod,label: row.label ?? undefined,+ options: row.options ?? undefined,page: row.page,required: row.required,signerId: row.signerId,@@ -609,6 +617,8 @@ async function listFieldRows(value,image_key AS "imageKey",checked,+ options,+ group_id AS "groupId",submitted_at AS "submittedAt",created_at AS "createdAt",updated_at AS "updatedAt"@@ -786,14 +796,49 @@ function isFieldSubmissionComplete(case "date":return typeof update.submittedAt === "number";case "text":+ case "number":+ case "dropdown":return typeof update.value === "string" && update.value.trim().length > 0;case "checkbox":return update.checked === true;+ case "radio":+ // One button is never the whole answer: the group is judged together,+ // once every button's value is known.+ return true;default:return false;}}+/**+ * Checks the radio buttons group by group: never more than one chosen, and+ * exactly one where the group is required.+ */+function assertRadioGroupsAnswered(+ fields: ReadonlyArray<ReturnType<typeof fieldRecordSchema.parse>>,+ updates: ReadonlyMap<string, FieldPersistenceUpdate>,+) {+ const verdict = judgeRadioGroups(+ fields,+ (field) =>+ field.id !== undefined && updates.get(field.id)?.checked === true,+ );++ if (verdict === "too_many") {+ throw new SigningMutationError(+ "Choose only one option in each group of radio buttons.",+ 400,+ );+ }++ if (verdict === "missing") {+ throw new SigningMutationError(+ "Complete all required fields before finishing.",+ 400,+ );+ }+}+function buildSignedAuditEvent(input: {authMethods: readonly SignerCheckMethod[];envelopeId: string;@@ -1520,9 +1565,11 @@ export async function getSigningPayloadForToken(const currentSignerFields = context.fields.filter((field) => field.signerId === context.signer.id).map((field) => ({+ groupId: field.groupId,height: field.height,id: field.id,label: field.label,+ options: field.options,page: field.page,required: field.required,signerId: field.signerId,@@ -1744,9 +1791,23 @@ export async function submitSigningForToken(continue;}- if (field.type === "text") {+ if (+ field.type === "text" ||+ field.type === "number" ||+ field.type === "dropdown"+ ) {const trimmedValue =- submission?.type === "text" ? submission.value.trim() : null;+ submission?.type === field.type ? submission.value.trim() : null;++ // What goes on the document is exactly what the signer entered, so a+ // number must be one and a choice must be one the sender offered.+ const entryProblem = trimmedValue+ ? describeEntryProblem(field, trimmedValue)+ : null;++ if (entryProblem) {+ throw new SigningMutationError(entryProblem, 400);+ }fieldUpdates.set(field.id, {checked: null,@@ -1760,7 +1821,9 @@ export async function submitSigningForToken(}const checkedValue =- submission?.type === "checkbox" ? submission.checked : false;+ submission?.type === "checkbox" || submission?.type === "radio"+ ? submission.checked+ : false;fieldUpdates.set(field.id, {checked: checkedValue,@@ -1785,6 +1848,8 @@ export async function submitSigningForToken();}+ assertRadioGroupsAnswered(currentSignerFields, fieldUpdates);+let signingStatePersisted = false;try {diff --git a/src/lib/types/domain.ts b/src/lib/types/domain.tsindex 77cdb94..35b7078 100644--- a/src/lib/types/domain.ts+++ b/src/lib/types/domain.ts@@ -40,6 +40,9 @@ export const fieldTypes = ["date","text","checkbox",+ "number",+ "dropdown",+ "radio",] as const;export const fieldInputMethods = ["typed", "drawn", "auto"] as const;