Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

25.5 KB
Raw Blame
import {Outlet, useBlocker, useLocation, useNavigate, useParams, useSearchParams} from "react-router";
import classes from './Checkout.module.scss';
import {useGetOrderPublic} from "../../../queries/useGetOrderPublic.ts";
import {t} from "@lingui/macro";
import {Countdown} from "../../common/Countdown";
import {ActionIcon, Button, Group, Modal, Tooltip} from "@mantine/core";
import {IconArrowLeft, IconCalendarDue, IconClock, IconPrinter, IconReceipt} from "@tabler/icons-react";
import {eventHomepagePath, eventHomepageUrl} from "../../../utilites/urlHelper.ts";
import {ShareComponent} from "../../common/ShareIcon";
import {AddToEventCalendarButton} from "../../common/AddEventToCalendarButton";
import classNames from "classnames";
import React, {useCallback, useEffect, useMemo, useRef, useState} from "react";
import {getEmbedMode, getParentOrigin} from "../../../utilites/iframeResize.ts";
import {resolveClientEmbedLocale} from "../../../utilites/embedLocale.ts";
import {Invoice} from "../../../types.ts";
import {orderClientPublic} from "../../../api/order.client.ts";
import {downloadBinary} from "../../../utilites/download.ts";
import {withLoadingNotification} from "../../../utilites/withLoadingNotification.tsx";
import {useAbandonOrderPublic} from "../../../mutations/useAbandonOrderPublic.ts";
import {showError, showInfo} from "../../../utilites/notifications.tsx";
import {dateToBrowserTz, formatDateWithLocale, isDateInFuture, utcDateToEpochMs} from "../../../utilites/dates.ts";
import {isSsr} from "../../../utilites/helpers.ts";
import {claimOrderCompletionReport, getCheckoutSessionIdentifier, isCheckoutSessionStored} from "../../../utilites/checkoutSession.ts";
import {PoweredByFooter} from "../../common/PoweredByFooter";
import {detectMode} from "../../../utilites/themeUtils.ts";
import {CheckoutThemeProvider} from "./CheckoutThemeProvider.tsx";
import {useOrganizerTrackingPixels} from "../../../hooks/useOrganizerTrackingPixels";
import {trackPixelEvent, hasActivePixels} from "../../../utilites/trackingPixels";
import {CookieSettingsLink} from "../../common/CookieSettingsLink";
import {useGetEventPublic} from "../../../queries/useGetEventPublic.ts";

const DEFAULT_ACCENT = '#7c3aed';

const Checkout = () => {
    const {eventId, orderShortId} = useParams();
    const {data: order, isError: isOrderError} = useGetOrderPublic(eventId, orderShortId, ['event']);
    const event = order?.event;
    const orderOccurrenceIds = Array.from(new Set(
        (order?.order_items ?? []).map(item => item.event_occurrence_id).filter((id): id is number => id != null)
    ));
    const orderOccurrenceId = orderOccurrenceIds.length === 1 ? orderOccurrenceIds[0] : null;
    const {data: publicEvent} = useGetEventPublic(eventId, !!eventId, false, null, orderOccurrenceId);
    const navigate = useNavigate();
    const location = useLocation();
    const [searchParams] = useSearchParams();
    const isModal = useMemo(() => {
        const fromUrl = searchParams.get('embed') === 'modal';
        const cached = getEmbedMode() === 'modal';
        return fromUrl || cached;
    }, [searchParams]);
    const orderIsCompleted = order?.status === 'COMPLETED';
    const orderIsReserved = order?.status === 'RESERVED';
    const orderIsAwaitingOfflinePayment = order?.status === 'AWAITING_OFFLINE_PAYMENT';
    const orderHasPaymentLink = orderIsReserved && !!order?.payment_link_created_at;
    const isPaymentLinkPayer = !!order?.is_payment_link_payer;
    const [isExpired, setIsExpired] = useState(false);
    const orderHasAttendees = order?.attendees && order.attendees.length > 0;
    const [showAbandonDialog, setShowAbandonDialog] = useState(false);
    const [pendingNavigation, setPendingNavigation] = useState<string | null>(null);
    const [isAbandoning, setIsAbandoning] = useState(false);
    const [pendingClose, setPendingClose] = useState(false);
    const abandonOrderMutation = useAbandonOrderPublic();

    const postToParent = useCallback((type: string, data?: Record<string, unknown>) => {
        if (typeof window === 'undefined') return;
        try {
            window.parent.postMessage({type, ...(data ?? {})}, getParentOrigin() || '*');
        } catch (e) {
            /* noop */
        }
    }, []);

    const closeModal = useCallback(() => postToParent('hievents:close-checkout'), [postToParent]);

    useEffect(() => {
        if (!orderShortId || !searchParams.has('session_identifier')) {
            return;
        }
        const token = getCheckoutSessionIdentifier(orderShortId);
        if (!token || !isCheckoutSessionStored(orderShortId, token)) {
            return;
        }
        const remaining = new URLSearchParams(searchParams);
        remaining.delete('session_identifier');
        const search = remaining.toString();
        navigate({pathname: location.pathname, search: search ? `?${search}` : ''}, {replace: true, preventScrollReset: true});
    }, [orderShortId, searchParams]);
    const reportedOrderRef = useRef<string | null>(null);

    const getCurrentStep = (): 'details' | 'payment' | 'summary' => {
        const pathname = location.pathname;
        if (pathname.includes('/payment')) return 'payment';
        if (pathname.includes('/summary')) return 'summary';
        return 'details';
    };
    const currentStep = getCurrentStep();

    const progressPercent = order?.is_payment_required
        ? {details: 33, payment: 66, summary: 100}[currentStep]
        : {details: 50, payment: 100, summary: 100}[currentStep];

    const stepCount = order?.is_payment_required ? 3 : 2;
    const stepNumber = order?.is_payment_required
        ? {details: 1, payment: 2, summary: 3}[currentStep]
        : {details: 1, payment: 2, summary: 2}[currentStep];

    const isOrderReservedAndNotExpired = orderIsReserved && order?.reserved_until
        && isDateInFuture(order.reserved_until);
    const canAbandonOrder = !!isOrderReservedAndNotExpired && !orderHasPaymentLink;

    const blocker = useBlocker(
        ({currentLocation, nextLocation}) => {
            const isLeavingCheckout = !nextLocation.pathname.startsWith('/checkout/');
            return (
                !isAbandoning &&
                canAbandonOrder &&
                currentLocation.pathname !== nextLocation.pathname &&
                isLeavingCheckout
            );
        }
    );

    const handleExpiry = () => {
        setIsExpired(true);
    };

    const handleReturn = () => {
        if (isModal) {
            closeModal();
            return;
        }
        navigate(`/event/${event?.id}/${event?.slug}`);
    };

    const handleRequestClose = useCallback(() => {
        postToParent('hievents:close-pending');
        if (canAbandonOrder) {
            setPendingClose(true);
            setShowAbandonDialog(true);
        } else {
            closeModal();
        }
    }, [postToParent, closeModal, canAbandonOrder]);

    useEffect(() => {
        if (!isModal) return;
        const parentOrigin = getParentOrigin();
        const onMessage = (event: MessageEvent) => {
            if (parentOrigin && event.origin !== parentOrigin) return;
            if (event.data?.type === 'hievents:request-close') {
                handleRequestClose();
            }
        };
        window.addEventListener('message', onMessage);
        return () => window.removeEventListener('message', onMessage);
    }, [isModal, handleRequestClose]);

    useEffect(() => {
        if (isModal && isOrderError) {
            postToParent('hievents:checkout-cleared');
            closeModal();
        }
    }, [isModal, isOrderError, postToParent, closeModal]);

    useEffect(() => {
        if (!isModal) return;
        if (isOrderReservedAndNotExpired) {
            const parentOrigin = getParentOrigin();
            postToParent('hievents:checkout-progress', {
                eventId,
                orderShortId,
                ...(parentOrigin ? {sessionId: getCheckoutSessionIdentifier(String(orderShortId))} : {}),
                step: currentStep,
                reservedUntil: order?.reserved_until ? utcDateToEpochMs(order.reserved_until) : null,
                locale: resolveClientEmbedLocale(),
            });
        } else if (orderIsCompleted || orderIsAwaitingOfflinePayment) {
            postToParent('hievents:checkout-cleared');
        }
    }, [isModal, isOrderReservedAndNotExpired, orderIsCompleted, orderIsAwaitingOfflinePayment, order?.reserved_until, currentStep, eventId, orderShortId, postToParent]);

    useEffect(() => {
        if (!isModal || !order || !(orderIsCompleted || orderIsAwaitingOfflinePayment) || reportedOrderRef.current === order.short_id) {
            return;
        }
        reportedOrderRef.current = order.short_id;
        if (!claimOrderCompletionReport(order.short_id)) {
            return;
        }
        postToParent('hievents:order-completed', {
            eventId,
            currency: order.currency,
            total: order.total_gross,
            quantity: (order.order_items ?? []).reduce((sum, item) => sum + item.quantity, 0),
            status: order.status,
        });
    }, [isModal, order, orderIsCompleted, orderIsAwaitingOfflinePayment, eventId, postToParent]);

    useEffect(() => {
        if (!isModal) return;
        const onKeydown = (event: KeyboardEvent) => {
            if (event.key === 'Escape' && !showAbandonDialog && !isExpired) {
                handleRequestClose();
            }
        };
        window.addEventListener('keydown', onKeydown);
        return () => window.removeEventListener('keydown', onKeydown);
    }, [isModal, showAbandonDialog, isExpired, handleRequestClose]);

    useEffect(() => {
        if (isModal && order?.is_expired) {
            setIsExpired(true);
        }
    }, [isModal, order?.is_expired]);

    useEffect(() => {
        if (!orderHasPaymentLink || !order?.reserved_until) {
            return;
        }
        const msUntilExpiry = utcDateToEpochMs(order.reserved_until) - Date.now();
        if (msUntilExpiry <= 0) {
            setIsExpired(true);
            return;
        }
        if (msUntilExpiry > 2147483647) {
            return;
        }
        const timeout = window.setTimeout(() => setIsExpired(true), msUntilExpiry);
        return () => window.clearTimeout(timeout);
    }, [orderHasPaymentLink, order?.reserved_until]);

    const handleInvoiceDownload = async (invoice: Invoice) => {
        await withLoadingNotification(
            async () => {
                const blob = await orderClientPublic.downloadInvoice(eventId, orderShortId);
                downloadBinary(blob, invoice.invoice_number + '.pdf');
            },
            {
                loading: {
                    title: t`Downloading Invoice`,
                    message: t`Please wait while we prepare your invoice...`
                },
                success: {
                    title: t`Success`,
                    message: t`Invoice downloaded successfully`
                },
                error: {
                    title: t`Error`,
                    message: t`Failed to download invoice. Please try again.`
                }
            }
        );
    }

    const handleAbandonConfirm = async () => {
        setIsAbandoning(true);
        try {
            await abandonOrderMutation.mutateAsync({
                eventId: Number(eventId),
                orderShortId: String(orderShortId),
            });
        } catch (error) {
            showError(t`Failed to abandon order. Please try again.`);
        } finally {
            setShowAbandonDialog(false);
            showInfo(t`Your order has been cancelled.`);

            if (pendingClose) {
                setPendingClose(false);
                closeModal();
            } else if (blocker.state === 'blocked') {
                blocker.proceed();
            } else if (pendingNavigation) {
                navigate(pendingNavigation);
            }

            setPendingNavigation(null);
            setIsAbandoning(false);
        }
    };

    const handleAbandonCancel = () => {
        if (blocker.state === 'blocked') {
            blocker.reset();
        }
        setShowAbandonDialog(false);
        setPendingNavigation(null);
        setPendingClose(false);
    };

    const handleEventHomepageClick = (e: React.MouseEvent) => {
        if (canAbandonOrder && event) {
            e.preventDefault();
            setPendingNavigation(eventHomepagePath(event));
            setShowAbandonDialog(true);
        } else if (event) {
            navigate(eventHomepagePath(event));
        }
    };

    useEffect(() => {
        if (blocker.state === 'blocked') {
            setShowAbandonDialog(true);
        }
    }, [blocker.state]);

    const {pixelsReady} = useOrganizerTrackingPixels(
        publicEvent?.organizer?.settings?.tracking_pixels
    );

    useEffect(() => {
        if (event && orderIsReserved && pixelsReady && hasActivePixels()) {
            trackPixelEvent({
                eventName: 'InitiateCheckout',
                contentName: event.title,
                contentId: event.id,
            });
        }
    }, [event?.id, orderIsReserved, pixelsReady]);

    useEffect(() => {
        if (!event || !order || !pixelsReady || !hasActivePixels()) return;
        if (!orderIsCompleted && !orderIsAwaitingOfflinePayment) return;

        const key = `purchase_tracked_${order.short_id}`;
        if (typeof sessionStorage !== 'undefined' && sessionStorage.getItem(key)) return;

        trackPixelEvent({
            eventName: 'Purchase',
            value: Number(order.total_gross) || 0,
            currency: order.currency || 'USD',
            contentName: event.title,
            contentId: event.id,
            transactionId: order.short_id,
        });

        if (typeof sessionStorage !== 'undefined') {
            sessionStorage.setItem(key, '1');
        }
    }, [order?.status, order?.short_id, pixelsReady]);

    const homepageSettings = event?.settings?.homepage_theme_settings;
    const accentColor = homepageSettings?.accent || DEFAULT_ACCENT;
    const checkoutMode = homepageSettings?.mode || detectMode(homepageSettings?.background || '#ffffff');

    return (
        <CheckoutThemeProvider accentColor={accentColor} mode={checkoutMode}>
            <div className={classes.container} data-mode={checkoutMode}>
                <div className={classes.mainContent}>
                    <header className={classes.header}>
                        {(event) && (
                            <>
                                <div
                                    className={classNames(classes.headerRow, (orderIsCompleted || orderIsAwaitingOfflinePayment) && classes.headerRowComplete)}
                                    style={isModal ? {paddingRight: '44px'} : undefined}
                                >
                                    {!isModal && (
                                        <>
                                            <ActionIcon
                                                className={classes.backButton}
                                                variant="subtle"
                                                title={t`Back to event page`}
                                                aria-label={t`Back to event page`}
                                                onClick={handleEventHomepageClick}
                                            >
                                                <IconArrowLeft size={19}/>
                                            </ActionIcon>
                                            <span className={classes.headerDivider}/>
                                        </>
                                    )}

                                    <div className={classes.titleBlock}>
                                        {(orderIsCompleted || orderIsAwaitingOfflinePayment) && (
                                            <span
                                                className={classNames(classes.eyebrow, orderIsAwaitingOfflinePayment ? classes.eyebrowAwaiting : classes.eyebrowComplete)}>
                                                {orderIsAwaitingOfflinePayment ? t`Awaiting payment` : t`Order complete`}
                                            </span>
                                        )}

                                        {orderIsReserved && (
                                            <span className={classes.eyebrow}>
                                                {isPaymentLinkPayer ? t`Payment request` : t`Checkout · step ${stepNumber} of ${stepCount}`}
                                            </span>
                                        )}
                                        <span className={classes.eventName}>{event.title}</span>
                                    </div>

                                    <div className={classes.headerSpacer}/>

                                    {orderHasPaymentLink && (
                                        <>
                                            <span className={classes.timerCaption}>{t`Pay by`}</span>
                                            <Tooltip label={t`Pay by ${dateToBrowserTz(order.reserved_until, event.timezone)}`}>
                                                <div className={classes.timerChip} data-testid="checkout-pay-by">
                                                    <IconCalendarDue size={14}/>
                                                    <span className={classes.countdown} suppressHydrationWarning>
                                                        {formatDateWithLocale(
                                                            order.reserved_until,
                                                            'dayMonthTime',
                                                            isSsr() ? event.timezone : Intl.DateTimeFormat().resolvedOptions().timeZone,
                                                        )}
                                                    </span>
                                                </div>
                                            </Tooltip>
                                        </>
                                    )}

                                    {orderIsReserved && !orderHasPaymentLink && (
                                        <>
                                            <span className={classes.timerCaption}>{t`Time left`}</span>
                                            <div className={classes.timerChip} data-testid="checkout-timer">
                                                <IconClock size={14}/>
                                                <Countdown
                                                    displayType={'short'}
                                                    className={classes.countdown}
                                                    closeToExpiryClassName={classes.countdownCloseToExpiry}
                                                    targetDate={order.reserved_until}
                                                    onExpiry={handleExpiry}
                                                />
                                            </div>
                                        </>
                                    )}

                                    {(orderIsCompleted || orderIsAwaitingOfflinePayment) && (
                                        <div className={classes.headerActions}>
                                            <ShareComponent
                                                title={event.title}
                                                text={t`Check out this event!`}
                                                url={eventHomepageUrl(event)}
                                                hideShareButtonText
                                            />

                                            {!isPaymentLinkPayer && (
                                                <AddToEventCalendarButton event={event} occurrence={order?.order_items?.[0]?.event_occurrence}/>
                                            )}

                                            {(orderHasAttendees && !isPaymentLinkPayer) && (
                                                <Tooltip label={t`Print Tickets`}>
                                                    <ActionIcon
                                                        variant="subtle"
                                                        onClick={() => window?.open(`/order/${eventId}/${orderShortId}/print`, '_blank')}
                                                    >
                                                        <IconPrinter size={20}/>
                                                    </ActionIcon>
                                                </Tooltip>
                                            )}

                                            {order.latest_invoice && (
                                                <Tooltip
                                                    label={t`Download Invoice`}>
                                                    <ActionIcon
                                                        variant="subtle"
                                                        data-testid="download-invoice-button"
                                                        onClick={() => handleInvoiceDownload(order.latest_invoice as Invoice)}
                                                    >
                                                        <IconReceipt size={20}/>
                                                    </ActionIcon>
                                                </Tooltip>
                                            )}
                                        </div>
                                    )}
                                </div>

                                {orderIsReserved && (
                                    <div className={classes.progressTrack}>
                                        <div className={classes.progressFill} style={{width: `${progressPercent}%`}}/>
                                    </div>
                                )}
                            </>
                        )}
                    </header>
                    <Outlet/>
                    {isModal && currentStep !== 'summary' && (
                        <>
                            <PoweredByFooter style={{marginTop: '12px', paddingBottom: '16px'}} brandingRemoved={!publicEvent || publicEvent.organizer?.branding_removed}/>
                            <CookieSettingsLink/>
                        </>
                    )}
                </div>
            </div>

            <Modal
                opened={isExpired}
                onClose={handleReturn}
                withCloseButton={false}
                centered
                size="m"
            >
                <div style={{textAlign: 'center', padding: '20px 0'}}>
                    <h3 style={{color: 'var(--checkout-text-primary)', margin: '0 0 8px 0'}}>
                        {orderHasPaymentLink
                            ? (isPaymentLinkPayer ? t`This payment link has expired` : t`Your payment link has expired`)
                            : t`You have run out of time to complete your order.`}
                    </h3>
                    <p style={{color: 'var(--checkout-text-secondary)', margin: '0'}}>
                        {orderHasPaymentLink
                            ? (isPaymentLinkPayer
                                ? (order?.first_name
                                    ? t`The order was not paid in time, so the places are no longer held. Let ${order.first_name} know so they can register again.`
                                    : t`The order was not paid in time, so the places are no longer held. Let the person who registered know so they can register again.`)
                                : t`The order was not paid in time, so your places have been released. Return to the event page to start a new order.`)
                            : t`Please return to the event page to start over.`}
                    </p>
                    <Button
                        onClick={handleReturn}
                        variant="filled"
                        mt="xl"
                    >
                        {t`Return to Event Page`}
                    </Button>
                </div>
            </Modal>

            <Modal
                opened={showAbandonDialog}
                onClose={handleAbandonCancel}
                withCloseButton={false}
                centered
                size="m"
            >
                <div style={{textAlign: 'center', padding: '20px 0'}}>
                    <h3 style={{color: 'var(--checkout-text-primary)', margin: '0 0 8px 0'}}>
                        {t`Are you sure you want to leave?`}
                    </h3>
                    <p style={{color: 'var(--checkout-text-secondary)', margin: '0'}}>
                        {t`Your current order will be lost.`}
                    </p>
                    <Group justify="center" gap="md" mt="xl">
                        <Button
                            onClick={handleAbandonCancel}
                            variant="subtle"
                        >
                            {t`No, keep me here`}
                        </Button>
                        <Button
                            onClick={handleAbandonConfirm}
                            variant="outline"
                            color="gray"
                            loading={abandonOrderMutation.isPending}
                        >
                            {t`Yes, cancel my order`}
                        </Button>
                    </Group>
                </div>
            </Modal>
        </CheckoutThemeProvider>
    );
}

export default Checkout;