1
+ -- Fix use correct distribution id and search on shares param
2
+ CREATE OR REPLACE FUNCTION public .update_referral_verifications(
3
+ distribution_id INTEGER ,
4
+ shares distribution_shares[]
5
+ )
6
+ RETURNS VOID
7
+ LANGUAGE plpgsql
8
+ SECURITY DEFINER
9
+ SET search_path TO ' public'
10
+ AS $function$
11
+ BEGIN
12
+ WITH qualifying_referrals AS (
13
+ SELECT DISTINCT
14
+ ds .user_id ::TEXT AS referred_id,
15
+ r .referrer_id
16
+ FROM
17
+ unnest(shares) ds
18
+ LEFT JOIN public .referrals r ON r .referred_id = ds .user_id
19
+ WHERE
20
+ ds .distribution_id = $1
21
+ )
22
+ UPDATE public .distribution_verifications dv
23
+ SET weight = CASE
24
+ WHEN dv .type = ' tag_referral' AND
25
+ dv .metadata - >> ' referred_id' IN (SELECT referred_id FROM qualifying_referrals)
26
+ THEN 1
27
+ WHEN dv .type = ' total_tag_referrals' AND
28
+ EXISTS (
29
+ SELECT 1
30
+ FROM qualifying_referrals qr
31
+ WHERE qr .referrer_id = dv .user_id
32
+ )
33
+ THEN (
34
+ SELECT COUNT (* )
35
+ FROM qualifying_referrals qr
36
+ WHERE qr .referrer_id = dv .user_id
37
+ )
38
+ ELSE 0
39
+ END
40
+ WHERE
41
+ dv .distribution_id = $1 AND
42
+ dv .type IN (' tag_referral' , ' total_tag_referrals' );
43
+ END;
44
+ $function$;
45
+
46
+ -- Remove deprecated metadata from distribution_verifications total_tag_referrals type
47
+ UPDATE public .distribution_verifications dv
48
+ SET metadata = NULL
49
+ WHERE dv .type = ' total_tag_referrals' ;
50
+
51
+ -- remove checks for distribution qualification
52
+ -- impossible for new referral to have entry in distribution shares
53
+ CREATE OR REPLACE FUNCTION "public "." insert_verification_referral" ()
54
+ RETURNS TRIGGER
55
+ LANGUAGE plpgsql
56
+ SECURITY DEFINER
57
+ SET search_path = public
58
+ AS $$
59
+ DECLARE
60
+ curr_distribution_id bigint ;
61
+ BEGIN
62
+ -- Get the current distribution id
63
+ SELECT
64
+ id INTO curr_distribution_id
65
+ FROM
66
+ distributions
67
+ WHERE
68
+ qualification_start <= now()
69
+ AND qualification_end >= now()
70
+ ORDER BY
71
+ qualification_start DESC
72
+ LIMIT 1 ;
73
+
74
+ -- Return early if current distribution doesn't exist
75
+ IF curr_distribution_id IS NULL THEN
76
+ RETURN NEW;
77
+ END IF;
78
+
79
+ -- Insert verification for referrer
80
+ INSERT INTO public .distribution_verifications (
81
+ distribution_id,
82
+ user_id,
83
+ type,
84
+ metadata,
85
+ weight
86
+ )
87
+ VALUES (
88
+ curr_distribution_id,
89
+ NEW .referrer_id ,
90
+ ' tag_referral' ::public .verification_type ,
91
+ jsonb_build_object(
92
+ ' referred_id' , NEW .referred_id
93
+ ),
94
+ 0
95
+ );
96
+ RETURN NEW;
97
+ END;
98
+ $$;
0 commit comments