feat: integrate Stripe for page purchases and reconciliation tasks

This commit is contained in:
DESKTOP-RTLN3BA\$punk 2026-03-31 18:39:45 -07:00
parent 17642493eb
commit a9fd45844d
31 changed files with 1948 additions and 166 deletions

View file

@ -0,0 +1,19 @@
"use client";
import { motion } from "motion/react";
import { BuyPagesContent } from "@/components/settings/buy-pages-content";
export default function BuyPagesPage() {
return (
<div className="flex min-h-[calc(100vh-64px)] select-none items-center justify-center px-4 py-8">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.3 }}
className="w-full max-w-md space-y-6"
>
<BuyPagesContent />
</motion.div>
</div>
);
}

View file

@ -0,0 +1,35 @@
"use client";
import { CircleSlash2 } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
export default function PurchaseCancelPage() {
const params = useParams();
const searchSpaceId = String(params.search_space_id ?? "");
return (
<div className="flex min-h-[calc(100vh-64px)] items-center justify-center px-4 py-8">
<Card className="w-full max-w-lg">
<CardHeader className="text-center">
<CircleSlash2 className="mx-auto h-10 w-10 text-muted-foreground" />
<CardTitle className="text-2xl">Checkout canceled</CardTitle>
<CardDescription>No charge was made and your current pages are unchanged.</CardDescription>
</CardHeader>
<CardContent className="text-center text-sm text-muted-foreground">
You can return to the pricing options and try again whenever you&apos;re ready.
</CardContent>
<CardFooter className="flex flex-col gap-2 sm:flex-row">
<Button asChild className="w-full">
<Link href={`/dashboard/${searchSpaceId}/more-pages`}>Back to Buy Pages</Link>
</Button>
<Button asChild variant="outline" className="w-full">
<Link href={`/dashboard/${searchSpaceId}/new-chat`}>Back to Dashboard</Link>
</Button>
</CardFooter>
</Card>
</div>
);
}

View file

@ -0,0 +1,47 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
import { CheckCircle2 } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect } from "react";
import { USER_QUERY_KEY } from "@/atoms/user/user-query.atoms";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
export default function PurchaseSuccessPage() {
const params = useParams();
const queryClient = useQueryClient();
const searchSpaceId = String(params.search_space_id ?? "");
useEffect(() => {
void queryClient.invalidateQueries({ queryKey: USER_QUERY_KEY });
}, [queryClient]);
return (
<div className="flex min-h-[calc(100vh-64px)] items-center justify-center px-4 py-8">
<Card className="w-full max-w-lg">
<CardHeader className="text-center">
<CheckCircle2 className="mx-auto h-10 w-10 text-emerald-500" />
<CardTitle className="text-2xl">Purchase complete</CardTitle>
<CardDescription>
Your additional pages are being applied to your account now.
</CardDescription>
</CardHeader>
<CardContent className="space-y-3 text-center">
<p className="text-sm text-muted-foreground">
Your sidebar usage meter should refresh automatically in a moment.
</p>
</CardContent>
<CardFooter className="flex flex-col gap-2">
<Button asChild className="w-full">
<Link href={`/dashboard/${searchSpaceId}/new-chat`}>Back to Dashboard</Link>
</Button>
<Button asChild variant="outline" className="w-full">
<Link href={`/dashboard/${searchSpaceId}/more-pages`}>Buy More Pages</Link>
</Button>
</CardFooter>
</Card>
</div>
);
}

View file

@ -0,0 +1,110 @@
"use client";
import { useQuery } from "@tanstack/react-query";
import { Receipt } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Spinner } from "@/components/ui/spinner";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import type { PagePurchase, PagePurchaseStatus } from "@/contracts/types/stripe.types";
import { stripeApiService } from "@/lib/apis/stripe-api.service";
import { cn } from "@/lib/utils";
const STATUS_STYLES: Record<PagePurchaseStatus, { label: string; className: string }> = {
completed: { label: "Completed", className: "bg-emerald-600 text-white border-transparent hover:bg-emerald-600" },
pending: { label: "Pending", className: "bg-yellow-600 text-white border-transparent hover:bg-yellow-600" },
failed: { label: "Failed", className: "bg-destructive text-white border-transparent hover:bg-destructive" },
};
function formatDate(iso: string): string {
return new Date(iso).toLocaleDateString(undefined, {
year: "numeric",
month: "short",
day: "numeric",
});
}
function formatAmount(purchase: PagePurchase): string {
if (purchase.amount_total == null) return "—";
const dollars = purchase.amount_total / 100;
const currency = (purchase.currency ?? "usd").toUpperCase();
return `$${dollars.toFixed(2)} ${currency}`;
}
export function PurchaseHistoryContent() {
const { data, isLoading } = useQuery({
queryKey: ["stripe-purchases"],
queryFn: () => stripeApiService.getPurchases(),
});
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Spinner size="md" className="text-muted-foreground" />
</div>
);
}
const purchases = data?.purchases ?? [];
if (purchases.length === 0) {
return (
<div className="flex flex-col items-center justify-center gap-2 py-16 text-center">
<Receipt className="h-8 w-8 text-muted-foreground" />
<p className="text-sm font-medium">No purchases yet</p>
<p className="text-xs text-muted-foreground">
Your page-pack purchases will appear here after checkout.
</p>
</div>
);
}
return (
<div className="space-y-4">
<div className="rounded-lg border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Date</TableHead>
<TableHead className="text-right">Pages</TableHead>
<TableHead className="text-right">Amount</TableHead>
<TableHead className="text-center">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{purchases.map((p) => {
const style = STATUS_STYLES[p.status];
return (
<TableRow key={p.id}>
<TableCell className="text-sm">
{formatDate(p.created_at)}
</TableCell>
<TableCell className="text-right tabular-nums text-sm">
{p.pages_granted.toLocaleString()}
</TableCell>
<TableCell className="text-right tabular-nums text-sm">
{formatAmount(p)}
</TableCell>
<TableCell className="text-center">
<Badge className={cn("text-[10px]", style.className)}>
{style.label}
</Badge>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<p className="text-center text-xs text-muted-foreground">
Showing your {purchases.length} most recent purchase{purchases.length !== 1 ? "s" : ""}.
</p>
</div>
);
}

View file

@ -1,8 +1,10 @@
"use client";
import { useEffect, useState } from "react";
import { USER_QUERY_KEY } from "@/atoms/user/user-query.atoms";
import { useGlobalLoadingEffect } from "@/hooks/use-global-loading";
import { getBearerToken, redirectToLogin } from "@/lib/auth-utils";
import { queryClient } from "@/lib/query-client/client";
interface DashboardLayoutProps {
children: React.ReactNode;
@ -22,6 +24,7 @@ export default function DashboardLayout({ children }: DashboardLayoutProps) {
redirectToLogin();
return;
}
queryClient.invalidateQueries({ queryKey: [...USER_QUERY_KEY] });
setIsCheckingAuth(false);
}, []);

View file

@ -1,16 +1,15 @@
import { atomWithQuery } from "jotai-tanstack-query";
import { userApiService } from "@/lib/apis/user-api.service";
import { getBearerToken, isPublicRoute } from "@/lib/auth-utils";
import { getBearerToken } from "@/lib/auth-utils";
export const USER_QUERY_KEY = ["user", "me"] as const;
const userQueryFn = () => userApiService.getMe();
export const currentUserAtom = atomWithQuery(() => {
const pathname = typeof window !== "undefined" ? window.location.pathname : null;
return {
queryKey: USER_QUERY_KEY,
staleTime: 5 * 60 * 1000,
enabled: !!getBearerToken() && pathname !== null && !isPublicRoute(pathname),
enabled: !!getBearerToken(),
queryFn: userQueryFn,
};
});

View file

@ -15,7 +15,6 @@ import { rightPanelCollapsedAtom } from "@/atoms/layout/right-panel.atom";
import { deleteSearchSpaceMutationAtom } from "@/atoms/search-spaces/search-space-mutation.atoms";
import { searchSpacesAtom } from "@/atoms/search-spaces/search-space-query.atoms";
import {
morePagesDialogAtom,
searchSpaceSettingsDialogAtom,
teamDialogAtom,
userSettingsDialogAtom,
@ -27,7 +26,6 @@ import {
type Tab,
} from "@/atoms/tabs/tabs.atom";
import { currentUserAtom } from "@/atoms/user/user-query.atoms";
import { MorePagesDialog } from "@/components/settings/more-pages-dialog";
import { SearchSpaceSettingsDialog } from "@/components/settings/search-space-settings-dialog";
import { TeamDialog } from "@/components/settings/team-dialog";
import { UserSettingsDialog } from "@/components/settings/user-settings-dialog";
@ -203,8 +201,6 @@ export function LayoutDataProvider({ searchSpaceId, children }: LayoutDataProvid
const seenPageLimitNotifications = useRef<Set<number>>(new Set());
const isInitialLoad = useRef(true);
const setMorePagesOpen = useSetAtom(morePagesDialogAtom);
// Effect to show toast for new page_limit_exceeded notifications
useEffect(() => {
if (statusInbox.loading) return;
@ -233,12 +229,12 @@ export function LayoutDataProvider({ searchSpaceId, children }: LayoutDataProvid
duration: 8000,
icon: <AlertTriangle className="h-5 w-5 text-amber-500" />,
action: {
label: "View Plans",
onClick: () => setMorePagesOpen(true),
label: "Get More Pages",
onClick: () => router.push(`/dashboard/${searchSpaceId}/more-pages`),
},
});
}
}, [statusInbox.inboxItems, statusInbox.loading, searchSpaceId, setMorePagesOpen]);
}, [statusInbox.inboxItems, statusInbox.loading, searchSpaceId, router]);
// Delete dialogs state
const [showDeleteChatDialog, setShowDeleteChatDialog] = useState(false);
@ -923,7 +919,6 @@ export function LayoutDataProvider({ searchSpaceId, children }: LayoutDataProvid
<SearchSpaceSettingsDialog searchSpaceId={Number(searchSpaceId)} />
<UserSettingsDialog />
<TeamDialog searchSpaceId={Number(searchSpaceId)} />
<MorePagesDialog />
</>
);
}

View file

@ -1,10 +1,12 @@
"use client";
import { useSetAtom } from "jotai";
import { Zap } from "lucide-react";
import { morePagesDialogAtom } from "@/atoms/settings/settings-dialog.atoms";
import { useQuery } from "@tanstack/react-query";
import { CreditCard, Zap } from "lucide-react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { stripeApiService } from "@/lib/apis/stripe-api.service";
interface PageUsageDisplayProps {
pagesUsed: number;
@ -12,12 +14,18 @@ interface PageUsageDisplayProps {
}
export function PageUsageDisplay({ pagesUsed, pagesLimit }: PageUsageDisplayProps) {
const setMorePagesOpen = useSetAtom(morePagesDialogAtom);
const params = useParams();
const searchSpaceId = params?.search_space_id ?? "";
const usagePercentage = (pagesUsed / pagesLimit) * 100;
const { data: stripeStatus } = useQuery({
queryKey: ["stripe-status"],
queryFn: () => stripeApiService.getStatus(),
});
const pageBuyingEnabled = stripeStatus?.page_buying_enabled ?? true;
return (
<div className="px-3 py-3 border-t">
<div className="space-y-2">
<div className="space-y-1.5">
<div className="flex justify-between items-center text-xs">
<span className="text-muted-foreground">
{pagesUsed.toLocaleString()} / {pagesLimit.toLocaleString()} pages
@ -25,19 +33,32 @@ export function PageUsageDisplay({ pagesUsed, pagesLimit }: PageUsageDisplayProp
<span className="font-medium">{usagePercentage.toFixed(0)}%</span>
</div>
<Progress value={usagePercentage} className="h-1.5" />
<button
type="button"
onClick={() => setMorePagesOpen(true)}
<Link
href={`/dashboard/${searchSpaceId}/more-pages`}
className="group flex w-full items-center justify-between rounded-md px-1.5 py-1 -mx-1.5 transition-colors hover:bg-accent"
>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground group-hover:text-accent-foreground">
<Zap className="h-3 w-3 shrink-0" />
Upgrade to PRO
Get Free Pages
</span>
<Badge className="h-4 rounded px-1 text-[10px] font-semibold leading-none bg-emerald-600 text-white border-transparent hover:bg-emerald-600">
FREE
</Badge>
</button>
</Link>
{pageBuyingEnabled && (
<Link
href={`/dashboard/${searchSpaceId}/buy-pages`}
className="group flex w-full items-center justify-between rounded-md px-1.5 py-1 -mx-1.5 transition-colors hover:bg-accent"
>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground group-hover:text-accent-foreground">
<CreditCard className="h-3 w-3 shrink-0" />
Buy Pages
</span>
<span className="text-[10px] font-medium text-muted-foreground">
$1/1k
</span>
</Link>
)}
</div>
</div>
);

View file

@ -8,11 +8,12 @@ const demoPlans = [
price: "0",
yearlyPrice: "0",
period: "",
billingText: "",
billingText: "1,000 pages included",
features: [
"Self Hostable",
"Upload and chat with 300+ pages of content",
"Includes access to ChatGPT text and audio models",
"1,000 pages included to start",
"Earn up to 6,000+ bonus pages for free",
"Includes access to OpenAI text, audio and image models",
"Realtime Collaborative Group Chats with teammates",
"Community support on Discord",
],
@ -22,21 +23,20 @@ const demoPlans = [
isPopular: false,
},
{
name: "PRO",
price: "0",
yearlyPrice: "0",
period: "",
billingText: "Free during beta",
name: "PAY AS YOU GO",
price: "1",
yearlyPrice: "1",
period: "1,000 pages",
billingText: "No subscription, buy only when you need more",
features: [
"Everything in Free",
"Includes 6000+ pages of content",
"Access to more models and providers",
"Buy 1,000-page packs at $1 each",
"Priority support on Discord",
],
description: "",
buttonText: "Get Started",
href: "/login",
isPopular: true,
isPopular: false,
},
{
name: "ENTERPRISE",
@ -45,7 +45,7 @@ const demoPlans = [
period: "",
billingText: "",
features: [
"Everything in Pro",
"Everything in Pay As You Go",
"On-prem or VPC deployment",
"Audit logs and compliance",
"SSO, OIDC & SAML",
@ -63,7 +63,11 @@ const demoPlans = [
function PricingBasic() {
return (
<Pricing plans={demoPlans} title="SurfSense Pricing" description="Choose what works for you" />
<Pricing
plans={demoPlans}
title="SurfSense Pricing"
description="Start free with 1,000 pages. Earn up to 6,000+ more or buy as you go."
/>
);
}

View file

@ -14,7 +14,7 @@ import { schema } from "@/zero/schema";
const cacheURL = process.env.NEXT_PUBLIC_ZERO_CACHE_URL || "http://localhost:4848";
function ZeroAuthGuard({ children }: { children: React.ReactNode }) {
function ZeroAuthSync() {
const zero = useZero();
const connectionState = useConnectionState();
const isRefreshingRef = useRef(false);
@ -37,7 +37,7 @@ function ZeroAuthGuard({ children }: { children: React.ReactNode }) {
});
}, [connectionState, zero]);
return <>{children}</>;
return null;
}
export function ZeroProvider({ children }: { children: React.ReactNode }) {
@ -59,7 +59,8 @@ export function ZeroProvider({ children }: { children: React.ReactNode }) {
return (
<ZeroReactProvider {...opts}>
{hasUser ? <ZeroAuthGuard>{children}</ZeroAuthGuard> : children}
{hasUser && <ZeroAuthSync />}
{children}
</ZeroReactProvider>
);
}

View file

@ -0,0 +1,145 @@
"use client";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Minus, Plus } from "lucide-react";
import { useParams } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { stripeApiService } from "@/lib/apis/stripe-api.service";
import { AppError } from "@/lib/error";
import { cn } from "@/lib/utils";
const PAGE_PACK_SIZE = 1000;
const PRICE_PER_PACK_USD = 1;
const PRESET_MULTIPLIERS = [1, 2, 5, 10, 25, 50] as const;
export function BuyPagesContent() {
const params = useParams();
const [quantity, setQuantity] = useState(1);
const { data: stripeStatus } = useQuery({
queryKey: ["stripe-status"],
queryFn: () => stripeApiService.getStatus(),
});
const purchaseMutation = useMutation({
mutationFn: stripeApiService.createCheckoutSession,
onSuccess: (response) => {
window.location.assign(response.checkout_url);
},
onError: (error) => {
if (error instanceof AppError && error.message) {
toast.error(error.message);
return;
}
toast.error("Failed to start checkout. Please try again.");
},
});
const searchSpaceId = Number(params.search_space_id);
const hasValidSearchSpace = Number.isFinite(searchSpaceId) && searchSpaceId > 0;
const totalPages = quantity * PAGE_PACK_SIZE;
const totalPrice = quantity * PRICE_PER_PACK_USD;
if (stripeStatus && !stripeStatus.page_buying_enabled) {
return (
<div className="w-full space-y-3 text-center">
<h2 className="text-xl font-bold tracking-tight">Buy Pages</h2>
<p className="text-sm text-muted-foreground">
Page purchases are temporarily unavailable.
</p>
</div>
);
}
const handleBuyNow = () => {
if (!hasValidSearchSpace) {
toast.error("Unable to determine the current workspace for checkout.");
return;
}
purchaseMutation.mutate({
quantity,
search_space_id: searchSpaceId,
});
};
return (
<div className="w-full space-y-5">
<div className="text-center">
<h2 className="text-xl font-bold tracking-tight">Buy Pages</h2>
<p className="mt-1 text-sm text-muted-foreground">
$1 per 1,000 pages, pay as you go
</p>
</div>
<div className="space-y-3">
{/* Stepper */}
<div className="flex items-center justify-center gap-3">
<button
type="button"
onClick={() => setQuantity((q) => Math.max(1, q - 1))}
disabled={quantity <= 1 || purchaseMutation.isPending}
className="flex h-8 w-8 items-center justify-center rounded-md border transition-colors hover:bg-muted disabled:opacity-40"
>
<Minus className="h-3.5 w-3.5" />
</button>
<span className="min-w-28 text-center text-lg font-semibold tabular-nums">
{totalPages.toLocaleString()}
</span>
<button
type="button"
onClick={() => setQuantity((q) => Math.min(100, q + 1))}
disabled={quantity >= 100 || purchaseMutation.isPending}
className="flex h-8 w-8 items-center justify-center rounded-md border transition-colors hover:bg-muted disabled:opacity-40"
>
<Plus className="h-3.5 w-3.5" />
</button>
</div>
{/* Quick-pick presets */}
<div className="flex flex-wrap justify-center gap-1.5">
{PRESET_MULTIPLIERS.map((m) => (
<button
key={m}
type="button"
onClick={() => setQuantity(m)}
disabled={purchaseMutation.isPending}
className={cn(
"rounded-md border px-2.5 py-1 text-xs font-medium tabular-nums transition-colors disabled:opacity-60",
quantity === m
? "border-emerald-500 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
: "border-border hover:border-emerald-500/40 hover:bg-muted/40"
)}
>
{(m * PAGE_PACK_SIZE).toLocaleString()}
</button>
))}
</div>
<div className="flex items-center justify-between rounded-lg border bg-muted/30 px-3 py-2">
<span className="text-sm font-medium tabular-nums">{totalPages.toLocaleString()} pages</span>
<span className="text-sm font-semibold tabular-nums">${totalPrice}</span>
</div>
<Button
className="w-full bg-emerald-600 text-white hover:bg-emerald-700"
disabled={purchaseMutation.isPending || !hasValidSearchSpace}
onClick={handleBuyNow}
>
{purchaseMutation.isPending ? (
<>
<Spinner size="xs" />
Redirecting
</>
) : (
<>Buy {totalPages.toLocaleString()} Pages for ${totalPrice}</>
)}
</Button>
<p className="text-center text-[11px] text-muted-foreground">
Secure checkout via Stripe
</p>
</div>
</div>
);
}

View file

@ -1,20 +1,16 @@
"use client";
import { IconCalendar, IconMailFilled } from "@tabler/icons-react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, ExternalLink, Gift, Mail, Star, Zap } from "lucide-react";
import { Check, ExternalLink, Mail } from "lucide-react";
import Link from "next/link";
import { useEffect } from "react";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { USER_QUERY_KEY } from "@/atoms/user/user-query.atoms";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Dialog,
@ -22,15 +18,14 @@ import {
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Separator } from "@/components/ui/separator";
import { Skeleton } from "@/components/ui/skeleton";
import { Spinner } from "@/components/ui/spinner";
import type { IncentiveTaskInfo } from "@/contracts/types/incentive-tasks.types";
import { incentiveTasksApiService } from "@/lib/apis/incentive-tasks-api.service";
import { stripeApiService } from "@/lib/apis/stripe-api.service";
import {
trackIncentiveContactOpened,
trackIncentivePageViewed,
trackIncentiveTaskClicked,
trackIncentiveTaskCompleted,
@ -38,7 +33,10 @@ import {
import { cn } from "@/lib/utils";
export function MorePagesContent() {
const params = useParams();
const queryClient = useQueryClient();
const searchSpaceId = params?.search_space_id ?? "";
const [claimOpen, setClaimOpen] = useState(false);
useEffect(() => {
trackIncentivePageViewed();
@ -48,6 +46,11 @@ export function MorePagesContent() {
queryKey: ["incentive-tasks"],
queryFn: () => incentiveTasksApiService.getTasks(),
});
const { data: stripeStatus } = useQuery({
queryKey: ["stripe-status"],
queryFn: () => stripeApiService.getStatus(),
});
const pageBuyingEnabled = stripeStatus?.page_buying_enabled ?? true;
const completeMutation = useMutation({
mutationFn: incentiveTasksApiService.completeTask,
@ -59,7 +62,7 @@ export function MorePagesContent() {
trackIncentiveTaskCompleted(taskType, task.pages_reward);
}
queryClient.invalidateQueries({ queryKey: ["incentive-tasks"] });
queryClient.invalidateQueries({ queryKey: ["user"] });
queryClient.invalidateQueries({ queryKey: USER_QUERY_KEY });
}
},
onError: () => {
@ -75,132 +78,138 @@ export function MorePagesContent() {
};
return (
<div className="w-full space-y-6">
<div className="w-full space-y-5">
<div className="text-center">
<Gift className="mx-auto mb-3 h-8 w-8 text-primary" />
<h2 className="text-xl font-bold tracking-tight">Get More Pages</h2>
<h2 className="text-xl font-bold tracking-tight">Get Free Pages</h2>
<p className="mt-1 text-sm text-muted-foreground">
Complete tasks to earn additional pages
Claim your free page offer and earn bonus pages
</p>
</div>
{isLoading ? (
<Card>
<CardContent className="flex items-center gap-3 p-3">
<Skeleton className="h-9 w-9 rounded-full bg-muted" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-3/4 bg-muted" />
<Skeleton className="h-3 w-1/4 bg-muted" />
</div>
<Skeleton className="h-8 w-16 bg-muted" />
</CardContent>
</Card>
) : (
<div className="space-y-2">
{data?.tasks.map((task) => (
<Card
key={task.task_type}
className={cn("transition-colors bg-transparent", task.completed && "bg-muted/50")}
>
<CardContent className="flex items-center gap-3 p-3">
<div
className={cn(
"flex h-9 w-9 shrink-0 items-center justify-center rounded-full",
task.completed ? "bg-primary text-primary-foreground" : "bg-muted"
)}
>
{task.completed ? <Check className="h-4 w-4" /> : <Star className="h-4 w-4" />}
</div>
<div className="min-w-0 flex-1">
{/* 6k free offer */}
<Card className="border-emerald-500/30 bg-emerald-500/5">
<CardContent className="flex items-center gap-3 p-4">
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-emerald-600 text-white text-xs font-bold">
6k
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold">Claim 6,000 Free Pages</p>
<p className="text-xs text-muted-foreground">
Limited offer. Schedule a meeting or email us to claim.
</p>
</div>
<Button size="sm" className="bg-emerald-600 text-white hover:bg-emerald-700" onClick={() => setClaimOpen(true)}>
Claim
</Button>
</CardContent>
</Card>
<Separator />
{/* Free tasks */}
<div className="space-y-2">
<h3 className="text-sm font-semibold">Earn Bonus Pages</h3>
{isLoading ? (
<Card>
<CardContent className="flex items-center gap-3 p-3">
<Skeleton className="h-8 w-8 rounded-full bg-muted" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-3/4 bg-muted" />
</div>
<Skeleton className="h-8 w-16 bg-muted" />
</CardContent>
</Card>
) : (
<div className="space-y-1.5">
{data?.tasks.map((task) => (
<Card
key={task.task_type}
className={cn("transition-colors bg-transparent", task.completed && "bg-muted/50")}
>
<CardContent className="flex items-center gap-3 p-3">
<div
className={cn(
"flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
task.completed ? "bg-primary text-primary-foreground" : "bg-muted"
)}
>
{task.completed ? <Check className="h-3.5 w-3.5" /> : <span className="text-xs font-semibold">+{task.pages_reward}</span>}
</div>
<p
className={cn(
"text-sm font-medium",
"min-w-0 flex-1 text-sm font-medium",
task.completed && "text-muted-foreground line-through"
)}
>
{task.title}
</p>
<p className="text-xs text-muted-foreground">+{task.pages_reward} pages</p>
</div>
<Button
variant="ghost"
size="sm"
disabled={task.completed || completeMutation.isPending}
onClick={() => handleTaskClick(task)}
asChild={!task.completed}
className="text-muted-foreground hover:text-foreground"
>
{task.completed ? (
<span>Done</span>
) : (
<a
href={task.action_url}
target="_blank"
rel="noopener noreferrer"
className="gap-1"
>
{completeMutation.isPending ? (
<Spinner size="xs" />
) : (
<ExternalLink className="h-3 w-3" />
)}
</a>
)}
</Button>
</CardContent>
</Card>
))}
</div>
)}
<Button
variant="ghost"
size="sm"
disabled={task.completed || completeMutation.isPending}
onClick={() => handleTaskClick(task)}
asChild={!task.completed}
className="text-muted-foreground hover:text-foreground"
>
{task.completed ? (
<span>Done</span>
) : (
<a
href={task.action_url}
target="_blank"
rel="noopener noreferrer"
className="gap-1"
>
{completeMutation.isPending ? (
<Spinner size="xs" />
) : (
<ExternalLink className="h-3 w-3" />
)}
</a>
)}
</Button>
</CardContent>
</Card>
))}
</div>
)}
</div>
<Separator />
<Card className="overflow-hidden border-emerald-500/20 bg-transparent">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<Zap className="h-4 w-4 text-emerald-500" />
<CardTitle className="text-base">Upgrade to PRO</CardTitle>
<Badge className="bg-emerald-600 text-white border-transparent hover:bg-emerald-600">
FREE
</Badge>
</div>
<CardDescription>
For a limited time, get{" "}
<span className="font-semibold text-foreground">6,000 additional pages</span> at no
cost. Contact us and we&apos;ll upgrade your account instantly.
</CardDescription>
</CardHeader>
<CardFooter className="pt-2">
<Dialog onOpenChange={(open) => open && trackIncentiveContactOpened()}>
<DialogTrigger asChild>
<Button className="w-full bg-emerald-600 text-white hover:bg-emerald-700">
<Mail className="h-4 w-4" />
Contact us to Upgrade
</Button>
</DialogTrigger>
<DialogContent className="select-none sm:max-w-sm">
<DialogHeader>
<DialogTitle>Get in Touch</DialogTitle>
<DialogDescription>Pick the option that works best for you.</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-2">
<Button asChild>
<Link href="https://cal.com/mod-rohan" target="_blank" rel="noopener noreferrer">
<IconCalendar className="h-4 w-4" />
Schedule a Meeting
</Link>
</Button>
<Button variant="outline" asChild>
<Link href="mailto:rohan@surfsense.com">
<IconMailFilled className="h-4 w-4" />
rohan@surfsense.com
</Link>
</Button>
</div>
</DialogContent>
</Dialog>
</CardFooter>
</Card>
{/* Link to buy pages */}
<div className="text-center">
<p className="text-sm text-muted-foreground">Need more?</p>
{pageBuyingEnabled ? (
<Button asChild variant="link" className="text-emerald-600 dark:text-emerald-400">
<Link href={`/dashboard/${searchSpaceId}/buy-pages`}>
Buy page packs at $1 per 1,000
</Link>
</Button>
) : (
<p className="text-xs text-muted-foreground">
Page purchases are temporarily unavailable.
</p>
)}
</div>
{/* Claim 6k dialog */}
<Dialog open={claimOpen} onOpenChange={setClaimOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Claim 6,000 Free Pages</DialogTitle>
<DialogDescription>
Send us an email to claim your free 6,000 pages. Include your account email and primary usecase for free pages.
</DialogDescription>
</DialogHeader>
<Button asChild className="w-full gap-2">
<a href="mailto:rohan@surfsense.com?subject=Claim%206%2C000%20Free%20Pages&body=Hi%2C%20I'd%20like%20to%20claim%20the%206%2C000%20free%20pages%20offer.%0A%0AMy%20account%20email%3A%20">
<Mail className="h-4 w-4" />
rohan@surfsense.com
</a>
</Button>
</DialogContent>
</Dialog>
</div>
);
}

View file

@ -1,12 +1,13 @@
"use client";
import { useAtom } from "jotai";
import { Globe, KeyRound, Sparkles, User } from "lucide-react";
import { Globe, KeyRound, Receipt, Sparkles, User } from "lucide-react";
import { useTranslations } from "next-intl";
import { ApiKeyContent } from "@/app/dashboard/[search_space_id]/user-settings/components/ApiKeyContent";
import { CommunityPromptsContent } from "@/app/dashboard/[search_space_id]/user-settings/components/CommunityPromptsContent";
import { ProfileContent } from "@/app/dashboard/[search_space_id]/user-settings/components/ProfileContent";
import { PromptsContent } from "@/app/dashboard/[search_space_id]/user-settings/components/PromptsContent";
import { PurchaseHistoryContent } from "@/app/dashboard/[search_space_id]/user-settings/components/PurchaseHistoryContent";
import { userSettingsDialogAtom } from "@/atoms/settings/settings-dialog.atoms";
import { SettingsDialog } from "@/components/settings/settings-dialog";
@ -31,6 +32,11 @@ export function UserSettingsDialog() {
label: "Community Prompts",
icon: <Globe className="h-4 w-4" />,
},
{
value: "purchases",
label: "Purchase History",
icon: <Receipt className="h-4 w-4" />,
},
];
return (
@ -47,6 +53,7 @@ export function UserSettingsDialog() {
{state.initialTab === "api-key" && <ApiKeyContent />}
{state.initialTab === "prompts" && <PromptsContent />}
{state.initialTab === "community-prompts" && <CommunityPromptsContent />}
{state.initialTab === "purchases" && <PurchaseHistoryContent />}
</div>
</SettingsDialog>
);

View file

@ -0,0 +1,40 @@
import { z } from "zod";
export const pagePurchaseStatusEnum = z.enum(["pending", "completed", "failed"]);
export const createCheckoutSessionRequest = z.object({
quantity: z.number().int().min(1).max(100),
search_space_id: z.number().int().min(1),
});
export const createCheckoutSessionResponse = z.object({
checkout_url: z.string(),
});
export const stripeStatusResponse = z.object({
page_buying_enabled: z.boolean(),
});
export const pagePurchase = z.object({
id: z.uuid(),
stripe_checkout_session_id: z.string(),
stripe_payment_intent_id: z.string().nullable(),
quantity: z.number(),
pages_granted: z.number(),
amount_total: z.number().nullable(),
currency: z.string().nullable(),
status: pagePurchaseStatusEnum,
completed_at: z.string().nullable(),
created_at: z.string(),
});
export const getPagePurchasesResponse = z.object({
purchases: z.array(pagePurchase),
});
export type PagePurchaseStatus = z.infer<typeof pagePurchaseStatusEnum>;
export type CreateCheckoutSessionRequest = z.infer<typeof createCheckoutSessionRequest>;
export type CreateCheckoutSessionResponse = z.infer<typeof createCheckoutSessionResponse>;
export type StripeStatusResponse = z.infer<typeof stripeStatusResponse>;
export type PagePurchase = z.infer<typeof pagePurchase>;
export type GetPagePurchasesResponse = z.infer<typeof getPagePurchasesResponse>;

View file

@ -0,0 +1,30 @@
import {
type CreateCheckoutSessionRequest,
type CreateCheckoutSessionResponse,
createCheckoutSessionResponse,
type GetPagePurchasesResponse,
getPagePurchasesResponse,
type StripeStatusResponse,
stripeStatusResponse,
} from "@/contracts/types/stripe.types";
import { baseApiService } from "./base-api.service";
class StripeApiService {
createCheckoutSession = async (
request: CreateCheckoutSessionRequest
): Promise<CreateCheckoutSessionResponse> => {
return baseApiService.post("/api/v1/stripe/create-checkout-session", createCheckoutSessionResponse, {
body: request,
});
};
getPurchases = async (): Promise<GetPagePurchasesResponse> => {
return baseApiService.get("/api/v1/stripe/purchases", getPagePurchasesResponse);
};
getStatus = async (): Promise<StripeStatusResponse> => {
return baseApiService.get("/api/v1/stripe/status", stripeStatusResponse);
};
}
export const stripeApiService = new StripeApiService();

View file

@ -45,3 +45,4 @@ export const isSelfHosted = () => DEPLOYMENT_MODE === "self-hosted";
// Helper to check if running in cloud mode
export const isCloud = () => DEPLOYMENT_MODE === "cloud";