Skip to content

Commit 6c6e020

Browse files
authored
feat(demo): auto-confirm demo bookings that came through the verified form and decline the rest (#9976)
* feat(demo): auto-confirm demo bookings that came through the verified form and decline the rest * fix(demo): open the calendar only after the request is recorded and keep webhook decisions stable * fix(demo): claim booking records atomically and lock the form while submitting
1 parent ce58845 commit 6c6e020

10 files changed

Lines changed: 629 additions & 141 deletions

File tree

‎apps/sim/app/(landing)/demo/components/demo-form/demo-form.tsx‎

Lines changed: 198 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
11
'use client'
22

3-
import { type ReactNode, useEffect, useId, useState } from 'react'
3+
import { type ReactNode, useEffect, useId, useRef, useState } from 'react'
4+
import { Turnstile, type TurnstileInstance } from '@marsidev/react-turnstile'
45
import { Chip, ChipDropdown, ChipInput, ChipTextarea, Label } from '@sim/emcn'
6+
import { toError } from '@sim/utils/errors'
57
import {
68
DEMO_REQUEST_COMPANY_SIZE_OPTIONS,
79
type DemoRequestBody,
810
} from '@/lib/api/contracts/demo-requests'
11+
import { getEnv } from '@/lib/core/config/env'
912
import { isFreeEmailDomain } from '@/lib/messaging/email/free-email'
1013
import { quickValidateEmail } from '@/lib/messaging/email/validation'
1114
import { useSubmitDemoRequest } from '@/hooks/queries/demo-requests'
1215

16+
/** Build-time-inlined Turnstile site key; absent when captcha isn't configured. */
17+
const TURNSTILE_SITE_KEY = getEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY')
18+
19+
/**
20+
* How long Continue waits on the invisible challenge before sending the request
21+
* without a token. An interactive challenge cannot be shown in the hidden
22+
* widget, so waiting longer only delays the calendar; the server then marks the
23+
* request unverified and the booking goes to manual review.
24+
*/
25+
const CAPTCHA_WAIT_MS = 5_000
26+
1327
/** Options for the "What can we help you with?" select; the first is the default. */
1428
const TOPIC_OPTIONS = [
1529
{ value: 'demo', label: 'Book a demo' },
@@ -155,17 +169,27 @@ function DemoField({ label, htmlFor, required, error, children }: DemoFieldProps
155169
* looks like an address attempt, and the primary {@link Chip} stays disabled until
156170
* every required field is valid.
157171
*
158-
* On a valid submit it fires the inbound-demo notification to sales (via
159-
* {@link useSubmitDemoRequest}, best-effort - never blocking) and composes a
160-
* {@link DemoLead} (name, email, and a notes summary) handed to `onComplete`,
161-
* which advances the card to the scheduler.
172+
* On a valid submit it sends the demo request (via {@link useSubmitDemoRequest})
173+
* with an invisible Turnstile token and a honeypot `website` field, and only
174+
* once the server has recorded it hands a {@link DemoLead} (name, email, and a
175+
* notes summary) to `onComplete`, which advances the card to the scheduler. The
176+
* record decides whether the booking is confirmed automatically or reviewed by
177+
* hand, so the calendar never opens before it exists. A failed request keeps the
178+
* form open with an inline error.
162179
*/
163180
export function DemoForm({ onComplete }: DemoFormProps) {
164181
const submitDemoRequest = useSubmitDemoRequest()
165182
const [form, setForm] = useState<DemoFormState>(INITIAL_STATE)
183+
const [website, setWebsite] = useState('')
184+
/** Turnstile mounts on first focus, like the scheduler preload, so its script never competes with page load. */
185+
const [captchaArmed, setCaptchaArmed] = useState(false)
186+
const turnstileRef = useRef<TurnstileInstance>(null)
187+
const widgetLoadedRef = useRef(false)
166188

167-
const setField = (key: keyof DemoFormState) => (value: string) =>
189+
const setField = (key: keyof DemoFormState) => (value: string) => {
168190
setForm((prev) => ({ ...prev, [key]: value }))
191+
if (submitDemoRequest.isError) submitDemoRequest.reset()
192+
}
169193

170194
/**
171195
* Prefill the email from the `?email=` param the landing hero's CTA forwards
@@ -204,24 +228,53 @@ export function DemoForm({ onComplete }: DemoFormProps) {
204228
? 'Please use your work email address.'
205229
: undefined
206230

207-
const handleSubmit = () => {
208-
if (!canSubmit) return
231+
/**
232+
* Runs the invisible challenge, falling back to no token when the widget never
233+
* loaded or does not answer; the server then treats the request as unverified
234+
* rather than rejecting it.
235+
*/
236+
const solveCaptcha = async (): Promise<string | undefined> => {
237+
const widget = turnstileRef.current
238+
if (!TURNSTILE_SITE_KEY || !widgetLoadedRef.current || !widget) return undefined
239+
try {
240+
widget.reset()
241+
widget.execute()
242+
return await widget.getResponsePromise(CAPTCHA_WAIT_MS)
243+
} catch {
244+
return undefined
245+
}
246+
}
247+
248+
const [isSolvingCaptcha, setIsSolvingCaptcha] = useState(false)
249+
const isSubmitting = isSolvingCaptcha || submitDemoRequest.isPending
250+
const submitError = submitDemoRequest.isError
251+
? toError(submitDemoRequest.error).message || 'Something went wrong. Please try again.'
252+
: null
209253

210-
// Best-effort sales notification — fire-and-forget so it never blocks scheduling.
211-
submitDemoRequest.mutate({
254+
const handleSubmit = async () => {
255+
if (!canSubmit || isSubmitting) return
256+
257+
const request: DemoRequestBody = {
212258
firstName: form.firstName.trim(),
213259
lastName: form.lastName.trim(),
214260
companyEmail: trimmedEmail,
215261
phoneNumber: form.phone.trim() || undefined,
216262
companySize: form.companySize as DemoRequestBody['companySize'],
217263
details: buildDetails(form),
218-
})
264+
website,
265+
}
219266

220-
onComplete({
267+
const lead: DemoLead = {
221268
name: `${form.firstName} ${form.lastName}`.trim(),
222269
email: trimmedEmail,
223270
notes: buildNotes(form),
224-
})
271+
}
272+
273+
setIsSolvingCaptcha(true)
274+
const captchaToken = await solveCaptcha()
275+
setIsSolvingCaptcha(false)
276+
277+
submitDemoRequest.mutate({ ...request, captchaToken }, { onSuccess: () => onComplete(lead) })
225278
}
226279

227280
return (
@@ -236,114 +289,158 @@ export function DemoForm({ onComplete }: DemoFormProps) {
236289
<form
237290
onSubmit={(event) => {
238291
event.preventDefault()
239-
handleSubmit()
292+
void handleSubmit()
240293
}}
241294
aria-labelledby='demo-form-heading'
242-
className='mt-5 flex flex-col gap-4'
295+
className='relative mt-5 flex flex-col gap-4'
243296
noValidate
297+
onFocusCapture={() => setCaptchaArmed(true)}
244298
>
245-
<div className='grid grid-cols-2 gap-3 max-sm:grid-cols-1'>
246-
<DemoField label='First name' htmlFor='demo-first-name' required>
299+
{/* Out of flow, so neither control adds a row or a gap to the pinned card height. */}
300+
<div
301+
aria-hidden='true'
302+
className='pointer-events-none absolute left-[-9999px] size-px overflow-hidden opacity-0'
303+
>
304+
<label htmlFor='demo-website'>Website</label>
305+
<input
306+
id='demo-website'
307+
name='website'
308+
type='text'
309+
tabIndex={-1}
310+
autoComplete='off'
311+
value={website}
312+
onChange={(event) => setWebsite(event.target.value)}
313+
data-lpignore='true'
314+
data-1p-ignore='true'
315+
/>
316+
{TURNSTILE_SITE_KEY && captchaArmed ? (
317+
<Turnstile
318+
ref={turnstileRef}
319+
siteKey={TURNSTILE_SITE_KEY}
320+
options={{ execution: 'execute', appearance: 'execute', size: 'invisible' }}
321+
onWidgetLoad={() => {
322+
widgetLoadedRef.current = true
323+
}}
324+
onError={() => {
325+
widgetLoadedRef.current = false
326+
}}
327+
onUnsupported={() => {
328+
widgetLoadedRef.current = false
329+
}}
330+
/>
331+
) : null}
332+
</div>
333+
{/* Locked while submitting, so the request and the scheduler's prefill never go stale mid-wait. */}
334+
<fieldset disabled={isSubmitting} className='m-0 flex min-w-0 flex-col gap-4 border-0 p-0'>
335+
<div className='grid grid-cols-2 gap-3 max-sm:grid-cols-1'>
336+
<DemoField label='First name' htmlFor='demo-first-name' required>
337+
<ChipInput
338+
id='demo-first-name'
339+
className={FIELD_HEIGHT}
340+
value={form.firstName}
341+
onChange={(event) => setField('firstName')(event.target.value)}
342+
placeholder='Jane'
343+
autoComplete='given-name'
344+
/>
345+
</DemoField>
346+
<DemoField label='Last name' htmlFor='demo-last-name' required>
347+
<ChipInput
348+
id='demo-last-name'
349+
className={FIELD_HEIGHT}
350+
value={form.lastName}
351+
onChange={(event) => setField('lastName')(event.target.value)}
352+
placeholder='Doe'
353+
autoComplete='family-name'
354+
/>
355+
</DemoField>
356+
</div>
357+
358+
<DemoField label='Work email' htmlFor='demo-email' required error={emailError}>
247359
<ChipInput
248-
id='demo-first-name'
360+
id='demo-email'
361+
type='email'
249362
className={FIELD_HEIGHT}
250-
value={form.firstName}
251-
onChange={(event) => setField('firstName')(event.target.value)}
252-
placeholder='Jane'
253-
autoComplete='given-name'
363+
value={form.email}
364+
onChange={(event) => setField('email')(event.target.value)}
365+
error={Boolean(emailError)}
366+
placeholder='jane@acme.co'
367+
autoComplete='email'
254368
/>
255369
</DemoField>
256-
<DemoField label='Last name' htmlFor='demo-last-name' required>
370+
371+
<DemoField label='Phone number (optional)' htmlFor='demo-phone'>
257372
<ChipInput
258-
id='demo-last-name'
373+
id='demo-phone'
374+
type='tel'
259375
className={FIELD_HEIGHT}
260-
value={form.lastName}
261-
onChange={(event) => setField('lastName')(event.target.value)}
262-
placeholder='Doe'
263-
autoComplete='family-name'
376+
value={form.phone}
377+
onChange={(event) => setField('phone')(event.target.value)}
378+
placeholder='+1 (555) 000-0000'
379+
autoComplete='tel'
264380
/>
265381
</DemoField>
266-
</div>
267382

268-
<DemoField label='Work email' htmlFor='demo-email' required error={emailError}>
269-
<ChipInput
270-
id='demo-email'
271-
type='email'
272-
className={FIELD_HEIGHT}
273-
value={form.email}
274-
onChange={(event) => setField('email')(event.target.value)}
275-
error={Boolean(emailError)}
276-
placeholder='jane@acme.co'
277-
autoComplete='email'
278-
/>
279-
</DemoField>
280-
281-
<DemoField label='Phone number (optional)' htmlFor='demo-phone'>
282-
<ChipInput
283-
id='demo-phone'
284-
type='tel'
285-
className={FIELD_HEIGHT}
286-
value={form.phone}
287-
onChange={(event) => setField('phone')(event.target.value)}
288-
placeholder='+1 (555) 000-0000'
289-
autoComplete='tel'
290-
/>
291-
</DemoField>
292-
293-
<DemoField label='Company' htmlFor='demo-company' required>
294-
<ChipInput
295-
id='demo-company'
296-
className={FIELD_HEIGHT}
297-
value={form.company}
298-
onChange={(event) => setField('company')(event.target.value)}
299-
placeholder='Acme Inc.'
300-
autoComplete='organization'
301-
/>
302-
</DemoField>
303-
304-
<DemoField label='Company size' required>
305-
<ChipDropdown
306-
fullWidth
307-
className={FIELD_HEIGHT}
308-
value={form.companySize || undefined}
309-
onChange={setField('companySize')}
310-
options={DEMO_REQUEST_COMPANY_SIZE_OPTIONS}
311-
placeholder='Select one'
312-
/>
313-
</DemoField>
314-
315-
<DemoField label='What can we help you with?'>
316-
<ChipDropdown
317-
fullWidth
318-
className={FIELD_HEIGHT}
319-
value={form.topic}
320-
onChange={setField('topic')}
321-
options={TOPIC_OPTIONS}
322-
/>
323-
</DemoField>
324-
325-
<DemoField label='Anything else we should know? (optional)' htmlFor='demo-message'>
326-
<ChipTextarea
327-
id='demo-message'
328-
value={form.message}
329-
onChange={(event) => setField('message')(event.target.value)}
330-
placeholder='What are you hoping to build with Sim?'
331-
rows={3}
332-
/>
333-
</DemoField>
383+
<DemoField label='Company' htmlFor='demo-company' required>
384+
<ChipInput
385+
id='demo-company'
386+
className={FIELD_HEIGHT}
387+
value={form.company}
388+
onChange={(event) => setField('company')(event.target.value)}
389+
placeholder='Acme Inc.'
390+
autoComplete='organization'
391+
/>
392+
</DemoField>
393+
394+
<DemoField label='Company size' required>
395+
<ChipDropdown
396+
fullWidth
397+
className={FIELD_HEIGHT}
398+
value={form.companySize || undefined}
399+
onChange={setField('companySize')}
400+
options={DEMO_REQUEST_COMPANY_SIZE_OPTIONS}
401+
placeholder='Select one'
402+
/>
403+
</DemoField>
404+
405+
<DemoField label='What can we help you with?'>
406+
<ChipDropdown
407+
fullWidth
408+
className={FIELD_HEIGHT}
409+
value={form.topic}
410+
onChange={setField('topic')}
411+
options={TOPIC_OPTIONS}
412+
/>
413+
</DemoField>
414+
415+
<DemoField label='Anything else we should know? (optional)' htmlFor='demo-message'>
416+
<ChipTextarea
417+
id='demo-message'
418+
value={form.message}
419+
onChange={(event) => setField('message')(event.target.value)}
420+
placeholder='What are you hoping to build with Sim?'
421+
rows={3}
422+
/>
423+
</DemoField>
424+
425+
{/*
426+
`Chip` gives its label span `flex-1`; under `fullWidth` that left-aligns the
427+
label, so center it with `justify-center` + a `flex-none` span override.
428+
*/}
429+
</fieldset>
430+
{submitError ? (
431+
<p role='alert' className='text-[var(--text-error)] text-caption'>
432+
{submitError}
433+
</p>
434+
) : null}
334435

335-
{/*
336-
`Chip` gives its label span `flex-1`; under `fullWidth` that left-aligns the
337-
label, so center it with `justify-center` + a `flex-none` span override.
338-
*/}
339436
<Chip
340437
type='submit'
341438
variant='primary'
342439
fullWidth
343-
disabled={!canSubmit}
440+
disabled={!canSubmit || isSubmitting}
344441
className='mt-1 justify-center [&>span]:flex-none'
345442
>
346-
Continue
443+
{isSubmitting ? 'Continuing…' : 'Continue'}
347444
</Chip>
348445
</form>
349446
</>

0 commit comments

Comments
 (0)