Skip to content

The open alternative to Salesforce, designed for AI.

2.1 KB
Raw Blame
import { useRedirect } from '@/domain-manager/hooks/useRedirect';
import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { useMutation } from '@apollo/client/react';
import { useState } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import {
  type BillingPlanKey,
  type SubscriptionInterval,
  CheckoutSessionDocument,
} from '~/generated-metadata/graphql';
import { useLingui } from '@lingui/react/macro';

export const useHandleCheckoutSession = ({
  recurringInterval,
  plan,
  requirePaymentMethod,
  successUrlPath,
}: {
  recurringInterval: SubscriptionInterval;
  plan: BillingPlanKey;
  requirePaymentMethod: boolean;
  successUrlPath: string;
}) => {
  const { t } = useLingui();
  const { redirect } = useRedirect();

  const { enqueueToast } = useToast();

  const [checkoutSession] = useMutation(CheckoutSessionDocument);

  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleCheckoutSession = async () => {
    setIsSubmitting(true);
    try {
      const { data } = await checkoutSession({
        variables: {
          recurringInterval,
          successUrlPath,
          plan,
          requirePaymentMethod,
        },
      });
      if (!data?.checkoutSession.url) {
        enqueueToast({
          status: 'error',
          children: t`Checkout session error. Please retry or contact Twenty team`,
        });
        return;
      }
      redirect(data.checkoutSession.url);
    } catch (error) {
      const toastOptions =
        CombinedGraphQLErrors.is(error) &&
        isDefined(error.errors[0]?.extensions?.userFriendlyMessage)
          ? getToastOptionsFromError({ error })
          : undefined;

      enqueueToast(
        toastOptions ?? {
          status: 'error',
          children: t`Checkout session error. Please retry or contact Twenty team`,
        },
      );
    } finally {
      setIsSubmitting(false);
    }
  };
  return { isSubmitting, handleCheckoutSession };
};