Skip to content

Commit d63adf9

Browse files
playlikeboyclaude
andcommitted
feat(invites): personal invite link, QR and top inviters board
Every student now has an invite card (Points tab and /invites) with their link, copy, WhatsApp, native share and QR. /invites ranks the students who brought the most verified friends, for the viewer's college or for all colleges. Adds the Invite friends menu entry, a rate limit for the new API and the matching guide text. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 6de82ac commit d63adf9

10 files changed

Lines changed: 415 additions & 4 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { InviteLeaderboard } from "@/components/invite/invite-leaderboard";
2+
import { privateMetadata } from "@/lib/seo";
3+
4+
export const metadata = privateMetadata("Invite friends");
5+
6+
export default function InvitesPage() {
7+
return <InviteLeaderboard />;
8+
}

‎src/app/(app)/(main)/profile/tabs/points-tab.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"use client";
22

3+
import { InviteCard } from "@/components/invite/invite-card";
34
import { ProfileStreakCard } from "@/components/streaks/profile-streak-card";
45
import { LoopPointsSticker } from "@/components/ui/stickers";
56
import { LP_ACTION_REWARDS } from "@/constants/gamification";
@@ -67,6 +68,8 @@ export function PointsTab({ profileId, points, isOwnProfile }: PointsTabProps) {
6768

6869
<ProfileStreakCard profileId={profileId} />
6970

71+
{isOwnProfile && <InviteCard />}
72+
7073
{isOwnProfile && (
7174
<section className="space-y-2" aria-labelledby="earn-title">
7275
<h2 id="earn-title" className="text-lg text-fg">
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { eq } from "drizzle-orm";
2+
import { NextResponse } from "next/server";
3+
import { getDb } from "@/db";
4+
import { userProfiles } from "@/db/schema";
5+
import { clampLeaderboardLimit, getInviteLeaderboard } from "@/lib/referrals/leaderboard";
6+
import { getCachedAuthUser } from "@/lib/server-cache";
7+
8+
export const dynamic = "force-dynamic";
9+
10+
/** GET /api/invites/leaderboard?scope=campus|all&limit=25 */
11+
export async function GET(request: Request) {
12+
try {
13+
const user = await getCachedAuthUser();
14+
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
15+
16+
const { searchParams } = new URL(request.url);
17+
const scope = searchParams.get("scope") === "all" ? "all" : "campus";
18+
const limit = clampLeaderboardLimit(searchParams.get("limit"));
19+
20+
const profile = await getDb().query.userProfiles.findFirst({
21+
where: eq(userProfiles.userId, user.id),
22+
columns: { id: true, username: true, institutionId: true, referralCount: true },
23+
});
24+
if (!profile) return NextResponse.json({ error: "Profile not found" }, { status: 404 });
25+
26+
const leaders = await getInviteLeaderboard({
27+
institutionId: scope === "campus" ? profile.institutionId : null,
28+
limit,
29+
});
30+
31+
return NextResponse.json({
32+
scope,
33+
leaders,
34+
me: { username: profile.username, invites: profile.referralCount },
35+
});
36+
} catch (error) {
37+
console.error("GET /api/invites/leaderboard error:", error);
38+
return NextResponse.json({ error: "Could not load the leaderboard." }, { status: 500 });
39+
}
40+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
"use client";
2+
3+
import { Check, Copy, MessageCircle, QrCode, Share2, Trophy } from "lucide-react";
4+
import Link from "next/link";
5+
import { useState } from "react";
6+
import { toast } from "sonner";
7+
import { BrandedQrModal } from "@/components/common/branded-qr-modal";
8+
import { Button } from "@/components/ui/button";
9+
import { LP_ACTION_REWARDS } from "@/constants/gamification";
10+
import { useProfile } from "@/hooks/use-profile";
11+
import { trackShare } from "@/lib/analytics/ga4";
12+
import { inviteUrl } from "@/lib/referrals/invite";
13+
import { cn } from "@/lib/utils";
14+
15+
const REWARD = LP_ACTION_REWARDS.REFERRAL_SIGNUP;
16+
17+
/** The signed-in student's personal invite link, with one-tap ways to send it. */
18+
export function InviteCard({ className }: { className?: string }) {
19+
const { profile } = useProfile();
20+
const [copied, setCopied] = useState(false);
21+
const [qrOpen, setQrOpen] = useState(false);
22+
23+
if (!profile?.username) return null;
24+
25+
const link = inviteUrl(profile.username);
26+
const invites = profile.referralCount ?? 0;
27+
const message = `Join me on CampusLoop, the app only for students of our college. ${link}`;
28+
29+
async function copy() {
30+
try {
31+
await navigator.clipboard.writeText(link);
32+
setCopied(true);
33+
toast.success("Invite link copied");
34+
trackShare("copy_link", "invite", profile?.username);
35+
setTimeout(() => setCopied(false), 2000);
36+
} catch {
37+
toast.error("Could not copy. Press and hold the link to copy it.");
38+
}
39+
}
40+
41+
async function share() {
42+
if (typeof navigator.share !== "function") return copy();
43+
try {
44+
await navigator.share({ title: "CampusLoop", text: message, url: link });
45+
trackShare("native", "invite", profile?.username);
46+
} catch {
47+
// The student closed the share sheet.
48+
}
49+
}
50+
51+
return (
52+
<section
53+
className={cn("space-y-3 rounded-lg border border-border bg-surface p-4", className)}
54+
aria-labelledby="invite-title"
55+
>
56+
<div className="flex items-start justify-between gap-3">
57+
<div className="space-y-1">
58+
<h2 id="invite-title" className="text-lg text-fg">
59+
Invite your friends
60+
</h2>
61+
<p className="text-sm text-fg-muted">
62+
You get <span className="font-semibold text-reward-text">+{REWARD} LP</span> for every friend who
63+
joins with their college email.
64+
</p>
65+
</div>
66+
<p className="shrink-0 text-right">
67+
<span className="block text-2xl font-bold tabular-nums text-fg">{invites}</span>
68+
<span className="text-xs text-fg-muted">{invites === 1 ? "friend joined" : "friends joined"}</span>
69+
</p>
70+
</div>
71+
72+
<button
73+
type="button"
74+
onClick={copy}
75+
className={cn(
76+
"flex w-full items-center justify-between gap-3 rounded-md border border-border",
77+
"bg-surface-muted px-3 py-2.5 text-left"
78+
)}
79+
aria-label="Copy your invite link"
80+
>
81+
<span className="min-w-0 truncate text-sm font-medium text-fg">{link.replace("https://", "")}</span>
82+
{copied ? (
83+
<Check className="size-4 shrink-0 text-success" aria-hidden />
84+
) : (
85+
<Copy className="size-4 shrink-0 text-fg-muted" aria-hidden />
86+
)}
87+
</button>
88+
89+
<div className="grid grid-cols-2 gap-2 sm:grid-cols-4">
90+
<Button asChild variant="success" size="sm">
91+
<a
92+
href={`https://wa.me/?text=${encodeURIComponent(message)}`}
93+
target="_blank"
94+
rel="noopener noreferrer"
95+
onClick={() => trackShare("whatsapp", "invite", profile.username)}
96+
>
97+
<MessageCircle aria-hidden /> WhatsApp
98+
</a>
99+
</Button>
100+
<Button variant="secondary" size="sm" onClick={share}>
101+
<Share2 aria-hidden /> Share
102+
</Button>
103+
<Button variant="secondary" size="sm" onClick={() => setQrOpen(true)}>
104+
<QrCode aria-hidden /> QR code
105+
</Button>
106+
<Button asChild variant="outline" size="sm">
107+
<Link href="/invites">
108+
<Trophy aria-hidden /> Top inviters
109+
</Link>
110+
</Button>
111+
</div>
112+
113+
<BrandedQrModal
114+
isOpen={qrOpen}
115+
onClose={() => setQrOpen(false)}
116+
title={`Join ${profile.displayName} on CampusLoop`}
117+
subtitle={profile.institution?.name ?? "Your campus. Only your campus."}
118+
shortUrl={link}
119+
category="profile"
120+
avatarUrl={profile.avatarUrl}
121+
/>
122+
</section>
123+
);
124+
}
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
"use client";
2+
3+
import { Trophy } from "lucide-react";
4+
import Link from "next/link";
5+
import { useState } from "react";
6+
import useSWR from "swr";
7+
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
8+
import { EmptyState } from "@/components/ui/empty-state";
9+
import { SegmentedControl } from "@/components/ui/segmented-control";
10+
import { Skeleton } from "@/components/ui/skeleton";
11+
import { fetcher } from "@/lib/api";
12+
import type { InviteLeader } from "@/lib/referrals/leaderboard";
13+
import { cn } from "@/lib/utils";
14+
import { InviteCard } from "./invite-card";
15+
16+
type Scope = "campus" | "all";
17+
18+
interface LeaderboardResponse {
19+
scope: Scope;
20+
leaders: InviteLeader[];
21+
me: { username: string; invites: number };
22+
}
23+
24+
const SCOPES: { value: Scope; label: string }[] = [
25+
{ value: "campus", label: "My college" },
26+
{ value: "all", label: "All colleges" },
27+
];
28+
29+
export function InviteLeaderboard() {
30+
const [scope, setScope] = useState<Scope>("campus");
31+
const { data, isLoading, error } = useSWR<LeaderboardResponse>(
32+
`/api/invites/leaderboard?scope=${scope}`,
33+
fetcher,
34+
{ keepPreviousData: true, dedupingInterval: 30_000 }
35+
);
36+
37+
return (
38+
<div className="mx-auto w-full max-w-2xl space-y-6 p-4">
39+
<header className="space-y-1">
40+
<h1 className="text-2xl text-fg">Top inviters</h1>
41+
<p className="text-sm text-fg-muted">
42+
Students who brought the most friends. An invite counts when your friend joins with a college email.
43+
</p>
44+
</header>
45+
46+
<InviteCard />
47+
48+
<SegmentedControl
49+
options={SCOPES}
50+
value={scope}
51+
onChange={setScope}
52+
fullWidth
53+
aria-label="Leaderboard"
54+
/>
55+
56+
{isLoading && !data ? (
57+
<div className="space-y-2">
58+
{Array.from({ length: 5 }, (_, i) => `row-${i}`).map((key) => (
59+
<Skeleton key={key} className="h-14 w-full rounded-lg" />
60+
))}
61+
</div>
62+
) : error ? (
63+
<EmptyState
64+
icon={Trophy}
65+
title="Could not load the leaderboard"
66+
description="Try again in a minute."
67+
/>
68+
) : !data?.leaders.length ? (
69+
<EmptyState
70+
icon={Trophy}
71+
title="Nobody is on the board yet"
72+
description="Send your link to one friend and you take first place."
73+
/>
74+
) : (
75+
<ol className="divide-y divide-border rounded-lg border border-border bg-surface">
76+
{data.leaders.map((leader) => (
77+
<LeaderRow key={leader.username} leader={leader} isMe={leader.username === data.me.username} />
78+
))}
79+
</ol>
80+
)}
81+
</div>
82+
);
83+
}
84+
85+
function LeaderRow({ leader, isMe }: { leader: InviteLeader; isMe: boolean }) {
86+
return (
87+
<li className={cn("flex items-center gap-3 px-4 py-3", isMe && "bg-brand-subtle")}>
88+
<span
89+
className={cn(
90+
"w-7 shrink-0 text-center text-sm font-bold tabular-nums",
91+
leader.rank <= 3 ? "text-reward-text" : "text-fg-muted"
92+
)}
93+
>
94+
{leader.rank}
95+
</span>
96+
<Avatar size="sm">
97+
{leader.avatarUrl ? <AvatarImage src={leader.avatarUrl} alt="" /> : null}
98+
<AvatarFallback>{leader.displayName.slice(0, 1).toUpperCase()}</AvatarFallback>
99+
</Avatar>
100+
<Link href={`/${leader.username}`} className="min-w-0 flex-1">
101+
<span className="block truncate text-sm font-semibold text-fg">
102+
{leader.displayName}
103+
{isMe ? " (you)" : ""}
104+
</span>
105+
<span className="block truncate text-xs text-fg-muted">
106+
{leader.college ?? `@${leader.username}`}
107+
</span>
108+
</Link>
109+
<span className="shrink-0 text-sm font-semibold tabular-nums text-fg">
110+
{leader.invites}
111+
<span className="ml-1 font-normal text-fg-muted">{leader.invites === 1 ? "invite" : "invites"}</span>
112+
</span>
113+
</li>
114+
);
115+
}

‎src/constants/navigation.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
Terminal,
3737
TrendingUp,
3838
User,
39+
UserPlus,
3940
Users,
4041
Zap,
4142
} from "lucide-react";
@@ -99,6 +100,7 @@ export const ROUTES = {
99100
articles: "/articles",
100101
developer: "/developer",
101102
streaks: "/streaks",
103+
invites: "/invites",
102104
saved: "/saved",
103105
settings: "/settings",
104106
safety: "/safety",
@@ -160,6 +162,7 @@ export const NAV_GROUPS: NavGroup[] = [
160162
{ icon: Bell, href: ROUTES.notifications, label: "Notifications", desc: "Replies, likes and mentions" },
161163
{ icon: Bookmark, href: ROUTES.saved, label: "Saved", desc: "Posts you saved" },
162164
{ icon: Flame, href: ROUTES.streaks, label: "Streaks", desc: "Your daily streak and Loop Points" },
165+
{ icon: UserPlus, href: ROUTES.invites, label: "Invite friends", desc: "Your link and top inviters" },
163166
{
164167
icon: Lock,
165168
href: ROUTES.crush,
@@ -254,6 +257,7 @@ export const MOBILE_BOTTOM_ITEMS: NavItem[] = [
254257
ROUTES.notifications,
255258
ROUTES.saved,
256259
ROUTES.streaks,
260+
ROUTES.invites,
257261
ROUTES.crush,
258262
ROUTES.settings,
259263
ROUTES.board,

‎src/lib/guide/entries/account-and-platform.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,19 +39,27 @@ export const ACCOUNT_AND_PLATFORM: GuideEntry[] = [
3939
summary: "Invite classmates with your link and earn Loop Points when they join.",
4040
category: "Account & safety",
4141
audiences: ["Students", "Investors"],
42-
routes: [{ path: "/join", label: "Join via invite" }],
42+
routes: [
43+
{ path: "/invites", label: "Your invite link and top inviters" },
44+
{ path: "/join", label: "Join via invite" },
45+
],
4346
purpose: "Campus networks grow person to person. Referrals reward students who bring their friends.",
4447
whyUse: ["Your friends make your feed better.", "Earn LP for every verified signup."],
4548
howToUse: [
46-
"Copy your invite link from the menu or the referral card in the feed.",
47-
"Share it in your class group.",
48-
"Earn LP when friends verify.",
49+
"Open Invite friends from the More menu, or the Points tab on your profile.",
50+
"Copy your link, send it on WhatsApp, or show the QR code.",
51+
"You earn 50 LP when a friend joins with a verified college email.",
52+
"See who invited the most students in your college under Top inviters.",
4953
],
5054
useCases: [{ who: "Class rep", scenario: "Invites the whole section in the first week." }],
5155
investorAngle:
5256
"Referral loops drive low-cost acquisition and campus-by-campus density, the key to network effects.",
5357
faq: [
5458
{ q: "Do invites work for other colleges?", a: "Yes, friends verify with their own college email." },
59+
{
60+
q: "My friend joined with a personal email. Do I get points?",
61+
a: "Yes, once they verify a college email. Until then they are in Campus Preview and do not count.",
62+
},
5563
],
5664
related: ["loop-points-and-streaks", "getting-started"],
5765
keywords: ["invite friends", "referral"],

‎src/lib/rate-limits.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ export const RATE_LIMITS: RateRule[] = [
4747
{ prefix: "/api/college-index-requests", methods: "WRITE", max: 5, windowSec: 600, store: "redis" },
4848
{ prefix: "/api/mcp", methods: "ALL", max: 120, windowSec: 60, store: "redis" },
4949
{ prefix: "/api/search", methods: "READ", max: 120, windowSec: 60, store: "memory" },
50+
{ prefix: "/api/invites", methods: "READ", max: 60, windowSec: 60, store: "memory" },
5051
{ prefix: "/api/gifs", methods: "READ", max: 60, windowSec: 60, store: "memory" },
5152
{ prefix: "/api/unsplash", methods: "READ", max: 60, windowSec: 60, store: "memory" },
5253

0 commit comments

Comments
 (0)