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

@ -1,6 +1,7 @@
import type { InferSelectModel } from "drizzle-orm";
import {
boolean,
integer,
json,
pgTable,
primaryKey,
@ -68,3 +69,49 @@ export const vote = pgTable(
);
export type Vote = InferSelectModel<typeof vote>;
export const subscription = pgTable("Subscription", {
userId: uuid("userId")
.primaryKey()
.notNull()
.references(() => user.id),
tier: varchar("tier", { enum: ["free", "pro"] })
.notNull()
.default("free"),
status: varchar("status", { enum: ["active", "canceled", "past_due"] })
.notNull()
.default("active"),
stripeCustomerId: text("stripeCustomerId"),
stripeSubscriptionId: text("stripeSubscriptionId"),
currentPeriodEnd: timestamp("currentPeriodEnd"),
createdAt: timestamp("createdAt").notNull().defaultNow(),
updatedAt: timestamp("updatedAt").notNull().defaultNow(),
});
export type Subscription = InferSelectModel<typeof subscription>;
export const usage = pgTable(
"Usage",
{
userId: uuid("userId")
.notNull()
.references(() => user.id),
periodKey: varchar("periodKey", { length: 10 }).notNull(),
messageCount: integer("messageCount").notNull().default(0),
toolCallCount: integer("toolCallCount").notNull().default(0),
updatedAt: timestamp("updatedAt").notNull().defaultNow(),
},
(table) => ({
pk: primaryKey({ columns: [table.userId, table.periodKey] }),
})
);
export type Usage = InferSelectModel<typeof usage>;
export const webhookEvent = pgTable("WebhookEvent", {
id: text("id").primaryKey().notNull(),
type: text("type").notNull(),
receivedAt: timestamp("receivedAt").notNull().defaultNow(),
});
export type WebhookEvent = InferSelectModel<typeof webhookEvent>;