Add Umami analytics, subscription tiers, tool-call metering

- Analytics: <Analytics /> in root layout loads umami when NEXT_PUBLIC_UMAMI_* env are set
- Subscription: free/pro tiers in Postgres, daily quotas (10msg/5tool free, 1000/500 pro)
- Chat route: checkAndConsume(chat_message) gate before streamText, 429 when exhausted
- Tool metering: getWeather wrapped with withLimit decorator that deducts tool_call quota
- Pricing page at /pricing with upgrade button
- /api/billing/checkout posts to EGBE payment gateway, /api/billing/webhook verifies HMAC and upgrades user on checkout.session.completed
- UsageBadge in chat header polls /api/usage every 15s
- Dropped now-unused entitlements.ts
This commit is contained in:
dmitry.galkin 2026-05-25 17:27:08 +04:00
parent 3e21c2334c
commit 22a172e92d
23 changed files with 1374 additions and 86 deletions

View file

@ -0,0 +1,41 @@
import { auth } from "@/app/(auth)/auth";
import {
createCheckoutSession,
isBillingConfigured,
} from "@/lib/billing/gateway";
import { ChatbotError } from "@/lib/errors";
export async function POST(request: Request) {
const session = await auth();
if (!session?.user) {
return new ChatbotError("unauthorized:chat").toResponse();
}
if (!isBillingConfigured()) {
return Response.json(
{
error: "billing_not_configured",
message:
"Set EGBE_PAYMENT_GATEWAY_URL, EGBE_GATEWAYS_TOKEN, and PRO_STRIPE_PRICE_ID to enable upgrades.",
},
{ status: 501 }
);
}
const appSlug = process.env.APP_SLUG ?? "chatbot";
const baseUrl =
process.env.NEXT_PUBLIC_BASE_URL ?? new URL(request.url).origin;
try {
const result = await createCheckoutSession({
userId: session.user.id,
customerEmail: session.user.email ?? undefined,
appSlug,
baseUrl,
});
return Response.json({ url: result.url, id: result.id });
} catch (error) {
const message = error instanceof Error ? error.message : "checkout failed";
return Response.json({ error: "checkout_failed", message }, { status: 502 });
}
}

View file

@ -0,0 +1,99 @@
import { eq } from "drizzle-orm";
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import {
verifyWebhookSignature,
webhookHeaderName,
} from "@/lib/billing/gateway";
import { webhookEvent } from "@/lib/db/schema";
import { cancelSubscription, upgradeToPro } from "@/lib/subscription/service";
const client = postgres(process.env.DATABASE_URL ?? "");
const db = drizzle(client);
type StripeCheckoutSession = {
id: string;
payment_status?: string;
customer?: string;
subscription?: string;
metadata?: { userId?: string };
};
type StripeSubscription = {
id: string;
customer?: string;
current_period_end?: number;
metadata?: { userId?: string };
};
type WebhookEnvelope = {
id: string;
type: string;
data: { object: StripeCheckoutSession | StripeSubscription };
};
export async function POST(request: Request) {
const rawBody = await request.text();
const signature = request.headers.get(webhookHeaderName);
if (!verifyWebhookSignature(rawBody, signature)) {
return Response.json({ error: "invalid_signature" }, { status: 401 });
}
let envelope: WebhookEnvelope;
try {
envelope = JSON.parse(rawBody);
} catch {
return Response.json({ error: "invalid_json" }, { status: 400 });
}
const existing = await db
.select()
.from(webhookEvent)
.where(eq(webhookEvent.id, envelope.id))
.limit(1);
if (existing[0]) {
return Response.json({ ok: true, dedup: true });
}
try {
await handleEvent(envelope);
} catch (error) {
console.error("webhook handler failed", error);
return Response.json({ error: "handler_failed" }, { status: 500 });
}
await db
.insert(webhookEvent)
.values({ id: envelope.id, type: envelope.type })
.onConflictDoNothing();
return Response.json({ ok: true });
}
async function handleEvent(envelope: WebhookEnvelope) {
switch (envelope.type) {
case "checkout.session.completed": {
const obj = envelope.data.object as StripeCheckoutSession;
const userId = obj.metadata?.userId;
if (!userId) {
return;
}
await upgradeToPro(userId, {
stripeCustomerId: obj.customer,
stripeSubscriptionId: obj.subscription,
});
return;
}
case "customer.subscription.deleted": {
const obj = envelope.data.object as StripeSubscription;
const userId = obj.metadata?.userId;
if (!userId) {
return;
}
await cancelSubscription(userId);
return;
}
default:
}
}

View file

@ -5,8 +5,7 @@ import {
stepCountIs,
streamText,
} from "ai";
import { auth, type UserType } from "@/app/(auth)/auth";
import { entitlementsByUserType } from "@/lib/ai/entitlements";
import { auth } from "@/app/(auth)/auth";
import {
allowedModelIds,
DEFAULT_CHAT_MODEL,
@ -15,10 +14,10 @@ import {
import { type RequestHints, systemPrompt } from "@/lib/ai/prompts";
import { getLanguageModel } from "@/lib/ai/providers";
import { getWeather } from "@/lib/ai/tools/get-weather";
import { withLimit } from "@/lib/ai/tools/with-limit";
import {
deleteChatById,
getChatById,
getMessageCountByUserId,
getMessagesByChatId,
saveChat,
saveMessages,
@ -28,6 +27,10 @@ import {
import type { DBMessage } from "@/lib/db/schema";
import { ChatbotError } from "@/lib/errors";
import { checkIpRateLimit } from "@/lib/ratelimit";
import {
checkAndConsume,
LimitExceededError,
} from "@/lib/subscription/service";
import type { ChatMessage } from "@/lib/types";
import { convertToUIMessages, generateUUID } from "@/lib/utils";
import { generateTitleFromUserMessage } from "../../actions";
@ -69,19 +72,25 @@ export async function POST(request: Request) {
await checkIpRateLimit(getClientIp(request));
const userType: UserType = session.user.type;
const messageCount = await getMessageCountByUserId({
id: session.user.id,
differenceInHours: 1,
});
if (messageCount > entitlementsByUserType[userType].maxMessagesPerHour) {
return new ChatbotError("rate_limit:chat").toResponse();
}
const isToolApprovalFlow = Boolean(messages);
if (!isToolApprovalFlow) {
try {
await checkAndConsume(session.user.id, "chat_message");
} catch (error) {
if (error instanceof LimitExceededError) {
return Response.json(
{
code: "rate_limit:chat",
message: `Daily message limit reached (${error.used}/${error.limit} on ${error.tier} tier). Upgrade to Pro at /pricing.`,
},
{ status: 429 }
);
}
throw error;
}
}
const chat = await getChatById({ id });
let messagesFromDb: DBMessage[] = [];
let titlePromise: Promise<string> | null = null;
@ -165,6 +174,8 @@ export async function POST(request: Request) {
const modelMessages = await convertToModelMessages(uiMessages);
const meteredWeather = withLimit(getWeather, "tool_call", session.user.id);
const stream = createUIMessageStream({
originalMessages: isToolApprovalFlow ? uiMessages : undefined,
execute: async ({ writer: dataStream }) => {
@ -176,7 +187,7 @@ export async function POST(request: Request) {
experimental_activeTools:
isReasoningModel && !supportsTools ? [] : ["getWeather"],
tools: {
getWeather,
getWeather: meteredWeather,
},
});

View file

@ -0,0 +1,16 @@
import { auth } from "@/app/(auth)/auth";
import { ChatbotError } from "@/lib/errors";
import { getQuotaSummary } from "@/lib/subscription/service";
export async function GET() {
const session = await auth();
if (!session?.user) {
return new ChatbotError("unauthorized:chat").toResponse();
}
const summary = await getQuotaSummary(session.user.id);
return Response.json(summary, {
headers: {
"Cache-Control": "no-store",
},
});
}

View file

@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import { Analytics } from "@/components/analytics";
import { ThemeProvider } from "@/components/theme-provider";
import { TooltipProvider } from "@/components/ui/tooltip";
@ -68,6 +69,7 @@ export default function RootLayout({
__html: THEME_COLOR_SCRIPT,
}}
/>
<Analytics />
</head>
<body className="antialiased">
<ThemeProvider

96
app/pricing/page.tsx Normal file
View file

@ -0,0 +1,96 @@
import { redirect } from "next/navigation";
import { auth } from "@/app/(auth)/auth";
import { PricingClient } from "@/components/pricing-client";
import { LIMITS, type Tier } from "@/lib/subscription/config";
import { ensureSubscription } from "@/lib/subscription/service";
export const dynamic = "force-dynamic";
export default async function PricingPage({
searchParams,
}: {
searchParams: Promise<{ upgraded?: string; canceled?: string }>;
}) {
const session = await auth();
if (!session?.user) {
redirect("/api/auth/guest?redirectUrl=%2Fpricing");
}
const sub = await ensureSubscription(session.user.id);
const params = await searchParams;
return (
<div className="mx-auto flex min-h-dvh max-w-5xl flex-col gap-8 px-6 py-12">
<div className="flex flex-col gap-2">
<a className="text-muted-foreground text-sm hover:text-foreground" href="/">
Back to chat
</a>
<h1 className="font-semibold text-3xl">Pricing</h1>
<p className="text-muted-foreground text-sm">
You are currently on the <strong>{sub.tier}</strong> tier.
{params.upgraded === "1" && (
<span className="ml-2 text-green-600">
Welcome to Pro limits updated.
</span>
)}
{params.canceled === "1" && (
<span className="ml-2 text-amber-600">Checkout canceled.</span>
)}
</p>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Plan
currentTier={sub.tier as Tier}
description="Try the chatbot with a small daily quota."
price="Free"
tier="free"
/>
<Plan
currentTier={sub.tier as Tier}
description="Higher daily quotas for serious use."
price="$10 / month"
tier="pro"
/>
</div>
<PricingClient currentTier={sub.tier as Tier} />
</div>
);
}
function Plan({
tier,
price,
description,
currentTier,
}: {
tier: Tier;
price: string;
description: string;
currentTier: Tier;
}) {
const tierLimits = LIMITS[tier];
const isCurrent = tier === currentTier;
return (
<div className="flex flex-col gap-4 rounded-2xl border border-border/40 bg-card p-6 shadow-sm">
<div>
<div className="flex items-baseline justify-between">
<div className="font-medium text-lg capitalize">{tier}</div>
{isCurrent && (
<span className="rounded-full bg-muted px-2 py-0.5 text-muted-foreground text-xs">
Current
</span>
)}
</div>
<div className="font-semibold text-2xl">{price}</div>
<p className="mt-1 text-muted-foreground text-sm">{description}</p>
</div>
<ul className="flex flex-col gap-1.5 text-sm">
<li> {tierLimits.chat_message} messages / day</li>
<li> {tierLimits.tool_call} tool calls / day</li>
<li> All available models</li>
</ul>
</div>
);
}