import type { BlitzPage, GetServerSideProps } from "blitz"; import { Routes, getSession, useRouter, useMutation } from "blitz"; import { useEffect } from "react"; import { useForm } from "react-hook-form"; import clsx from "clsx"; import db from "../../../../db"; import OnboardingLayout from "../../components/onboarding-layout"; import setPhoneNumber from "../../mutations/set-phone-number"; import getTwilioClient from "../../../../integrations/twilio"; type PhoneNumber = { phoneNumber: string; sid: string; }; type Props = { availablePhoneNumbers: PhoneNumber[]; }; type Form = { phoneNumberSid: string; }; const StepThree: BlitzPage = ({ availablePhoneNumbers }) => { const { register, handleSubmit, setValue, formState: { isSubmitting }, } = useForm
(); const router = useRouter(); const [setPhoneNumberMutation] = useMutation(setPhoneNumber); useEffect(() => { if (availablePhoneNumbers[0]) { setValue("phoneNumberSid", availablePhoneNumbers[0].sid); } }); const onSubmit = handleSubmit(async ({ phoneNumberSid }) => { if (isSubmitting) { return; } await setPhoneNumberMutation({ phoneNumberSid }); await router.push(Routes.Messages()); }); return (
); }; StepThree.getLayout = (page) => ( {page} ); StepThree.authenticate = { redirectTo: Routes.SignIn() }; export const getServerSideProps: GetServerSideProps = async ({ req, res }) => { const session = await getSession(req, res); if (!session.userId) { await session.$revoke(); return { redirect: { destination: Routes.Home().pathname, permanent: false, }, }; } const phoneNumber = await db.phoneNumber.findFirst({ where: { organizationId: session.orgId } }); if (phoneNumber) { await session.$setPublicData({ hasCompletedOnboarding: true }); return { redirect: { destination: Routes.Messages().pathname, permanent: false, }, }; } const organization = await db.organization.findFirst({ where: { id: session.orgId } }); if (!organization) { return { redirect: { destination: Routes.StepOne().pathname, permanent: false, }, }; } if (!organization.twilioAccountSid || !organization.twilioAuthToken) { return { redirect: { destination: Routes.StepTwo().pathname, permanent: false, }, }; } const twilioClient = getTwilioClient(organization); const incomingPhoneNumbers = await twilioClient.incomingPhoneNumbers.list(); const phoneNumbers = incomingPhoneNumbers.map(({ phoneNumber, sid }) => ({ phoneNumber, sid })); return { props: { availablePhoneNumbers: phoneNumbers, }, }; }; export default StepThree;