1+ import React , { useEffect } from 'react' ;
2+ import { EXTERNAL } from '@/constant' ;
3+ import { getUserProfile } from '@/lib/utils' ;
4+
5+ interface ReferralHandlerProps {
6+ children ?: React . ReactNode ;
7+ }
8+
9+ export default function ReferralHandler ( { children } : ReferralHandlerProps ) {
10+ useEffect ( ( ) => {
11+ async function handleReferralCode ( ) {
12+ try {
13+ // Check for ref parameter in URL
14+ const urlParams = new URLSearchParams ( window . location . search ) ;
15+ const refCode = urlParams . get ( 'ref' ) ;
16+
17+ if ( refCode ) {
18+ // Store referral code in localStorage
19+ localStorage . setItem ( 'ref_code' , refCode ) ;
20+ }
21+
22+
23+ // Check if user is logged in and handle claimed referral codes
24+ const user = await getUserProfile ( EXTERNAL . directus_url ) ;
25+
26+ if ( user ) {
27+ const storedRefCode = localStorage . getItem ( 'ref_code' ) ;
28+
29+ if ( storedRefCode ) {
30+ console . log ( 'Referral code handling initiated.' ) ;
31+
32+ // get data if currently passed ref code
33+ const checkUrl = `${ EXTERNAL . directus_url } /items/referral_code?filter[code][_eq]=${ encodeURIComponent ( storedRefCode ) } &fields=*,user_claimed&limit=1` ;
34+
35+ const response = await fetch ( checkUrl , {
36+ credentials : 'include' ,
37+ headers : { 'Accept' : 'application/json' }
38+ } ) ;
39+
40+ if ( response . ok ) {
41+ const result = await response . json ( ) ;
42+ console . log ( result ) ;
43+
44+ // Check if the current user is in the user_claimed many-to-many relationship
45+ if ( result . data && result . data . length > 0 ) {
46+ const referralCode = result . data [ 0 ] ;
47+ const isAlreadyClaimed = referralCode . user_claimed ?. some ( ( userId : string ) => userId === user . id ) ;
48+
49+ if ( isAlreadyClaimed ) {
50+ console . log ( 'user already claimed ref code before' ) ;
51+
52+ localStorage . removeItem ( 'ref_code' ) ;
53+ }
54+ // TODO
55+ }
56+ }
57+ }
58+ }
59+ } catch ( error ) {
60+ console . error ( 'Error handling referral code:' , error ) ;
61+ }
62+ }
63+
64+ handleReferralCode ( ) ;
65+ } , [ ] ) ;
66+
67+ // Just render children if provided, otherwise render nothing
68+ return children ? < > { children } </ > : null ;
69+ }
0 commit comments