feat: cooking history/gallery, unit conversion, nutrition diary, pantry scan, digest cron, nutrition-targeted meal plans
Six M-sized items from HANDOFF.md's new-features backlog: - Profile tabs: cooking-history stats (total cooked, last-cooked, streak) and a "cooked it" photo gallery, both owner-only - Display-time unit conversion (metric<->imperial) for recipe ingredients, respecting each user's unitPref; original value always shown alongside the conversion - Nutrition daily diary: per-day macro totals computed from cooking history x recipe nutritionData, compared against user goals - Pantry scan: real barcode lookup (zxing + Open Food Facts, no API key) with an AI-vision fallback for unbarcoded items, always confirm-before- insert, both paths tier/rate-limited like other AI features - Weekly digest email: new followers/comments/ratings + trending recipes, sent via a new `cron` Docker stage (alpine+crond+curl) and `digest-cron` compose service hitting a bearer-token-protected internal route - Meal-plan generation can now target a user's nutrition goals as a prompt-level nudge (recipes are AI-invented, not DB-sourced, so this can't be a hard macro constraint) Caught a real deploy-breaking issue while adding the cron stage: appending it after `runner` silently changed the Dockerfile's default build target, and `web`'s compose config didn't pin one — fixed by pinning `target: runner` explicitly. Verified with typecheck, lint, and three separate `docker build --target` runs (runner/cron/migrator) plus `docker compose config` validation. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,7 +6,7 @@ import { X, ChevronLeft, ChevronRight, List, Mic, MicOff, Play, Square, HelpCirc
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLocale } from "@/lib/i18n/provider";
|
||||
import { hasQuantity } from "@/lib/fractions";
|
||||
import { formatIngredientQuantity, type UnitPref } from "@/lib/unit-conversion";
|
||||
import { useWakeLock } from "@/lib/hooks/use-wake-lock";
|
||||
|
||||
type Step = { id: string; instruction: string; timerSeconds: number | null };
|
||||
@@ -68,11 +68,13 @@ export function CookingMode({
|
||||
recipeTitle,
|
||||
steps,
|
||||
ingredients,
|
||||
unitPref = "metric",
|
||||
}: {
|
||||
recipeId: string;
|
||||
recipeTitle: string;
|
||||
steps: Step[];
|
||||
ingredients: Ingredient[];
|
||||
unitPref?: UnitPref;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const t = useTranslations("cookingMode");
|
||||
@@ -342,7 +344,7 @@ export function CookingMode({
|
||||
{ingredients.map((ing, i) => (
|
||||
<li key={i} className="text-sm flex gap-2">
|
||||
<span className="text-muted-foreground shrink-0 w-16 text-right">
|
||||
{hasQuantity(ing.quantity) ? ing.quantity : ""}{ing.unit ? ` ${ing.unit}` : ""}
|
||||
{formatIngredientQuantity(ing.quantity, ing.unit, unitPref)}
|
||||
</span>
|
||||
<span>{ing.rawName}</span>
|
||||
</li>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useTheme } from "next-themes";
|
||||
import { BookOpen, Calendar, Package, ChefHat, User, Rss, FolderOpen, ShoppingCart, Shield, Search, Compass, Menu, Sun, Moon } from "lucide-react";
|
||||
import { BookOpen, Calendar, Package, ChefHat, User, Rss, FolderOpen, ShoppingCart, Shield, Search, Compass, Menu, Sun, Moon, Apple } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -33,6 +33,7 @@ const NAV_ITEMS = [
|
||||
{ href: "/feed", key: "feed", icon: Rss },
|
||||
{ href: "/collections", key: "collections", icon: FolderOpen },
|
||||
{ href: "/meal-plan", key: "mealPlan", icon: Calendar },
|
||||
{ href: "/nutrition", key: "nutrition", icon: Apple },
|
||||
{ href: "/pantry", key: "pantry", icon: Package },
|
||||
{ href: "/shopping-lists", key: "shopping", icon: ShoppingCart },
|
||||
] as const;
|
||||
|
||||
@@ -117,10 +117,12 @@ export function MealPlanner({
|
||||
weekStart,
|
||||
initialEntries,
|
||||
userRecipes,
|
||||
hasNutritionGoals = false,
|
||||
}: {
|
||||
weekStart: string;
|
||||
initialEntries: Entry[];
|
||||
userRecipes: UserRecipe[];
|
||||
hasNutritionGoals?: boolean;
|
||||
}) {
|
||||
const [entries, setEntries] = useState<Entry[]>(initialEntries);
|
||||
const [adding, setAdding] = useState<{ day: Day; mealType: MealType } | null>(null);
|
||||
@@ -132,6 +134,7 @@ export function MealPlanner({
|
||||
const [usePantry, setUsePantry] = useState(true);
|
||||
const [pantryMode, setPantryMode] = useState(false);
|
||||
const [aiDifficulty, setAiDifficulty] = useState<"" | "easy" | "medium" | "hard">("");
|
||||
const [targetNutritionGoals, setTargetNutritionGoals] = useState(false);
|
||||
const t = useTranslations("mealPlan");
|
||||
const tRecipe = useTranslations("recipe");
|
||||
|
||||
@@ -158,6 +161,7 @@ export function MealPlanner({
|
||||
usePantry,
|
||||
pantryMode,
|
||||
difficulty: aiDifficulty || undefined,
|
||||
targetNutritionGoals: hasNutritionGoals && targetNutritionGoals,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -390,6 +394,21 @@ export function MealPlanner({
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
{hasNutritionGoals && (
|
||||
<label className="flex items-start gap-2 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 mt-0.5"
|
||||
checked={targetNutritionGoals}
|
||||
onChange={(e) => setTargetNutritionGoals(e.target.checked)}
|
||||
disabled={aiGenerating}
|
||||
/>
|
||||
<span className="space-y-0.5">
|
||||
<span className="text-sm font-medium block">{t("targetNutritionGoals")}</span>
|
||||
<span className="text-sm text-muted-foreground block">{t("targetNutritionGoalsDescription")}</span>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<FakeProgressBar active={aiGenerating} durationMs={20000} label={aiPhase} />
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button variant="ghost" onClick={() => setShowAiModal(false)} disabled={aiGenerating}>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Plus, Trash2, AlertTriangle } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { PantryScanDialog } from "@/components/pantry/pantry-scan-dialog";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
@@ -33,6 +35,7 @@ function daysUntilExpiry(dateStr: string): number {
|
||||
export function PantryManager({ initialItems }: { initialItems: PantryItem[] }) {
|
||||
const t = useTranslations("pantry");
|
||||
const tCommon = useTranslations("common");
|
||||
const router = useRouter();
|
||||
const [items, setItems] = useState<PantryItem[]>(initialItems);
|
||||
const [name, setName] = useState("");
|
||||
const [quantity, setQuantity] = useState("");
|
||||
@@ -90,6 +93,7 @@ export function PantryManager({ initialItems }: { initialItems: PantryItem[] })
|
||||
<Button onClick={add} disabled={!name.trim() || adding} size="sm">
|
||||
<Plus className="h-4 w-4" /> {t("add")}
|
||||
</Button>
|
||||
<PantryScanDialog onAdded={() => router.refresh()} />
|
||||
</div>
|
||||
|
||||
{/* Item list */}
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type NutritionTotals = {
|
||||
calories: number;
|
||||
proteinG: number;
|
||||
carbsG: number;
|
||||
fatG: number;
|
||||
fiberG: number;
|
||||
sodiumMg: number;
|
||||
};
|
||||
|
||||
type NutritionGoals = {
|
||||
caloriesKcal: number | null;
|
||||
proteinG: number | null;
|
||||
carbsG: number | null;
|
||||
fatG: number | null;
|
||||
} | null;
|
||||
|
||||
type NutritionCoverage = {
|
||||
calories: number;
|
||||
protein: number;
|
||||
carbs: number;
|
||||
fat: number;
|
||||
};
|
||||
|
||||
type DiaryEntry = {
|
||||
id: string;
|
||||
recipeId: string;
|
||||
title: string;
|
||||
servings: number;
|
||||
cookedAt: string;
|
||||
nutritionKnown: boolean;
|
||||
};
|
||||
|
||||
type DiaryResponse = {
|
||||
date: string;
|
||||
totals: NutritionTotals;
|
||||
goals: NutritionGoals;
|
||||
coverage: NutritionCoverage;
|
||||
entries: DiaryEntry[];
|
||||
unknownCount: number;
|
||||
};
|
||||
|
||||
function todayIso(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function NutritionDiary() {
|
||||
const t = useTranslations("nutritionDiary");
|
||||
const [date, setDate] = useState(todayIso());
|
||||
// Tagged with the date it was fetched for, and set only from inside the
|
||||
// fetch's own then/catch — never synchronously in the effect body — so we
|
||||
// don't need a separate "loading" setState call at the top of the effect.
|
||||
const [result, setResult] = useState<
|
||||
{ date: string; ok: true; data: DiaryResponse } | { date: string; ok: false } | null
|
||||
>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch(`/api/v1/users/me/nutrition-diary?date=${date}`)
|
||||
.then((res) => (res.ok ? res.json() : Promise.reject(new Error("request failed"))))
|
||||
.then((json: DiaryResponse) => {
|
||||
if (!cancelled) setResult({ date, ok: true, data: json });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setResult({ date, ok: false });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [date]);
|
||||
|
||||
const loading = result === null || result.date !== date;
|
||||
const error = !loading && result !== null && !result.ok;
|
||||
const data = !loading && result !== null && result.ok ? result.data : null;
|
||||
|
||||
const bars = data
|
||||
? [
|
||||
{
|
||||
label: t("calories"),
|
||||
value: data.totals.calories,
|
||||
goal: data.goals?.caloriesKcal ?? null,
|
||||
unit: "kcal",
|
||||
percentage: data.coverage.calories,
|
||||
colorClass: "bg-orange-500",
|
||||
},
|
||||
{
|
||||
label: t("protein"),
|
||||
value: data.totals.proteinG,
|
||||
goal: data.goals?.proteinG ?? null,
|
||||
unit: "g",
|
||||
percentage: data.coverage.protein,
|
||||
colorClass: "bg-blue-500",
|
||||
},
|
||||
{
|
||||
label: t("carbs"),
|
||||
value: data.totals.carbsG,
|
||||
goal: data.goals?.carbsG ?? null,
|
||||
unit: "g",
|
||||
percentage: data.coverage.carbs,
|
||||
colorClass: "bg-green-500",
|
||||
},
|
||||
{
|
||||
label: t("fat"),
|
||||
value: data.totals.fatG,
|
||||
goal: data.goals?.fatG ?? null,
|
||||
unit: "g",
|
||||
percentage: data.coverage.fat,
|
||||
colorClass: "bg-yellow-500",
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-end gap-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="diary-date">{t("dateLabel")}</Label>
|
||||
<Input
|
||||
id="diary-date"
|
||||
type="date"
|
||||
value={date}
|
||||
max={todayIso()}
|
||||
onChange={(e) => setDate(e.target.value || todayIso())}
|
||||
className="w-auto"
|
||||
/>
|
||||
</div>
|
||||
{date !== todayIso() && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDate(todayIso())}
|
||||
className={cn(buttonVariants({ variant: "ghost", size: "sm" }))}
|
||||
>
|
||||
{t("today")}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading && <p className="text-sm text-muted-foreground">{t("loading")}</p>}
|
||||
{error && <p className="text-sm text-destructive">{t("loadError")}</p>}
|
||||
|
||||
{!loading && !error && data && (
|
||||
<>
|
||||
{!data.goals && (
|
||||
<Card>
|
||||
<CardContent className="flex flex-col gap-2 py-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p className="text-sm text-muted-foreground">{t("goalNotSet")}</p>
|
||||
<Link
|
||||
href="/settings/nutrition"
|
||||
className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
|
||||
>
|
||||
{t("setGoalsCta")}
|
||||
</Link>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data.goals && (
|
||||
<Card>
|
||||
<CardContent className="space-y-3 py-4">
|
||||
{bars.map((bar) =>
|
||||
bar.goal == null ? null : (
|
||||
<div key={bar.label} className="space-y-1">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="font-medium">{bar.label}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{bar.value} / {bar.goal} {bar.unit}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 w-full rounded bg-muted overflow-hidden">
|
||||
<div
|
||||
className={`h-full rounded ${bar.colorClass}`}
|
||||
style={{ width: `${Math.min(bar.percentage, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3 pt-2 text-sm sm:grid-cols-2">
|
||||
<div className="flex justify-between rounded-md bg-muted px-3 py-2">
|
||||
<span className="text-muted-foreground">{t("fiber")}</span>
|
||||
<span className="font-medium tabular-nums">{data.totals.fiberG}g</span>
|
||||
</div>
|
||||
<div className="flex justify-between rounded-md bg-muted px-3 py-2">
|
||||
<span className="text-muted-foreground">{t("sodium")}</span>
|
||||
<span className="font-medium tabular-nums">{data.totals.sodiumMg}mg</span>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-semibold">{t("entriesTitle")}</h3>
|
||||
{data.entries.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">{t("noEntries")}</p>
|
||||
) : (
|
||||
<ul className="space-y-1.5">
|
||||
{data.entries.map((entry) => (
|
||||
<li
|
||||
key={entry.id}
|
||||
className="flex items-center justify-between rounded-md border px-3 py-2 text-sm"
|
||||
>
|
||||
<Link href={`/recipes/${entry.recipeId}`} className="hover:underline">
|
||||
{entry.title}
|
||||
</Link>
|
||||
<span className="flex items-center gap-2 text-muted-foreground">
|
||||
<span>{t("servingsLabel", { count: entry.servings })}</span>
|
||||
{!entry.nutritionKnown && (
|
||||
<span className="rounded bg-muted px-1.5 py-0.5 text-xs">
|
||||
{t("nutritionUnknownBadge")}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{data.unknownCount > 0 && (
|
||||
<p className="text-xs text-muted-foreground">{t("unknownNote", { count: data.unknownCount })}</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export function BarcodeScanner({
|
||||
onDetected,
|
||||
onError,
|
||||
}: {
|
||||
onDetected: (barcode: string) => void;
|
||||
onError?: (message: string) => void;
|
||||
}) {
|
||||
const t = useTranslations("pantry");
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const [starting, setStarting] = useState(true);
|
||||
const detectedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let controls: { stop: () => void } | null = null;
|
||||
|
||||
async function start() {
|
||||
try {
|
||||
const { BrowserMultiFormatReader } = await import("@zxing/browser");
|
||||
const reader = new BrowserMultiFormatReader();
|
||||
if (cancelled || !videoRef.current) return;
|
||||
|
||||
controls = await reader.decodeFromVideoDevice(
|
||||
undefined,
|
||||
videoRef.current,
|
||||
(result) => {
|
||||
if (result && !detectedRef.current) {
|
||||
detectedRef.current = true;
|
||||
onDetected(result.getText());
|
||||
controls?.stop();
|
||||
}
|
||||
}
|
||||
);
|
||||
if (!cancelled) setStarting(false);
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
onError?.(err instanceof Error ? err.message : t("cameraError"));
|
||||
setStarting(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void start();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
controls?.stop();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative aspect-video w-full overflow-hidden rounded-lg bg-black">
|
||||
<video ref={videoRef} className="h-full w-full object-cover" muted playsInline />
|
||||
{starting && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-white" />
|
||||
</div>
|
||||
)}
|
||||
<div className="pointer-events-none absolute inset-x-8 top-1/2 h-16 -translate-y-1/2 rounded-md border-2 border-white/70" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { ScanBarcode, Camera, Loader2, X, ArrowLeft } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import { BarcodeScanner } from "@/components/pantry/barcode-scanner";
|
||||
|
||||
type Step = "choose" | "barcode-scan" | "barcode-confirm" | "photo-loading" | "photo-confirm";
|
||||
|
||||
type DraftItem = { rawName: string; quantity: string; unit: string };
|
||||
|
||||
function fileToBase64(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const result = reader.result as string;
|
||||
const comma = result.indexOf(",");
|
||||
resolve(comma !== -1 ? result.slice(comma + 1) : result);
|
||||
};
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
export function PantryScanDialog({ onAdded }: { onAdded: () => void }) {
|
||||
const t = useTranslations("pantry");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [step, setStep] = useState<Step>("choose");
|
||||
const [barcodeDraft, setBarcodeDraft] = useState<DraftItem | null>(null);
|
||||
const [photoDrafts, setPhotoDrafts] = useState<DraftItem[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
function reset() {
|
||||
setStep("choose");
|
||||
setBarcodeDraft(null);
|
||||
setPhotoDrafts([]);
|
||||
}
|
||||
|
||||
function handleOpenChange(next: boolean) {
|
||||
setOpen(next);
|
||||
if (!next) reset();
|
||||
}
|
||||
|
||||
async function handleBarcodeDetected(barcode: string) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/pantry/scan/barcode", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ barcode }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(t("scanLookupFailed"));
|
||||
setStep("choose");
|
||||
return;
|
||||
}
|
||||
const data = await res.json() as { found: boolean; rawName?: string; quantity?: string; unit?: string };
|
||||
if (!data.found || !data.rawName) {
|
||||
toast.error(t("scanNotFound"));
|
||||
setStep("choose");
|
||||
return;
|
||||
}
|
||||
setBarcodeDraft({ rawName: data.rawName, quantity: data.quantity ?? "", unit: data.unit ?? "" });
|
||||
setStep("barcode-confirm");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePhotoFile(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setStep("photo-loading");
|
||||
try {
|
||||
const imageBase64 = await fileToBase64(file);
|
||||
const mimeType = (["image/jpeg", "image/png", "image/webp"].includes(file.type) ? file.type : "image/jpeg") as
|
||||
| "image/jpeg"
|
||||
| "image/png"
|
||||
| "image/webp";
|
||||
|
||||
const res = await fetch("/api/v1/pantry/scan/photo", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ imageBase64, mimeType }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({})) as { error?: string };
|
||||
toast.error(data.error ?? t("scanPhotoFailed"));
|
||||
setStep("choose");
|
||||
return;
|
||||
}
|
||||
const data = await res.json() as { items: { rawName: string; estimatedQuantity?: string; unit?: string }[] };
|
||||
if (data.items.length === 0) {
|
||||
toast.error(t("scanNoItemsFound"));
|
||||
setStep("choose");
|
||||
return;
|
||||
}
|
||||
setPhotoDrafts(
|
||||
data.items.map((i) => ({ rawName: i.rawName, quantity: i.estimatedQuantity ?? "", unit: i.unit ?? "" }))
|
||||
);
|
||||
setStep("photo-confirm");
|
||||
} finally {
|
||||
if (fileRef.current) fileRef.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmItems(items: DraftItem[]) {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/pantry/bulk", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
items: items
|
||||
.filter((i) => i.rawName.trim())
|
||||
.map((i) => ({
|
||||
rawName: i.rawName.trim(),
|
||||
quantity: i.quantity.trim() || undefined,
|
||||
unit: i.unit.trim() || undefined,
|
||||
})),
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
toast.error(t("addFailed"));
|
||||
return;
|
||||
}
|
||||
toast.success(t("scanAdded"));
|
||||
onAdded();
|
||||
handleOpenChange(false);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="outline" size="sm" onClick={() => setOpen(true)}>
|
||||
<ScanBarcode className="h-4 w-4" /> {t("scan")}
|
||||
</Button>
|
||||
|
||||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{step === "choose" && t("scanTitle")}
|
||||
{step === "barcode-scan" && t("scanBarcodeTitle")}
|
||||
{step === "barcode-confirm" && t("scanConfirmTitle")}
|
||||
{step === "photo-loading" && t("scanAnalyzingTitle")}
|
||||
{step === "photo-confirm" && t("scanConfirmTitle")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{step === "choose" && t("scanDescription")}
|
||||
{step === "barcode-scan" && t("scanBarcodeDescription")}
|
||||
{(step === "barcode-confirm" || step === "photo-confirm") && t("scanConfirmDescription")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{step === "choose" && (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStep("barcode-scan")}
|
||||
className="flex flex-col items-center gap-2 rounded-lg border p-4 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<ScanBarcode className="h-6 w-6" />
|
||||
<span className="text-sm font-medium">{t("scanBarcodeOption")}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
className="flex flex-col items-center gap-2 rounded-lg border p-4 hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<Camera className="h-6 w-6" />
|
||||
<span className="text-sm font-medium">{t("scanPhotoOption")}</span>
|
||||
</button>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
capture="environment"
|
||||
className="hidden"
|
||||
onChange={handlePhotoFile}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "barcode-scan" && (
|
||||
<div className="space-y-3">
|
||||
<BarcodeScanner
|
||||
onDetected={(barcode) => void handleBarcodeDetected(barcode)}
|
||||
onError={() => { toast.error(t("cameraError")); setStep("choose"); }}
|
||||
/>
|
||||
<Button variant="ghost" size="sm" onClick={() => setStep("choose")} disabled={busy}>
|
||||
<ArrowLeft className="h-4 w-4" /> {t("scanBack")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "barcode-confirm" && barcodeDraft && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={barcodeDraft.rawName}
|
||||
onChange={(e) => setBarcodeDraft({ ...barcodeDraft, rawName: e.target.value })}
|
||||
placeholder={t("itemNamePlaceholder")}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={barcodeDraft.quantity}
|
||||
onChange={(e) => setBarcodeDraft({ ...barcodeDraft, quantity: e.target.value })}
|
||||
placeholder={t("qtyPlaceholder")}
|
||||
className="w-20"
|
||||
/>
|
||||
<Input
|
||||
value={barcodeDraft.unit}
|
||||
onChange={(e) => setBarcodeDraft({ ...barcodeDraft, unit: e.target.value })}
|
||||
placeholder={t("unitPlaceholder")}
|
||||
className="w-20"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "photo-loading" && (
|
||||
<div className="flex flex-col items-center justify-center gap-3 py-8">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
<p className="text-sm text-muted-foreground">{t("scanAnalyzingDescription")}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "photo-confirm" && (
|
||||
<div className="space-y-2 max-h-80 overflow-y-auto">
|
||||
{photoDrafts.map((draft, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
value={draft.rawName}
|
||||
onChange={(e) =>
|
||||
setPhotoDrafts((prev) => prev.map((d, idx) => (idx === i ? { ...d, rawName: e.target.value } : d)))
|
||||
}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={draft.quantity}
|
||||
onChange={(e) =>
|
||||
setPhotoDrafts((prev) => prev.map((d, idx) => (idx === i ? { ...d, quantity: e.target.value } : d)))
|
||||
}
|
||||
placeholder={t("qtyPlaceholder")}
|
||||
className="w-16"
|
||||
/>
|
||||
<Input
|
||||
value={draft.unit}
|
||||
onChange={(e) =>
|
||||
setPhotoDrafts((prev) => prev.map((d, idx) => (idx === i ? { ...d, unit: e.target.value } : d)))
|
||||
}
|
||||
placeholder={t("unitPlaceholder")}
|
||||
className="w-16"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPhotoDrafts((prev) => prev.filter((_, idx) => idx !== i))}
|
||||
className="text-muted-foreground hover:text-destructive transition-colors"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(step === "barcode-confirm" || step === "photo-confirm") && (
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={reset} disabled={busy}>
|
||||
{t("scanBack")}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() =>
|
||||
void confirmItems(step === "barcode-confirm" && barcodeDraft ? [barcodeDraft] : photoDrafts)
|
||||
}
|
||||
disabled={busy}
|
||||
>
|
||||
{busy ? <Loader2 className="h-4 w-4 animate-spin" /> : t("scanAddToPantry")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { useTranslations, useLocale } from "next-intl";
|
||||
import { Flame, ChefHat, History } from "lucide-react";
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
|
||||
import { getPublicUrl } from "@/lib/storage";
|
||||
|
||||
export type HistoryEntry = {
|
||||
id: string;
|
||||
recipeId: string;
|
||||
recipeTitle: string;
|
||||
cookedAt: string;
|
||||
servings: number | null;
|
||||
};
|
||||
|
||||
export type HistoryData = {
|
||||
totalCooked: number;
|
||||
streak: number;
|
||||
lastCooked: { recipeId: string; recipeTitle: string; cookedAt: string } | null;
|
||||
recentEntries: HistoryEntry[];
|
||||
};
|
||||
|
||||
export type PhotoItem = {
|
||||
id: string;
|
||||
recipeId: string;
|
||||
recipeTitle: string;
|
||||
photoKey: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type PhotosData = {
|
||||
items: PhotoItem[];
|
||||
page: number;
|
||||
totalPages: number;
|
||||
total: number;
|
||||
};
|
||||
|
||||
function StatCard({ label, value }: { label: string; value: React.ReactNode }) {
|
||||
return (
|
||||
<div className="rounded-xl border bg-card p-4 space-y-1">
|
||||
<p className="text-sm text-muted-foreground">{label}</p>
|
||||
<p className="text-2xl font-semibold">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ProfileTabs({
|
||||
username,
|
||||
defaultTab,
|
||||
recipesContent,
|
||||
history,
|
||||
photos,
|
||||
}: {
|
||||
username: string;
|
||||
defaultTab: string;
|
||||
recipesContent: React.ReactNode;
|
||||
history: HistoryData;
|
||||
photos: PhotosData;
|
||||
}) {
|
||||
const t = useTranslations("profilePage");
|
||||
const locale = useLocale();
|
||||
|
||||
return (
|
||||
<Tabs defaultValue={defaultTab} className="gap-6">
|
||||
<TabsList>
|
||||
<TabsTrigger value="recipes">{t("tabRecipes")}</TabsTrigger>
|
||||
<TabsTrigger value="history">{t("tabHistory")}</TabsTrigger>
|
||||
<TabsTrigger value="photos">{t("tabPhotos")}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="recipes">{recipesContent}</TabsContent>
|
||||
|
||||
<TabsContent value="history">
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<StatCard
|
||||
label={t("statTotalCooked")}
|
||||
value={
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<ChefHat className="h-5 w-5 text-primary" />
|
||||
{history.totalCooked}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<StatCard
|
||||
label={t("statStreak")}
|
||||
value={
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<Flame className="h-5 w-5 text-orange-500" />
|
||||
{t("streakDays", { count: history.streak })}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<StatCard
|
||||
label={t("statLastCooked")}
|
||||
value={
|
||||
history.lastCooked ? (
|
||||
<Link href={`/recipes/${history.lastCooked.recipeId}`} className="text-base font-medium hover:underline line-clamp-1">
|
||||
{history.lastCooked.recipeTitle}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-base font-normal text-muted-foreground">{t("noneYet")}</span>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{history.recentEntries.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-muted-foreground">{t("recentActivity")}</h3>
|
||||
<div className="rounded-xl border divide-y overflow-hidden">
|
||||
{history.recentEntries.map((entry) => (
|
||||
<Link
|
||||
key={entry.id}
|
||||
href={`/recipes/${entry.recipeId}`}
|
||||
className="flex items-center gap-3 px-4 py-3 hover:bg-accent transition-colors"
|
||||
>
|
||||
<History className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<span className="flex-1 text-sm font-medium truncate">{entry.recipeTitle}</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0">
|
||||
{new Date(entry.cookedAt).toLocaleDateString(locale)}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-16 text-muted-foreground">
|
||||
<p className="text-lg">{t("noHistoryYet")}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="photos">
|
||||
{photos.items.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
|
||||
{photos.items.map((photo) => (
|
||||
<Link
|
||||
key={photo.id}
|
||||
href={`/recipes/${photo.recipeId}`}
|
||||
className="group block rounded-xl overflow-hidden border bg-card hover:shadow-md transition-shadow"
|
||||
>
|
||||
<div className="relative aspect-square bg-muted overflow-hidden">
|
||||
<Image
|
||||
src={getPublicUrl(photo.photoKey)}
|
||||
alt={photo.recipeTitle}
|
||||
fill
|
||||
sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, 25vw"
|
||||
className="object-cover group-hover:scale-105 transition-transform duration-200"
|
||||
/>
|
||||
</div>
|
||||
<div className="p-2">
|
||||
<p className="text-sm font-medium leading-tight line-clamp-2">{photo.recipeTitle}</p>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{photos.totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-2 pt-2">
|
||||
{photos.page > 1 && (
|
||||
<Link
|
||||
href={`/u/${username}?tab=photos&ppage=${photos.page - 1}`}
|
||||
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
|
||||
>
|
||||
{t("previous")}
|
||||
</Link>
|
||||
)}
|
||||
<span className="text-sm text-muted-foreground px-2">
|
||||
{t("pageOf", { page: photos.page, total: photos.totalPages })}
|
||||
</span>
|
||||
{photos.page < photos.totalPages && (
|
||||
<Link
|
||||
href={`/u/${username}?tab=photos&ppage=${photos.page + 1}`}
|
||||
className="rounded-md border px-3 py-1.5 text-sm hover:bg-accent"
|
||||
>
|
||||
{t("next")}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-16 text-muted-foreground">
|
||||
<p className="text-lg">{t("noPhotosYet")}</p>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Minus, Plus, Sparkles, X } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { scaleQuantity, hasQuantity } from "@/lib/fractions";
|
||||
import { formatIngredientQuantity, type UnitPref } from "@/lib/unit-conversion";
|
||||
import { SubstituteIngredientPopover } from "@/components/recipe/substitute-ingredient-popover";
|
||||
|
||||
type Ingredient = {
|
||||
@@ -29,12 +29,14 @@ export function ServingScaler({
|
||||
recipeTitle,
|
||||
recipeId,
|
||||
onAiScale,
|
||||
unitPref = "metric",
|
||||
}: {
|
||||
baseServings: number;
|
||||
ingredients: Ingredient[];
|
||||
recipeTitle?: string;
|
||||
recipeId?: string;
|
||||
onAiScale?: (ingredients: ScaledIngredient[] | null) => void;
|
||||
unitPref?: UnitPref;
|
||||
}) {
|
||||
const t = useTranslations("servingScaler");
|
||||
const [servings, setServings] = useState(baseServings);
|
||||
@@ -132,15 +134,15 @@ export function ServingScaler({
|
||||
.sort((a, b) => a.order - b.order)
|
||||
.map((ing) => {
|
||||
const aiIng = aiScaledIngredients?.find((s) => s.rawName === ing.rawName);
|
||||
const scaled = scaleQuantity(ing.quantity, baseServings, servings);
|
||||
return (
|
||||
<li key={ing.id} className="flex gap-2 text-sm group">
|
||||
<span className="font-medium tabular-nums min-w-[3rem] text-right">
|
||||
{aiIng
|
||||
? `${hasQuantity(aiIng.quantity) ? aiIng.quantity : ""}${aiIng.unit ? ` ${aiIng.unit}` : ""}`
|
||||
: scaled
|
||||
? `${scaled}${ing.unit ? ` ${ing.unit}` : ""}`
|
||||
: ing.unit ?? ""}
|
||||
? formatIngredientQuantity(aiIng.quantity, aiIng.unit, unitPref)
|
||||
: formatIngredientQuantity(ing.quantity, ing.unit, unitPref, {
|
||||
base: baseServings,
|
||||
desired: servings,
|
||||
})}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
{ing.rawName}
|
||||
|
||||
Reference in New Issue
Block a user