Files
Epicure/apps/web/lib/site-settings.ts
T
Arnaud f871f4f588 feat: real Stripe billing -- Checkout, Customer Portal, admin billing dashboard (v0.73.0)
Implements plans/STRIPE_PLAN.md sections 1-9 for solo Pro/Family
billing (family multi-user sharing, section 1a, deliberately deferred
-- flagged in that plan as the most novel/error-prone piece).

Decisions locked in: cancel/downgrade at period end (Stripe Portal
default), no trial period.

- lib/stripe.ts: single client factory reading STRIPE_SECRET_KEY via
  site-settings (DB overrides env, same pattern as every other
  provider key in this codebase).
- Webhook route rewritten on the real `stripe` SDK
  (stripe.webhooks.constructEvent replaces the hand-rolled HMAC
  verifier) and now handles the full event set: checkout.session.completed,
  customer.subscription.{updated,deleted}, invoice.{payment_failed,paid}.
  past_due deliberately never downgrades tier on its own -- Stripe
  retries the card first, recovering via invoice.paid or eventually
  giving up via subscription.deleted. Every handler audit-logs under
  billing.<event>. Dedup via the existing processed_stripe_events
  table, unchanged.
- Schema: tierDefinitions gained stripe{ProductId,PriceIdMonthly,
  PriceIdYearly} (the lookup table mapping a Price back to a tier on
  checkout); users gained stripeSubscriptionId/subscriptionStatus/
  currentPeriodEnd.
- New POST /api/v1/billing/checkout (creates a subscription Checkout
  Session, allow_promotion_codes: true), POST /api/v1/billing/portal
  (Stripe's hosted self-serve cancel/upgrade/card-update), GET
  /api/v1/billing/status.
- /settings/billing: current plan + renewal date, past_due warning,
  usage-vs-limits (reuses the existing UsageQuotaSection), plan
  comparison cards with per-tier Checkout buttons, manage-billing
  button once a Stripe customer exists.
- /admin/billing: connection status (test/live mode detection),
  subscriber counts, past-due list, recent billing audit events, link
  to Stripe Dashboard. Tier Limits page extended with the three Stripe
  price fields per tier (own render branch, not the numeric+Unlimited-
  switch machinery the existing fields use).

Before going live: an admin needs to create real Products/Prices in
Stripe, enter the IDs on Tier Limits, and configure the Stripe-side
webhook endpoint -- all operational steps the plan always called for,
none of it code.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 13:37:14 +02:00

142 lines
4.0 KiB
TypeScript

import { db, siteSettings, eq } from "@epicure/db";
import { encrypt, decrypt } from "@/lib/encrypt";
export type SiteSettingKey =
| "OPENAI_API_KEY"
| "ANTHROPIC_API_KEY"
| "OPENROUTER_API_KEY"
| "OPENROUTER_DEFAULT_MODEL"
| "OLLAMA_BASE_URL"
| "NEXT_PUBLIC_VAPID_PUBLIC_KEY"
| "VAPID_PRIVATE_KEY"
| "SIGNUPS_DISABLED"
| "DEFAULT_TEXT_PROVIDER"
| "DEFAULT_TEXT_MODEL"
| "DEFAULT_VISION_PROVIDER"
| "DEFAULT_VISION_MODEL"
| "DEFAULT_MEAL_PLAN_PROVIDER"
| "DEFAULT_MEAL_PLAN_MODEL"
| "DEFAULT_CHAT_PROVIDER"
| "DEFAULT_CHAT_MODEL"
| "AI_TOOL_CALLING_ENABLED"
| "GITEA_URL"
| "GITEA_TOKEN"
| "GITEA_REPO"
| "GITEA_WEBHOOK_SECRET"
| "USDA_API_KEY"
| "STRIPE_SECRET_KEY"
| "STRIPE_PUBLISHABLE_KEY"
| "STRIPE_WEBHOOK_SECRET";
const SECRET_KEYS: SiteSettingKey[] = [
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"OPENROUTER_API_KEY",
"VAPID_PRIVATE_KEY",
"GITEA_TOKEN",
"GITEA_WEBHOOK_SECRET",
"USDA_API_KEY",
"STRIPE_SECRET_KEY",
"STRIPE_WEBHOOK_SECRET",
];
export function isSecretKey(key: SiteSettingKey): boolean {
return SECRET_KEYS.includes(key);
}
export async function getSiteSetting(key: SiteSettingKey): Promise<string | null> {
try {
const row = await db.query.siteSettings.findFirst({ where: eq(siteSettings.key, key) });
if (row?.value) {
return row.isSecret ? decrypt(row.value) : row.value;
}
} catch {
// fall through to env
}
return process.env[key] ?? null;
}
export async function getAllSiteSettings(): Promise<Record<string, { value: string | null; isSecret: boolean; fromDb: boolean }>> {
const rows = await db.query.siteSettings.findMany();
const dbMap = new Map(rows.map((r) => [r.key, r]));
const KNOWN_KEYS: SiteSettingKey[] = [
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"OPENROUTER_API_KEY",
"OPENROUTER_DEFAULT_MODEL",
"OLLAMA_BASE_URL",
"NEXT_PUBLIC_VAPID_PUBLIC_KEY",
"VAPID_PRIVATE_KEY",
"DEFAULT_TEXT_PROVIDER",
"DEFAULT_TEXT_MODEL",
"DEFAULT_VISION_PROVIDER",
"DEFAULT_VISION_MODEL",
"DEFAULT_MEAL_PLAN_PROVIDER",
"DEFAULT_MEAL_PLAN_MODEL",
"DEFAULT_CHAT_PROVIDER",
"DEFAULT_CHAT_MODEL",
"AI_TOOL_CALLING_ENABLED",
"GITEA_URL",
"GITEA_TOKEN",
"GITEA_REPO",
"GITEA_WEBHOOK_SECRET",
"USDA_API_KEY",
"STRIPE_SECRET_KEY",
"STRIPE_PUBLISHABLE_KEY",
"STRIPE_WEBHOOK_SECRET",
];
const result: Record<string, { value: string | null; isSecret: boolean; fromDb: boolean }> = {};
for (const k of KNOWN_KEYS) {
const row = dbMap.get(k);
const secret = isSecretKey(k);
if (row) {
result[k] = {
value: secret ? "••••••••••••" : (row.value ?? null),
isSecret: secret,
fromDb: true,
};
} else {
const envVal = process.env[k];
result[k] = {
value: envVal ? (secret ? "••••••••••••" : envVal) : null,
isSecret: secret,
fromDb: false,
};
}
}
return result;
}
export async function isSignupsDisabled(): Promise<boolean> {
return (await getSiteSetting("SIGNUPS_DISABLED")) === "true";
}
/** Defaults to enabled — the chatbot's createRecipe/addToShoppingList tools
* only get turned off explicitly, e.g. for a local model that can't reliably
* call tools. */
export async function isAiToolCallingEnabled(): Promise<boolean> {
return (await getSiteSetting("AI_TOOL_CALLING_ENABLED")) !== "false";
}
export async function setSiteSetting(
key: SiteSettingKey,
value: string | null,
updatedById: string
): Promise<void> {
if (value === null || value === "") {
await db.delete(siteSettings).where(eq(siteSettings.key, key));
return;
}
const secret = isSecretKey(key);
const stored = secret ? encrypt(value) : value;
await db
.insert(siteSettings)
.values({ key, value: stored, isSecret: secret, updatedById, updatedAt: new Date() })
.onConflictDoUpdate({
target: siteSettings.key,
set: { value: stored, updatedAt: new Date(), updatedById },
});
}