import { Button } from "@/src/components/ui/button"; import { useEffect } from "react"; import type * as z from "zod/v4"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, FormDescription, } from "@/src/components/ui/form"; import { Input } from "@/src/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/src/components/ui/select"; import { api } from "@/src/utils/api"; import { useSession } from "next-auth/react"; import { organizationFormSchema } from "@/src/features/organizations/utils/organizationNameSchema"; import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture"; import { SurveyName } from "@prisma/client"; import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks"; export const NewOrganizationForm = ({ onSuccess, }: { onSuccess: (orgId: string) => void; }) => { const { update: updateSession } = useSession(); const form = useForm({ resolver: zodResolver(organizationFormSchema), defaultValues: { name: "", type: "Personal", size: undefined, }, }); const capture = usePostHogClientCapture(); const createOrgMutation = api.organizations.create.useMutation({ onError: (error) => form.setError("name", { message: error.message }), }); const createSurveyMutation = api.surveys.create.useMutation(); const watchedType = form.watch("type"); const { isLangfuseCloud } = useLangfuseCloudRegion(); function onSubmit(values: z.infer) { capture("organizations:new_form_submit"); createOrgMutation .mutateAsync({ name: values.name, }) .then(async (org) => { // Submit survey with organization data only on Cloud and if type is provided if (isLangfuseCloud && values.type) { const surveyResponse: Record = { type: values.type, }; if (values.size) { surveyResponse.size = values.size; } try { await createSurveyMutation.mutateAsync({ surveyName: SurveyName.ORG_ONBOARDING, response: surveyResponse, orgId: org.id, }); } catch (error) { console.error("Failed to submit survey:", error); // Continue with organization creation even if survey fails } } void updateSession(); onSuccess(org.id); form.reset(); }) .catch((error) => { console.error(error); }); } // Clear size whenever type is not Company or Agency to avoid submitting hidden values useEffect(() => { if (watchedType !== "Company" && watchedType !== "Agency") { form.setValue("size", undefined); } }, [watchedType, form]); return (
{ if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); void form.handleSubmit(onSubmit)(); } }} > ( Organization name )} /> {isLangfuseCloud && ( <> ( Type What would best describe your organization? )} /> {(watchedType === "Company" || watchedType === "Agency") && ( ( {watchedType} size How many people are in your {watchedType}? )} /> )} )} ); };