1- import { eq , sql , or } from 'drizzle-orm'
1+ import { eq , sql , or , and } from 'drizzle-orm'
22import { NextResponse } from 'next/server'
33import { CREDITS_REFERRAL_BONUS } from 'common/constants'
44import db from 'common/db'
@@ -7,28 +7,45 @@ import { hasMaxedReferrals } from 'common/util/server/referral'
77
88export async function redeemReferralCode ( referralCode : string , userId : string ) {
99 try {
10- // Check if the user has already used a referral code
11- const existingReferral = await db
10+ // Check if the user has already used this referral code
11+ const alreadyUsed = await db
1212 . select ( )
1313 . from ( schema . referral )
1414 . where ( eq ( schema . referral . referred_id , userId ) )
1515 . limit ( 1 )
1616
17- if ( existingReferral . length > 0 ) {
17+ if ( alreadyUsed . length > 0 ) {
1818 return NextResponse . json (
19- { error : 'You have already used a referral code' } ,
19+ { error : 'You have already used this referral code' } ,
2020 { status : 429 }
2121 )
2222 }
2323
2424 // Check if the user is trying to use their own referral code
25- const currentUser = await db
26- . select ( { referral_code : schema . user . referral_code } )
25+ const referringUser = await db
26+ . select ( { userId : schema . user . id } )
2727 . from ( schema . user )
28- . where ( eq ( schema . user . id , userId ) )
28+ . where ( eq ( schema . user . referral_code , referralCode ) )
2929 . limit ( 1 )
30+ . then ( ( users ) => {
31+ if ( users . length === 1 ) {
32+ return users [ 0 ]
33+ }
34+ return
35+ } )
3036
31- if ( currentUser [ 0 ] ?. referral_code === referralCode ) {
37+ if ( ! referringUser ) {
38+ return NextResponse . json (
39+ {
40+ error :
41+ "Uh-oh, this referral code doesn't exist! Try again or reach out to support@manicode.ai if the problem persists." ,
42+ } ,
43+ {
44+ status : 404 ,
45+ }
46+ )
47+ }
48+ if ( referringUser . userId === userId ) {
3249 return NextResponse . json (
3350 {
3451 error : "Nice try bud, you can't use your own referral code" ,
@@ -39,6 +56,27 @@ export async function redeemReferralCode(referralCode: string, userId: string) {
3956 )
4057 }
4158
59+ // Check if the user has been referred by someone they were referred by
60+ const doubleDipping = await db
61+ . select ( )
62+ . from ( schema . referral )
63+ . where (
64+ and (
65+ eq ( schema . referral . referrer_id , userId ) ,
66+ eq ( schema . referral . referred_id , referringUser . userId )
67+ )
68+ )
69+ . limit ( 1 )
70+ if ( doubleDipping . length > 0 ) {
71+ return NextResponse . json (
72+ {
73+ error :
74+ 'You were referred by this user already.o double dipping, refer someone new!' ,
75+ } ,
76+ { status : 429 }
77+ )
78+ }
79+
4280 // Find the referrer user
4381 const referrers = await db
4482 . select ( )
0 commit comments