|
| 1 | +import type { ReactElement } from 'react'; |
| 2 | +import React, { useEffect, useMemo, useRef, useState } from 'react'; |
| 3 | +import { useQuery } from '@tanstack/react-query'; |
| 4 | +import { useRouter } from 'next/router'; |
| 5 | +import { PurchaseType } from '../../graphql/paddle'; |
| 6 | +import { usePaddlePayment } from '../../hooks/usePaddlePayment'; |
| 7 | +import { useLogContext } from '../LogContext'; |
| 8 | +import { useAuthContext } from '../AuthContext'; |
| 9 | +import type { |
| 10 | + RecruiterPaymentContextData, |
| 11 | + RecruiterContextProviderProps, |
| 12 | + RecruiterProductOption, |
| 13 | +} from './types'; |
| 14 | +import { RecruiterPaymentContext } from './types'; |
| 15 | +import { webappUrl } from '../../lib/constants'; |
| 16 | +import { recruiterPricesQueryOptions } from '../../features/opportunity/graphql'; |
| 17 | + |
| 18 | +export const RecruiterPaymentPaddleContextProvider = ({ |
| 19 | + onCompletion, |
| 20 | + origin, |
| 21 | + children, |
| 22 | +}: RecruiterContextProviderProps): ReactElement => { |
| 23 | + const router = useRouter(); |
| 24 | + const { user, isLoggedIn } = useAuthContext(); |
| 25 | + const { logEvent } = useLogContext(); |
| 26 | + const [selectedProduct, setSelectedProduct] = |
| 27 | + useState<RecruiterProductOption>(); |
| 28 | + const logRef = useRef<typeof logEvent>(); |
| 29 | + logRef.current = logEvent; |
| 30 | + |
| 31 | + const { data: prices } = useQuery( |
| 32 | + recruiterPricesQueryOptions({ |
| 33 | + user, |
| 34 | + isLoggedIn, |
| 35 | + }), |
| 36 | + ); |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + if (!prices?.length) { |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + if (selectedProduct) { |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + setSelectedProduct({ |
| 48 | + id: prices[0].priceId, |
| 49 | + }); |
| 50 | + }, [prices, selectedProduct]); |
| 51 | + |
| 52 | + const { paddle, openCheckout } = usePaddlePayment({ |
| 53 | + successCallback: () => { |
| 54 | + router.push( |
| 55 | + `${webappUrl}recruiter/${router.query.opportunityId}/prepare`, |
| 56 | + ); |
| 57 | + }, |
| 58 | + priceType: PurchaseType.Recruiter, |
| 59 | + }); |
| 60 | + |
| 61 | + const contextData = useMemo<RecruiterPaymentContextData>( |
| 62 | + () => ({ |
| 63 | + paddle, |
| 64 | + onCompletion, |
| 65 | + selectedProduct, |
| 66 | + setSelectedProduct, |
| 67 | + openCheckout, |
| 68 | + origin, |
| 69 | + }), |
| 70 | + [onCompletion, openCheckout, origin, paddle, selectedProduct], |
| 71 | + ); |
| 72 | + |
| 73 | + return ( |
| 74 | + <RecruiterPaymentContext.Provider value={contextData}> |
| 75 | + {children} |
| 76 | + </RecruiterPaymentContext.Provider> |
| 77 | + ); |
| 78 | +}; |
0 commit comments