Back

94.54% Statements 52/55
80.95% Branches 17/21
100% Functions 11/11
94.33% Lines 50/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163                                                                    2234x   2234x 2234x 2234x   2234x   2234x     2234x         2234x 2234x   2234x     918x 918x 918x     918x   918x 651x     267x 267x 267x   267x   255x     255x 255x 188x     67x     67x   32x     67x 46x       21x   21x     19x       21x           11x     11x 4x 4x     7x 7x   7x     267x 267x               2234x 14x     14x               2234x 11x 11x   11x     2234x                      
/**
 * PayPal Payment Buttons — The PayPal payment resource.
 *
 * @package
 */
 
import apiFetch from '@wordpress/api-fetch'; // eslint-disable-line import/no-unresolved
import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { API_BASE } from '../utils/api-base';
import { deleteExistingLink, removeExistingLink } from '../utils/existing-links';
import { getResourceAttributeUpdates, isBookkeeping, isSameValue } from '../utils/resource-sync';
import { recordBlockMounted, recordPaymentRead } from '../utils/sync-on-save';
import { getUserFriendlyError, isNotFound } from '../utils/validation';
 
/**
 * The PayPal payment resource this block points at: reading it back and
 * deleting it. Creating and updating happen with the post save, in
 * utils/sync-on-save.js.
 *
 * @param {object}   props                      - Hook props.
 * @param {object}   props.attributes           - Block attributes.
 * @param {Function} props.setAttributes        - Function to update block attributes.
 * @param {boolean}  props.isConnected          - Whether the site is connected to PayPal.
 * @param {string}   props.clientId             - The block's client id.
 * @param {Function} props.setShowDeleteConfirm - Setter for the delete confirmation dialog.
 * @return {object} The payment as last read, resource state, and the delete handlers.
 */
export function usePayPalResource( {
	attributes,
	setAttributes,
	isConnected,
	clientId,
	setShowDeleteConfirm,
} ) {
	const { isApiManaged, resourceId } = attributes;
 
	const [ isBusy, setIsBusy ] = useState( false );
	const [ linkDeleted, setLinkDeleted ] = useState( false );
	const [ paymentChanged, setPaymentChanged ] = useState( false );
	// PayPal's message for a read that failed for any reason but a deleted payment.
	const [ readError, setReadError ] = useState( '' );
	// What PayPal holds, with the site's own embed count - the details view reads it.
	const [ resource, setResource ] = useState( null );
 
	// The screen showing the warning decides when the merchant is done with it.
	const dismissPaymentChanged = useCallback( () => setPaymentChanged( false ), [] );
 
	// Two blocks can share one PayPal payment — a duplicate, or one product
	// shown as a button, a link and a QR code — and only the block that saved
	// last has seen what PayPal holds. Read it back so every block agrees.
	const latestAttributes = useRef( attributes );
	latestAttributes.current = attributes;
 
	useEffect( () => {
		// Above the guard: deleting the button re-runs this with no resourceId, and a
		// warning about a payment that is gone has to clear too.
		setLinkDeleted( false );
		setPaymentChanged( false );
		setReadError( '' );
 
		// Above the early return: the block rendered even when there is no payment to fetch.
		recordBlockMounted( clientId );
 
		if ( ! isConnected || ! isApiManaged || ! resourceId ) {
			return;
		}
 
		let cancelled = false;
		const atRequest = latestAttributes.current;
		setResource( null );
 
		apiFetch( { path: `${ API_BASE }/buttons/${ resourceId }` } )
			.then( response => {
				Iif ( cancelled ) {
					return;
				}
				setResource( response || null );
				if ( ! response?.attributes ) {
					return;
				}
				// The block now has PayPal's values, so the save can write this payment.
				recordPaymentRead( clientId, resourceId, response.attributes );
				// Take PayPal's value only where the attribute still matches what the block had
				// when the request went out; anything else is the merchant's own edit.
				const updates = Object.fromEntries(
					Object.entries( getResourceAttributeUpdates( atRequest, response.attributes ) ).filter(
						( [ key ] ) => isSameValue( key, latestAttributes.current[ key ], atRequest[ key ] )
					)
				);
				if ( ! Object.keys( updates ).length ) {
					return;
				}
				// The mode, and a first SDK URL, are the block catching up with the payment
				// rather than a change someone made at PayPal.
				if (
					Object.keys( updates ).some(
						key => ! isBookkeeping( key, atRequest[ key ], atRequest.format )
					)
				) {
					setPaymentChanged( true );
				}
				// An ordinary edit, so the post is dirty: the page renders the saved values, and
				// they are stale until the post is saved again.
				setAttributes( updates );
			} )
			// A payment deleted on PayPal is re-created when the post is next saved,
			// so the merchant is told before that happens. Any other failure holds the
			// save back until the read succeeds, so the merchant is told about that too.
			.catch( err => {
				Iif ( cancelled ) {
					return;
				}
				if ( ! isNotFound( err ) ) {
					setReadError( getUserFriendlyError( err ) );
					return;
				}
				// A 404 counts as the read, so the save can run and re-create the payment.
				recordPaymentRead( clientId, resourceId );
				setLinkDeleted( true );
				// Gone from PayPal, so drop it from every block's picker.
				removeExistingLink( resourceId );
			} );
 
		return () => {
			cancelled = true;
		};
	}, [ isConnected, isApiManaged, resourceId, clientId, setAttributes ] );
 
	/**
	 * Request delete confirmation via DeleteLinkDialog.
	 * Actual deletion runs in executeDeleteButton().
	 */
	const handleDeleteButton = useCallback( () => {
		Iif ( ! resourceId ) {
			return;
		}
		setShowDeleteConfirm( true );
	}, [ resourceId, setShowDeleteConfirm ] );
 
	/**
	 * Execute the button deletion after the user confirms.
	 *
	 * @return {Promise<boolean>} Whether the link is gone, including when PayPal had already deleted it.
	 */
	const executeDeleteButton = useCallback( () => {
		setShowDeleteConfirm( false );
		setIsBusy( true );
 
		return deleteExistingLink( resourceId ).finally( () => setIsBusy( false ) );
	}, [ resourceId, setShowDeleteConfirm ] );
 
	return {
		resource,
		isBusy,
		linkDeleted,
		readError,
		paymentChanged,
		dismissPaymentChanged,
		handleDeleteButton,
		executeDeleteButton,
	};
}