feat: add "cooked it" photo reviews
Users can rate a recipe with review text and an optional photo. Adds ratings.photo_key column, a reviews list endpoint, and a review-purpose presign path (reviewer isn't the recipe owner, so the upload authorization differs from cover-photo uploads). Also fixes CSP connect-src/img-src to allow the storage origin — direct-to-S3/MinIO presigned uploads and stored images were silently blocked by Content-Security-Policy in the browser. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -26,6 +26,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/comp
|
||||
import { ServingScaler } from "@/components/recipe/serving-scaler";
|
||||
import { FavoriteButton } from "@/components/social/favorite-button";
|
||||
import { RatingStars } from "@/components/social/rating-stars";
|
||||
import { CookedItReview } from "@/components/social/cooked-it-review";
|
||||
import { CommentsSection } from "@/components/social/comments-section";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -386,7 +387,16 @@ export default async function RecipePage({ params }: Params) {
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-4">
|
||||
<RatingStars recipeId={id} initialScore={myScore} />
|
||||
{isOwner ? (
|
||||
<RatingStars recipeId={id} initialScore={myScore} readonly />
|
||||
) : (
|
||||
<CookedItReview
|
||||
recipeId={id}
|
||||
initialScore={myScore}
|
||||
initialText={myRating?.reviewText ?? ""}
|
||||
initialPhotoKey={myRating?.photoKey ?? null}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<Separator />
|
||||
<CommentsSection recipeId={id} currentUserId={session.user.id} />
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createNotification } from "@/lib/notifications";
|
||||
const Schema = z.object({
|
||||
score: z.number().int().min(1).max(5),
|
||||
reviewText: z.string().max(2000).optional(),
|
||||
photoKey: z.string().max(500).optional(),
|
||||
});
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
@@ -34,7 +35,12 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
|
||||
if (existing) {
|
||||
await db.update(ratings)
|
||||
.set({ score: parsed.data.score, reviewText: parsed.data.reviewText, updatedAt: new Date() })
|
||||
.set({
|
||||
score: parsed.data.score,
|
||||
reviewText: parsed.data.reviewText,
|
||||
photoKey: parsed.data.photoKey,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(ratings.id, existing.id));
|
||||
return NextResponse.json({ updated: true });
|
||||
}
|
||||
@@ -45,6 +51,7 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
userId: session!.user.id,
|
||||
score: parsed.data.score,
|
||||
reviewText: parsed.data.reviewText,
|
||||
photoKey: parsed.data.photoKey,
|
||||
});
|
||||
void createNotification({ userId: recipe.authorId, type: "rating", actorId: session!.user.id, recipeId: id });
|
||||
return NextResponse.json({ created: true }, { status: 201 });
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, recipes, ratings, eq, and, or, inArray, desc } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function GET(_req: NextRequest, { params }: Params) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
const { id } = await params;
|
||||
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: and(
|
||||
eq(recipes.id, id),
|
||||
or(eq(recipes.authorId, session!.user.id), inArray(recipes.visibility, ["public", "unlisted"]))
|
||||
),
|
||||
columns: { id: true },
|
||||
});
|
||||
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const rows = await db.query.ratings.findMany({
|
||||
where: eq(ratings.recipeId, id),
|
||||
orderBy: desc(ratings.createdAt),
|
||||
limit: 50,
|
||||
with: {
|
||||
user: { columns: { id: true, name: true, username: true, avatarUrl: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const reviews = rows
|
||||
.filter((r) => r.reviewText || r.photoKey)
|
||||
.map((r) => ({
|
||||
id: r.id,
|
||||
score: r.score,
|
||||
reviewText: r.reviewText,
|
||||
photoKey: r.photoKey,
|
||||
createdAt: r.createdAt,
|
||||
user: r.user,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ data: reviews });
|
||||
}
|
||||
@@ -12,6 +12,7 @@ const Schema = z.object({
|
||||
message: "Content type must be jpeg, png, webp, or avif",
|
||||
}),
|
||||
recipeId: z.string().uuid(),
|
||||
purpose: z.enum(["recipe", "review"]).default("recipe"),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
@@ -24,15 +25,22 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const owned = await db.query.recipes.findFirst({
|
||||
where: and(eq(recipes.id, parsed.data.recipeId), eq(recipes.authorId, session!.user.id)),
|
||||
columns: { id: true },
|
||||
const { recipeId, contentType, purpose } = parsed.data;
|
||||
const recipe = await db.query.recipes.findFirst({
|
||||
where: purpose === "recipe"
|
||||
? and(eq(recipes.id, recipeId), eq(recipes.authorId, session!.user.id))
|
||||
: eq(recipes.id, recipeId),
|
||||
columns: { id: true, visibility: true, authorId: true },
|
||||
});
|
||||
if (!owned) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
if (purpose === "review" && recipe.visibility === "private" && recipe.authorId !== session!.user.id) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const ext = parsed.data.contentType.split("/")[1] ?? "jpg";
|
||||
const key = `recipes/${parsed.data.recipeId}/photos/${session!.user.id}-${crypto.randomUUID()}.${ext}`;
|
||||
const url = await createPresignedUploadUrl(key, parsed.data.contentType);
|
||||
const ext = contentType.split("/")[1] ?? "jpg";
|
||||
const folder = purpose === "review" ? "reviews" : "photos";
|
||||
const key = `recipes/${recipeId}/${folder}/${session!.user.id}-${crypto.randomUUID()}.${ext}`;
|
||||
const url = await createPresignedUploadUrl(key, contentType);
|
||||
|
||||
return NextResponse.json({ url, key });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useTranslations, useLocale } from "next-intl";
|
||||
import { Star, Camera, X, ChefHat } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Review = {
|
||||
id: string;
|
||||
score: number;
|
||||
reviewText: string | null;
|
||||
photoKey: string | null;
|
||||
createdAt: string;
|
||||
user: { id: string; name: string; username: string | null; avatarUrl: string | null };
|
||||
};
|
||||
|
||||
function Stars({
|
||||
value,
|
||||
hovered,
|
||||
onHover,
|
||||
onPick,
|
||||
}: {
|
||||
value: number;
|
||||
hovered: number;
|
||||
onHover: (v: number) => void;
|
||||
onPick: (v: number) => void;
|
||||
}) {
|
||||
const display = hovered || value;
|
||||
return (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<button
|
||||
key={i}
|
||||
type="button"
|
||||
onMouseEnter={() => onHover(i)}
|
||||
onMouseLeave={() => onHover(0)}
|
||||
onClick={() => onPick(i)}
|
||||
className="hover:scale-110 transition-transform"
|
||||
>
|
||||
<Star className={cn("h-6 w-6", i <= display ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground/30")} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CookedItReview({
|
||||
recipeId,
|
||||
initialScore = 0,
|
||||
initialText = "",
|
||||
initialPhotoKey = null,
|
||||
}: {
|
||||
recipeId: string;
|
||||
initialScore?: number;
|
||||
initialText?: string;
|
||||
initialPhotoKey?: string | null;
|
||||
}) {
|
||||
const t = useTranslations("social");
|
||||
const locale = useLocale();
|
||||
const [score, setScore] = useState(initialScore);
|
||||
const [hovered, setHovered] = useState(0);
|
||||
const [text, setText] = useState(initialText);
|
||||
const [photoKey, setPhotoKey] = useState<string | null>(initialPhotoKey);
|
||||
const [preview, setPreview] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [reviews, setReviews] = useState<Review[]>([]);
|
||||
const [loadingReviews, setLoadingReviews] = useState(true);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`/api/v1/recipes/${recipeId}/reviews`)
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((data: { data: Review[] } | null) => setReviews(data?.data ?? []))
|
||||
.finally(() => setLoadingReviews(false));
|
||||
}, [recipeId]);
|
||||
|
||||
async function handlePhoto(file: File) {
|
||||
setUploading(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/upload/presign", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ recipeId, contentType: file.type, purpose: "review" }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(t("reviewPhotoFailed"));
|
||||
return;
|
||||
}
|
||||
const { url, key } = (await res.json()) as { url: string; key: string };
|
||||
await fetch(url, { method: "PUT", body: file, headers: { "Content-Type": file.type } });
|
||||
setPhotoKey(key);
|
||||
setPreview(URL.createObjectURL(file));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (score < 1) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const res = await fetch(`/api/v1/recipes/${recipeId}/rate`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ score, reviewText: text.trim() || undefined, photoKey: photoKey ?? undefined }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = (await res.json()) as { error?: string };
|
||||
toast.error(err.error ?? t("ratingFailed"));
|
||||
return;
|
||||
}
|
||||
toast.success(t("ratingSaved"));
|
||||
const listRes = await fetch(`/api/v1/recipes/${recipeId}/reviews`);
|
||||
if (listRes.ok) {
|
||||
const data = (await listRes.json()) as { data: Review[] };
|
||||
setReviews(data.data);
|
||||
}
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-lg border p-4 space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<ChefHat className="h-4 w-4 text-primary" />
|
||||
{t("cookedItPrompt")}
|
||||
</div>
|
||||
<Stars value={score} hovered={hovered} onHover={setHovered} onPick={setScore} />
|
||||
<Textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={t("reviewTextPlaceholder")}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex items-center gap-3">
|
||||
{(preview || photoKey) && (
|
||||
<div className="relative">
|
||||
<img
|
||||
src={preview ?? getPublicUrl(photoKey!)}
|
||||
alt=""
|
||||
className="h-16 w-16 rounded-lg object-cover border"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setPhotoKey(null); setPreview(null); }}
|
||||
className="absolute -top-1.5 -right-1.5 rounded-full bg-background border p-0.5"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={uploading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
>
|
||||
<Camera className="h-4 w-4 mr-1.5" />
|
||||
{uploading ? t("reviewPhotoUploading") : t("reviewPhotoAdd")}
|
||||
</Button>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,image/avif"
|
||||
className="hidden"
|
||||
onChange={(e) => e.target.files?.[0] && handlePhoto(e.target.files[0])}
|
||||
/>
|
||||
<Button type="button" size="sm" className="ml-auto" disabled={score < 1 || saving} onClick={submit}>
|
||||
{saving ? t("reviewSubmitting") : t("reviewSubmit")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!loadingReviews && reviews.length > 0 && (
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">{t("reviewsTitle", { count: reviews.length })}</h3>
|
||||
{reviews.map((r) => (
|
||||
<div key={r.id} className="flex gap-3">
|
||||
<Avatar className="h-8 w-8">
|
||||
<AvatarImage src={r.user.avatarUrl ?? undefined} />
|
||||
<AvatarFallback>{r.user.name.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<span className="font-medium">{r.user.name}</span>
|
||||
<div className="flex items-center">
|
||||
{[1, 2, 3, 4, 5].map((i) => (
|
||||
<Star key={i} className={cn("h-3 w-3", i <= r.score ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground/30")} />
|
||||
))}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(r.createdAt).toLocaleDateString(locale)}
|
||||
</span>
|
||||
</div>
|
||||
{r.reviewText && <p className="text-sm text-muted-foreground">{r.reviewText}</p>}
|
||||
{r.photoKey && (
|
||||
<img
|
||||
src={getPublicUrl(r.photoKey)}
|
||||
alt=""
|
||||
className="h-32 w-32 rounded-lg object-cover border"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -744,6 +744,14 @@
|
||||
"replyButton": "Reply",
|
||||
"reportButton": "Report",
|
||||
"ratingFailed": "Failed to rate",
|
||||
"cookedItPrompt": "Cooked it? Rate it and share a photo",
|
||||
"reviewTextPlaceholder": "How did it turn out?",
|
||||
"reviewPhotoAdd": "Add photo",
|
||||
"reviewPhotoUploading": "Uploading…",
|
||||
"reviewPhotoFailed": "Failed to upload photo",
|
||||
"reviewSubmit": "Post review",
|
||||
"reviewSubmitting": "Posting…",
|
||||
"reviewsTitle": "{count, plural, one {# review} other {# reviews}}",
|
||||
"justNow": "just now",
|
||||
"minutesAgo": "{mins}m ago",
|
||||
"hoursAgo": "{hours}h ago",
|
||||
|
||||
@@ -732,6 +732,14 @@
|
||||
"replyButton": "Répondre",
|
||||
"reportButton": "Signaler",
|
||||
"ratingFailed": "Échec de la notation",
|
||||
"cookedItPrompt": "Vous l'avez cuisiné ? Notez-la et partagez une photo",
|
||||
"reviewTextPlaceholder": "Comment était le résultat ?",
|
||||
"reviewPhotoAdd": "Ajouter une photo",
|
||||
"reviewPhotoUploading": "Envoi…",
|
||||
"reviewPhotoFailed": "Échec de l'envoi de la photo",
|
||||
"reviewSubmit": "Publier l'avis",
|
||||
"reviewSubmitting": "Publication…",
|
||||
"reviewsTitle": "{count, plural, one {# avis} other {# avis}}",
|
||||
"justNow": "à l'instant",
|
||||
"minutesAgo": "il y a {mins} min",
|
||||
"hoursAgo": "il y a {hours} h",
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const storagePublicUrl = process.env["STORAGE_PUBLIC_URL"] ?? "http://localhost:9000";
|
||||
const storageOrigin = new URL(storagePublicUrl).origin;
|
||||
|
||||
const securityHeaders = [
|
||||
{
|
||||
key: "X-Content-Type-Options",
|
||||
@@ -31,9 +34,9 @@ const securityHeaders = [
|
||||
"default-src 'self'",
|
||||
"script-src 'self' 'unsafe-inline' 'unsafe-eval'", // unsafe-eval needed by Next.js dev; tighten in prod
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob:",
|
||||
`img-src 'self' data: blob: ${storageOrigin}`,
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
`connect-src 'self' ${storageOrigin}`,
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "ratings" ADD COLUMN "photo_key" text;--> statement-breakpoint
|
||||
CREATE INDEX "ratings_recipe_idx" ON "ratings" USING btree ("recipe_id");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -148,6 +148,13 @@
|
||||
"when": 1783109825851,
|
||||
"tag": "0020_acoustic_exiles",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 21,
|
||||
"version": "7",
|
||||
"when": 1783602591480,
|
||||
"tag": "0021_mysterious_madame_masque",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -26,10 +26,12 @@ export const ratings = pgTable("ratings", {
|
||||
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||
score: integer("score").notNull(),
|
||||
reviewText: text("review_text"),
|
||||
photoKey: text("photo_key"),
|
||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at").notNull().defaultNow(),
|
||||
}, (t) => [
|
||||
index("ratings_user_idx").on(t.userId),
|
||||
index("ratings_recipe_idx").on(t.recipeId),
|
||||
]);
|
||||
|
||||
export const favorites = pgTable("favorites", {
|
||||
|
||||
Reference in New Issue
Block a user