import { zodResolver } from "@hookform/resolvers/zod"; import { noop } from "lodash"; import { useCallback, useState } from "react"; import { Controller, FormProvider, useForm, useFormState } from "react-hook-form"; import * as z from "zod"; import { classNames } from "@calcom/lib"; import { CONSOLE_URL } from "@calcom/lib/constants"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { RouterInputs, RouterOutputs, trpc } from "@calcom/trpc/react"; import { Button, TextField } from "@calcom/ui"; import { FiCheck, FiExternalLink, FiLoader } from "@calcom/ui/components/icon"; type EnterpriseLicenseFormValues = { licenseKey: string; }; const makeSchemaLicenseKey = (args: { callback: (valid: boolean) => void; onSuccessValidate: () => void }) => z.object({ licenseKey: z .string() .uuid({ message: "License key must follow UUID format: 8-4-4-4-12", }) .superRefine(async (data, ctx) => { const parse = z.string().uuid().safeParse(data); if (parse.success) { args.callback(true); const response = await fetch(`${CONSOLE_URL}/api/license?key=${data}`); args.callback(false); const json = await response.json(); if (!json.valid) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: `License key ${json.message.toLowerCase()}`, }); } else { args.onSuccessValidate(); } } }), }); const EnterpriseLicense = ( props: { licenseKey?: string; initialValue?: Partial; onSuccessValidate: () => void; onSubmit: (value: EnterpriseLicenseFormValues) => void; onSuccess?: ( data: RouterOutputs["viewer"]["deploymentSetup"]["update"], variables: RouterInputs["viewer"]["deploymentSetup"]["update"] ) => void; } & Omit ) => { const { onSubmit, onSuccess = noop, onSuccessValidate = noop, ...rest } = props; const { t } = useLocale(); const [checkLicenseLoading, setCheckLicenseLoading] = useState(false); const mutation = trpc.viewer.deploymentSetup.update.useMutation({ onSuccess, }); const schemaLicenseKey = useCallback( () => makeSchemaLicenseKey({ callback: setCheckLicenseLoading, onSuccessValidate, }), [setCheckLicenseLoading, onSuccessValidate] ); const formMethods = useForm({ defaultValues: { licenseKey: props.licenseKey || "", }, resolver: zodResolver(schemaLicenseKey()), }); const handleSubmit = formMethods.handleSubmit((values) => { onSubmit(values); setCheckLicenseLoading(false); mutation.mutate(values); }); const { isDirty, errors } = useFormState(formMethods); return (

OR
{t("already_have_key")} ( ) : errors.licenseKey === undefined && isDirty ? ( ) : undefined } color={errors.licenseKey ? "warn" : ""} onBlur={onBlur} onChange={async (e: React.ChangeEvent) => { onChange(e.target.value); formMethods.setValue("licenseKey", e.target.value); await formMethods.trigger("licenseKey"); }} /> )} />
); }; export default EnterpriseLicense;