Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

12.1 KB
Raw Blame
import React, { useEffect } from "react";
import { Modal, Text, Group } from "@mantine/core";
import { ActionIcon } from "@editor/ui/ActionIcon";
import { useTranslation } from "react-i18next";
import { Icon } from "@editor/ui/Icon";
import licenseService from "@editor/services/licenseService";
import { useIsMobile } from "@editor/hooks/useIsMobile";
import { Z_INDEX_OVER_CONFIG_MODAL } from "@editor/styles/zIndex";
import { StripeCheckoutProps } from "@editor/components/shared/stripeCheckout/types/checkout";
import { getModalTitle } from "@editor/components/shared/stripeCheckout/utils/checkoutUtils";
import { calculateSavings } from "@editor/components/shared/stripeCheckout/utils/savingsCalculator";
import { useCheckoutState } from "@editor/components/shared/stripeCheckout/hooks/useCheckoutState";
import { useCheckoutNavigation } from "@editor/components/shared/stripeCheckout/hooks/useCheckoutNavigation";
import { useLicensePolling } from "@editor/components/shared/stripeCheckout/hooks/useLicensePolling";
import { useCheckoutSession } from "@editor/components/shared/stripeCheckout/hooks/useCheckoutSession";
import { PlanSelectionStage } from "@editor/components/shared/stripeCheckout/stages/PlanSelectionStage";
import { CapacityStage } from "@editor/components/shared/stripeCheckout/stages/CapacityStage";
import { blocksForUsers } from "@editor/components/shared/stripeCheckout/utils/capacity";
import { PaymentStage } from "@editor/components/shared/stripeCheckout/stages/PaymentStage";
import { SuccessStage } from "@editor/components/shared/stripeCheckout/stages/SuccessStage";
import { ErrorStage } from "@editor/components/shared/stripeCheckout/stages/ErrorStage";

// Validate Stripe key (static validation, no dynamic imports)
const STRIPE_KEY = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY;

if (!STRIPE_KEY) {
  console.error(
    "VITE_STRIPE_PUBLISHABLE_KEY environment variable is required. " +
      "Please add it to your .env file. " +
      "Get your key from https://dashboard.stripe.com/apikeys",
  );
}

if (STRIPE_KEY && !STRIPE_KEY.startsWith("pk_")) {
  console.error(
    `Invalid Stripe publishable key format. ` +
      `Expected key starting with 'pk_', got: ${STRIPE_KEY.substring(0, 10)}...`,
  );
}

const StripeCheckout: React.FC<StripeCheckoutProps> = ({
  opened,
  onClose,
  planGroup,
  minimumSeats = 1,
  combinedChoose: requestedCombinedChoose = false,
  currentLimit = null,
  capacityNotice,
  onContactSales,
  onSuccess,
  onError,
  onLicenseActivated,
  hostedCheckoutSuccess,
}) => {
  const { t } = useTranslation();
  const isMobile = useIsMobile();
  const sellsCapacity = planGroup.tier === "server";
  const combinedChoose = requestedCombinedChoose && sellsCapacity;
  const minimumCapacity = Math.max(minimumSeats, currentLimit ?? 0);

  // Initialize all state via custom hook
  const checkoutState = useCheckoutState(planGroup);

  // Initialize navigation hooks
  const navigation = useCheckoutNavigation(
    checkoutState.state,
    checkoutState.setState,
    checkoutState.stageHistory,
    checkoutState.setStageHistory,
  );

  // Initialize license polling hook
  const polling = useLicensePolling(
    checkoutState.isMountedRef,
    checkoutState.setPollingStatus,
    checkoutState.setLicenseKey,
    onLicenseActivated,
  );

  // Initialize checkout session hook
  const session = useCheckoutSession(
    checkoutState.selectedPlan,
    checkoutState.state,
    checkoutState.setState,
    checkoutState.installationId,
    checkoutState.setInstallationId,
    checkoutState.currentLicenseKey,
    checkoutState.setCurrentLicenseKey,
    checkoutState.setPollingStatus,
    minimumSeats,
    checkoutState.serverQuantity,
    polling.pollForLicenseKey,
    onSuccess,
    onError,
    onLicenseActivated,
    undefined,
    () => checkoutState.isMountedRef.current,
  );

  // Calculate savings
  const savings = calculateSavings(planGroup, minimumSeats);

  // Plan selection handler
  const handlePlanSelect = (period: "monthly" | "yearly") => {
    checkoutState.setSelectedPeriod(period);
    if (sellsCapacity) {
      // Arrive on the capacity an installation already needs rather than on a blocked minimum.
      checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));
      navigation.goToStage("capacity");
      return;
    }
    navigation.goToStage("payment");
  };

  // Close handler
  const handleClose = () => {
    checkoutState.isMountedRef.current = false;
    // Clear any active polling
    if (checkoutState.pollingTimeoutRef.current) {
      clearTimeout(checkoutState.pollingTimeoutRef.current);
      checkoutState.pollingTimeoutRef.current = null;
    }

    checkoutState.resetState();
    onClose();
  };

  // Cleanup on unmount
  useEffect(() => {
    checkoutState.isMountedRef.current = true;

    return () => {
      checkoutState.isMountedRef.current = false;
      if (checkoutState.pollingTimeoutRef.current) {
        clearTimeout(checkoutState.pollingTimeoutRef.current);
        checkoutState.pollingTimeoutRef.current = null;
      }
    };
  }, [checkoutState.isMountedRef, checkoutState.pollingTimeoutRef]);

  // Initialize stage based on existing license
  useEffect(() => {
    if (!opened) return;
    checkoutState.isMountedRef.current = true;

    // Handle hosted checkout success - open directly to success state
    if (hostedCheckoutSuccess) {
      console.log("Opening modal to success state for hosted checkout return");

      // Set appropriate state based on upgrade vs new subscription
      if (hostedCheckoutSuccess.isUpgrade) {
        checkoutState.setCurrentLicenseKey("existing"); // Flag to indicate upgrade
        checkoutState.setPollingStatus("ready");
      } else if (hostedCheckoutSuccess.licenseKey) {
        checkoutState.setLicenseKey(hostedCheckoutSuccess.licenseKey);
        checkoutState.setPollingStatus("ready");
      }

      // Set to success state to show success UI
      checkoutState.setState({ currentStage: "success", loading: false });
      return;
    }

    // Only installed licence upgrades need the previous key; Team belongs to the cloud account.
    const openOnFirstChoice = async () => {
      const landing = combinedChoose ? "choose" : "plan-selection";
      try {
        if (combinedChoose && sellsCapacity)
          checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));
        const licenseInfo = sellsCapacity
          ? null
          : await licenseService.getLicenseInfo();
        if (licenseInfo?.licenseType && licenseInfo.licenseType !== "NORMAL") {
          checkoutState.setCurrentLicenseKey(licenseInfo.licenseKey || null);
        }
      } catch (error) {
        // An unreadable licence only costs the upgrade metadata, so the purchase still proceeds.
        console.warn("Could not check for existing license:", error);
      }
      checkoutState.setState({ currentStage: landing, loading: false });
    };

    openOnFirstChoice();
  }, [
    opened,
    hostedCheckoutSuccess,
    combinedChoose,
    sellsCapacity,
    minimumCapacity,
    checkoutState.setServerQuantity,
    checkoutState.setEmailInput,
    checkoutState.setCurrentLicenseKey,
    checkoutState.setPollingStatus,
    checkoutState.setLicenseKey,
    checkoutState.setState,
  ]);

  // Trigger checkout session creation when entering payment stage
  useEffect(() => {
    if (
      checkoutState.state.currentStage === "payment" &&
      !checkoutState.state.clientSecret &&
      !checkoutState.state.loading
    ) {
      session.createCheckoutSession();
    }
  }, [
    checkoutState.state.currentStage,
    checkoutState.state.clientSecret,
    checkoutState.state.loading,
    session,
  ]);

  // Render stage content
  const renderContent = () => {
    // Don't block checkout - hosted mode works without publishable key
    // The checkout will automatically redirect to Stripe hosted page if key is missing
    switch (checkoutState.state.currentStage) {
      // Page 1 of 2: both choices at once, which is how the design puts them in front of a buyer.
      // The period cards select rather than navigate, and capacity supplies the single continue.
      case "choose":
        return (
          <CapacityStage
            selectedPlan={checkoutState.selectedPlan}
            serverQuantity={checkoutState.serverQuantity}
            setServerQuantity={checkoutState.setServerQuantity}
            currentUsers={minimumSeats}
            currentLimit={currentLimit}
            capacityNotice={capacityNotice}
            periodPicker={
              <PlanSelectionStage
                compact
                planGroup={planGroup}
                minimumSeats={minimumSeats}
                savings={savings}
                selectedPeriod={checkoutState.selectedPeriod}
                onSelectPlan={checkoutState.setSelectedPeriod}
              />
            }
            onContinue={() => navigation.goToStage("payment")}
            onContactSales={onContactSales}
          />
        );

      case "plan-selection":
        return (
          <PlanSelectionStage
            planGroup={planGroup}
            minimumSeats={minimumSeats}
            savings={savings}
            onSelectPlan={handlePlanSelect}
          />
        );

      case "capacity":
        return (
          <CapacityStage
            selectedPlan={checkoutState.selectedPlan}
            serverQuantity={checkoutState.serverQuantity}
            setServerQuantity={checkoutState.setServerQuantity}
            currentUsers={minimumSeats}
            currentLimit={currentLimit}
            capacityNotice={capacityNotice}
            onContinue={() => navigation.goToStage("payment")}
            onContactSales={onContactSales}
          />
        );

      case "payment":
        return (
          <PaymentStage
            clientSecret={checkoutState.state.clientSecret || null}
            selectedPlan={checkoutState.selectedPlan}
            onPaymentComplete={session.handlePaymentComplete}
          />
        );

      case "success":
        return (
          <SuccessStage
            isTeam={sellsCapacity}
            pollingStatus={checkoutState.pollingStatus}
            currentLicenseKey={checkoutState.currentLicenseKey}
            licenseKey={checkoutState.licenseKey}
            onClose={handleClose}
          />
        );

      case "error":
        return (
          <ErrorStage
            error={
              checkoutState.state.error ||
              t("payment.unknownError", "An unknown error occurred")
            }
            onClose={handleClose}
          />
        );

      default:
        return null;
    }
  };

  const canGoBack = checkoutState.stageHistory.length > 0;

  return (
    <Modal
      opened={opened}
      onClose={handleClose}
      title={
        <Group gap="sm" wrap="nowrap">
          {canGoBack && (
            <ActionIcon
              variant="tertiary"
              size="lg"
              disabled={checkoutState.state.loading}
              onClick={navigation.goBack}
              aria-label={t("common.back", "Back")}
            >
              <Icon name="arrow-left" size={20} />
            </ActionIcon>
          )}
          <Text fw={600} size="lg">
            {combinedChoose
              ? currentLimit != null
                ? t("payment.adjustTeam.title", "Adjust Team plan")
                : t("payment.upgradeTeam.title", "Get Stirling Team")
              : getModalTitle(
                  checkoutState.state.currentStage,
                  planGroup.name,
                  t,
                )}
          </Text>
        </Group>
      }
      size={isMobile ? "100%" : combinedChoose ? 860 : 980}
      centered
      radius="lg"
      withCloseButton
      closeOnEscape={true}
      closeOnClickOutside={false}
      fullScreen={isMobile}
      zIndex={Z_INDEX_OVER_CONFIG_MODAL}
      styles={{
        header: combinedChoose
          ? { borderBottom: 0, padding: "1.25rem 1.25rem 0.25rem" }
          : undefined,
        body: combinedChoose ? { padding: "0 1.25rem 1.25rem" } : undefined,
        close: combinedChoose ? { borderRadius: "50%" } : undefined,
        content: {
          maxHeight: "95vh",
        },
      }}
    >
      {renderContent()}
    </Modal>
  );
};

export default StripeCheckout;