checkout controller:
/** @format */
/**
 * External dependencies
 */
import i18n from 'i18n-calypso';
import React from 'react';
import { get, isEmpty } from 'lodash';

/**
 * Internal Dependencies
 */
import { setDocumentHeadTitle as setTitle } from 'state/document-head/actions';
import { setSection } from 'state/ui/actions';
import { getSiteBySlug } from 'state/sites/selectors';
import { getSelectedSite } from 'state/ui/selectors';
import GSuiteNudge from 'my-sites/checkout/gsuite-nudge';
import CheckoutContainer from './checkout/checkout-container';
import CartData from 'components/data/cart';
import CheckoutPendingComponent from './checkout-thank-you/pending';
import CheckoutThankYouComponent from './checkout-thank-you';
import UpsellNudge from './upsell-nudge';
import { isGSuiteRestricted } from 'lib/gsuite';
import { getRememberedCoupon } from 'lib/upgrades/actions';

export function checkout( context, next ) {
        const { feature, plan, product, purchaseId } = context.params;

        const state = context.store.getState();
        const selectedSite = getSelectedSite( state );

        if ( 'thank-you' === product ) {
                return;
        }

        // FIXME: Auto-converted from the Flux setTitle action. Please use <DocumentHead> instead.
        context.store.dispatch( setTitle( i18n.translate( 'Checkout' ) ) );

        context.store.dispatch( setSection( { name: 'checkout' }, { hasSidebar: false } ) );

        context.primary = (
                <CheckoutContainer
                        product={ product }
                        purchaseId={ purchaseId }
                        selectedFeature={ feature }
                        // NOTE: `context.query.code` is deprecated in favor of `context.query.coupon`.
                        couponCode={ context.query.coupon || context.query.code || getRememberedCoupon() }
                        plan={ plan }
                        selectedSite={ selectedSite }
                        reduxStore={ context.store }
                        redirectTo={ context.query.redirect_to }
                        clearTransaction={ false }
                />
        );

        next();
}

export function checkoutPending( context, next ) {
        const orderId = Number( context.params.orderId );
        const siteSlug = context.params.site;

        context.store.dispatch( setSection( { name: 'checkout-thank-you' }, { hasSidebar: false } ) );

        context.primary = <CheckoutPendingComponent orderId={ orderId } siteSlug={ siteSlug } />;

        next();
}

export function checkoutThankYou( context, next ) {
        const receiptId = Number( context.params.receiptId );
        const gsuiteReceiptId = Number( context.params.gsuiteReceiptId ) || 0;

        const state = context.store.getState();
        const selectedSite = getSelectedSite( state );
        const displayMode = get( context, 'query.d' );

        context.store.dispatch( setSection( { name: 'checkout-thank-you' }, { hasSidebar: false } ) );

        // FIXME: Auto-converted from the Flux setTitle action. Please use <DocumentHead> instead.
        context.store.dispatch( setTitle( i18n.translate( 'Thank You' ) ) );

        context.primary = (
                <CheckoutThankYouComponent
                        receiptId={ receiptId }
                        gsuiteReceiptId={ gsuiteReceiptId }
                        domainOnlySiteFlow={ isEmpty( context.params.site ) }
                        selectedFeature={ context.params.feature }
                        selectedSite={ selectedSite }
                        displayMode={ displayMode }
                />
        );

        next();
}

export function gsuiteNudge( context, next ) {
        const { domain, site, receiptId } = context.params;
        context.store.dispatch( setSection( { name: 'gsuite-nudge' }, { hasSidebar: false } ) );

        const state = context.store.getState();
        const selectedSite =
                getSelectedSite( state ) || getSiteBySlug( state, site ) || getSiteBySlug( state, domain );

        if ( ! selectedSite ) {
                return null;
        }

        if ( isGSuiteRestricted() ) {
                next();
        }

        context.primary = (
                <CartData>
                        <GSuiteNudge
                                domain={ domain }
                                receiptId={ Number( receiptId ) }
                                selectedSiteId={ selectedSite.ID }
                        />
                </CartData>
        );

        next();
}

export function upsellNudge( context, next ) {
        const { receiptId, site } = context.params;

        let upsellType;

        if ( context.path.includes( 'offer-quickstart-session' ) ) {
                upsellType = 'concierge-quickstart-session';
        } else if ( context.path.match( /(add|offer)-support-session/ ) ) {
                upsellType = 'concierge-support-session';
        }
        context.store.dispatch( setSection( { name: upsellType }, { hasSidebar: false } ) );

        context.primary = (
                <CheckoutContainer
                        shouldShowCart={ false }
                        clearTransaction={ true }
                        purchaseId={ Number( receiptId ) }
                >
                        <UpsellNudge
                                siteSlugParam={ site }
                                receiptId={ Number( receiptId ) }
                                upsellType={ upsellType }
                        />
                </CheckoutContainer>
        );

        next();
}

checkout container:
/**
 * External dependencies
 */
import React from 'react';

/**
 * Internal dependencies
 */
import { localize } from 'i18n-calypso';
import FormattedHeader from 'components/formatted-header';
import Checkout from '../checkout';
import CartData from 'components/data/cart';
import CheckoutData from 'components/data/checkout';
import SecondaryCart from '../cart/secondary-cart';

class CheckoutContainer extends React.Component {
        constructor() {
                super();
                this.state = {
                        headerText: '',
                };
        }

        renderCheckoutHeader() {
                return this.state.headerText && <FormattedHeader headerText={ this.state.headerText } />;
        }

        setHeaderText = newHeaderText => {
                this.setState( { headerText: newHeaderText } );
        };

        render() {
                const {
                        product,
                        purchaseId,
                        feature,
                        couponCode,
                        plan,
                        selectedSite,
                        reduxStore,
                        redirectTo,
                        shouldShowCart = true,
                        clearTransaction,
                } = this.props;

                const TransactionData = clearTransaction ? CartData : CheckoutData;
                return (
                        <>
                                { this.renderCheckoutHeader() }
                                <div className="checkout__container">
                                        <TransactionData>
                                                <Checkout
                                                        product={ product }
                                                        purchaseId={ purchaseId }
                                                        selectedFeature={ feature }
                                                        couponCode={ couponCode }
                                                        plan={ plan }
                                                        setHeaderText={ this.setHeaderText }
                                                        reduxStore={ reduxStore }
                                                        redirectTo={ redirectTo }
                                                >
                                                        { this.props.children }
                                                </Checkout>
                                        </TransactionData>

                                        { shouldShowCart && (
                                                <CartData>
                                                        <SecondaryCart selectedSite={ selectedSite } />
                                                </CartData>
                                        ) }
                                </div>
                        </>
                );
        }
}

export default localize( CheckoutContainer );

checkout index imports and render areas:
/** @format */
/**
 * External dependencies
 */
import { connect } from 'react-redux';
import { flatten, filter, find, get, isEmpty, isEqual, reduce, startsWith } from 'lodash';
import i18n, { localize } from 'i18n-calypso';
import page from 'page';
import PropTypes from 'prop-types';
import React from 'react';

/**
 * Internal dependencies
 */
import analytics from 'lib/analytics';
import { shouldShowTax, hasPendingPayment, getEnabledPaymentMethods } from 'lib/cart-values';
import {
        conciergeSessionItem,
        domainMapping,
        planItem as getCartItemForPlan,
        themeItem,
        hasGoogleApps,
        getGoogleApps,
        hasRenewalItem,
        getRenewalItemFromCartItem,
        getAllCartItems,
        getDomainRegistrations,
        getRenewalItems,
        hasFreeTrial,
        hasConciergeSession,
        hasDomainRegistration,
        hasJetpackPlan,
        hasBloggerPlan,
        hasPersonalPlan,
        hasPremiumPlan,
        hasPlan,
        hasOnlyRenewalItems,
        hasTransferProduct,
} from 'lib/cart-values/cart-items';
import PendingPaymentBlocker from './pending-payment-blocker';
import { clearSitePlans } from 'state/sites/plans/actions';
import { clearPurchases } from 'state/purchases/actions';
import DomainDetailsForm from './domain-details-form';
import { fetchReceiptCompleted } from 'state/receipts/actions';
import { getExitCheckoutUrl } from 'lib/checkout';
import { hasDomainDetails } from 'lib/store-transactions';
import notices from 'notices';
import { managePurchase } from 'me/purchases/paths';
import SubscriptionLengthPicker from 'blocks/subscription-length-picker';
import QueryContactDetailsCache from 'components/data/query-contact-details-cache';
import QueryStoredCards from 'components/data/query-stored-cards';
import QuerySitePlans from 'components/data/query-site-plans';
import QueryPlans from 'components/data/query-plans';
import SecurePaymentForm from './secure-payment-form';
import SecurePaymentFormPlaceholder from './secure-payment-form-placeholder';
import { AUTO_RENEWAL } from 'lib/url/support';
import {
        RECEIVED_WPCOM_RESPONSE,
        SUBMITTING_WPCOM_REQUEST,
} from 'lib/store-transactions/step-types';
import {
        addItem,
        replaceCartWithItems,
        replaceItem,
        applyCoupon,
        resetTransaction,
        setDomainDetails,
} from 'lib/upgrades/actions';
import getContactDetailsCache from 'state/selectors/get-contact-details-cache';
import getUpgradePlanSlugFromPath from 'state/selectors/get-upgrade-plan-slug-from-path';
import isDomainOnlySite from 'state/selectors/is-domain-only-site';
import isEligibleForCheckoutToChecklist from 'state/selectors/is-eligible-for-checkout-to-checklist';
import { getStoredCards } from 'state/stored-cards/selectors';
import { isValidFeatureKey } from 'lib/plans/features-list';
import { getPlan, findPlansKeys } from 'lib/plans';
import { GROUP_WPCOM } from 'lib/plans/constants';
import { recordViewCheckout } from 'lib/analytics/ad-tracking';
import { requestSite } from 'state/sites/actions';
import { isJetpackSite, isNewSite } from 'state/sites/selectors';
import { getSelectedSite, getSelectedSiteId, getSelectedSiteSlug } from 'state/ui/selectors';
import { getCurrentUserCountryCode } from 'state/current-user/selectors';
import { canDomainAddGSuite } from 'lib/gsuite';
import { getDomainNameFromReceiptOrCart } from 'lib/domains/cart-utils';
import { fetchSitesAndUser } from 'lib/signup/step-actions';
import { getProductsList, isProductsListFetching } from 'state/products-list/selectors';
import QueryProducts from 'components/data/query-products-list';
import { isRequestingSitePlans } from 'state/sites/plans/selectors';
import { isRequestingPlans } from 'state/plans/selectors';
import { isApplePayAvailable } from 'lib/web-payment';
import PageViewTracker from 'lib/analytics/page-view-tracker';
import isAtomicSite from 'state/selectors/is-site-automated-transfer';
import config from 'config';
import { abtest } from 'lib/abtest';

/**
 * Style dependencies
 */
import './style.scss';

export class Checkout extends React.Component {
        static propTypes = {
                cards: PropTypes.array.isRequired,
                couponCode: PropTypes.string,
                isJetpackNotAtomic: PropTypes.bool,
                selectedFeature: PropTypes.string,
        };

        state = {
                previousCart: null,
                cartSettled: false,
        };

        // TODO: update this component to not use deprecated life cycle methods
        /* eslint-disable-next-line react/no-deprecated */
        componentWillMount() {
                resetTransaction();
        }

        componentDidMount() {
                if ( this.redirectIfEmptyCart() ) {
                        return;
                }

                if ( this.props.cart.hasLoadedFromServer ) {
                        this.trackPageView();
                }

                if ( this.props.cart.hasLoadedFromServer && this.props.product ) {
                        this.addProductToCart();
                } else if ( this.props.couponCode ) {
                        applyCoupon( this.props.couponCode );
                }

                window.scrollTo( 0, 0 );
        }

        // TODO: update this component to not use deprecated life cycle methods
        /* eslint-disable-next-line react/no-deprecated */
        componentWillReceiveProps( nextProps ) {
                if ( ! this.props.cart.hasLoadedFromServer && nextProps.cart.hasLoadedFromServer ) {
                        if ( this.props.product ) {
                                this.addProductToCart();
                        }

                        this.trackPageView( nextProps );
                }

                if ( ! this.state.cartSettled && ! nextProps.cart.hasPendingServerUpdates ) {
                        this.setState( {
                                cartSettled: true,
                        } );
                }
        }

        componentDidUpdate() {
                if ( ! this.props.cart.hasLoadedFromServer ) {
                        return false;
                }

                const previousCart = this.<response clipped><NOTE>Due to the max output limit, only part of the full response has been shown to you.</NOTE>fter the user purchases a qualifying plan
                // This tests the flow that was not eligible for G Suite
                // There's an additional test above that tests directly aginst the G Suite upsell
                if (
                        config.isEnabled( 'upsell/concierge-session' ) &&
                        ! hasConciergeSession( cart ) &&
                        ! hasJetpackPlan( cart ) &&
                        ( hasBloggerPlan( cart ) || hasPersonalPlan( cart ) || hasPremiumPlan( cart ) )
                ) {
                        // A user just purchased one of the qualifying plans
                        // Show them the concierge session upsell page
                        if ( 'offer' === abtest( 'conciergeUpsellDial' ) ) {
                                return `/checkout/${ selectedSiteSlug }/offer-quickstart-session/${ receiptId }`;
                        }
                }

                if ( hasConciergeSession( cart ) ) {
                        displayModeParam = 'd=concierge';
                }

                const queryParam = displayModeParam ? `?${ displayModeParam }` : '';

                if ( this.props.isEligibleForCheckoutToChecklist & ( ':receiptId' !== receiptId ) ) {
                        const destination = abtest( 'improvedOnboarding' ) === 'main' ? 'checklist' : 'view';

                        return `/${ destination }/${ selectedSiteSlug }${ queryParam }`;
                }

                if ( this.props.isJetpackNotAtomic ) {
                        return `/plans/my-plan/${ selectedSiteSlug }?thank-you&install=all`;
                }

                return this.props.selectedFeature && isValidFeatureKey( this.props.selectedFeature )
                        ? `/checkout/thank-you/features/${
                                        this.props.selectedFeature
                          }/${ selectedSiteSlug }/${ receiptId }`
                        : `/checkout/thank-you/${ selectedSiteSlug }/${ receiptId }${ queryParam }`;
        };

        handleCheckoutExternalRedirect( redirectUrl ) {
                window.location.href = redirectUrl;
        }

        handleCheckoutCompleteRedirect = () => {
                let product, purchasedProducts, renewalItem;

                const {
                        cart,
                        isDomainOnly,
                        reduxStore,
                        selectedSiteId,
                        transaction: { step: { data: receipt = null } = {} } = {},
                        translate,
                } = this.props;
                const redirectPath = this.getCheckoutCompleteRedirectPath();

                this.props.clearPurchases();

                if ( hasRenewalItem( cart ) ) {
                        // checkouts for renewals redirect back to `/purchases` with a notice

                        renewalItem = getRenewalItems( cart )[ 0 ];
                        // group all purchases into an array
                        purchasedProducts = reduce(
                                ( receipt && receipt.purchases ) || {},
                                function( result, value ) {
                                        return result.concat( value );
                                },
                                []
                        );
                        // and take the first product which matches the product id of the renewalItem
                        product = find( purchasedProducts, function( item ) {
                                return item.product_id === renewalItem.product_id;
                        } );

                        if ( product && product.will_auto_renew ) {
                                notices.success(
                                        translate(
                                                '%(productName)s has been renewed and will now auto renew in the future. ' +
                                                        '{{a}}Learn more{{/a}}',
                                                {
                                                        args: {
                                                                productName: renewalItem.product_name,
                                                        },
                                                        components: {
                                                                a: <a href={ AUTO_RENEWAL } target="_blank" rel="noopener noreferrer" />,
                                                        },
                                                }
                                        ),
                                        { persistent: true }
                                );
                        } else if ( product ) {
                                notices.success(
                                        translate(
                                                'Success! You renewed %(productName)s for %(duration)s, until %(date)s. ' +
                                                        'We sent your receipt to %(email)s.',
                                                {
                                                        args: {
                                                                productName: renewalItem.product_name,
                                                                duration: i18n.moment.duration( { days: renewalItem.bill_period } ).humanize(),
                                                                date: i18n.moment( product.expiry ).format( 'LL' ),
                                                                email: product.user_email,
                                                        },
                                                }
                                        ),
                                        { persistent: true }
                                );
                        }
                } else if ( hasFreeTrial( cart ) ) {
                        this.props.clearSitePlans( selectedSiteId );
                }

                if ( receipt && receipt.receipt_id ) {
                        const receiptId = receipt.receipt_id;

                        this.props.fetchReceiptCompleted( receiptId, {
                                ...receipt,
                                purchases: this.flattenPurchases( this.props.transaction.step.data.purchases ),
                                failedPurchases: this.flattenPurchases( this.props.transaction.step.data.failed_purchases ),
                        } );
                }

                if ( selectedSiteId ) {
                        this.props.requestSite( selectedSiteId );
                }

                this.props.setHeaderText( '' );

                if (
                        ( cart.create_new_blog && receipt && isEmpty( receipt.failed_purchases ) ) ||
                        ( isDomainOnly && hasPlan( cart ) && ! selectedSiteId )
                ) {
                        notices.info( translate( 'Almost done…' ) );

                        const domainName = getDomainNameFromReceiptOrCart( receipt, cart );

                        if ( domainName ) {
                                fetchSitesAndUser(
                                        domainName,
                                        () => {
                                                page( redirectPath );
                                        },
                                        reduxStore
                                );

                                return;
                        }
                }

                page( redirectPath );
        };

        content() {
                const {
                        selectedSite,
                        transaction,
                        cart,
                        cards,
                        productsList,
                        setHeaderText,
                        userCountryCode,
                } = this.props;

                if ( this.isLoading() ) {
                        return <SecurePaymentFormPlaceholder />;
                }

                if ( config.isEnabled( 'async-payments' ) && hasPendingPayment( this.props.cart ) ) {
                        return <PendingPaymentBlocker />;
                }

                if ( this.needsDomainDetails() ) {
                        return (
                                <DomainDetailsForm
                                        cart={ cart }
                                        productsList={ productsList }
                                        userCountryCode={ userCountryCode }
                                />
                        );
                }

                return (
                        <SecurePaymentForm
                                cart={ cart }
                                transaction={ transaction }
                                cards={ cards }
                                paymentMethods={ this.paymentMethodsAbTestFilter() }
                                products={ productsList }
                                selectedSite={ selectedSite }
                                setHeaderText={ setHeaderText }
                                redirectTo={ this.getCheckoutCompleteRedirectPath }
                                handleCheckoutCompleteRedirect={ this.handleCheckoutCompleteRedirect }
                                handleCheckoutExternalRedirect={ this.handleCheckoutExternalRedirect }
                        >
                                { this.renderSubscriptionLengthPicker() }
                        </SecurePaymentForm>
                );
        }

        renderSubscriptionLengthPicker() {
                const planInCart = this.getPlanProducts()[ 0 ];
                if ( ! planInCart ) {
                        return false;
                }

                const currentPlanSlug = this.props.selectedSite.plan.product_slug;
                const chosenPlan = getPlan( planInCart.product_slug );

                // Only render this for WP.com plans
                if ( chosenPlan.group !== GROUP_WPCOM ) {
                        return false;
                }

                // Don't render when we're renewing a plan. Stick with the current period.
                if ( planInCart.product_slug === currentPlanSlug ) {
                        return false;
                }

                const availableTerms = findPlansKeys( {
                        group: chosenPlan.group,
                        type: chosenPlan.type,
                } ).filter( planSlug => getPlan( planSlug ).availableFor( currentPlanSlug ) );

                if ( availableTerms.length < 2 ) {
                        return false;
                }

                return (
                        <React.Fragment>
                                <SubscriptionLengthPicker
                                        cart={ this.props.cart }
                                        plans={ availableTerms }
                                        initialValue={ planInCart.product_slug }
                                        onChange={ this.handleTermChange }
                                        shouldShowTax={ shouldShowTax( this.props.cart ) }
                                        key="picker"
                                />
                                <hr className="checkout__subscription-length-picker-separator" key="separator" />
                        </React.Fragment>
                );
        }

        handleTermChange = ( { value: planSlug } ) => {
                const product = this.getPlanProducts()[ 0 ];
                const cartItem = getCartItemForPlan( planSlug, {
                        domainToBundle: get( product, 'extra.domain_to_bundle', '' ),
                } );
                analytics.tracks.recordEvent( 'calypso_signup_plan_select', {
                        product_slug: cartItem.product_slug,
                        free_trial: cartItem.free_trial,
                        from_section: 'checkout',
                } );
                replaceItem( product, cartItem );
        };

        paymentMethodsAbTestFilter() {
                // This methods can be used to filter payment methods
                // For example, for the purpose of AB tests.
                return getEnabledPaymentMethods( this.props.cart );
        }

        isLoading() {
                const isLoadingCart = ! this.props.cart.hasLoadedFromServer;
                const isLoadingProducts = this.props.isProductsListFetching;
                const isLoadingPlans = this.props.isPlansListFetching;
                const isLoadingSitePlans = this.props.isSitePlansListFetching;
                const isCartSettled = this.state.cartSettled;

                return (
                        isLoadingCart || isLoadingProducts || isLoadingPlans || isLoadingSitePlans || ! isCartSettled
                );
        }

        needsDomainDetails() {
                const cart = this.props.cart;
                const transaction = this.props.transaction;

                if ( cart && hasOnlyRenewalItems( cart ) ) {
                        return false;
                }

                return (
                        cart &&
                        transaction &&
                        ! hasDomainDetails( transaction ) &&
                        ( hasDomainRegistration( cart ) || hasGoogleApps( cart ) || hasTransferProduct( cart ) )
                );
        }

        render() {
                const { plan, product, purchaseId, selectedFeature, selectedSiteSlug } = this.props;
                let analyticsPath = '';
                let analyticsProps = {};
                if ( purchaseId && product ) {
                        analyticsPath = '/checkout/:product/renew/:purchase_id/:site';
                        analyticsProps = { product, purchase_id: purchaseId, site: selectedSiteSlug };
                } else if ( selectedFeature && plan ) {
                        analyticsPath = '/checkout/features/:feature/:site/:plan';
                        analyticsProps = { feature: selectedFeature, plan, site: selectedSiteSlug };
                } else if ( selectedFeature && ! plan ) {
                        analyticsPath = '/checkout/features/:feature/:site';
                        analyticsProps = { feature: selectedFeature, site: selectedSiteSlug };
                } else if ( product && ! purchaseId ) {
                        analyticsPath = '/checkout/:site/:product';
                        analyticsProps = { product, site: selectedSiteSlug };
                } else if ( selectedSiteSlug ) {
                        analyticsPath = '/checkout/:site';
                        analyticsProps = { site: selectedSiteSlug };
                } else {
                        analyticsPath = '/checkout/no-site';
                }
[The command completed with exit code 0.]
[Current working directory: /workspace/wp-calypso]
[Python interpreter: /usr/bin/python]
[Command finished with exit code 0]