002f14ced0
Shopping list add already worked generically for batch-cook recipes — no code needed there. New: mark a specific batch-cook dish as "cooked today", track its fridge expiry (cookingHistory.batchDishId), surface a "Leftovers expiring soon" widget on the pantry page, and send a daily push+email reminder via a new /api/internal/cron/leftover-reminders endpoint (mirrors the weekly-digest cron pattern; doesn't use the social notifications table, which requires a non-null actor and isn't built for self-reminders). Also fixes, from user-reported bugs: - Recipe cards showed no batch-cook badge/dish-count/prep-time in some views — added dishCount + prepMins/cookMins (now generated by the AI and persisted) to the card component and /recipes query. - Batch-cook descriptions occasionally contained raw markdown (**bold**) — added explicit "plain prose only" prompt instructions and a stripMarkdown() defensive fallback at render time. - Truncated/cut-off descriptions — the generateObject call had no maxOutputTokens set, so long structured responses could get cut off mid-field; now capped explicitly at 8000. - Generate dialogs (batch-cook + the main AI dialog) could show buttons unreachable once the progress bar appeared mid-generation — restructured so the action row is pinned outside the scrollable content area, not affected by content height changes. - /api/internal/* routes were being redirected to /login by middleware before their own CRON_SECRET check ever ran (pre-existing bug, affected the weekly-digest cron too) — added to PUBLIC_PATHS. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
399 lines
14 KiB
TypeScript
399 lines
14 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useRef } from "react";
|
|
import Image from "next/image";
|
|
import { useTranslations } from "next-intl";
|
|
import { useRouter } from "next/navigation";
|
|
import { Sparkles, Loader2, Camera, Type, Upload, X, Shuffle, ChefHat } from "lucide-react";
|
|
import { toast } from "sonner";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogDescription,
|
|
} from "@/components/ui/dialog";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
|
import { cn } from "@/lib/utils";
|
|
import { FakeProgressBar } from "@/components/ui/fake-progress-bar";
|
|
import { useLocale } from "@/lib/i18n/provider";
|
|
import { BatchCookFields, type BatchCookFieldsState } from "./batch-cook-fields";
|
|
|
|
const LANGUAGES = [
|
|
{ code: "en", label: "English" },
|
|
{ code: "fr", label: "French" },
|
|
{ code: "es", label: "Spanish" },
|
|
{ code: "de", label: "German" },
|
|
{ code: "it", label: "Italian" },
|
|
{ code: "pt", label: "Portuguese" },
|
|
{ code: "ja", label: "Japanese" },
|
|
{ code: "zh", label: "Chinese" },
|
|
{ code: "ar", label: "Arabic" },
|
|
];
|
|
|
|
const SURPRISE_PROMPTS = [
|
|
"A cozy one-pot dish with whatever is in my pantry on a rainy evening",
|
|
"A vibrant street food recipe from Southeast Asia",
|
|
"A classic French bistro dish reimagined as a weeknight dinner",
|
|
"A hearty plant-based bowl with bold spices",
|
|
"A 5-ingredient pasta with pantry staples",
|
|
"An unexpected fusion of Japanese and Mexican flavors",
|
|
"A light summer salad with fresh herbs and a citrus dressing",
|
|
"A slow-cooked braise that fills the house with aroma",
|
|
"A festive appetizer that looks impressive but is easy to make",
|
|
"A warming spiced soup from the Middle East",
|
|
"A crowd-pleasing comfort food with a twist",
|
|
"A 20-minute weeknight dinner using chicken thighs",
|
|
"A rich chocolate dessert with a molten center",
|
|
"A crispy baked dish that tastes deep-fried",
|
|
"A refreshing no-cook meal for hot summer days",
|
|
];
|
|
|
|
type Tab = "describe" | "photo" | "batch";
|
|
|
|
type GeneratedRecipe = {
|
|
title: string;
|
|
description?: string;
|
|
baseServings?: number;
|
|
prepMins?: number;
|
|
cookMins?: number;
|
|
difficulty?: "easy" | "medium" | "hard";
|
|
dietaryTags?: Record<string, boolean>;
|
|
ingredients: Array<{ rawName: string; quantity?: string; unit?: string; note?: string }>;
|
|
steps: Array<{ instruction: string; timerSeconds?: number }>;
|
|
};
|
|
|
|
export function AiGenerateDialog({
|
|
open,
|
|
onOpenChange,
|
|
}: {
|
|
open: boolean;
|
|
onOpenChange: (open: boolean) => void;
|
|
}) {
|
|
const t = useTranslations("ai.generate");
|
|
const tCommon = useTranslations("common");
|
|
const tRecipe = useTranslations("recipe");
|
|
const tBatch = useTranslations("batchCooking");
|
|
const router = useRouter();
|
|
const { locale } = useLocale();
|
|
const [tab, setTab] = useState<Tab>("describe");
|
|
|
|
// describe tab
|
|
const [prompt, setPrompt] = useState("");
|
|
const [language, setLanguage] = useState(locale);
|
|
const [difficulty, setDifficulty] = useState<"" | "easy" | "medium" | "hard">("");
|
|
|
|
// photo tab
|
|
const [photoPreview, setPhotoPreview] = useState<string | null>(null);
|
|
const [photoBase64, setPhotoBase64] = useState<string | null>(null);
|
|
const [photoMime, setPhotoMime] = useState<string>("image/jpeg");
|
|
const fileRef = useRef<HTMLInputElement>(null);
|
|
|
|
// batch tab
|
|
const [batchFields, setBatchFields] = useState<BatchCookFieldsState>({
|
|
dinners: 4,
|
|
lunches: 0,
|
|
servings: 4,
|
|
difficulty: "",
|
|
dietaryPrefs: "",
|
|
});
|
|
|
|
const [busy, setBusy] = useState(false);
|
|
|
|
function handleClose() {
|
|
if (busy) return;
|
|
onOpenChange(false);
|
|
setTimeout(() => {
|
|
setPrompt("");
|
|
setPhotoPreview(null);
|
|
setPhotoBase64(null);
|
|
setBatchFields({ dinners: 4, lunches: 0, servings: 4, difficulty: "", dietaryPrefs: "" });
|
|
setTab("describe");
|
|
}, 200);
|
|
}
|
|
|
|
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
|
const file = e.target.files?.[0];
|
|
if (!file) return;
|
|
setPhotoMime(file.type);
|
|
const reader = new FileReader();
|
|
reader.onload = (ev) => {
|
|
const dataUrl = ev.target?.result as string;
|
|
setPhotoPreview(dataUrl);
|
|
// strip the data:mime;base64, prefix
|
|
setPhotoBase64(dataUrl.split(",")[1] ?? null);
|
|
};
|
|
reader.readAsDataURL(file);
|
|
e.target.value = "";
|
|
}
|
|
|
|
async function handleDescribeGenerate() {
|
|
if (!prompt.trim()) return;
|
|
setBusy(true);
|
|
try {
|
|
const res = await fetch("/api/v1/ai/generate", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ prompt: prompt.trim(), language, difficulty: difficulty || undefined }),
|
|
});
|
|
if (!res.ok) {
|
|
const err = await res.json() as { error?: string };
|
|
toast.error(err.error ?? t("error"));
|
|
return;
|
|
}
|
|
const generated = await res.json() as GeneratedRecipe;
|
|
const saveRes = await fetch("/api/v1/recipes", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ ...generated, visibility: "private", aiGenerated: true, language }),
|
|
});
|
|
if (!saveRes.ok) { toast.error(t("saveError")); return; }
|
|
const saved = await saveRes.json() as { id: string };
|
|
toast.success(t("success"));
|
|
handleClose();
|
|
router.push(`/recipes/${saved.id}/edit`);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
async function handlePhotoGenerate() {
|
|
if (!photoBase64) return;
|
|
setBusy(true);
|
|
try {
|
|
const res = await fetch("/api/v1/ai/import-photo", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ imageBase64: photoBase64, mimeType: photoMime }),
|
|
});
|
|
if (!res.ok) {
|
|
let msg = t("photoError");
|
|
try { msg = ((await res.json()) as { error?: string }).error ?? msg; } catch { /* non-JSON body */ }
|
|
toast.error(msg);
|
|
return;
|
|
}
|
|
const { id } = await res.json() as { id: string };
|
|
toast.success(t("photoSuccess"));
|
|
handleClose();
|
|
router.push(`/recipes/${id}/edit`);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
async function handleBatchGenerate() {
|
|
setBusy(true);
|
|
try {
|
|
const res = await fetch("/api/v1/ai/batch-cook/generate", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
dinners: batchFields.dinners,
|
|
lunches: batchFields.lunches,
|
|
servings: batchFields.servings,
|
|
dietaryPrefs: batchFields.dietaryPrefs.trim() || undefined,
|
|
difficulty: batchFields.difficulty || undefined,
|
|
}),
|
|
});
|
|
if (!res.ok) {
|
|
const err = await res.json() as { error?: string };
|
|
toast.error(err.error ?? tBatch("generateFailed"));
|
|
return;
|
|
}
|
|
const { id } = await res.json() as { id: string };
|
|
toast.success(tBatch("generateSuccess"));
|
|
handleClose();
|
|
router.push(`/recipes/${id}`);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
const canSubmit = tab === "describe" ? !!prompt.trim() : tab === "photo" ? !!photoBase64 : batchFields.dinners + batchFields.lunches > 0;
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={handleClose}>
|
|
<DialogContent className="max-w-xl max-h-[85vh] flex flex-col gap-0 p-0">
|
|
<div className="overflow-y-auto p-4 space-y-4 min-h-0">
|
|
<DialogHeader>
|
|
<DialogTitle className="flex items-center gap-2">
|
|
<Sparkles className="h-5 w-5 text-primary" />
|
|
{t("title")}
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
{t("descriptionFull")}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{/* Tab switcher */}
|
|
<div className="flex gap-1 p-1 bg-muted rounded-lg">
|
|
{([
|
|
{ key: "describe", label: t("tabDescribe"), icon: Type },
|
|
{ key: "photo", label: t("tabPhoto"), icon: Camera },
|
|
{ key: "batch", label: tBatch("title"), icon: ChefHat },
|
|
] as { key: Tab; label: string; icon: React.ElementType }[]).map(({ key, label, icon: Icon }) => (
|
|
<button
|
|
key={key}
|
|
onClick={() => setTab(key)}
|
|
disabled={busy}
|
|
className={cn(
|
|
"flex-1 flex items-center justify-center gap-2 py-2 px-3 rounded-md text-sm font-medium transition-all",
|
|
tab === key
|
|
? "bg-background shadow-sm text-foreground"
|
|
: "text-muted-foreground hover:text-foreground"
|
|
)}
|
|
>
|
|
<Icon className="h-4 w-4" />
|
|
{label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
|
|
{/* Describe tab */}
|
|
{tab === "describe" && (
|
|
<div className="space-y-4">
|
|
<div className="space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<Label htmlFor="ai-prompt">{t("prompt")}</Label>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const idx = Math.floor(Math.random() * SURPRISE_PROMPTS.length);
|
|
setPrompt(SURPRISE_PROMPTS[idx]!);
|
|
}}
|
|
disabled={busy}
|
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-primary transition-colors disabled:opacity-50"
|
|
>
|
|
<Shuffle className="h-3 w-3" />
|
|
{t("surpriseMe")}
|
|
</button>
|
|
</div>
|
|
<Textarea
|
|
id="ai-prompt"
|
|
value={prompt}
|
|
onChange={(e) => setPrompt(e.target.value)}
|
|
placeholder={t("placeholder")}
|
|
rows={4}
|
|
disabled={busy}
|
|
/>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div className="space-y-2">
|
|
<Label>{t("language")}</Label>
|
|
<Select value={language} onValueChange={(v) => v && setLanguage(v)} disabled={busy}>
|
|
<SelectTrigger>
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
{LANGUAGES.map((l) => (
|
|
<SelectItem key={l.code} value={l.code}>{l.label}</SelectItem>
|
|
))}
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
<div className="space-y-2">
|
|
<Label>{t("difficulty")}</Label>
|
|
<Select value={difficulty} onValueChange={(v) => setDifficulty(v as typeof difficulty)} disabled={busy}>
|
|
<SelectTrigger>
|
|
<SelectValue placeholder={t("anyDifficulty")} />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="">{t("anyDifficulty")}</SelectItem>
|
|
<SelectItem value="easy">{tRecipe("difficulty.easy")}</SelectItem>
|
|
<SelectItem value="medium">{tRecipe("difficulty.medium")}</SelectItem>
|
|
<SelectItem value="hard">{tRecipe("difficulty.hard")}</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Photo tab */}
|
|
{tab === "photo" && (
|
|
<div className="space-y-3">
|
|
<input
|
|
ref={fileRef}
|
|
type="file"
|
|
accept="image/jpeg,image/png,image/webp"
|
|
className="hidden"
|
|
onChange={handleFileChange}
|
|
/>
|
|
{photoPreview ? (
|
|
<div className="relative rounded-xl overflow-hidden border bg-muted aspect-video">
|
|
<Image
|
|
src={photoPreview}
|
|
alt="Preview of uploaded dish photo for AI recipe generation"
|
|
fill
|
|
className="object-cover"
|
|
/>
|
|
<button
|
|
onClick={() => { setPhotoPreview(null); setPhotoBase64(null); }}
|
|
className="absolute top-2 right-2 h-7 w-7 rounded-full bg-black/60 flex items-center justify-center text-white hover:bg-black/80 transition-colors"
|
|
disabled={busy}
|
|
>
|
|
<X className="h-4 w-4" />
|
|
</button>
|
|
</div>
|
|
) : (
|
|
<button
|
|
onClick={() => fileRef.current?.click()}
|
|
disabled={busy}
|
|
className="w-full border-2 border-dashed rounded-xl p-10 flex flex-col items-center gap-3 text-muted-foreground hover:border-primary/50 hover:text-foreground transition-colors"
|
|
>
|
|
<Upload className="h-8 w-8" />
|
|
<div className="text-sm text-center">
|
|
<span className="font-medium text-foreground">{t("uploadClick")}</span> {t("uploadDrag")}
|
|
<p className="text-xs mt-1">{t("uploadFormats")}</p>
|
|
</div>
|
|
</button>
|
|
)}
|
|
{photoPreview && (
|
|
<p className="text-xs text-muted-foreground text-center">
|
|
{t("photoAnalysisNote")}
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Batch cooking tab */}
|
|
{tab === "batch" && (
|
|
<BatchCookFields state={batchFields} onChange={setBatchFields} disabled={busy} />
|
|
)}
|
|
|
|
<div className="min-h-[26px]">
|
|
<FakeProgressBar
|
|
active={busy}
|
|
durationMs={tab === "photo" ? 12000 : tab === "batch" ? 20000 : 10000}
|
|
label={busy ? (tab === "photo" ? t("analyzePhoto") : tab === "batch" ? tBatch("generating") : t("generating")) : undefined}
|
|
/>
|
|
</div>
|
|
</div>
|
|
{/* Actions */}
|
|
<div className="flex gap-2 justify-end p-4 border-t shrink-0">
|
|
<Button variant="ghost" onClick={handleClose} disabled={busy}>
|
|
{tCommon("cancel")}
|
|
</Button>
|
|
<Button
|
|
onClick={
|
|
tab === "describe" ? () => { void handleDescribeGenerate(); }
|
|
: tab === "photo" ? () => { void handlePhotoGenerate(); }
|
|
: () => { void handleBatchGenerate(); }
|
|
}
|
|
disabled={!canSubmit || busy}
|
|
>
|
|
{busy ? (
|
|
<><Loader2 className="h-4 w-4 animate-spin" />{tab === "batch" ? tBatch("generating") : t("analyzing")}</>
|
|
) : (
|
|
<><Sparkles className="h-4 w-4" />{tab === "photo" ? t("recognizeDish") : tab === "batch" ? tBatch("generate") : t("button")}</>
|
|
)}
|
|
</Button>
|
|
</div>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|