Skip to content

Commit 928d7f2

Browse files
Add functions instead for affiliate stats an referrals
1 parent b7f6ed1 commit 928d7f2

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
CREATE OR REPLACE FUNCTION get_affiliate_stats_summary()
2+
RETURNS TABLE(
3+
id uuid,
4+
created_at timestamptz,
5+
user_id uuid,
6+
send_plus_minus bigint,
7+
referral_count bigint,
8+
network_plus_minus numeric,
9+
affiliate_send_score numeric)
10+
LANGUAGE plpgsql
11+
SECURITY DEFINER
12+
SET search_path = public
13+
AS $$
14+
BEGIN
15+
RETURN QUERY
16+
SELECT
17+
a.id,
18+
a.created_at,
19+
a.user_id,
20+
a.send_plus_minus,
21+
COUNT(r.referred_id)::bigint AS referral_count,
22+
COALESCE(SUM(ra.send_plus_minus), 0) AS network_plus_minus,
23+
(COALESCE((
24+
SELECT
25+
SUM(amount)
26+
FROM distribution_shares ds2
27+
WHERE
28+
ds2.user_id = a.user_id
29+
AND ds2.distribution_id >= 6), 0) + COALESCE(SUM(ds.amount), 0)) AS affiliate_send_score
30+
FROM
31+
affiliate_stats a
32+
LEFT JOIN referrals r ON r.referrer_id = a.user_id
33+
LEFT JOIN affiliate_stats ra ON ra.user_id = r.referred_id
34+
LEFT JOIN distribution_shares ds ON ds.user_id = r.referred_id
35+
AND ds.distribution_id >= 6
36+
WHERE
37+
a.user_id = auth.uid()
38+
GROUP BY
39+
a.id,
40+
a.created_at,
41+
a.user_id,
42+
a.send_plus_minus;
43+
END;
44+
$$;
45+
46+
CREATE OR REPLACE FUNCTION get_affiliate_referrals()
47+
RETURNS TABLE(
48+
referred_id uuid,
49+
send_plus_minus bigint,
50+
avatar_url text,
51+
tag citext,
52+
created_at timestamptz)
53+
LANGUAGE plpgsql
54+
SECURITY DEFINER
55+
SET search_path = public
56+
AS $$
57+
BEGIN
58+
RETURN QUERY WITH ordered_referrals AS(
59+
SELECT
60+
r.referred_id,
61+
COALESCE(a.send_plus_minus, 0)::bigint AS send_plus_minus,
62+
p.avatar_url,
63+
t.name AS tag,
64+
t.created_at,
65+
COALESCE((
66+
SELECT
67+
SUM(amount)
68+
FROM distribution_shares ds
69+
WHERE
70+
ds.user_id = r.referred_id
71+
AND distribution_id >= 6), 0) AS send_score
72+
FROM
73+
referrals r
74+
LEFT JOIN affiliate_stats a ON a.user_id = r.referred_id
75+
LEFT JOIN profiles p ON p.id = r.referred_id
76+
LEFT JOIN tags t ON t.name = r.tag
77+
WHERE
78+
r.referrer_id = auth.uid())
79+
SELECT
80+
o.referred_id,
81+
o.send_plus_minus,
82+
o.avatar_url,
83+
o.tag,
84+
o.created_at
85+
FROM
86+
ordered_referrals o
87+
ORDER BY
88+
send_score DESC;
89+
END;
90+
$$;
91+

0 commit comments

Comments
 (0)