Skip to content

Commit 6de82ac

Browse files
playlikeboyclaude
andcommitted
fix(invites): make invite links credit the inviter
/join set its cookie while rendering a page, which Next.js rejects, so no invite was ever recorded. It is now a route handler that accepts ?invite= and ?ref=, keeps the college hint, return path and UTM tags, and sets the cookie on the redirect. Onboarding now credits the inviter once, through awardPoints with the REFERRAL_SIGNUP reward the UI already promises (50, was a hard-coded 20), only for a verified student, never for a self-invite or a repeat onboarding. Students who join in Campus Preview credit their inviter when they verify in the campus upgrade flow. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent a4b339d commit 6de82ac

8 files changed

Lines changed: 256 additions & 52 deletions

File tree

‎src/app/(app)/onboarding/actions.ts‎

Lines changed: 44 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"use server";
22

3-
import { eq, sql } from "drizzle-orm";
3+
import { eq } from "drizzle-orm";
44
import { cookies } from "next/headers";
55
import { getDb } from "@/db";
66
import { institutionDomains, institutions, userProfiles } from "@/db/schema";
@@ -9,6 +9,8 @@ import { runInBackground } from "@/lib/background";
99
import { sendEmail } from "@/lib/email";
1010
import { buildWelcomeEmail } from "@/lib/email-templates";
1111
import { findWhitelistedDomain } from "@/lib/institutions";
12+
import { creditInviter } from "@/lib/referrals/credit";
13+
import { canCreditInvite, INVITE_COOKIE, pickInviter, REF_COOKIE } from "@/lib/referrals/invite";
1214
import { invalidateProfileCache } from "@/lib/server-cache";
1315
import { getAvatarUrl } from "@/lib/utils";
1416
import { validateDisplayName, validateUsername } from "@/lib/validation";
@@ -115,20 +117,29 @@ export async function completeOnboarding(formData: FormData): Promise<Onboarding
115117
? whitelistedDomain!.institutionId
116118
: await getViewerInstitutionId();
117119

118-
// Handle referral tracking
120+
// Invite tracking. The inviter is remembered on the profile for everyone who
121+
// joined through a link, and credited once the invited student is verified
122+
// (here, or later in the campus upgrade flow).
119123
const cookieStore = await cookies();
120-
const referredByUsername = cookieStore.get("cl_referred_by")?.value;
121-
let referrerId: string | null = null;
122-
let referrerProfile = null;
124+
const inviterUsername = pickInviter(
125+
cookieStore.get(INVITE_COOKIE)?.value,
126+
cookieStore.get(REF_COOKIE)?.value
127+
);
128+
const existingProfile = await db.query.userProfiles.findFirst({
129+
where: eq(userProfiles.userId, user.id),
130+
columns: { id: true, onboardingCompleted: true },
131+
});
132+
const wasAlreadyOnboarded = Boolean(existingProfile?.onboardingCompleted);
123133

124-
if (referredByUsername) {
125-
referrerProfile = await db.query.userProfiles.findFirst({
126-
where: eq(userProfiles.username, referredByUsername),
134+
let referrerProfile: { id: string; userId: string } | null = null;
135+
if (inviterUsername && !wasAlreadyOnboarded) {
136+
const found = await db.query.userProfiles.findFirst({
137+
where: eq(userProfiles.username, inviterUsername),
138+
columns: { id: true, userId: true },
127139
});
128-
if (referrerProfile) {
129-
referrerId = referrerProfile.id;
130-
}
140+
if (found && found.userId !== user.id) referrerProfile = found;
131141
}
142+
const referrerId = referrerProfile?.id ?? null;
132143

133144
const rawUsername = email.split("@")[0] || "student";
134145
const officialName = rawUsername
@@ -189,19 +200,32 @@ export async function completeOnboarding(formData: FormData): Promise<Onboarding
189200
institutionId,
190201
isCollegeVerified: isVerifiedCollegeEmail,
191202
onboardingCompleted: true,
203+
// A profile row created before onboarding has no inviter yet.
204+
...(referrerId && !wasAlreadyOnboarded ? { referredById: referrerId } : {}),
192205
},
193206
});
194207
invalidateProfileCache(user.id);
195208

196-
if (referrerProfile) {
197-
await db
198-
.update(userProfiles)
199-
.set({
200-
referralCount: sql`${userProfiles.referralCount} + 1`,
201-
points: sql`${userProfiles.points} + 20`,
202-
})
203-
.where(eq(userProfiles.id, referrerProfile.id));
204-
invalidateProfileCache(referrerProfile.userId);
209+
if (
210+
referrerProfile &&
211+
canCreditInvite({
212+
inviterUserId: referrerProfile.userId,
213+
invitedUserId: user.id,
214+
isVerifiedStudent: isVerifiedCollegeEmail,
215+
wasAlreadyOnboarded,
216+
})
217+
) {
218+
try {
219+
await creditInviter(referrerProfile.id, existingProfile?.id);
220+
} catch (error) {
221+
console.error("[invite] Failed to credit inviter:", error);
222+
}
223+
}
224+
try {
225+
cookieStore.delete(INVITE_COOKIE);
226+
cookieStore.delete(REF_COOKIE);
227+
} catch {
228+
// Cookies are best-effort here; the onboarded check above prevents a second credit.
205229
}
206230

207231
// Dispatch welcome email asynchronously via mail.campusloop.space

‎src/app/api/profile/upgrade-campus/confirm/route.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { runInBackground } from "@/lib/background";
77
import { checkCampusUpgradeEligibility } from "@/lib/campus-upgrade";
88
import { sendEmail } from "@/lib/email";
99
import { buildWelcomeEmail } from "@/lib/email-templates";
10+
import { creditInviter } from "@/lib/referrals/credit";
1011
import { invalidateProfileCache } from "@/lib/server-cache";
1112

1213
export const dynamic = "force-dynamic";
@@ -84,6 +85,16 @@ export async function POST(req: Request) {
8485
.where(eq(userProfiles.id, profile.id));
8586
invalidateProfileCache(user.id);
8687

88+
// A student who joined in Campus Preview through an invite link counts for
89+
// their inviter now, the first time they become verified.
90+
if (!profile.isCollegeVerified && profile.referredById && profile.referredById !== profile.id) {
91+
try {
92+
await creditInviter(profile.referredById, profile.id);
93+
} catch (error) {
94+
console.error("[invite] Failed to credit inviter on upgrade:", error);
95+
}
96+
}
97+
8798
// Dispatch welcome / verification email asynchronously via mail.campusloop.space
8899
try {
89100
const { subject, html, text } = buildWelcomeEmail({

‎src/app/join/page.tsx‎

Lines changed: 0 additions & 31 deletions
This file was deleted.

‎src/app/join/route.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { type NextRequest, NextResponse } from "next/server";
2+
import {
3+
buildJoinTarget,
4+
cleanInviteCode,
5+
INVITE_COOKIE,
6+
INVITE_COOKIE_MAX_AGE,
7+
} from "@/lib/referrals/invite";
8+
9+
export const dynamic = "force-dynamic";
10+
11+
/**
12+
* Invite link entry point: `/join?invite=<username>`.
13+
* A route handler, because a cookie cannot be set while rendering a page.
14+
*/
15+
export function GET(request: NextRequest) {
16+
const params = request.nextUrl.searchParams;
17+
const inviter = cleanInviteCode(params.get("invite") ?? params.get("ref"));
18+
19+
const response = NextResponse.redirect(new URL(buildJoinTarget(params), request.url), 307);
20+
if (inviter) {
21+
response.cookies.set(INVITE_COOKIE, inviter, {
22+
path: "/",
23+
maxAge: INVITE_COOKIE_MAX_AGE,
24+
sameSite: "lax",
25+
secure: process.env.NODE_ENV === "production",
26+
});
27+
}
28+
response.headers.set("X-Robots-Tag", "noindex");
29+
return response;
30+
}

‎src/components/landing/landing-features.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
QuestionSticker,
99
Sticker,
1010
} from "@/components/ui/stickers";
11+
import { LP_ACTION_REWARDS } from "@/constants/gamification";
1112
import type { Course } from "@/db/schema";
1213
import { formatDuration } from "@/lib/courses/format";
1314
import type { PublicStats } from "@/lib/public-stats";
@@ -267,7 +268,7 @@ export function LandingFeatures({ courses, stats }: { courses: Course[]; stats:
267268
tilt="rotate-2"
268269
stickerClassName="w-auto self-start"
269270
title="Bring your friends"
270-
text="Invite a friend, get 20 Loop Points when they join."
271+
text={`Invite a friend, get ${LP_ACTION_REWARDS.REFERRAL_SIGNUP} Loop Points when they join.`}
271272
href="/sign-up"
272273
sticker={
273274
<LoopPointsSticker

‎src/lib/referrals/credit.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { eq, sql } from "drizzle-orm";
2+
import { LP_ACTION_REWARDS } from "@/constants/gamification";
3+
import { getDb } from "@/db";
4+
import { userProfiles } from "@/db/schema";
5+
import { awardPoints } from "@/lib/gamification-server";
6+
import { invalidateProfileCache } from "@/lib/server-cache";
7+
8+
/**
9+
* Credits an inviter for one verified student who joined through their link:
10+
* one more invite on their count, and the referral Loop Points.
11+
* The caller decides eligibility (see `canCreditInvite`).
12+
*/
13+
export async function creditInviter(inviterProfileId: string, invitedProfileId?: string) {
14+
const db = getDb();
15+
const [inviter] = await db
16+
.update(userProfiles)
17+
.set({ referralCount: sql`${userProfiles.referralCount} + 1` })
18+
.where(eq(userProfiles.id, inviterProfileId))
19+
.returning({ userId: userProfiles.userId });
20+
21+
// An invite is a rare, deliberate event: it is not subject to the per-action
22+
// cooldown or the daily caps that guard likes and comments.
23+
await awardPoints(inviterProfileId, LP_ACTION_REWARDS.REFERRAL_SIGNUP, "REFERRAL_SIGNUP", {
24+
actorId: invitedProfileId,
25+
referenceId: invitedProfileId,
26+
bypassCaps: true,
27+
});
28+
if (inviter?.userId) invalidateProfileCache(inviter.userId);
29+
}

‎src/lib/referrals/invite.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { NextRequest } from "next/server";
2+
import { describe, expect, it } from "vitest";
3+
import { GET } from "@/app/join/route";
4+
import { buildJoinTarget, canCreditInvite, cleanInviteCode, inviteUrl, pickInviter } from "./invite";
5+
6+
describe("cleanInviteCode", () => {
7+
it("normalises a username", () => {
8+
expect(cleanInviteCode(" @Riya_01 ")).toBe("riya_01");
9+
});
10+
it("rejects anything that cannot be a username", () => {
11+
for (const bad of ["", "ab", "a b c", "../etc", "x".repeat(31), "<script>", null, undefined]) {
12+
expect(cleanInviteCode(bad)).toBeNull();
13+
}
14+
});
15+
});
16+
17+
describe("pickInviter", () => {
18+
it("prefers the invite cookie over the generic ref cookie", () => {
19+
expect(pickInviter("riya", "campaign_x")).toBe("riya");
20+
expect(pickInviter(undefined, "arjun")).toBe("arjun");
21+
expect(pickInviter("!!", undefined)).toBeNull();
22+
});
23+
});
24+
25+
describe("buildJoinTarget", () => {
26+
it("defaults to sign-up and keeps the college hint and UTM tags", () => {
27+
const target = buildJoinTarget(
28+
new URLSearchParams("invite=riya&college=bit-mesra&utm_source=instagram&utm_campaign=reel12&x=1")
29+
);
30+
expect(target).toBe("/sign-up?college=bit-mesra&utm_source=instagram&utm_campaign=reel12");
31+
});
32+
it("honours sign-in mode and a local return path only", () => {
33+
const signIn = buildJoinTarget(new URLSearchParams("mode=signin&returnUrl=/events"));
34+
expect(signIn).toBe("/sign-in?returnTo=%2Fevents");
35+
expect(buildJoinTarget(new URLSearchParams("returnUrl=//evil.example"))).toBe("/sign-up");
36+
expect(buildJoinTarget(new URLSearchParams("returnTo=https://evil.example"))).toBe("/sign-up");
37+
});
38+
});
39+
40+
describe("canCreditInvite", () => {
41+
const base = {
42+
inviterUserId: "u1",
43+
invitedUserId: "u2",
44+
isVerifiedStudent: true,
45+
wasAlreadyOnboarded: false,
46+
};
47+
it("credits a new verified student once", () => {
48+
expect(canCreditInvite(base)).toBe(true);
49+
});
50+
it("never credits a self-invite, a repeat onboarding, or an unverified account", () => {
51+
expect(canCreditInvite({ ...base, inviterUserId: "u2" })).toBe(false);
52+
expect(canCreditInvite({ ...base, wasAlreadyOnboarded: true })).toBe(false);
53+
expect(canCreditInvite({ ...base, isVerifiedStudent: false })).toBe(false);
54+
expect(canCreditInvite({ ...base, inviterUserId: null })).toBe(false);
55+
});
56+
});
57+
58+
describe("inviteUrl", () => {
59+
it("builds the public link", () => {
60+
expect(inviteUrl("Riya")).toBe("https://campusloop.space/join?invite=riya");
61+
});
62+
});
63+
64+
describe("GET /join", () => {
65+
it("sets the invite cookie and redirects to sign-up", () => {
66+
const res = GET(new NextRequest("https://campusloop.space/join?invite=Riya&utm_source=instagram"));
67+
expect(res.status).toBe(307);
68+
expect(res.headers.get("location")).toBe("https://campusloop.space/sign-up?utm_source=instagram");
69+
expect(res.cookies.get("cl_referred_by")?.value).toBe("riya");
70+
});
71+
it("accepts ?ref= and sets no cookie for a bad code", () => {
72+
const viaRef = GET(new NextRequest("https://campusloop.space/join?ref=arjun"));
73+
expect(viaRef.cookies.get("cl_referred_by")?.value).toBe("arjun");
74+
const bad = GET(new NextRequest("https://campusloop.space/join?invite=a%20b"));
75+
expect(bad.cookies.get("cl_referred_by")).toBeUndefined();
76+
expect(bad.headers.get("location")).toBe("https://campusloop.space/sign-up");
77+
});
78+
});

‎src/lib/referrals/invite.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Invite links: `/join?invite=<username>` (also `?ref=<username>`).
3+
*
4+
* Pure helpers shared by the `/join` route handler and onboarding. Kept free of
5+
* database imports so both the edge route and unit tests can use them.
6+
*/
7+
8+
/** Set by `/join`. Holds the inviter's username for 7 days. */
9+
export const INVITE_COOKIE = "cl_referred_by";
10+
/** Set by `/s/[slug]` and the `?ref=` tracker. Used when no invite cookie exists. */
11+
export const REF_COOKIE = "campusloop_ref";
12+
export const INVITE_COOKIE_MAX_AGE = 7 * 24 * 60 * 60;
13+
14+
const USERNAME_PATTERN = /^[a-z0-9_]{3,30}$/;
15+
const PASS_THROUGH_PARAMS = ["college", "domain", "utm_source", "utm_medium", "utm_campaign", "utm_content"];
16+
17+
/** Normalises an invite code to a username, or null when it cannot be one. */
18+
export function cleanInviteCode(raw: string | null | undefined): string | null {
19+
if (!raw || typeof raw !== "string") return null;
20+
const code = raw.trim().toLowerCase().replace(/^@/, "");
21+
return USERNAME_PATTERN.test(code) ? code : null;
22+
}
23+
24+
/** The inviter to credit: the explicit invite wins over a generic `?ref=` click. */
25+
export function pickInviter(inviteCookie?: string | null, refCookie?: string | null): string | null {
26+
return cleanInviteCode(inviteCookie) ?? cleanInviteCode(refCookie);
27+
}
28+
29+
/** Where `/join` sends the visitor, keeping the college hint, return path and UTM tags. */
30+
export function buildJoinTarget(params: URLSearchParams): string {
31+
const base = params.get("mode") === "signin" ? "/sign-in" : "/sign-up";
32+
const out = new URLSearchParams();
33+
const returnTo = params.get("returnTo") || params.get("returnUrl");
34+
if (returnTo?.startsWith("/") && !returnTo.startsWith("//")) out.set("returnTo", returnTo);
35+
for (const key of PASS_THROUGH_PARAMS) {
36+
const value = params.get(key);
37+
if (value) out.set(key, value.slice(0, 120));
38+
}
39+
const query = out.toString();
40+
return query ? `${base}?${query}` : base;
41+
}
42+
43+
/**
44+
* An invite is credited once, when the invited student first becomes a verified
45+
* student of a college, and never to the student's own account.
46+
*/
47+
export function canCreditInvite(input: {
48+
inviterUserId: string | null | undefined;
49+
invitedUserId: string;
50+
isVerifiedStudent: boolean;
51+
wasAlreadyOnboarded: boolean;
52+
}): boolean {
53+
if (!input.inviterUserId) return false;
54+
if (input.inviterUserId === input.invitedUserId) return false;
55+
if (input.wasAlreadyOnboarded) return false;
56+
return input.isVerifiedStudent;
57+
}
58+
59+
/** The public invite link for a username. */
60+
export function inviteUrl(username: string, origin = "https://campusloop.space"): string {
61+
return `${origin}/join?invite=${encodeURIComponent(username.toLowerCase())}`;
62+
}

0 commit comments

Comments
 (0)