Skip to content

The open alternative to Salesforce, designed for AI.

5.9 KB
Raw Blame
import { currentUserState } from '@/auth/states/currentUserState';
import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
import { START_SUBSCRIPTION_AFTER_PAYMENT_METHOD_QUERY_PARAM } from '@/settings/billing/constants/StartSubscriptionAfterPaymentMethodQueryParam';
import { useStripeAppearance } from '@/settings/billing/hooks/useStripeAppearance';
import { useStripePromise } from '@/settings/billing/hooks/useStripePromise';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { useMutation } from '@apollo/client/react';
import { styled } from '@linaria/react';
import {
  Elements,
  PaymentElement,
  useElements,
  useStripe,
} from '@stripe/react-stripe-js';
import { useState } from 'react';
import { useLocation } from 'react-router-dom';
import { isDefined } from 'twenty-shared/utils';
import { InlineBanner, useToast } from 'twenty-ui/components/feedback';
import { Button } from 'twenty-ui/primitives/input';
import { themeCssVariables } from 'twenty-ui/theme';
import { CreateBillingPaymentMethodSetupIntentDocument } from '~/generated-metadata/graphql';
import { useLingui } from '@lingui/react/macro';

type AddPaymentMethodFormContentProps = {
  finalRedirectPath?: string;
  onPaymentMethodAdded: () => Promise<void>;
  shouldStartSubscriptionAfterPaymentMethod?: boolean;
};

type AddPaymentMethodFormProps = AddPaymentMethodFormContentProps;

const StyledFormContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: ${themeCssVariables.spacing[4]};
  width: 100%;
`;

const AddPaymentMethodFormContent = ({
  finalRedirectPath,
  onPaymentMethodAdded,
  shouldStartSubscriptionAfterPaymentMethod = true,
}: AddPaymentMethodFormContentProps) => {
  const { t } = useLingui();
  const stripe = useStripe();
  const elements = useElements();
  const { enqueueToast } = useToast();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const location = useLocation();

  const customerEmail = useAtomStateValue(currentUserState)?.email;

  const [createBillingPaymentMethodSetupIntent] = useMutation(
    CreateBillingPaymentMethodSetupIntentDocument,
  );

  const isStripeReady = isDefined(stripe) && isDefined(elements);

  const buildReturnUrl = () => {
    const basePath =
      finalRedirectPath ?? `${location.pathname}${location.search}`;
    const returnUrl = new URL(basePath, window.location.origin);

    if (shouldStartSubscriptionAfterPaymentMethod) {
      returnUrl.searchParams.set(
        START_SUBSCRIPTION_AFTER_PAYMENT_METHOD_QUERY_PARAM,
        'true',
      );
    }

    return returnUrl.toString();
  };

  const handleSubmit = async () => {
    if (!isStripeReady) {
      return;
    }

    setIsSubmitting(true);

    try {
      const { error: submitError } = await elements.submit();
      if (isDefined(submitError)) {
        enqueueToast({
          status: 'error',
          children:
            submitError.message ??
            t`Your payment details are incomplete. Please review and retry.`,
        });
        setIsSubmitting(false);
        return;
      }

      const { data } = await createBillingPaymentMethodSetupIntent();

      const clientSecret =
        data?.createBillingPaymentMethodSetupIntent?.clientSecret;
      if (!isDefined(clientSecret)) {
        enqueueToast({
          status: 'error',
          children: t`Subscription error. Please retry or contact Twenty team`,
        });
        setIsSubmitting(false);
        return;
      }

      const { error, setupIntent } = await stripe.confirmSetup({
        elements,
        clientSecret,
        confirmParams: { return_url: buildReturnUrl() },
        redirect: 'if_required',
      });

      if (isDefined(error)) {
        enqueueToast({
          status: 'error',
          children:
            error.message ??
            t`We couldn't confirm your payment method. Please retry.`,
        });
        setIsSubmitting(false);
        return;
      }

      if (setupIntent?.status === 'succeeded') {
        await onPaymentMethodAdded();
      }
    } catch (error) {
      if (CombinedGraphQLErrors.is(error)) {
        enqueueToast(getToastOptionsFromError({ error }));
      } else {
        enqueueToast({
          status: 'error',
          children: t`Subscription error. Please retry or contact Twenty team`,
        });
      }
      setIsSubmitting(false);
    }
  };

  return (
    <StyledFormContainer>
      <PaymentElement
        options={{
          defaultValues: isDefined(customerEmail)
            ? { billingDetails: { email: customerEmail } }
            : undefined,
        }}
      />
      <Button
        onClick={handleSubmit}
        fullWidth
        loading={isSubmitting}
        disabled={!isStripeReady || isSubmitting}
        variant="outline"
        color="accent"
      >{t`Add credit card`}</Button>
    </StyledFormContainer>
  );
};

export const AddPaymentMethodForm = ({
  finalRedirectPath,
  onPaymentMethodAdded,
  shouldStartSubscriptionAfterPaymentMethod,
}: AddPaymentMethodFormProps) => {
  const { t } = useLingui();
  const stripePromise = useStripePromise();
  const appearance = useStripeAppearance();

  if (!isDefined(stripePromise)) {
    return (
      <StyledFormContainer>
        <InlineBanner
          layout="compact"
          status="error"
        >{t`Card payment is currently unavailable. Please verify your Stripe configuration or contact your workspace admin.`}</InlineBanner>
      </StyledFormContainer>
    );
  }

  return (
    <Elements
      stripe={stripePromise}
      options={{ mode: 'setup', currency: 'usd', appearance }}
    >
      <AddPaymentMethodFormContent
        finalRedirectPath={finalRedirectPath}
        onPaymentMethodAdded={onPaymentMethodAdded}
        shouldStartSubscriptionAfterPaymentMethod={
          shouldStartSubscriptionAfterPaymentMethod
        }
      />
    </Elements>
  );
};