Files
Epicure/apps/web/app/(app)/recipes/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

193 lines
8.2 KiB
TypeScript

import type { Metadata } from "next";
import { headers } from "next/headers";
import Link from "next/link";
import { auth } from "@/lib/auth/server";
import { db, recipes, favorites, sql, count } from "@epicure/db";
import { eq, desc, asc, and, ilike, or, inArray } from "@epicure/db";
import { RecipesHeader } from "@/components/recipe/recipes-header";
import { RecipesEmptyState } from "@/components/recipe/recipes-empty-state";
import { RecipesGrid } from "@/components/recipe/recipes-grid";
import { CookingAssistantPanel } from "@/components/recipe/cooking-assistant-panel";
import { getMessages } from "@/lib/i18n/server";
import { getFeaturePrefs } from "@/lib/feature-prefs";
import { getFeatureFlagMatrix, type Tier } from "@/lib/feature-flags";
export const metadata: Metadata = {};
const PAGE_SIZE = 24;
type SearchParams = Promise<{
q?: string;
sort?: string;
visibility?: string;
difficulty?: string;
tag?: string;
page?: string;
batchCook?: string;
recipeType?: string;
// OS Share Target params (manifest.ts's share_target) — a browser share
// sheet navigates here with these appended.
url?: string;
text?: string;
title?: string;
}>;
const URL_PATTERN = /https?:\/\/\S+/;
/** Web Share Target's GET params vary by sender: some apps put the shared
* link in `url`, others (notably many Android apps) put it inside `text`
* alongside other text. Prefer `url`, fall back to extracting the first
* http(s) URL out of `text`. */
function extractSharedUrl(params: { url?: string; text?: string }): string | undefined {
if (params.url && URL_PATTERN.test(params.url)) return params.url;
const match = params.text?.match(URL_PATTERN);
return match?.[0];
}
const SORT_MAP = {
updated_desc: desc(recipes.updatedAt),
updated_asc: asc(recipes.updatedAt),
created_desc: desc(recipes.createdAt),
created_asc: asc(recipes.createdAt),
title_asc: asc(recipes.title),
title_desc: desc(recipes.title),
} as const;
type SortKey = keyof typeof SORT_MAP;
export default async function RecipesPage({ searchParams }: { searchParams: SearchParams }) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const m = getMessages((session.user as { locale?: string }).locale);
const featurePrefs = await getFeaturePrefs(session.user.id);
const viewerTier = (session.user as { tier?: string }).tier as Tier | undefined ?? "free";
const featureFlags = await getFeatureFlagMatrix();
const canImportUrl = featureFlags.recipe_import_url[viewerTier];
const { q, sort, visibility, difficulty, tag, page: pageParam, batchCook, recipeType, url, text } = await searchParams;
const sharedUrl = extractSharedUrl({ url, text });
const query = (q ?? "").trim().slice(0, 200);
const sortKey: SortKey = (sort && sort in SORT_MAP ? sort : "updated_desc") as SortKey;
const tagFilter = tag?.trim().slice(0, 50) || undefined;
const page = Math.max(1, parseInt(pageParam ?? "1", 10) || 1);
const offset = (page - 1) * PAGE_SIZE;
const visibilityFilter = visibility && ["private", "unlisted", "public", "followers"].includes(visibility)
? (visibility as "private" | "unlisted" | "public" | "followers")
: undefined;
const difficultyFilter = difficulty && ["easy", "medium", "hard"].includes(difficulty)
? (difficulty as "easy" | "medium" | "hard")
: undefined;
const batchCookFilter = batchCook === "1" || batchCook === "0" ? batchCook : undefined;
const recipeTypeFilter = recipeType === "dish" || recipeType === "drink" ? recipeType : undefined;
// Escape ilike wildcard chars (% and _) so a search like "100%" matches literally.
const escapedQuery = query.replace(/[\\%_]/g, (c) => `\\${c}`);
const where = and(
eq(recipes.authorId, session.user.id),
batchCookFilter ? eq(recipes.isBatchCook, batchCookFilter === "1") : undefined,
query
? or(
ilike(recipes.title, `%${escapedQuery}%`),
ilike(recipes.description, `%${escapedQuery}%`),
// Plain SQL identifiers rather than drizzle's column proxies —
// inside db.query.recipes.findMany's `where`, the relational query
// builder rewrites embedded column refs to the outer query's own
// table alias regardless of which table they actually belong to,
// producing broken SQL (recipes.raw_name doesn't exist). Using
// literal identifiers for the ingredients subquery sidesteps that.
sql`exists (select 1 from recipe_ingredients ri where ri.recipe_id = ${recipes.id} and ri.raw_name ilike ${`%${escapedQuery}%`})`,
sql`exists (select 1 from unnest(${recipes.tags}) as tag where tag ilike ${`%${escapedQuery}%`})`
)
: undefined,
visibilityFilter ? eq(recipes.visibility, visibilityFilter) : undefined,
difficultyFilter ? eq(recipes.difficulty, difficultyFilter) : undefined,
tagFilter ? sql`${recipes.tags} @> ARRAY[${tagFilter}]::text[]` : undefined,
recipeTypeFilter ? eq(recipes.recipeType, recipeTypeFilter) : undefined,
);
const [userRecipes, totalRow] = await Promise.all([
db.query.recipes.findMany({
where,
orderBy: SORT_MAP[sortKey],
with: { photos: true, batchDishes: { columns: { id: true } } },
limit: PAGE_SIZE,
offset,
}),
db.select({ count: count() }).from(recipes).where(where),
]);
const total = totalRow[0]?.count ?? 0;
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
const recipeIds = userRecipes.map((r) => r.id);
const favoritedRows = recipeIds.length > 0
? await db
.select({ recipeId: favorites.recipeId })
.from(favorites)
.where(and(eq(favorites.userId, session.user.id), inArray(favorites.recipeId, recipeIds)))
: [];
const favoritedIds = new Set(favoritedRows.map((r) => r.recipeId));
const recipesWithFavorites = userRecipes.map((r) => ({ ...r, isFavorited: favoritedIds.has(r.id), dishCount: r.batchDishes.length }));
const pageHref = (p: number) => {
const params = new URLSearchParams();
if (query) params.set("q", query);
if (sortKey !== "updated_desc") params.set("sort", sortKey);
if (visibilityFilter) params.set("visibility", visibilityFilter);
if (difficultyFilter) params.set("difficulty", difficultyFilter);
if (tagFilter) params.set("tag", tagFilter);
if (batchCookFilter) params.set("batchCook", batchCookFilter);
if (recipeTypeFilter) params.set("recipeType", recipeTypeFilter);
if (p > 1) params.set("page", String(p));
const qs = params.toString();
return qs ? `/recipes?${qs}` : "/recipes";
};
return (
<div className="space-y-4 sm:space-y-6">
<div className="flex items-center gap-2 text-sm">
<span className="rounded-full bg-accent px-3 py-1 font-medium">{m.recipes.tabMine}</span>
<Link href="/recipes/favorites" className="rounded-full px-3 py-1 text-muted-foreground hover:bg-accent">
{m.recipes.tabFavorites}
</Link>
</div>
<RecipesHeader
count={total}
initialQuery={query}
initialSort={sortKey}
initialVisibility={visibilityFilter ?? ""}
initialDifficulty={difficultyFilter ?? ""}
initialTag={tagFilter ?? ""}
initialBatchCook={batchCookFilter ?? ""}
initialRecipeType={recipeTypeFilter ?? ""}
sharedUrl={canImportUrl ? sharedUrl : undefined}
showImportUrl={canImportUrl}
/>
<RecipesEmptyState query={query} count={total} />
<RecipesGrid key={`${query}-${sortKey}-${visibilityFilter}-${difficultyFilter}-${tagFilter}-${batchCookFilter}-${recipeTypeFilter}-${page}`} recipes={recipesWithFavorites} />
{totalPages > 1 && (
<div className="flex items-center justify-center gap-2 pt-2">
{page > 1 && (
<Link href={pageHref(page - 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
Previous
</Link>
)}
<span className="text-sm text-muted-foreground px-2">
Page {page} of {totalPages}
</span>
{page < totalPages && (
<Link href={pageHref(page + 1)} className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent">
Next
</Link>
)}
</div>
)}
{featurePrefs.chatbots && <CookingAssistantPanel />}
</div>
);
}