feat: add bulk "add to collection" action on recipes page
Select recipes → add to an existing collection or create a new one inline. Fixes duplicate "visibility" i18n key bug found during verification. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db, collections, collectionRecipes, recipes, eq, and, or, ne } from "@epicure/db";
|
import { db, collections, collectionRecipes, recipes, eq, and, or, ne, inArray } from "@epicure/db";
|
||||||
import { requireSession } from "@/lib/api-auth";
|
import { requireSession } from "@/lib/api-auth";
|
||||||
|
|
||||||
type Params = { params: Promise<{ id: string }> };
|
type Params = { params: Promise<{ id: string }> };
|
||||||
@@ -35,6 +35,7 @@ export async function PUT(req: NextRequest, { params }: Params) {
|
|||||||
description: z.string().max(500).optional(),
|
description: z.string().max(500).optional(),
|
||||||
isPublic: z.boolean().optional(),
|
isPublic: z.boolean().optional(),
|
||||||
addRecipeId: z.string().optional(),
|
addRecipeId: z.string().optional(),
|
||||||
|
addRecipeIds: z.array(z.string()).max(200).optional(),
|
||||||
removeRecipeId: z.string().optional(),
|
removeRecipeId: z.string().optional(),
|
||||||
}).safeParse(body);
|
}).safeParse(body);
|
||||||
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||||
@@ -49,15 +50,19 @@ export async function PUT(req: NextRequest, { params }: Params) {
|
|||||||
}).where(eq(collections.id, id));
|
}).where(eq(collections.id, id));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (data.addRecipeId) {
|
const idsToAdd = [...(data.addRecipeId ? [data.addRecipeId] : []), ...(data.addRecipeIds ?? [])];
|
||||||
const recipe = await db.query.recipes.findFirst({
|
if (idsToAdd.length > 0) {
|
||||||
|
const owned = await db.query.recipes.findMany({
|
||||||
where: and(
|
where: and(
|
||||||
eq(recipes.id, data.addRecipeId),
|
inArray(recipes.id, idsToAdd),
|
||||||
or(eq(recipes.authorId, session!.user.id), ne(recipes.visibility, "private"))
|
or(eq(recipes.authorId, session!.user.id), ne(recipes.visibility, "private"))
|
||||||
),
|
),
|
||||||
|
columns: { id: true },
|
||||||
});
|
});
|
||||||
if (recipe) {
|
if (owned.length > 0) {
|
||||||
await db.insert(collectionRecipes).values({ collectionId: id, recipeId: data.addRecipeId }).onConflictDoNothing();
|
await db.insert(collectionRecipes)
|
||||||
|
.values(owned.map((r) => ({ collectionId: id, recipeId: r.id })))
|
||||||
|
.onConflictDoNothing();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { FolderPlus, FolderOpen, Plus, Check } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
|
||||||
|
type CollectionSummary = { id: string; name: string };
|
||||||
|
|
||||||
|
export function AddToCollectionDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
recipeIds,
|
||||||
|
onDone,
|
||||||
|
}: {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
recipeIds: string[];
|
||||||
|
onDone: () => void;
|
||||||
|
}) {
|
||||||
|
const t = useTranslations("recipe");
|
||||||
|
const [collections, setCollections] = useState<CollectionSummary[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [newName, setNewName] = useState("");
|
||||||
|
const [showNewForm, setShowNewForm] = useState(false);
|
||||||
|
const [busyId, setBusyId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setShowNewForm(false);
|
||||||
|
setNewName("");
|
||||||
|
setLoading(true);
|
||||||
|
fetch("/api/v1/collections?limit=50")
|
||||||
|
.then((res) => (res.ok ? res.json() : null))
|
||||||
|
.then((data: { data: CollectionSummary[] } | null) => {
|
||||||
|
setCollections(data?.data ?? []);
|
||||||
|
})
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
async function addTo(collectionId: string, collectionName: string) {
|
||||||
|
setBusyId(collectionId);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/v1/collections/${collectionId}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ addRecipeIds: recipeIds }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error();
|
||||||
|
toast.success(t("addToCollectionSuccess", { count: recipeIds.length, name: collectionName }));
|
||||||
|
onOpenChange(false);
|
||||||
|
onDone();
|
||||||
|
} catch {
|
||||||
|
toast.error(t("addToCollectionFailed"));
|
||||||
|
} finally {
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createAndAdd() {
|
||||||
|
if (!newName.trim()) return;
|
||||||
|
setCreating(true);
|
||||||
|
try {
|
||||||
|
const createRes = await fetch("/api/v1/collections", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ name: newName.trim() }),
|
||||||
|
});
|
||||||
|
if (!createRes.ok) throw new Error();
|
||||||
|
const { id } = (await createRes.json()) as { id: string };
|
||||||
|
await addTo(id, newName.trim());
|
||||||
|
} catch {
|
||||||
|
toast.error(t("createCollectionFailed"));
|
||||||
|
} finally {
|
||||||
|
setCreating(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle className="flex items-center gap-2">
|
||||||
|
<FolderPlus className="h-5 w-5 text-primary" />
|
||||||
|
{t("addToCollectionTitle", { count: recipeIds.length })}
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
{loading ? (
|
||||||
|
<p className="text-sm text-muted-foreground py-2">…</p>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-1 max-h-64 overflow-y-auto">
|
||||||
|
{collections.length === 0 && !showNewForm && (
|
||||||
|
<p className="text-sm text-muted-foreground py-2">{t("noCollectionsYet")}</p>
|
||||||
|
)}
|
||||||
|
{collections.map((c) => (
|
||||||
|
<button
|
||||||
|
key={c.id}
|
||||||
|
onClick={() => { void addTo(c.id, c.name); }}
|
||||||
|
disabled={busyId !== null}
|
||||||
|
className="w-full flex items-center gap-2 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors disabled:opacity-50 text-left"
|
||||||
|
>
|
||||||
|
<FolderOpen className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||||
|
<span className="flex-1 truncate">{c.name}</span>
|
||||||
|
{busyId === c.id && <Check className="h-4 w-4 text-primary" />}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showNewForm ? (
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
value={newName}
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
placeholder={t("newCollectionNamePlaceholder")}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && void createAndAdd()}
|
||||||
|
disabled={creating}
|
||||||
|
/>
|
||||||
|
<Button onClick={() => { void createAndAdd(); }} disabled={!newName.trim() || creating}>
|
||||||
|
{t("addToCollection")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
onClick={() => setShowNewForm(true)}
|
||||||
|
className="w-full flex items-center gap-2 rounded-md px-3 py-2 text-sm text-primary hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
{t("newCollectionOption")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,7 +2,8 @@
|
|||||||
|
|
||||||
import { useState, useCallback, useEffect } from "react";
|
import { useState, useCallback, useEffect } from "react";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3 } from "lucide-react";
|
import { Trash2, Globe, Lock, Link2, X, Check, ListChecks, LayoutGrid, List, Rows3, FolderPlus } from "lucide-react";
|
||||||
|
import { AddToCollectionDialog } from "@/components/recipe/add-to-collection-dialog";
|
||||||
import { Button, buttonVariants } from "@/components/ui/button";
|
import { Button, buttonVariants } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
@@ -262,6 +263,7 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
|
|||||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [viewMode, setViewMode] = useState<ViewMode>("grid");
|
const [viewMode, setViewMode] = useState<ViewMode>("grid");
|
||||||
|
const [addToCollectionOpen, setAddToCollectionOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const stored = localStorage.getItem(VIEW_STORAGE_KEY) as ViewMode | null;
|
const stored = localStorage.getItem(VIEW_STORAGE_KEY) as ViewMode | null;
|
||||||
@@ -409,6 +411,10 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
|
<Button variant="ghost" size="sm" onClick={() => setAddToCollectionOpen(true)} disabled={busy} className="gap-1.5">
|
||||||
|
<FolderPlus className="h-4 w-4" />
|
||||||
|
{t("addToCollection")}
|
||||||
|
</Button>
|
||||||
<Button variant="destructive" size="sm" onClick={() => { void bulkDelete(); }} disabled={busy} className="gap-1.5">
|
<Button variant="destructive" size="sm" onClick={() => { void bulkDelete(); }} disabled={busy} className="gap-1.5">
|
||||||
<Trash2 className="h-4 w-4" />
|
<Trash2 className="h-4 w-4" />
|
||||||
{tCommon("delete")}
|
{tCommon("delete")}
|
||||||
@@ -416,6 +422,13 @@ export function RecipesGrid({ recipes: initialRecipes }: { recipes: Recipe[] })
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<AddToCollectionDialog
|
||||||
|
open={addToCollectionOpen}
|
||||||
|
onOpenChange={setAddToCollectionOpen}
|
||||||
|
recipeIds={[...selected]}
|
||||||
|
onDone={exitSelect}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -121,6 +121,14 @@
|
|||||||
"viewList": "List view",
|
"viewList": "List view",
|
||||||
"viewCompact": "Compact view",
|
"viewCompact": "Compact view",
|
||||||
"updatedLabel": "Updated {date}",
|
"updatedLabel": "Updated {date}",
|
||||||
|
"addToCollection": "Add to collection",
|
||||||
|
"addToCollectionTitle": "Add {count, plural, one {1 recipe} other {{count} recipes}} to a collection",
|
||||||
|
"newCollectionOption": "New collection…",
|
||||||
|
"newCollectionNamePlaceholder": "Collection name",
|
||||||
|
"addToCollectionSuccess": "{count, plural, one {1 recipe} other {{count} recipes}} added to \"{name}\"",
|
||||||
|
"addToCollectionFailed": "Failed to add to collection",
|
||||||
|
"createCollectionFailed": "Failed to create collection",
|
||||||
|
"noCollectionsYet": "You don't have any collections yet.",
|
||||||
"versionHistoryTitle": "Version History",
|
"versionHistoryTitle": "Version History",
|
||||||
"versionsLoading": "Loading versions...",
|
"versionsLoading": "Loading versions...",
|
||||||
"versionsEmpty": "No versions yet. Versions are saved automatically when you edit this recipe.",
|
"versionsEmpty": "No versions yet. Versions are saved automatically when you edit this recipe.",
|
||||||
|
|||||||
@@ -121,6 +121,14 @@
|
|||||||
"viewList": "Vue liste",
|
"viewList": "Vue liste",
|
||||||
"viewCompact": "Vue compacte",
|
"viewCompact": "Vue compacte",
|
||||||
"updatedLabel": "Mis à jour le {date}",
|
"updatedLabel": "Mis à jour le {date}",
|
||||||
|
"addToCollection": "Ajouter à une collection",
|
||||||
|
"addToCollectionTitle": "Ajouter {count, plural, one {1 recette} other {{count} recettes}} à une collection",
|
||||||
|
"newCollectionOption": "Nouvelle collection…",
|
||||||
|
"newCollectionNamePlaceholder": "Nom de la collection",
|
||||||
|
"addToCollectionSuccess": "{count, plural, one {1 recette} other {{count} recettes}} ajoutée(s) à « {name} »",
|
||||||
|
"addToCollectionFailed": "Échec de l'ajout à la collection",
|
||||||
|
"createCollectionFailed": "Échec de la création de la collection",
|
||||||
|
"noCollectionsYet": "Vous n'avez pas encore de collection.",
|
||||||
"versionHistoryTitle": "Historique des versions",
|
"versionHistoryTitle": "Historique des versions",
|
||||||
"versionsLoading": "Chargement des versions...",
|
"versionsLoading": "Chargement des versions...",
|
||||||
"versionsEmpty": "Aucune version pour l'instant. Les versions sont enregistrées automatiquement lorsque vous modifiez cette recette.",
|
"versionsEmpty": "Aucune version pour l'instant. Les versions sont enregistrées automatiquement lorsque vous modifiez cette recette.",
|
||||||
|
|||||||
Reference in New Issue
Block a user