:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signup): point org creation errors at the field that failed (#91381)
posthog[bot]6f9b8b357027
diff --git a/frontend/src/lib/components/SignupReferralSource.tsx b/frontend/src/lib/components/SignupReferralSource.tsxindex 7a470c908248..5767219865a1 100644--- a/frontend/src/lib/components/SignupReferralSource.tsx+++ b/frontend/src/lib/components/SignupReferralSource.tsx@@ -82,7 +82,7 @@ export default function SignupReferralSource({ disabled }: { disabled: boolean }<LemonInputclassName="ph-ignore-input"data-attr="signup-referral-source"- placeholder=""+ placeholder="e.g. a colleague, or a web search"disabled={disabled}value={value ?? ''}onChange={onChange}diff --git a/frontend/src/lib/components/SignupRoleSelect.tsx b/frontend/src/lib/components/SignupRoleSelect.tsxindex 2a885a6e8cba..718017c1e1fd 100644--- a/frontend/src/lib/components/SignupRoleSelect.tsx+++ b/frontend/src/lib/components/SignupRoleSelect.tsx@@ -31,7 +31,18 @@ const roleOptions = [...shuffle(ROLE_OPTIONS), OTHER_ROLE_OPTION]export default function SignupRoleSelect({ className }: { className?: string }): JSX.Element {return (<LemonField name="role_at_organization" label="What is your role?" className={className}>- <LemonSelect fullWidth data-attr="signup-role-at-organization" options={roleOptions} />+ {({ value, onChange }) => (+ <LemonSelect+ fullWidth+ data-attr="signup-role-at-organization"+ options={roleOptions}+ // The signup forms default this to an empty string, which LemonSelect treats as a+ // selected value and renders as a blank button rather than the placeholder+ value={value || undefined}+ onChange={onChange}+ placeholder="Select your role"+ />+ )}</LemonField>)}diff --git a/frontend/src/scenes/organization/ConfirmOrganization/ConfirmOrganization.test.tsx b/frontend/src/scenes/organization/ConfirmOrganization/ConfirmOrganization.test.tsxnew file mode 100644index 000000000000..07cf7eb70dd2--- /dev/null+++ b/frontend/src/scenes/organization/ConfirmOrganization/ConfirmOrganization.test.tsx@@ -0,0 +1,48 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { Provider } from 'kea'+import { router } from 'kea-router'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { ConfirmOrganization } from './ConfirmOrganization'++describe('ConfirmOrganization', () => {+ beforeEach(() => {+ useMocks({+ get: {+ // The page only renders for a logged-out person+ '/api/users/@me/': () => [401, { detail: 'Not authenticated' }],+ },+ })+ window.POSTHOG_APP_CONTEXT = { current_user: null } as any+ initKeaTests()+ // The social signup redirect fills in everything except the organization name+ router.actions.push('/organization/confirm-creation', { email: '[email protected]', first_name: 'Spike' })+ render(+ <Provider>+ <ConfirmOrganization />+ </Provider>+ )+ })++ afterEach(() => {+ cleanup()+ })++ it('points a failed submit at the organization name input', async () => {+ await userEvent.click(screen.getByText('Create organization'))++ expect(screen.getByLabelText('Organization name')).toHaveFocus()+ expect(screen.getByText(/You can use your own name/)).toBeInTheDocument()+ })++ it('prompts for a role while the dropdown has nothing selected', () => {+ // The form defaults the role to an empty string, which LemonSelect would otherwise render+ // as a blank button+ expect(screen.getByText('Select your role')).toBeInTheDocument()+ })+})diff --git a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.test.ts b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.test.tsindex 599f90de5ff8..9badcbb42984 100644--- a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.test.ts+++ b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.test.ts@@ -1,10 +1,14 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { confirmOrganizationLogic } from './confirmOrganizationLogic'+const ORGANIZATION_NAME_ERROR =+ "Please enter an organization name. You can use your own name if you don't belong to one."+describe('confirmOrganizationLogic', () => {let logic: ReturnType<typeof confirmOrganizationLogic.build>@@ -15,37 +19,96 @@ describe('confirmOrganizationLogic', () => {})describe('query params', () => {- it('set the default values', async () => {+ it('prefills the form from the URL', async () => {router.actions.push('/organization/confirm-creation', {email: '[email protected]',first_name: 'Spike',organization_name: 'Spikes Inc',- role_at_organization: 'engineering',})- expectLogic(logic)+ await expectLogic(logic).toDispatchActions(['setEmail', 'setConfirmOrganizationValues']).toMatchValues({- confirmOrganization: {+ confirmOrganization: expect.objectContaining({first_name: 'Spike',organization_name: 'Spikes Inc',- role_at_organization: 'engineering',- },+ }),email: '[email protected]',})})++ it('keeps user input when a later location change re-fires the handler', async () => {+ router.actions.push('/organization/confirm-creation', { email: '[email protected]' })++ logic.actions.setConfirmOrganizationValue('organization_name', 'Spikes Inc')++ // The docs side panel and similar links change the URL without the prefill params.+ router.actions.push('/organization/confirm-creation', { panel: 'docs' })++ await expectLogic(logic).toMatchValues({+ confirmOrganization: expect.objectContaining({ organization_name: 'Spikes Inc' }),+ })+ })})describe('form', () => {- it('requires org name and first name to be set', async () => {+ it('requires a name and an organization name', async () => {await expectLogic(logic, () => {logic.actions.submitConfirmOrganization()}).toMatchValues({confirmOrganizationValidationErrors: {first_name: 'Please enter your name',- organization_name: 'Please enter your organization name',+ organization_name: ORGANIZATION_NAME_ERROR,},})})++ it.each([+ [' ', ORGANIZATION_NAME_ERROR],+ [' Spikes Inc ', undefined],+ ])('validates the organization name %p on its trimmed value', (organizationName, expectedError) => {+ logic.actions.setConfirmOrganizationValue('organization_name', organizationName)++ expect(logic.values.confirmOrganizationValidationErrors.organization_name).toEqual(expectedError)+ })++ it('shows the organization name error on touch, before any submit', () => {+ expect(logic.values.confirmOrganizationErrors).toEqual({})++ logic.actions.touchConfirmOrganizationField('organization_name')+ expect(logic.values.confirmOrganizationErrors).toEqual({ organization_name: ORGANIZATION_NAME_ERROR })++ logic.actions.setConfirmOrganizationValue('organization_name', 'Spikes Inc')+ expect(logic.values.confirmOrganizationErrors).toEqual({})+ })++ it('puts an API error on the field it names, and lets the next attempt through', async () => {+ useMocks({+ post: {+ '/api/social_signup/': () => [+ 400,+ {+ type: 'validation_error',+ code: 'invalid_input',+ detail: 'This name is not allowed.',+ attr: 'organization_name',+ },+ ],+ },+ })+ logic.actions.setConfirmOrganizationValues({ first_name: 'Spike', organization_name: 'Spikes Inc' })++ await expectLogic(logic, () => {+ logic.actions.submitConfirmOrganization()+ }).toFinishAllListeners()++ expect(logic.values.confirmOrganizationErrors).toEqual({ organization_name: 'This name is not allowed.' })++ // A manual error only clears when its own field is touched, so without preSubmit clearing+ // it the person could never retry+ await expectLogic(logic, () => {+ logic.actions.submitConfirmOrganization()+ }).toDispatchActions(['submitConfirmOrganizationRequest'])+ })})})diff --git a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.tsindex 06d4ad6faa80..4a1228899e9c 100644--- a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts+++ b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts@@ -1,4 +1,4 @@-import { MakeLogicType, actions, kea, path, reducers } from 'kea'+import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { urlToAction } from 'kea-router'@@ -16,6 +16,21 @@ export interface ConfirmOrganizationFormValues {referral_source_ai_prompt?: string}+const LOGIC_PATH = ['scenes', 'organization', 'confirmOrganizationLogic']+const FORM_KEY = 'confirmOrganization'++// In the order the form renders them, so a failed submit lands on the first field to fix+const FIELDS_IN_RENDER_ORDER: (keyof ConfirmOrganizationFormValues)[] = [+ 'first_name',+ 'organization_name',+ 'role_at_organization',+ 'referral_source',+ 'referral_source_ai_prompt',+]++// kea-forms ids each field input `<logic path>.<form key>.<field>`+const fieldInputId = (field: keyof ConfirmOrganizationFormValues): string => [...LOGIC_PATH, FORM_KEY, field].join('.')+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface confirmOrganizationLogicValues {confirmOrganization: ConfirmOrganizationFormValues@@ -28,6 +43,7 @@ export interface confirmOrganizationLogicValues {confirmOrganizationTouches: Record<string, boolean>confirmOrganizationValidationErrors: DeepPartialMap<ConfirmOrganizationFormValues, ValidationErrorType>email: string+ hasPrefilled: booleanisConfirmOrganizationSubmitting: booleanisConfirmOrganizationValid: booleanshowConfirmOrganizationErrors: boolean@@ -55,6 +71,9 @@ export interface confirmOrganizationLogicActions {setEmail: (email: string) => {email: string}+ setHasPrefilled: () => {+ value: true+ }setShowNewOrgWarning: (show: boolean) => {show: boolean}@@ -85,11 +104,12 @@ export type confirmOrganizationLogicType = MakeLogicType<>export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([- path(['scenes', 'organization', 'confirmOrganizationLogic']),+ path(LOGIC_PATH),actions({setEmail: (email: string) => ({email,}),+ setHasPrefilled: true,setShowNewOrgWarning: (show: boolean) => ({ show }),}),@@ -106,43 +126,111 @@ export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([setEmail: (_, { email }) => email,},],+ hasPrefilled: [+ false,+ {+ setHasPrefilled: () => true,+ },+ ],}),- forms(() => ({+ forms(({ actions }) => ({confirmOrganization: {+ options: {+ showErrorsOnTouch: true,+ },defaults: {+ organization_name: '',+ first_name: '',+ role_at_organization: '',// The partner that started the OAuth connection is where this person heard about PostHogreferral_source: readPendingOAuthConnection()?.clientName ?? '',+ referral_source_ai_prompt: '',} as ConfirmOrganizationFormValues,errors: ({ organization_name, first_name }) => ({- first_name: !first_name ? 'Please enter your name' : undefined,- organization_name: !organization_name ? 'Please enter your organization name' : undefined,+ first_name: !first_name?.trim() ? 'Please enter your name' : undefined,+ organization_name: !organization_name?.trim()+ ? "Please enter an organization name. You can use your own name if you don't belong to one."+ : undefined,}),+ // A manual error from a rejected attempt counts as a validation error, and only its own+ // field being touched clears it. Without this, fixing a different field never submits.+ preSubmit: () => {+ actions.setConfirmOrganizationManualErrors({})+ },+submit: async (formValues) => {- await api- .create('api/social_signup/', {+ try {+ await api.create('api/social_signup/', {...formValues,+ // Trim rather than reject: surrounding whitespace is still a good signup+ first_name: formValues.first_name?.trim(),+ organization_name: formValues.organization_name?.trim(),})- .then(() => {- const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)-- // this url is validated in getRelativeNextPath as either being relative or on the same origin- // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect- location.href = nextUrl || '/'- })- .catch((error: any) => {+ } catch (error: any) {+ const attr = error.attr as keyof ConfirmOrganizationFormValues | undefined+ if (attr && FIELDS_IN_RENDER_ORDER.includes(attr) && error.detail) {+ // Put the message on the field the API names, rather than in a toast that+ // leaves the person guessing which input to fix+ actions.setConfirmOrganizationManualErrors({ [attr]: String(error.detail) })+ } else {console.error('error', error)lemonToast.error(error.detail || 'Failed to create organization')- })+ }+ // Rethrow so kea-forms keeps the errors on screen. A swallowed rejection counts+ // as a successful submit, which hides them again.+ throw error+ }++ const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)++ // this url is validated in getRelativeNextPath as either being relative or on the same origin+ // nosemgrep: javascript.browser.security.open-redirect.js-open-redirect+ location.href = nextUrl || '/'},},})),- urlToAction(({ actions }) => ({+ listeners(({ values }) => ({+ // kea-forms passes its own `errors` payload here, but reads it off a selector that does not+ // exist, so it always arrives undefined. Take the errors from the logic instead.+ submitConfirmOrganizationFailure: () => {+ const errors = values.confirmOrganizationAllErrors+ const firstInvalidField = FIELDS_IN_RENDER_ORDER.find((field) => errors[field])+ if (!firstInvalidField) {+ return+ }+ const input = document.getElementById(fieldInputId(firstInvalidField))+ // preventScroll so the smooth scroll below is the only movement the person sees+ input?.focus({ preventScroll: true })+ input?.scrollIntoView({ behavior: 'smooth', block: 'center' })+ },+ })),++ urlToAction(({ actions, values }) => ({'/organization/confirm-creation': (_, { email, organization_name, first_name }) => {- actions.setConfirmOrganizationValues({ organization_name, first_name })- actions.setEmail(email)+ // Prefill from the URL once. Later location changes on this same page (for example+ // opening the docs side panel) re-fire this handler with empty params, which would+ // otherwise wipe what the user has typed.+ if (values.hasPrefilled) {+ return+ }+ actions.setHasPrefilled()++ if (email) {+ actions.setEmail(email)+ }+ const prefill: DeepPartial<ConfirmOrganizationFormValues> = {}+ if (organization_name) {+ prefill.organization_name = organization_name+ }+ if (first_name) {+ prefill.first_name = first_name+ }+ if (Object.keys(prefill).length > 0) {+ actions.setConfirmOrganizationValues(prefill)+ }},})),])