| 1 |
import {useCallback, useState} from 'react'; |
| 2 |
import dismissRecommendation from '@givewp/promotions/requests/dismissRecommendation'; |
| 3 |
|
| 4 |
type EnumValues = |
| 5 |
| 'givewp_donations_recurring_recommendation_dismissed' |
| 6 |
| 'givewp_donations_fee_recovery_recommendation_dismissed' |
| 7 |
| 'givewp_donations_designated_funds_recommendation_dismissed' |
| 8 |
| 'givewp_reports_recurring_recommendation_dismissed' |
| 9 |
| 'givewp_reports_fee_recovery_recommendation_dismissed' |
| 10 |
| 'givewp_donors_fee_recovery_recommendation_dismissed' |
| 11 |
| 'givewp_reports_fee_recovery_recommendation_dismissed'; |
| 12 |
|
| 13 |
export interface RecommendedProductData { |
| 14 |
enum: EnumValues; |
| 15 |
documentationPage: string; |
| 16 |
message: string; |
| 17 |
innerHtml: string; |
| 18 |
} |
| 19 |
|
| 20 |
/** |
| 21 |
* @since 2.27.1 |
| 22 |
*/ |
| 23 |
export function useRecommendations(apiSettings, options) { |
| 24 |
const [dismissedRecommendations, setDismissedRecommendations] = useState<string[]>( |
| 25 |
apiSettings.dismissedRecommendations |
| 26 |
); |
| 27 |
|
| 28 |
const getRandomRecommendation = useCallback((): RecommendedProductData | null => { |
| 29 |
const availableOptions = options.filter((option) => !dismissedRecommendations.includes(option.enum)); |
| 30 |
|
| 31 |
if (availableOptions.length === 0) { |
| 32 |
return null; |
| 33 |
} |
| 34 |
|
| 35 |
const randomIndex = Math.floor(Math.random() * availableOptions.length); |
| 36 |
|
| 37 |
return availableOptions[randomIndex]; |
| 38 |
}, [dismissedRecommendations]); |
| 39 |
|
| 40 |
const getRecommendation = useCallback((): RecommendedProductData | null => { |
| 41 |
const availableOptions = options.filter((option) => !dismissedRecommendations.includes(option.enum)); |
| 42 |
|
| 43 |
if (availableOptions.length === 0) { |
| 44 |
return null; |
| 45 |
} |
| 46 |
|
| 47 |
return availableOptions[0]; |
| 48 |
}, [dismissedRecommendations]); |
| 49 |
|
| 50 |
const removeRecommendation = async (data: {option: EnumValues}): Promise<void> => { |
| 51 |
setDismissedRecommendations((prev) => [...prev, data.option]); |
| 52 |
|
| 53 |
await dismissRecommendation(data.option, apiSettings.apiNonce); |
| 54 |
}; |
| 55 |
|
| 56 |
return {getRecommendation, getRandomRecommendation, removeRecommendation}; |
| 57 |
} |
| 58 |
|