|
| 1 | +/* |
| 2 | + * Copyright (c) 2025, Salesforce, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * SPDX-License-Identifier: BSD-3-Clause |
| 5 | + * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause |
| 6 | + */ |
| 7 | + |
| 8 | +import {useCallback, useMemo, useState} from 'react' |
| 9 | +import { |
| 10 | + CONSENT_CHANNELS, |
| 11 | + CONSENT_STATUS |
| 12 | +} from '@salesforce/retail-react-app/app/constants/marketing-consent' |
| 13 | +import {useMarketingConsent} from '@salesforce/retail-react-app/app/hooks/use-marketing-consent' |
| 14 | +import {validateEmail} from '@salesforce/retail-react-app/app/utils/subscription-validators' |
| 15 | +import {useIntl} from 'react-intl' |
| 16 | + |
| 17 | +/** |
| 18 | + * Hook for managing email subscription form state and submission. |
| 19 | + * This hook dynamically fetches all subscriptions matching a given tag and email channel, |
| 20 | + * then opts the user into ALL matching subscriptions when they submit their email. |
| 21 | + * |
| 22 | + * Subscriptions are fetched on-demand when the user clicks submit, not on component mount. |
| 23 | + * |
| 24 | + * This allows marketers to configure subscriptions without code changes to the storefront UI. |
| 25 | + * |
| 26 | + * @param {Object} options |
| 27 | + * @param {string|Array<string>} options.tag - The consent tag(s) to filter subscriptions by (e.g., CONSENT_TAGS.EMAIL_CAPTURE or [CONSENT_TAGS.EMAIL_CAPTURE, CONSENT_TAGS.ACCOUNT]) |
| 28 | + * @returns {Object} Email subscription state and actions |
| 29 | + * @returns {Object} return.state - Current form state |
| 30 | + * @returns {string} return.state.email - Current email value |
| 31 | + * @returns {boolean} return.state.isLoading - Whether submission is in progress |
| 32 | + * @returns {Object} return.state.feedback - Feedback message and type |
| 33 | + * @returns {string} return.state.feedback.message - User-facing message |
| 34 | + * @returns {string} return.state.feedback.type - Message type ('success' | 'error') |
| 35 | + * @returns {Object} return.actions - Available actions |
| 36 | + * @returns {Function} return.actions.setEmail - Update email value |
| 37 | + * @returns {Function} return.actions.submit - Submit the subscription |
| 38 | + * |
| 39 | + * @example |
| 40 | + * const {state, actions} = useEmailSubscription({ |
| 41 | + * tag: CONSENT_TAGS.EMAIL_CAPTURE |
| 42 | + * }) |
| 43 | + */ |
| 44 | +export const useEmailSubscription = ({tag} = {}) => { |
| 45 | + // Normalize tag to array for API call |
| 46 | + const tags = useMemo(() => { |
| 47 | + if (!tag) return [] |
| 48 | + return Array.isArray(tag) ? tag : [tag] |
| 49 | + }, [tag]) |
| 50 | + |
| 51 | + const { |
| 52 | + refetch: fetchSubscriptions, |
| 53 | + updateSubscriptions, |
| 54 | + isUpdating |
| 55 | + } = useMarketingConsent({ |
| 56 | + tags, |
| 57 | + enabled: false |
| 58 | + }) |
| 59 | + |
| 60 | + const intl = useIntl() |
| 61 | + const {formatMessage} = intl |
| 62 | + |
| 63 | + const [email, setEmail] = useState('') |
| 64 | + const [message, setMessage] = useState(null) |
| 65 | + const [messageType, setMessageType] = useState('success') |
| 66 | + |
| 67 | + const messages = useMemo( |
| 68 | + () => ({ |
| 69 | + success_confirmation: formatMessage({ |
| 70 | + id: 'footer.success_confirmation', |
| 71 | + defaultMessage: 'Thanks for subscribing!' |
| 72 | + }), |
| 73 | + error: { |
| 74 | + enter_valid_email: formatMessage({ |
| 75 | + id: 'footer.error.enter_valid_email', |
| 76 | + defaultMessage: 'Enter a valid email address.' |
| 77 | + }), |
| 78 | + generic_error: formatMessage({ |
| 79 | + id: 'footer.error.generic_error', |
| 80 | + defaultMessage: "We couldn't process the subscription. Try again." |
| 81 | + }) |
| 82 | + } |
| 83 | + }), |
| 84 | + [formatMessage] |
| 85 | + ) |
| 86 | + |
| 87 | + const handleSignUp = useCallback(async () => { |
| 88 | + // Validate email using the utility validator |
| 89 | + const validation = validateEmail(email) |
| 90 | + |
| 91 | + if (!validation.valid) { |
| 92 | + setMessage(messages.error.enter_valid_email) |
| 93 | + setMessageType('error') |
| 94 | + return |
| 95 | + } |
| 96 | + |
| 97 | + try { |
| 98 | + setMessage(null) |
| 99 | + |
| 100 | + // Fetch subscriptions on-demand when submitting |
| 101 | + const {data: freshSubscriptionsData} = await fetchSubscriptions() |
| 102 | + const allSubscriptions = freshSubscriptionsData?.data || [] |
| 103 | + |
| 104 | + // Find matching subscriptions |
| 105 | + const matchingSubs = allSubscriptions.filter((sub) => { |
| 106 | + const hasEmailChannel = sub.channels?.includes(CONSENT_CHANNELS.EMAIL) |
| 107 | + const hasAnyTag = tags.some((t) => sub.tags?.includes(t)) |
| 108 | + return hasEmailChannel && hasAnyTag |
| 109 | + }) |
| 110 | + |
| 111 | + // Check if there are any matching subscriptions |
| 112 | + if (matchingSubs.length === 0) { |
| 113 | + const tagList = tags.join(', ') |
| 114 | + console.error( |
| 115 | + `[useEmailSubscription] No subscriptions found for tag(s) "${tagList}" and channel "${CONSENT_CHANNELS.EMAIL}".` |
| 116 | + ) |
| 117 | + setMessage(messages.error.generic_error) |
| 118 | + setMessageType('error') |
| 119 | + return |
| 120 | + } |
| 121 | + |
| 122 | + // Build array of subscription updates for ALL matching subscriptions |
| 123 | + const subscriptionUpdates = matchingSubs.map((sub) => ({ |
| 124 | + subscriptionId: sub.subscriptionId, |
| 125 | + contactPointValue: email, |
| 126 | + channel: CONSENT_CHANNELS.EMAIL, |
| 127 | + status: CONSENT_STATUS.OPT_IN |
| 128 | + })) |
| 129 | + |
| 130 | + console.log( |
| 131 | + `[useEmailSubscription] Opting in to ${subscriptionUpdates.length} subscription(s):`, |
| 132 | + subscriptionUpdates.map((s) => s.subscriptionId) |
| 133 | + ) |
| 134 | + |
| 135 | + // Submit the consent using bulk API (ShopperConsents API v1.1.3) |
| 136 | + await updateSubscriptions(subscriptionUpdates) |
| 137 | + |
| 138 | + setMessage(messages.success_confirmation) |
| 139 | + setMessageType('success') |
| 140 | + setEmail('') |
| 141 | + } catch (err) { |
| 142 | + console.error('[useEmailSubscription] Subscription error:', err) |
| 143 | + setMessage(messages.error.generic_error) |
| 144 | + setMessageType('error') |
| 145 | + } |
| 146 | + }, [email, tags, fetchSubscriptions, updateSubscriptions, messages]) |
| 147 | + |
| 148 | + return { |
| 149 | + state: { |
| 150 | + email, |
| 151 | + isLoading: isUpdating, |
| 152 | + feedback: {message, type: messageType} |
| 153 | + }, |
| 154 | + actions: { |
| 155 | + setEmail, |
| 156 | + submit: handleSignUp |
| 157 | + } |
| 158 | + } |
| 159 | +} |
| 160 | + |
| 161 | +export default useEmailSubscription |
0 commit comments