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:
parent
3e21c2334c
commit
22a172e92d
23 changed files with 1374 additions and 86 deletions
41
app/(chat)/api/billing/checkout/route.ts
Normal file
41
app/(chat)/api/billing/checkout/route.ts
Normal 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 });
|
||||
}
|
||||
}
|
||||
99
app/(chat)/api/billing/webhook/route.ts
Normal file
99
app/(chat)/api/billing/webhook/route.ts
Normal 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:
|
||||
}
|
||||
}
|
||||
|
|
@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
16
app/(chat)/api/usage/route.ts
Normal file
16
app/(chat)/api/usage/route.ts
Normal 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",
|
||||
},
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue