Files
Epicure/apps/web/app/(app)/settings/ai/page.tsx
T
Arnaud 55c6fc5ab7 feat: 6 new per-tier feature flags (off by default) + flag-icon locale switcher + hide BYOK when disabled (v0.74.0)
Extends the existing feature-flags system (previously 3 keys, all
default-enabled) with 6 more: recipe_import_url, recipe_import_photo,
nutrition_estimation, markdown_export, weekly_nutrition,
grocery_delivery. Each FEATURE_DEFINITIONS entry now carries its own
defaultEnabled -- the new 6 default to false, the original 3 stay
true -- so no migration/seed was needed for the "off by default"
requirement, just a per-key fallback instead of a blanket true.

Gated server-side (requireFeatureEnabledResponse, a new shared
helper avoiding six copies of the same try/catch) on: import-url,
import-photo, nutrition POST estimate, bulk markdown export, weekly
meal-plan nutrition GET, Instacart export. Gated client-side by
hiding the trigger entirely (not just disabling) on every page that
renders one: recipe detail (meal/drink pairing buttons, nutrition
panel's estimate button, markdown export), recipes list (import-URL
button, including the OS Share Target auto-import path), new-recipe
page (photo import), meal-plan page (markdown export, weekly
nutrition bar), shopping-list/collection/pantry pages (markdown
export), shopping-list page (Instacart button, now gated by both the
existing env-var check AND the tier flag).

Also: BYOK section on Settings -> AI now hidden entirely for
non-BYOK users (previously showed a locked-and-teased notice, same
inconsistency the Model Prefs fix closed yesterday). Language
switcher shows a flag icon (FlagGB/FlagFR, moved from
components/marketing to components/shared so both the logged-in
settings switcher and the logged-out marketing one can use it)
instead of plain "English"/"Français" text-only options.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 11:16:41 +02:00

102 lines
3.8 KiB
TypeScript

import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, userAiKeys, userModelPrefs, users, tierDefinitions, userUsage, eq, and } from "@epicure/db";
import { UNLIMITED, getRecipeCount, getStorageUsedMb } from "@/lib/tiers";
import { ByokManager } from "@/components/settings/byok-manager";
import { ModelPrefsForm } from "@/components/settings/model-prefs-form";
import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
import { getMessages, formatMessage } from "@/lib/i18n/server";
export const metadata: Metadata = {};
export default async function AiSettingsPage() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const currentMonth = new Date().toISOString().slice(0, 7);
const [aiKeys, modelPrefs, dbUser] = await Promise.all([
db.query.userAiKeys.findMany({
where: eq(userAiKeys.userId, session.user.id),
columns: { provider: true },
}),
db.query.userModelPrefs.findFirst({
where: eq(userModelPrefs.userId, session.user.id),
}),
// Tier comes from the DB, not the (up to 5-minute-stale) session cookie
// cache, so a just-changed tier's limits show up immediately here.
db.query.users.findFirst({ where: eq(users.id, session.user.id), columns: { tier: true, isByokEnabled: true } }),
]);
const [tierDef, usage, recipeCount, storageUsedMb] = await Promise.all([
db.query.tierDefinitions.findFirst({ where: eq(tierDefinitions.tier, dbUser?.tier ?? "free") }),
db.query.userUsage.findFirst({ where: and(eq(userUsage.userId, session.user.id), eq(userUsage.month, currentMonth)) }),
getRecipeCount(session.user.id),
getStorageUsedMb(session.user.id),
]);
const asLimit = (n: number | undefined) => (n === undefined || n === UNLIMITED ? null : n);
const usageMetrics = [
{
label: m.settings.usage.aiCalls,
used: usage?.aiCallsUsed ?? 0,
limit: asLimit(tierDef?.aiCallsPerMonth),
unlimitedLabel: m.settings.usage.unlimited,
},
{
label: m.settings.usage.recipes,
used: recipeCount,
limit: asLimit(tierDef?.maxRecipes),
unlimitedLabel: m.settings.usage.unlimited,
},
{
label: m.settings.usage.storage,
used: storageUsedMb,
limit: asLimit(tierDef?.storageMb),
unit: " MB",
unlimitedLabel: m.settings.usage.unlimited,
},
];
return (
<div className="space-y-8">
<section className="rounded-xl border p-6 space-y-4">
<div>
<h2 className="font-semibold text-lg">{m.settings.usage.title}</h2>
<p className="text-sm text-muted-foreground mt-1">
{formatMessage(m.settings.usage.description, { month: currentMonth })}
</p>
</div>
<UsageQuotaSection metrics={usageMetrics} />
</section>
{dbUser?.isByokEnabled && (
<section className="rounded-xl border p-6 space-y-4">
<div>
<h2 className="font-semibold text-lg">{m.settings.byok.title}</h2>
<p className="text-sm text-muted-foreground mt-1">
{m.settings.byok.description}
</p>
</div>
<ByokManager initialKeys={aiKeys.map((k) => k.provider)} />
</section>
)}
{dbUser?.isByokEnabled && (
<section className="rounded-xl border p-6 space-y-4">
<div>
<h2 className="font-semibold text-lg">{m.settings.modelPrefs.title}</h2>
<p className="text-sm text-muted-foreground mt-1">
{m.settings.modelPrefs.description}
</p>
</div>
<ModelPrefsForm initialPrefs={modelPrefs ?? null} />
</section>
)}
</div>
);
}