Skip to content

The open alternative to Salesforce, designed for AI.

3.3 KB
Raw Blame
import { PAYMENT_RECOVERY_POLLING_INTERVAL_MS } from '@/settings/billing/constants/PaymentRecoveryPollingIntervalMs';
import { PAYMENT_RECOVERY_POLLING_MAX_ATTEMPTS } from '@/settings/billing/constants/PaymentRecoveryPollingMaxAttempts';
import { useApplyCurrentWorkspaceBillingUpdate } from '@/settings/billing/hooks/useApplyCurrentWorkspaceBillingUpdate';
import { useMarkBillingPaymentMethodAsAdded } from '@/settings/billing/hooks/useMarkBillingPaymentMethodAsAdded';
import { waitForSubscriptionRecovery } from '@/settings/billing/utils/waitForSubscriptionRecovery';
import { NavigationButton } from '@/ui/input/components/NavigationButton';
import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
import { useApolloClient } from '@apollo/client/react';
import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import { GetCurrentUserDocument } from '~/generated-metadata/graphql';
import { logError } from '~/utils/logError';
import { sleep } from '~/utils/sleep';
import { useLingui } from '@lingui/react/macro';

export const useWaitForPaymentRecovery = () => {
  const { t } = useLingui();
  const client = useApolloClient();
  const { loadCurrentUser } = useLoadCurrentUser();
  const { applyCurrentWorkspaceBillingUpdate } =
    useApplyCurrentWorkspaceBillingUpdate();
  const { markBillingPaymentMethodAsAdded } =
    useMarkBillingPaymentMethodAsAdded();
  const { enqueueToast } = useToast();

  const fetchWorkspaceBilling = async () => {
    const { data } = await client.query({
      query: GetCurrentUserDocument,
      fetchPolicy: 'network-only',
    });

    return data?.currentUser.currentWorkspace;
  };

  // The retry itself runs server-side from the setup_intent.succeeded webhook
  // and only reaches the persisted subscription through the invoice and
  // subscription webhooks, so its outcome can only be observed by polling
  const waitForPaymentRecovery = async () => {
    const recovery = await waitForSubscriptionRecovery({
      fetchWorkspaceBilling,
      getSubscriptionStatus: (workspaceBilling) =>
        workspaceBilling?.currentBillingSubscription?.status,
      waitBeforeAttempt: () => sleep(PAYMENT_RECOVERY_POLLING_INTERVAL_MS),
      maxAttempts: PAYMENT_RECOVERY_POLLING_MAX_ATTEMPTS,
    });

    if (recovery.outcome !== 'recovered') {
      enqueueToast({
        status: 'warning',
        children: t`Your card was saved, but the payment still needs attention.`,
        action: (
          <NavigationButton
            to={getSettingsPath(SettingsPath.Billing)}
            variant="ghost"
            size="sm"
          >
            {t`Go to billing`}
          </NavigationButton>
        ),
      });

      return;
    }

    try {
      await loadCurrentUser();
    } catch {
      const hasAppliedBillingUpdate = applyCurrentWorkspaceBillingUpdate(
        recovery.workspaceBilling,
      );

      if (!hasAppliedBillingUpdate) {
        logError(
          'Payment recovered but the workspace billing state could not be refreshed',
        );
      }
    }

    // The payment method webhook can still be in flight
    markBillingPaymentMethodAsAdded();

    enqueueToast({ status: 'success', children: t`Payment successful.` });
  };

  return { waitForPaymentRecovery };
};