Skip to content

The open alternative to Salesforce, designed for AI.

5.8 KB
Raw Blame
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { useRedirect } from '@/domain-manager/hooks/useRedirect';
import { START_SUBSCRIPTION_AFTER_PAYMENT_METHOD_QUERY_PARAM } from '@/settings/billing/constants/StartSubscriptionAfterPaymentMethodQueryParam';
import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';
import { useLazyQuery, useMutation } from '@apollo/client/react';
import { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import {
  BillingPortalSessionDocument,
  EndSubscriptionTrialPeriodDocument,
  GetResourceCreditUsageDocument,
} from '~/generated-metadata/graphql';
import { useLingui } from '@lingui/react/macro';

export const useEndSubscriptionTrialPeriod = () => {
  const { t } = useLingui();
  const { enqueueToast } = useToast();
  const [endSubscriptionTrialPeriod] = useMutation(
    EndSubscriptionTrialPeriodDocument,
    {
      refetchQueries: [GetResourceCreditUsageDocument],
    },
  );
  const [getBillingPortalSession] = useLazyQuery(BillingPortalSessionDocument);
  const [currentWorkspace, setCurrentWorkspace] = useAtomState(
    currentWorkspaceState,
  );
  const { applyCurrentWorkspaceBillingUpdate } =
    useApplyCurrentWorkspaceBillingUpdate();
  const [isLoading, setIsLoading] = useState(false);
  const { redirect } = useRedirect();
  const location = useLocation();

  const redirectToPaymentMethodUpdate = async (
    fallbackUrl: string | null | undefined,
    finalRedirectPath: string,
  ) => {
    const returnUrl = new URL(finalRedirectPath, 'https://placeholder.invalid');
    returnUrl.searchParams.set(
      START_SUBSCRIPTION_AFTER_PAYMENT_METHOD_QUERY_PARAM,
      'true',
    );
    const confirmReturnPath = `${returnUrl.pathname}${returnUrl.search}${returnUrl.hash}`;

    try {
      const { data } = await getBillingPortalSession({
        variables: {
          returnUrlPath: confirmReturnPath,
          forPaymentMethodUpdate: true,
        },
      });

      const portalUrl = data?.billingPortalSession.url ?? fallbackUrl;

      if (isDefined(portalUrl)) {
        redirect(portalUrl);
        return;
      }
    } catch {
      if (isDefined(fallbackUrl)) {
        redirect(fallbackUrl);
        return;
      }
    }

    enqueueToast({
      status: 'error',
      children: t`No payment method found. Please update your billing details.`,
    });
  };

  const endTrialPeriod = async (options?: {
    finalRedirectPath?: string;
    skipPaymentMethodRedirect?: boolean;
  }): Promise<{ success: boolean; hasPaymentMethod?: boolean }> => {
    try {
      setIsLoading(true);

      if (options?.skipPaymentMethodRedirect === true) {
        enqueueToast({
          status: 'info',
          children: t`Activating subscription...`,
        });
      }

      const finalRedirectPath =
        options?.finalRedirectPath ?? `${location.pathname}${location.search}`;

      const { data } = await endSubscriptionTrialPeriod();
      const endTrialPeriodOutput = data?.endSubscriptionTrialPeriod;

      const hasPaymentMethod = endTrialPeriodOutput?.hasPaymentMethod;

      if (isDefined(hasPaymentMethod) && hasPaymentMethod === false) {
        if (options?.skipPaymentMethodRedirect !== true) {
          await redirectToPaymentMethodUpdate(
            endTrialPeriodOutput?.billingPortalUrl,
            finalRedirectPath,
          );
        }

        return { success: false, hasPaymentMethod: false };
      }

      const updatedCurrentBillingSubscription =
        endTrialPeriodOutput?.currentBillingSubscription;
      const updatedBillingSubscriptions =
        endTrialPeriodOutput?.billingSubscriptions;

      const hasAppliedFullBillingUpdate =
        isDefined(updatedCurrentBillingSubscription) &&
        isDefined(updatedBillingSubscriptions)
          ? applyCurrentWorkspaceBillingUpdate({
              currentBillingSubscription: updatedCurrentBillingSubscription,
              billingSubscriptions: updatedBillingSubscriptions,
            })
          : false;

      const updatedSubscriptionStatus = endTrialPeriodOutput?.status;
      if (
        !hasAppliedFullBillingUpdate &&
        isDefined(updatedSubscriptionStatus) &&
        isDefined(currentWorkspace?.currentBillingSubscription)
      ) {
        setCurrentWorkspace({
          ...currentWorkspace,
          currentBillingSubscription: {
            ...currentWorkspace?.currentBillingSubscription,
            status: updatedSubscriptionStatus,
            billingSubscriptionItems:
              currentWorkspace?.currentBillingSubscription?.billingSubscriptionItems?.map(
                (item) => ({
                  ...item,
                  hasReachedCurrentPeriodCap: false,
                }),
              ),
          },
        });
      }

      setCurrentWorkspace((previousWorkspace) =>
        isDefined(previousWorkspace) &&
        isDefined(previousWorkspace.billingCustomer)
          ? {
              ...previousWorkspace,
              billingCustomer: {
                ...previousWorkspace.billingCustomer,
                hasPaymentMethod: true,
              },
            }
          : previousWorkspace,
      );

      enqueueToast({
        status: 'success',
        children: t`Subscription activated.`,
      });

      return { success: true, hasPaymentMethod: true };
    } catch {
      enqueueToast({
        status: 'error',
        children: t`Error while ending trial period. Please contact Twenty team.`,
      });
      return { success: false };
    } finally {
      setIsLoading(false);
    }
  };

  return {
    endTrialPeriod,
    isLoading,
  };
};