feat(recipes): full recipe CRUD with photos, print, version history

List, detail, new, edit pages. Server-side pagination, dietary tags, difficulty.
Photo upload to S3-compatible storage. Version history. Multi-select grid with
bulk delete/visibility. Print view. Delete confirmation dialog.
This commit is contained in:
Arnaud
2026-07-01 08:10:11 +02:00
parent fa2d797918
commit 84d6cfeb07
45 changed files with 5300 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
import { Nav } from "@/components/layout/nav";
export default function AppLayout({ children }: { children: React.ReactNode }) {
return (
<>
<Nav />
<main className="flex-1 container mx-auto px-4 py-8">{children}</main>
</>
);
}
@@ -0,0 +1,46 @@
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db";
import { CookingMode } from "@/components/cooking-mode/cooking-mode";
type Params = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Params) {
const { id } = await params;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
return { title: recipe ? `Cooking: ${recipe.title}` : "Cooking Mode" };
}
export default async function CookPage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
with: {
steps: { orderBy: (t, { asc }) => asc(t.order) },
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe || recipe.steps.length === 0) notFound();
return (
<CookingMode
recipeId={id}
recipeTitle={recipe.title}
steps={recipe.steps.map((s) => ({
id: s.id,
instruction: s.instruction,
timerSeconds: s.timerSeconds,
}))}
ingredients={recipe.ingredients.map((i) => ({
rawName: i.rawName,
quantity: i.quantity,
unit: i.unit,
}))}
/>
);
}
@@ -0,0 +1,67 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes } from "@epicure/db";
import { and, eq } from "@epicure/db";
import { RecipeForm } from "@/components/recipe/recipe-form";
import { getPublicUrl } from "@/lib/storage";
type Params = { params: Promise<{ id: string }> };
export const metadata: Metadata = { title: "Edit Recipe" };
export default async function EditRecipePage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
photos: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe) notFound();
const defaultValues = {
title: recipe.title,
description: recipe.description ?? undefined,
baseServings: recipe.baseServings,
visibility: recipe.visibility,
difficulty: recipe.difficulty,
prepMins: recipe.prepMins,
cookMins: recipe.cookMins,
dietaryTags: (recipe.dietaryTags as Record<string, boolean | undefined>) ?? {},
ingredients: recipe.ingredients.map((ing) => ({
id: ing.id,
rawName: ing.rawName,
quantity: ing.quantity ?? "",
unit: ing.unit ?? "",
note: ing.note ?? "",
})),
steps: recipe.steps.map((step) => ({
id: step.id,
instruction: step.instruction,
timerSeconds: step.timerSeconds ? String(step.timerSeconds) : "",
})),
photos: recipe.photos.map((photo) => ({
key: photo.storageKey,
isCover: photo.isCover,
preview: getPublicUrl(photo.storageKey),
})),
};
return (
<div className="space-y-6">
<div>
<h1 className="text-3xl font-bold tracking-tight">Edit recipe</h1>
<p className="text-muted-foreground mt-1">{recipe.title}</p>
</div>
<RecipeForm recipeId={id} defaultValues={defaultValues} />
</div>
);
}
+290
View File
@@ -0,0 +1,290 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import Link from "next/link";
import { Clock, Users, Globe, Lock, Link2, Pencil, ChefHat, ExternalLink, Play } from "lucide-react";
import { VariationsButton } from "@/components/recipe/variations-button";
import { TranslateButton } from "@/components/recipe/translate-button";
import { AddToShoppingListButton } from "@/components/recipe/add-to-shopping-list-button";
import { MealPairingButton } from "@/components/recipe/meal-pairing-button";
import { DrinkPairingButton } from "@/components/recipe/drink-pairing-button";
import { AdaptRecipeButton } from "@/components/recipe/adapt-recipe-button";
import { PrintButton } from "@/components/recipe/print-button";
import { VersionHistoryButton } from "@/components/recipe/version-history-button";
import { DeleteRecipeButton } from "@/components/recipe/delete-recipe-button";
import { NutritionPanel } from "@/components/recipe/nutrition-panel";
import { auth } from "@/lib/auth/server";
import { db, recipes, ratings, favorites, avg } from "@epicure/db";
import { and, eq, count } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ServingScaler } from "@/components/recipe/serving-scaler";
import { FavoriteButton } from "@/components/social/favorite-button";
import { RatingStars } from "@/components/social/rating-stars";
import { CommentsSection } from "@/components/social/comments-section";
import { getPublicUrl } from "@/lib/storage";
import { cn } from "@/lib/utils";
type Params = { params: Promise<{ id: string }> };
export async function generateMetadata({ params }: Params): Promise<Metadata> {
const { id } = await params;
const recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
return { title: recipe?.title ?? "Recipe" };
}
const VISIBILITY_LABEL = { private: "Private", unlisted: "Unlisted", public: "Public" };
const VISIBILITY_ICON = { private: Lock, unlisted: Link2, public: Globe };
const DIFFICULTY_COLOR = { easy: "default", medium: "secondary", hard: "destructive" } as const;
const DIETARY_LABELS: Record<string, string> = {
vegan: "Vegan",
vegetarian: "Vegetarian",
glutenFree: "Gluten-free",
dairyFree: "Dairy-free",
nutFree: "Nut-free",
halal: "Halal",
kosher: "Kosher",
};
export default async function RecipePage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const [recipe, ratingData, favoriteData] = await Promise.all([
db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
photos: { orderBy: (t, { asc }) => asc(t.order) },
},
}),
db.select({ avgScore: avg(ratings.score), total: count() }).from(ratings).where(eq(ratings.recipeId, id)),
db.query.favorites.findFirst({ where: and(eq(favorites.userId, session.user.id), eq(favorites.recipeId, id)) }),
]);
if (!recipe) notFound();
const avgScore = ratingData[0]?.avgScore ? parseFloat(ratingData[0].avgScore) : null;
const ratingCount = ratingData[0]?.total ?? 0;
const isFavorited = !!favoriteData;
const cover = recipe.photos.find((p) => p.isCover) ?? recipe.photos[0];
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const activeDietaryTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v)
.map(([k]) => DIETARY_LABELS[k])
.filter(Boolean);
const VisibilityIcon = VISIBILITY_ICON[recipe.visibility];
return (
<div className="max-w-4xl mx-auto space-y-8">
{/* Header */}
<div className="space-y-4">
<h1 className="text-3xl font-bold tracking-tight">{recipe.title}</h1>
<div className="flex items-center gap-2 overflow-x-auto pb-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
<FavoriteButton recipeId={id} initialFavorited={isFavorited} />
<MealPairingButton recipeId={id} />
<DrinkPairingButton recipeId={id} />
{recipe.visibility === "public" && (
<Link href={`/r/${id}`} target="_blank" className={cn(buttonVariants({ variant: "ghost", size: "sm" }))}>
<ExternalLink className="h-4 w-4" />
</Link>
)}
{recipe.ingredients.length > 0 && (
<AddToShoppingListButton
recipeId={id}
recipeTitle={recipe.title}
baseServings={recipe.baseServings}
ingredients={recipe.ingredients.map((ing) => ({
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
}))}
/>
)}
<TranslateButton recipeId={id} />
{recipe.ingredients.length > 0 && (
<AdaptRecipeButton
recipeId={id}
ingredients={recipe.ingredients.map((ing) => ({ rawName: ing.rawName }))}
/>
)}
<VariationsButton
recipeId={id}
baseServings={recipe.baseServings}
difficulty={recipe.difficulty}
prepMins={recipe.prepMins}
cookMins={recipe.cookMins}
ingredients={recipe.ingredients.map((ing) => ({
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
note: ing.note,
order: ing.order,
}))}
steps={recipe.steps.map((s) => ({
instruction: s.instruction,
timerSeconds: s.timerSeconds,
order: s.order,
}))}
/>
{recipe.steps.length > 0 && (
<Link href={`/recipes/${id}/cook`} className={cn(buttonVariants({ variant: "default", size: "sm" }))}>
<Play className="h-4 w-4" />
Cook
</Link>
)}
<PrintButton recipeId={id} />
<VersionHistoryButton recipeId={id} />
<Link href={`/recipes/${id}/edit`} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}>
<Pencil className="h-4 w-4" />
Edit
</Link>
<DeleteRecipeButton recipeId={id} />
</div>
{avgScore !== null && (
<div className="flex items-center gap-2">
<RatingStars recipeId={id} initialScore={Math.round(avgScore)} readonly size="sm" />
<span className="text-sm text-muted-foreground">{avgScore.toFixed(1)} ({ratingCount})</span>
</div>
)}
{recipe.description && (
<p className="text-muted-foreground leading-relaxed">{recipe.description}</p>
)}
<div className="flex flex-wrap items-center gap-3 text-sm">
{recipe.difficulty && (
<Badge variant={DIFFICULTY_COLOR[recipe.difficulty]}>{recipe.difficulty}</Badge>
)}
<span className="flex items-center gap-1 text-muted-foreground">
<Users className="h-4 w-4" />
{recipe.baseServings} servings
</span>
{recipe.prepMins && (
<span className="flex items-center gap-1 text-muted-foreground">
<Clock className="h-4 w-4" />
{recipe.prepMins}m prep
</span>
)}
{recipe.cookMins && (
<span className="flex items-center gap-1 text-muted-foreground">
<ChefHat className="h-4 w-4" />
{recipe.cookMins}m cook
</span>
)}
{totalMins > 0 && recipe.prepMins && recipe.cookMins && (
<span className="text-muted-foreground">({totalMins}m total)</span>
)}
<span className="flex items-center gap-1 text-muted-foreground ml-auto">
<VisibilityIcon className="h-4 w-4" />
{VISIBILITY_LABEL[recipe.visibility]}
</span>
</div>
{activeDietaryTags.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{activeDietaryTags.map((tag) => (
<Badge key={tag} variant="secondary" className="text-xs">{tag}</Badge>
))}
</div>
)}
</div>
{/* Cover photo */}
{cover && (
<div className="aspect-video overflow-hidden rounded-xl bg-muted">
<img
src={getPublicUrl(cover.storageKey)}
alt={recipe.title}
className="w-full h-full object-cover"
/>
</div>
)}
<Separator />
{/* Serving scaler + ingredients */}
{recipe.ingredients.length > 0 && (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Ingredients</h2>
<ServingScaler
baseServings={recipe.baseServings}
recipeTitle={recipe.title}
ingredients={recipe.ingredients.map((ing) => ({
id: ing.id,
rawName: ing.rawName,
quantity: ing.quantity,
unit: ing.unit,
note: ing.note,
order: ing.order,
}))}
/>
<NutritionPanel recipeId={id} initialData={recipe.nutritionData} />
</div>
)}
{recipe.steps.length > 0 && (
<>
<Separator />
<div className="space-y-6">
<h2 className="text-xl font-semibold">Instructions</h2>
<ol className="space-y-6">
{recipe.steps.map((step, i) => (
<li key={step.id} className="flex gap-4">
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-bold">
{i + 1}
</div>
<div className="flex-1 space-y-1 pt-1">
<p className="leading-relaxed">{step.instruction}</p>
{step.timerSeconds && (
<p className="text-xs text-muted-foreground flex items-center gap-1">
<Clock className="h-3 w-3" />
{step.timerSeconds >= 60
? `${Math.floor(step.timerSeconds / 60)}m ${step.timerSeconds % 60 > 0 ? `${step.timerSeconds % 60}s` : ""}`
: `${step.timerSeconds}s`}
</p>
)}
</div>
</li>
))}
</ol>
</div>
</>
)}
{recipe.photos.length > 1 && (
<>
<Separator />
<div className="space-y-3">
<h2 className="text-xl font-semibold">Photos</h2>
<div className="grid grid-cols-3 gap-3">
{recipe.photos.map((photo) => (
<div key={photo.id} className="aspect-square rounded-lg overflow-hidden bg-muted">
<img src={getPublicUrl(photo.storageKey)} alt="" className="w-full h-full object-cover" />
</div>
))}
</div>
</div>
</>
)}
{recipe.visibility !== "private" && (
<>
<Separator />
<div className="space-y-4">
<RatingStars recipeId={id} initialScore={0} />
</div>
<Separator />
<CommentsSection recipeId={id} currentUserId={session.user.id} />
</>
)}
</div>
);
}
@@ -0,0 +1,142 @@
import { notFound } from "next/navigation";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, eq, and } from "@epicure/db";
import { PrintTrigger } from "@/components/recipe/print-trigger";
type Params = { params: Promise<{ id: string }> };
export default async function RecipePrintPage({ params }: Params) {
const { id } = await params;
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const recipe = await db.query.recipes.findFirst({
where: and(eq(recipes.id, id), eq(recipes.authorId, session.user.id)),
with: {
ingredients: { orderBy: (t, { asc }) => asc(t.order) },
steps: { orderBy: (t, { asc }) => asc(t.order) },
},
});
if (!recipe) notFound();
const totalMins = (recipe.prepMins ?? 0) + (recipe.cookMins ?? 0);
const DIETARY_LABELS: Record<string, string> = {
vegan: "Vegan",
vegetarian: "Vegetarian",
glutenFree: "Gluten-free",
dairyFree: "Dairy-free",
nutFree: "Nut-free",
halal: "Halal",
kosher: "Kosher",
};
const activeTags = Object.entries(recipe.dietaryTags ?? {})
.filter(([, v]) => v)
.map(([k]) => DIETARY_LABELS[k])
.filter(Boolean);
return (
<>
<style>{`
@media print {
body { margin: 0; }
.no-print { display: none !important; }
}
body {
font-family: Georgia, 'Times New Roman', serif;
color: #1a1a1a;
max-width: 680px;
margin: 40px auto;
padding: 0 24px;
font-size: 14px;
line-height: 1.6;
}
h1 { font-size: 2em; margin: 0 0 8px; line-height: 1.2; }
h2 { font-size: 1.1em; text-transform: uppercase; letter-spacing: 0.08em; border-bottom: 1px solid #ccc; padding-bottom: 4px; margin: 24px 0 12px; }
.meta { display: flex; gap: 24px; font-size: 0.85em; color: #555; margin: 12px 0 16px; flex-wrap: wrap; }
.meta span { display: flex; align-items: center; gap: 4px; }
.tags { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 16px; }
.tag { border: 1px solid #ccc; border-radius: 4px; padding: 1px 8px; font-size: 0.8em; font-family: system-ui, sans-serif; }
.description { color: #444; font-style: italic; margin-bottom: 16px; }
ul.ingredients { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 4px 24px; }
ul.ingredients li { padding: 4px 0; border-bottom: 1px dotted #e0e0e0; font-family: system-ui, sans-serif; font-size: 0.9em; }
ul.ingredients li .qty { color: #666; min-width: 60px; display: inline-block; }
ol.steps { padding-left: 20px; margin: 0; }
ol.steps li { padding: 6px 0 6px 4px; border-bottom: 1px dotted #e0e0e0; font-size: 0.95em; }
ol.steps li:last-child { border-bottom: none; }
.timer { font-size: 0.85em; color: #666; font-family: system-ui, sans-serif; margin-left: 8px; }
footer { margin-top: 40px; font-size: 0.75em; color: #aaa; text-align: center; font-family: system-ui, sans-serif; }
.print-btn {
position: fixed; top: 16px; right: 16px; padding: 8px 16px;
background: #18181b; color: white; border: none; border-radius: 6px;
cursor: pointer; font-size: 13px; font-family: system-ui, sans-serif;
}
.print-btn:hover { background: #3f3f46; }
`}</style>
<PrintTrigger />
<article>
<h1>{recipe.title}</h1>
{recipe.description && (
<p className="description">{recipe.description}</p>
)}
<div className="meta">
{recipe.baseServings && <span>Serves {recipe.baseServings}</span>}
{recipe.prepMins && <span>Prep {recipe.prepMins} min</span>}
{recipe.cookMins && <span>Cook {recipe.cookMins} min</span>}
{totalMins > 0 && <span>Total {totalMins} min</span>}
{recipe.difficulty && <span>{recipe.difficulty.charAt(0).toUpperCase() + recipe.difficulty.slice(1)}</span>}
</div>
{activeTags.length > 0 && (
<div className="tags">
{activeTags.map((tag) => (
<span key={tag} className="tag">{tag}</span>
))}
</div>
)}
{recipe.ingredients.length > 0 && (
<>
<h2>Ingredients</h2>
<ul className="ingredients">
{recipe.ingredients.map((ing) => (
<li key={ing.id}>
<span className="qty">
{[ing.quantity, ing.unit].filter(Boolean).join(" ")}
</span>
{ing.rawName}
{ing.note && <span style={{ color: "#888" }}> ({ing.note})</span>}
</li>
))}
</ul>
</>
)}
{recipe.steps.length > 0 && (
<>
<h2>Instructions</h2>
<ol className="steps">
{recipe.steps.map((step) => (
<li key={step.id}>
{step.instruction}
{step.timerSeconds && (
<span className="timer"> {Math.floor(step.timerSeconds / 60)} min</span>
)}
</li>
))}
</ol>
</>
)}
</article>
<footer>Printed from Epicure</footer>
</>
);
}
@@ -0,0 +1,58 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, pantryItems } from "@epicure/db";
import { eq } from "@epicure/db";
import { getPublicUrl } from "@/lib/storage";
import { CanCookContent } from "@/components/recipe/can-cook-content";
export const metadata: Metadata = { title: "What can I cook?" };
export default async function CanCookPage() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const [userRecipes, pantry] = await Promise.all([
db.query.recipes.findMany({
where: eq(recipes.authorId, session.user.id),
with: {
ingredients: true,
photos: true,
},
}),
db.query.pantryItems.findMany({
where: eq(pantryItems.userId, session.user.id),
}),
]);
const pantryKeys = new Set(pantry.map((p) => p.rawName.toLowerCase()));
const scored = userRecipes
.filter((r) => r.ingredients.length > 0)
.map((recipe) => {
const matched = recipe.ingredients.filter((ing) =>
pantryKeys.has(ing.rawName.toLowerCase())
).length;
const missing = recipe.ingredients
.filter((ing) => !pantryKeys.has(ing.rawName.toLowerCase()))
.map((ing) => ing.rawName)
.slice(0, 5);
const total = recipe.ingredients.length;
const cover = recipe.photos?.find((p) => p.isCover) ?? recipe.photos?.[0];
return {
recipe: {
id: recipe.id,
title: recipe.title,
description: recipe.description,
photos: cover ? [{ url: getPublicUrl(cover.storageKey) }] : [],
},
matched,
total,
pct: Math.round((matched / total) * 100),
missing,
};
})
.sort((a, b) => b.pct - a.pct);
return <CanCookContent pantryCount={pantry.length} scored={scored} />;
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { RecipeForm } from "@/components/recipe/recipe-form";
import { NewRecipeHeader } from "@/components/recipe/new-recipe-header";
import { PhotoImportButton } from "@/components/recipe/photo-import-button";
export const metadata: Metadata = { title: "New Recipe" };
export default function NewRecipePage() {
return (
<div className="space-y-6">
<div className="flex items-start justify-between gap-4">
<NewRecipeHeader />
<PhotoImportButton />
</div>
<RecipeForm />
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, recipes, recipeIngredients } from "@epicure/db";
import { eq, desc, and, ilike, or, sql } 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";
export const metadata: Metadata = { title: "Recipes" };
type SearchParams = Promise<{ q?: string }>;
export default async function RecipesPage({ searchParams }: { searchParams: SearchParams }) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) return null;
const { q } = await searchParams;
const query = q?.trim() ?? "";
const whereClause = query
? and(
eq(recipes.authorId, session.user.id),
or(
ilike(recipes.title, `%${query}%`),
ilike(recipes.description, `%${query}%`)
)
)
: eq(recipes.authorId, session.user.id);
const userRecipes = await db.query.recipes.findMany({
where: whereClause,
orderBy: desc(recipes.updatedAt),
with: { photos: true },
});
const totalCount = query ? undefined : userRecipes.length;
return (
<div className="space-y-6">
<RecipesHeader count={totalCount ?? userRecipes.length} initialQuery={query} />
<RecipesEmptyState query={query} count={userRecipes.length} />
<RecipesGrid recipes={userRecipes} />
</div>
);
}