File size: 1,937 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { PLAN_FREE, getPlan } from '@automattic/calypso-products';
import { useEffect } from '@wordpress/element';
import { sprintf, getLocaleData } from '@wordpress/i18n';
import { useI18n } from '@wordpress/react-i18n';
import { useDispatch } from 'calypso/state';
import { successNotice } from 'calypso/state/notices/actions';

const getStorageKey = ( siteId: number ): string => `show-purchase-plan-notification-${ siteId }`;

type UsePurchasePlanNotificationReturn = {
	setShouldShowNotification: ( siteId: number ) => void;
};

/**
 * This hook is used to show a notification when a site is created with the purchase plan
 * The notification is shown only once and is stored in the localStorage
 */
export const usePurchasePlanNotification = (
	siteId?: number,
	sitePlanSlug?: string
): UsePurchasePlanNotificationReturn => {
	const dispatch = useDispatch();
	const { __ } = useI18n();

	useEffect( () => {
		if ( ! siteId ) {
			return;
		}

		const storageKey = getStorageKey( siteId );
		const shouldShowNotification = localStorage.getItem( storageKey ) === 'true';

		if ( ! sitePlanSlug || sitePlanSlug === PLAN_FREE || ! shouldShowNotification ) {
			return;
		}

		const plan = getPlan( sitePlanSlug );
		// Only display the notification after translation data has been loaded
		const localeSlug = getLocaleData()[ '' ].localeSlug;
		if ( ! localeSlug ) {
			return;
		}

		dispatch(
			successNotice(
				sprintf(
					/* translators: %(planName)s is the name of the plan, e.g. "Business Plan" */
					__( "You're in! The %(planName)s Plan is now active." ),
					{ planName: plan?.getTitle() || '' }
				)
			)
		);

		// Reset the flag after showing the notification
		localStorage.removeItem( storageKey );
	}, [ dispatch, __, siteId, sitePlanSlug ] );

	const setShouldShowNotification = ( siteId: number ) => {
		localStorage.setItem( getStorageKey( siteId ), 'true' );
	};

	return { setShouldShowNotification };
};