import type { BlitzPage, GetServerSideProps } from "blitz"; import { Routes, getSession, useRouter, useMutation } from "blitz"; import { useEffect } from "react"; import twilio from "twilio"; 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"; 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.authenticate = true; 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: { customerId: session.userId } }); if (phoneNumber) { return { redirect: { destination: Routes.Messages().pathname, permanent: false, }, }; } const customer = await db.customer.findFirst({ where: { id: session.userId } }); if (!customer) { return { redirect: { destination: Routes.StepOne().pathname, permanent: false, }, }; } if (!customer.accountSid || !customer.authToken) { return { redirect: { destination: Routes.StepTwo().pathname, permanent: false, }, }; } const incomingPhoneNumbers = await twilio( customer.accountSid, customer.authToken ).incomingPhoneNumbers.list(); const phoneNumbers = incomingPhoneNumbers.map(({ phoneNumber, sid }) => ({ phoneNumber, sid })); return { props: { availablePhoneNumbers: phoneNumbers, }, }; }; export default StepThree;