Back

82.48% Statements 113/137
62.35% Branches 53/85
86.95% Functions 20/23
82.48% Lines 113/137

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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369                                                11x 11x   11x   11x   11x 11x   11x 1x 1x           1x   1x                       1x 1x       1x     11x 1x   1x 1x 1x 1x 1x         11x 1x                                                     11x 5x 2x     3x 3x       2x                       2x 2x 1x     1x     11x 1x       1x                       1x 1x       1x     11x 2x       2x         2x       2x 2x 1x     1x     11x                                           11x 1x   11x 1x     1x 1x 1x       11x       1x     11x           4x   4x 3x 3x 3x     1x 1x         1x 1x 1x 1x   1x                   1x   1x           1x         11x 1x 1x   1x 1x 1x                       1x 1x   1x         11x 5x 5x   5x 5x 5x 3x           2x   5x         11x 3x 3x 2x 2x     1x   1x   1x 1x 1x                   1x         11x 5x 5x 3x     2x   2x 2x 2x 1x             1x   2x      
import { isSimpleSite } from '@automattic/jetpack-script-data';
import { isCurrentUserConnected } from '@automattic/jetpack-shared-extension-utils';
import apiFetch from '@wordpress/api-fetch';
import { store as editorStore } from '@wordpress/editor';
import { addQueryArgs, getQueryArg } from '@wordpress/url';
import { PRODUCT_TYPE_PAYMENT_PLAN } from '../../shared/components/product-management-controls/constants';
import { getMessageByProductType } from '../../shared/components/product-management-controls/utils';
import executionLock from '../../shared/execution-lock';
import getConnectUrl from '../../shared/get-connect-url';
import {
	saveProduct,
	setApiState,
	setConnectUrl,
	setProducts,
	setSiteSlug,
	setConnectedAccountDefaultCurrency,
	setSubscriberCounts,
	setNewsletterCategories,
	setTotalEmailsSentCount,
	setPostEmailSentState,
} from './actions';
import { API_STATE_CONNECTED, API_STATE_NOTCONNECTED } from './constants';
import { onError } from './utils';
 
const EXECUTION_KEY = 'membership-products-resolver-getProducts';
const SUBSCRIBER_COUNT_EXECUTION_KEY = 'membership-products-resolver-getSubscriberCounts';
const TOTAL_EMAILS_SENT_COUNT_EXECUTION_KEY =
	'membership-products-resolver-getTotalEmailsSentCount';
const GET_NEWSLETTER_CATEGORIES_EXECUTION_KEY =
	'membership-products-resolver-getNewsletterCategories';
const GET_POST_EMAIL_SENT_STATE_EXECUTION_KEY =
	'membership-products-resolver-getPostEmailSentState';
let hydratedFromAPI = false;
 
const fetchMemberships = async () => {
	const origin = getQueryArg( window.location.href, 'origin' );
	const path = addQueryArgs( '/wpcom/v2/memberships/status', {
		source: origin === 'https://wordpress.com' ? 'gutenberg-wpcom' : 'gutenberg',
		type: 'all',
		is_editable: true,
	} );
 
	const response = await apiFetch( { path, method: 'GET' } );
 
	Iif ( ! response && typeof response !== 'object' ) {
		throw new Error( 'Unexpected API response' );
	}
 
	/**
	 * WP_Error returns a list of errors with custom names:
	 * `errors: { foo: [ 'message' ], bar: [ 'message' ] }`
	 * Since we don't know their names, to get the message, we transform the object
	 * into an array, and just pick the first message of the first error.
	 *
	 * @see https://developer.wordpress.org/reference/classes/wp_error/
	 */
	const wpError = response?.errors && Object.values( response.errors )?.[ 0 ]?.[ 0 ];
	Iif ( wpError ) {
		throw new Error( wpError );
	}
 
	return response;
};
 
const mapAPIResponseToMembershipProductsStoreData = ( response, registry, dispatch ) => {
	const postId = registry.select( editorStore ).getCurrentPostId();
 
	dispatch( setConnectUrl( getConnectUrl( postId, response.connect_url ) ) );
	dispatch( setSiteSlug( response.site_slug ) );
	dispatch( setProducts( response.products ) );
	dispatch( setConnectedAccountDefaultCurrency( response.connected_account_default_currency ) );
	dispatch(
		setApiState( response.connected_account_id ? API_STATE_CONNECTED : API_STATE_NOTCONNECTED )
	);
};
 
const fetchSubscriberCounts = async () => {
	const response = await apiFetch( {
		path: addQueryArgs( '/wpcom/v2/subscribers/counts', {
			subscriber_status: 'active',
			subscription_status: 'active',
		} ),
	} );
 
	if ( ! response || typeof response !== 'object' ) {
		throw new Error( 'Unexpected API response' );
	}
 
	/**
	 * WP_Error returns a list of errors with custom names:
	 * `errors: { foo: [ 'message' ], bar: [ 'message' ] }`
	 * Since we don't know their names, to get the message, we transform the object
	 * into an array, and just pick the first message of the first error.
	 *
	 * @see https://developer.wordpress.org/reference/classes/wp_error/
	 */
	const wpError = response?.errors && Object.values( response.errors )?.[ 0 ]?.[ 0 ];
	if ( wpError ) {
		throw new Error( wpError );
	}
 
	return response;
};
 
const fetchTotalEmailsSentCount = async ( blogId, postId ) => {
	if ( ! blogId || ! postId ) {
		return;
	}
 
	const baseUrl = isSimpleSite() ? '/rest/v1.1/sites' : '/jetpack/v4/stats-app/sites';
	const response = await apiFetch( {
		path: baseUrl + `/${ blogId }/stats/opens/emails/${ postId }/rate`,
	} );
 
	Iif ( ! response || typeof response !== 'object' ) {
		throw new Error( 'Unexpected API response' );
	}
 
	/**
	 * WP_Error returns a list of errors with custom names:
	 * `errors: { foo: [ 'message' ], bar: [ 'message' ] }`
	 * Since we don't know their names, to get the message, we transform the object
	 * into an array, and just pick the first message of the first error.
	 *
	 * @see https://developer.wordpress.org/reference/classes/wp_error/
	 */
	const wpError = response?.errors && Object.values( response.errors )?.[ 0 ]?.[ 0 ];
	if ( wpError ) {
		throw new Error( wpError );
	}
 
	return response;
};
 
const fetchNewsletterCategories = async () => {
	const response = await apiFetch( {
		path: '/wpcom/v2/newsletter-categories',
	} );
 
	Iif ( ! response || typeof response !== 'object' ) {
		throw new Error( 'Unexpected API response' );
	}
 
	/**
	 * WP_Error returns a list of errors with custom names:
	 * `errors: { foo: [ 'message' ], bar: [ 'message' ] }`
	 * Since we don't know their names, to get the message, we transform the object
	 * into an array, and just pick the first message of the first error.
	 *
	 * @see https://developer.wordpress.org/reference/classes/wp_error/
	 */
	const wpError = response?.errors && Object.values( response.errors )?.[ 0 ]?.[ 0 ];
	Iif ( wpError ) {
		throw new Error( wpError );
	}
 
	return response;
};
 
const fetchPostEmailSentState = async postId => {
	Iif ( ! postId ) {
		return { email_sent_at: null, stats_on_send: null };
	}
 
	const response = await apiFetch( {
		path: addQueryArgs( '/wpcom/v2/newsletter-email-sent-status', { post_id: postId } ),
		method: 'GET',
	} );
 
	Iif ( ! response || typeof response !== 'object' ) {
		throw new Error( 'Unexpected API response' );
	}
 
	const wpError = response?.errors && Object.values( response.errors )?.[ 0 ]?.[ 0 ];
	if ( wpError ) {
		throw new Error( wpError );
	}
 
	return response;
};
 
const createDefaultProduct = async (
	productType,
	setSelectedProductIds,
	dispatch,
	shouldDisplayProductCreationNotice
) => {
	await dispatch(
		saveProduct(
			{
				title: getMessageByProductType( 'default new product title', productType ),
				currency: 'USD',
				price: 5,
				interval: '1 month',
			},
			productType,
			setSelectedProductIds,
			() => {},
			shouldDisplayProductCreationNotice
		)
	);
};
 
const shouldCreateDefaultProduct = response =>
	! response.products.length && response.connected_account_id;
 
const setDefaultProductIfNeeded = ( selectedProductIds, setSelectedProductIds, select ) => {
	Iif ( selectedProductIds.length > 0 ) {
		return;
	}
	const defaultProductId = select.getProductsNoResolver()[ 0 ]?.id;
	Eif ( defaultProductId ) {
		setSelectedProductIds( [ defaultProductId ] );
	}
};
 
export const getNewsletterTierProducts = (
	productType = PRODUCT_TYPE_PAYMENT_PLAN,
	selectedProductIds = [],
	setSelectedProductIds = () => {}
) => getProducts( productType, selectedProductIds, setSelectedProductIds, false );
 
export const getProducts =
	(
		productType = PRODUCT_TYPE_PAYMENT_PLAN,
		selectedProductIds = [],
		setSelectedProductIds = () => {},
		shouldDisplayProductCreationNotice = true
	) =>
	async ( { dispatch, registry, select } ) => {
		// The memberships, categories and email-sent requests need the user's own WordPress.com connection.
		if ( ! isCurrentUserConnected() ) {
			dispatch( setConnectUrl( null ) );
			dispatch( setApiState( API_STATE_NOTCONNECTED ) );
			return;
		}
 
		await executionLock.blockExecution( EXECUTION_KEY );
		Iif ( hydratedFromAPI ) {
			setDefaultProductIfNeeded( selectedProductIds, setSelectedProductIds, select );
			return;
		}
 
		const lock = executionLock.acquire( EXECUTION_KEY );
		try {
			const response = await fetchMemberships();
			mapAPIResponseToMembershipProductsStoreData( response, registry, dispatch );
 
			Iif ( shouldCreateDefaultProduct( response ) ) {
				// Is ready to use and has no product set up yet. Let's create one!
				await createDefaultProduct(
					productType,
					setSelectedProductIds,
					dispatch,
					shouldDisplayProductCreationNotice
				);
			}
 
			setDefaultProductIfNeeded( selectedProductIds, setSelectedProductIds, select );
 
			hydratedFromAPI = true;
		} catch ( error ) {
			dispatch( setConnectUrl( null ) );
			dispatch( setApiState( API_STATE_NOTCONNECTED ) );
			onError( error.message, registry );
		} finally {
			executionLock.release( lock );
		}
	};
 
export const getSubscriberCounts =
	() =>
	async ( { dispatch, registry } ) => {
		await executionLock.blockExecution( SUBSCRIBER_COUNT_EXECUTION_KEY );
 
		const lock = executionLock.acquire( SUBSCRIBER_COUNT_EXECUTION_KEY );
		try {
			const response = await fetchSubscriberCounts();
			dispatch(
				setSubscriberCounts( {
					totalSubscribers: response.counts.total_subscribers,
					socialFollowers: response.counts.social_followers,
					emailSubscribers: response.counts.email_subscribers,
					paidSubscribers: response.counts.paid_subscribers,
					paidNewsletterSubscribers: response.counts.paid_newsletter_subscribers ?? null,
					paidSubscribersByTier: response.counts.paid_subscribers_by_tier ?? null,
				} )
			);
		} catch ( error ) {
			dispatch( setApiState( API_STATE_NOTCONNECTED ) );
			onError( error.message, registry );
		} finally {
			executionLock.release( lock );
		}
	};
 
export const getTotalEmailsSentCount =
	( blogId, postId ) =>
	async ( { dispatch } ) => {
		await executionLock.blockExecution( TOTAL_EMAILS_SENT_COUNT_EXECUTION_KEY );
 
		const lock = executionLock.acquire( TOTAL_EMAILS_SENT_COUNT_EXECUTION_KEY );
		try {
			const response = await fetchTotalEmailsSentCount( blogId, postId );
			dispatch( setTotalEmailsSentCount( response?.total_sends ) );
		} catch ( error ) {
			// Email open stats are informational. Fail silently so a slow or
			// failed WPCOM response (e.g. 5s timeout on stats/opens/emails) does
			// not surface a snackbar error in the editor. See NL-578.
			// eslint-disable-next-line no-console
			console.warn( 'Failed to fetch total emails sent count:', error?.message );
		} finally {
			executionLock.release( lock );
		}
	};
 
export const getNewsletterCategories =
	() =>
	async ( { dispatch, registry } ) => {
		if ( ! isCurrentUserConnected() ) {
			dispatch( setApiState( API_STATE_NOTCONNECTED ) );
			return;
		}
 
		await executionLock.blockExecution( GET_NEWSLETTER_CATEGORIES_EXECUTION_KEY );
 
		const lock = executionLock.acquire( GET_NEWSLETTER_CATEGORIES_EXECUTION_KEY );
 
		try {
			const response = await fetchNewsletterCategories();
			dispatch(
				setNewsletterCategories( {
					enabled: response.enabled,
					categories: response.newsletter_categories,
				} )
			);
		} catch ( error ) {
			dispatch( setApiState( API_STATE_NOTCONNECTED ) );
			onError( error.message, registry );
		} finally {
			executionLock.release( lock );
		}
	};
 
export const getPostEmailSentState =
	postId =>
	async ( { dispatch, registry } ) => {
		if ( ! postId || ! isCurrentUserConnected() ) {
			return;
		}
 
		await executionLock.blockExecution( GET_POST_EMAIL_SENT_STATE_EXECUTION_KEY );
 
		const lock = executionLock.acquire( GET_POST_EMAIL_SENT_STATE_EXECUTION_KEY );
		try {
			const response = await fetchPostEmailSentState( postId );
			dispatch(
				setPostEmailSentState( postId, {
					email_sent_at: response.email_sent_at ?? null,
					stats_on_send: response.stats_on_send ?? null,
				} )
			);
		} catch ( error ) {
			onError( error.message, registry );
		} finally {
			executionLock.release( lock );
		}
	};