feat: garden containers crud (task 71)

- add listContainers/getContainer/searchContainers queries
- add createContainer/updateContainer/deleteContainer server actions with logActivity
- add ContainerList, ContainerDetail, ContainerForm client components
- add /garden, /garden/containers/[id], /garden/containers/new pages
- register garden.container entity with share + search in manifest
- add sprout icon to NavIcon registry
- add garden e2e test spec
This commit is contained in:
ginnoir
2026-06-01 19:28:34 -05:00
parent 2fd0677c5f
commit 5f6b756342
12 changed files with 756 additions and 4 deletions
+14
View File
@@ -0,0 +1,14 @@
import { notFound } from "next/navigation";
import { getContainer } from "@/modules/garden/server/queries";
import { ContainerDetail } from "@/modules/garden/components/container-detail";
export default async function ContainerPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const container = await getContainer(id);
if (!container) notFound();
return (
<div className="page-content">
<ContainerDetail container={container} />
</div>
);
}
+70
View File
@@ -0,0 +1,70 @@
import { redirect } from "next/navigation";
import { createContainer } from "@/modules/garden/server/actions";
export default function NewContainerPage() {
async function handleCreate(formData: FormData) {
"use server";
await createContainer({
name: formData.get("name") as string,
type: (formData.get("type") as string) || "other",
locationNotes: (formData.get("locationNotes") as string) || null,
});
redirect("/garden");
}
return (
<div className="page-content max-w-lg">
<h1 className="page-title">New container</h1>
<form action={handleCreate} className="flex flex-col gap-4 mt-4">
<div className="flex flex-col gap-1">
<label htmlFor="name" className="text-sm font-medium">
Name
</label>
<input id="name" name="name" required maxLength={120} className="input" />
</div>
<div className="flex flex-col gap-1">
<label htmlFor="type" className="text-sm font-medium">
Type
</label>
<select id="type" name="type" defaultValue="other">
{(
[
["shelf", "Shelf"],
["terrarium", "Terrarium"],
["raised-bed", "Raised bed"],
["window-box", "Window box"],
["single-pot", "Single pot"],
["outdoor", "Outdoor"],
["other", "Other"],
] as const
).map(([v, l]) => (
<option key={v} value={v}>
{l}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="locationNotes" className="text-sm font-medium">
Location notes
</label>
<textarea
id="locationNotes"
name="locationNotes"
maxLength={500}
rows={2}
className="input"
/>
</div>
<div className="flex gap-2 justify-end">
<a href="/garden" className="btn btn-ghost">
Cancel
</a>
<button type="submit" className="btn btn-primary">
Create
</button>
</div>
</form>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { listContainers } from "@/modules/garden/server/queries";
import { ContainerList } from "@/modules/garden/components/container-list";
export default async function GardenPage() {
const containers = await listContainers();
return (
<div className="page-content">
<h1 className="page-title">Garden</h1>
<ContainerList containers={containers} />
</div>
);
}
+2
View File
@@ -1,6 +1,7 @@
import {
Bell,
Calendar,
Sprout,
CalendarDays,
CheckSquare,
ChevronDown,
@@ -68,6 +69,7 @@ const ICONS: Record<string, React.ComponentType<LucideProps>> = {
phone: Phone,
filter: Filter,
sun: Sun,
sprout: Sprout,
mail: Mail,
menu: Menu,
more: MoreHorizontal,
@@ -0,0 +1,127 @@
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { deleteContainer } from "../server/actions";
import { ContainerForm } from "./container-form";
import type { ContainerDetailDto } from "../server/queries";
type Props = { container: ContainerDetailDto };
export function ContainerDetail({ container }: Props) {
const [editing, setEditing] = useState(false);
const [confirming, setConfirming] = useState(false);
const [isPending, startTransition] = useTransition();
const router = useRouter();
function handleDelete() {
startTransition(async () => {
await deleteContainer({ id: container.id });
router.push("/garden");
router.refresh();
});
}
return (
<div className="flex flex-col gap-6">
{container.coverImageUrl && (
<img
src={container.coverImageUrl}
alt=""
className="w-full max-h-48 object-cover rounded-lg"
/>
)}
<div className="flex items-start justify-between gap-4">
<div>
<h1 className="text-2xl font-bold">{container.name}</h1>
<p className="text-sm text-[var(--ink-mute)] capitalize mt-1">{container.type}</p>
{container.locationNotes && <p className="text-sm mt-2">{container.locationNotes}</p>}
</div>
<div className="flex gap-2 shrink-0">
<button className="btn btn-ghost btn-sm" onClick={() => setEditing(true)}>
Edit
</button>
{confirming ? (
<div className="flex gap-1">
<button className="btn btn-danger btn-sm" onClick={handleDelete} disabled={isPending}>
Confirm
</button>
<button
className="btn btn-ghost btn-sm"
onClick={() => setConfirming(false)}
disabled={isPending}
>
Cancel
</button>
</div>
) : (
<button className="btn btn-ghost btn-sm" onClick={() => setConfirming(true)}>
Delete
</button>
)}
</div>
</div>
{editing && (
<div className="card p-4">
<h2 className="font-medium mb-3">Edit container</h2>
<ContainerForm
existing={container}
onSuccess={() => {
setEditing(false);
router.refresh();
}}
onCancel={() => setEditing(false)}
/>
</div>
)}
<div>
<div className="flex items-center justify-between mb-3">
<h2 className="text-lg font-semibold">Plants ({container.plantCount})</h2>
<a
href={`/garden/plants/new?containerId=${container.id}`}
className="btn btn-ghost btn-sm"
>
+ Add plant
</a>
</div>
{container.plants.length === 0 ? (
<p className="text-sm text-[var(--ink-mute)]">No plants in this container yet.</p>
) : (
<div className="grid gap-2 sm:grid-cols-2">
{container.plants.map((p) => (
<a
key={p.id}
href={`/garden/plants/${p.id}`}
className="card p-3 hover:bg-[var(--surface-2)] transition-colors"
>
<div className="flex items-center gap-3">
{p.primaryImageUrl && (
<img
src={p.primaryImageUrl}
alt=""
className="w-10 h-10 rounded-full object-cover shrink-0"
/>
)}
<div>
<p className="font-medium text-sm">{p.name}</p>
{p.scientificName && (
<p className="text-xs text-[var(--ink-mute)] italic">{p.scientificName}</p>
)}
</div>
<span
className={`ml-auto text-xs badge ${p.healthStatus === "healthy" ? "badge-success" : "badge-warning"}`}
>
{p.healthStatus}
</span>
</div>
</a>
))}
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,112 @@
"use client";
import { useRef, useState, useTransition } from "react";
import { createContainer, updateContainer } from "../server/actions";
import type { ContainerDto } from "../server/queries";
const CONTAINER_TYPES = [
{ value: "shelf", label: "Shelf" },
{ value: "terrarium", label: "Terrarium" },
{ value: "raised-bed", label: "Raised bed" },
{ value: "window-box", label: "Window box" },
{ value: "single-pot", label: "Single pot" },
{ value: "outdoor", label: "Outdoor" },
{ value: "other", label: "Other" },
];
type Props = {
existing?: ContainerDto;
onSuccess?: () => void;
onCancel?: () => void;
};
export function ContainerForm({ existing, onSuccess, onCancel }: Props) {
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const formRef = useRef<HTMLFormElement>(null);
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const input = {
name: fd.get("name") as string,
type: fd.get("type") as string,
locationNotes: (fd.get("locationNotes") as string) || null,
};
setError(null);
startTransition(async () => {
try {
if (existing) {
await updateContainer({ id: existing.id, ...input });
} else {
await createContainer(input);
}
formRef.current?.reset();
onSuccess?.();
} catch {
setError("Something went wrong. Please try again.");
}
});
}
return (
<form ref={formRef} onSubmit={handleSubmit} className="flex flex-col gap-4">
<div className="flex flex-col gap-1">
<label htmlFor="container-name" className="text-sm font-medium">
Name
</label>
<input
id="container-name"
name="name"
required
maxLength={120}
defaultValue={existing?.name}
placeholder="e.g. Living Room Shelf"
className="input"
/>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="container-type" className="text-sm font-medium">
Type
</label>
<select id="container-type" name="type" defaultValue={existing?.type ?? "other"}>
{CONTAINER_TYPES.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="container-notes" className="text-sm font-medium">
Location notes
</label>
<textarea
id="container-notes"
name="locationNotes"
maxLength={500}
rows={2}
defaultValue={existing?.locationNotes ?? ""}
placeholder="Optional — e.g. south-facing window"
className="input"
/>
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<div className="flex gap-2 justify-end">
{onCancel && (
<button type="button" onClick={onCancel} className="btn btn-ghost" disabled={isPending}>
Cancel
</button>
)}
<button type="submit" className="btn btn-primary" disabled={isPending}>
{isPending ? "Saving…" : existing ? "Save" : "Create"}
</button>
</div>
</form>
);
}
@@ -0,0 +1,65 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ContainerForm } from "./container-form";
import type { ContainerDto } from "../server/queries";
type Props = { containers: ContainerDto[] };
export function ContainerList({ containers }: Props) {
const [showNew, setShowNew] = useState(false);
const router = useRouter();
return (
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold">Containers</h2>
<button className="btn btn-primary btn-sm" onClick={() => setShowNew(true)}>
New container
</button>
</div>
{showNew && (
<div className="card p-4">
<h3 className="font-medium mb-3">New container</h3>
<ContainerForm
onSuccess={() => {
setShowNew(false);
router.refresh();
}}
onCancel={() => setShowNew(false)}
/>
</div>
)}
{containers.length === 0 && !showNew && (
<p className="text-sm text-[var(--ink-mute)]">
No containers yet. Add one to start organising your plants.
</p>
)}
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{containers.map((c) => (
<Link
key={c.id}
href={`/garden/containers/${c.id}`}
className="card p-4 hover:bg-[var(--surface-2)] transition-colors"
>
{c.coverImageUrl && (
<img src={c.coverImageUrl} alt="" className="w-full h-32 object-cover rounded mb-3" />
)}
<div className="flex items-start justify-between gap-2">
<span className="font-medium leading-tight">{c.name}</span>
<span className="badge badge-outline text-xs shrink-0 capitalize">{c.type}</span>
</div>
<p className="text-sm text-[var(--ink-mute)] mt-1">
{c.plantCount} {c.plantCount === 1 ? "plant" : "plants"}
</p>
</Link>
))}
</div>
</div>
);
}
+53 -2
View File
@@ -1,12 +1,63 @@
import type { ModuleManifest } from "../_core/module";
import { loadContainerForShare, type ContainerShareData } from "./server/share-queries";
import { searchContainers } from "./server/queries";
const gardenManifest: ModuleManifest = {
id: "garden",
name: "Garden",
nav: { href: "/garden", label: "Garden", icon: "sprout" },
entities: [],
entities: [
{
type: "garden.container",
label: { singular: "Container", plural: "Containers" },
share: { canShare: true, defaultCapabilities: ["read"] },
search: { search: searchContainers },
resolveUrl: (id) => `/garden/containers/${id}`,
loadForShare: (id) => loadContainerForShare(id),
renderSharedView: ({ data }) => {
const d = data as ContainerShareData;
return (
<div className="flex flex-col gap-3">
<h2 className="text-xl font-bold">{d.name}</h2>
<p className="text-sm capitalize text-[var(--ink-mute)]">{d.type}</p>
{d.locationNotes && <p className="text-sm">{d.locationNotes}</p>}
{d.plants.length > 0 && (
<div>
<p className="text-sm font-medium mb-1">Plants</p>
<ul className="text-sm space-y-1">
{d.plants.map((p) => (
<li key={p.id}>
{p.name}
{p.scientificName && (
<span className="text-[var(--ink-mute)] italic ml-1">
({p.scientificName})
</span>
)}
</li>
))}
</ul>
</div>
)}
</div>
);
},
renderActivity: (entry) => {
const name = entry.payload?.name as string | undefined;
if (entry.action === "create") return `Created container${name ? ` "${name}"` : ""}`;
if (entry.action === "delete") return "Deleted container";
return `Updated container${name ? ` "${name}"` : ""}`;
},
},
],
dashboardWidgets: [],
quickAdds: [],
quickAdds: [
{
id: "garden.add-container",
label: "Add container",
icon: "sprout",
url: "/garden/containers/new",
},
],
};
export default gardenManifest;
+95 -1
View File
@@ -1,3 +1,97 @@
"use server";
// Garden server actions — implemented in tasks 7174
import { and, eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { db } from "@/lib/db";
import { getCurrentSession } from "@/lib/session";
import { logActivity } from "@/modules/_core/activity";
import { gardenContainers } from "../schema";
const containerInput = z.object({
name: z.string().trim().min(1).max(120),
type: z.string().trim().min(1).max(40).default("other"),
locationNotes: z.string().trim().max(500).nullable().optional(),
coverImageUrl: z.string().trim().max(500).nullable().optional(),
});
export async function createContainer(input: z.input<typeof containerInput>) {
const parsed = containerInput.parse(input);
const { household } = await getCurrentSession();
const [container] = await db
.insert(gardenContainers)
.values({
householdId: household.id,
name: parsed.name,
type: parsed.type,
locationNotes: parsed.locationNotes ?? null,
coverImageUrl: parsed.coverImageUrl ?? null,
})
.returning();
if (!container) throw new Error("Container was not created");
await logActivity({
entityType: "garden.container",
entityId: container.id,
action: "create",
payload: { name: container.name },
});
revalidatePath("/garden");
return container;
}
export async function updateContainer(
input: { id: string } & Partial<z.input<typeof containerInput>>,
) {
const parsed = z.object({ id: z.string().uuid() }).and(containerInput.partial()).parse(input);
const { household } = await getCurrentSession();
await assertCanAccessContainer(parsed.id, household.id);
await db
.update(gardenContainers)
.set({
name: parsed.name,
type: parsed.type,
locationNotes:
parsed.locationNotes === undefined ? undefined : (parsed.locationNotes ?? null),
coverImageUrl:
parsed.coverImageUrl === undefined ? undefined : (parsed.coverImageUrl ?? null),
updatedAt: new Date(),
})
.where(eq(gardenContainers.id, parsed.id));
await logActivity({
entityType: "garden.container",
entityId: parsed.id,
action: "update",
payload: { name: parsed.name },
});
revalidatePath("/garden");
revalidatePath(`/garden/containers/${parsed.id}`);
}
export async function deleteContainer(input: { id: string }) {
const parsed = z.object({ id: z.string().uuid() }).parse(input);
const { household } = await getCurrentSession();
await assertCanAccessContainer(parsed.id, household.id);
await logActivity({
entityType: "garden.container",
entityId: parsed.id,
action: "delete",
});
await db.delete(gardenContainers).where(eq(gardenContainers.id, parsed.id));
revalidatePath("/garden");
}
async function assertCanAccessContainer(id: string, householdId: string) {
const [row] = await db
.select({ id: gardenContainers.id })
.from(gardenContainers)
.where(and(eq(gardenContainers.id, id), eq(gardenContainers.householdId, householdId)))
.limit(1);
if (!row) throw new Error("Forbidden");
}
+135 -1
View File
@@ -1 +1,135 @@
// Garden query functions — implemented in tasks 7174
import { and, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db";
import { getCurrentSession } from "@/lib/session";
import { gardenContainers, gardenPlants } from "../schema";
export type ContainerDto = {
id: string;
householdId: string;
name: string;
type: string;
locationNotes: string | null;
coverImageUrl: string | null;
plantCount: number;
createdAt: string;
updatedAt: string;
};
export type ContainerDetailDto = ContainerDto & {
plants: PlantSummaryDto[];
};
export type PlantSummaryDto = {
id: string;
name: string;
scientificName: string | null;
healthStatus: string;
primaryImageUrl: string | null;
category: string;
};
export async function listContainers(): Promise<ContainerDto[]> {
const { household } = await getCurrentSession();
const rows = await db
.select({
id: gardenContainers.id,
householdId: gardenContainers.householdId,
name: gardenContainers.name,
type: gardenContainers.type,
locationNotes: gardenContainers.locationNotes,
coverImageUrl: gardenContainers.coverImageUrl,
createdAt: gardenContainers.createdAt,
updatedAt: gardenContainers.updatedAt,
plantCount: sql<number>`count(${gardenPlants.id})::int`,
})
.from(gardenContainers)
.leftJoin(gardenPlants, eq(gardenPlants.containerId, gardenContainers.id))
.where(eq(gardenContainers.householdId, household.id))
.groupBy(gardenContainers.id)
.orderBy(gardenContainers.name);
return rows.map((r) => ({
...r,
plantCount: r.plantCount ?? 0,
createdAt: r.createdAt.toISOString(),
updatedAt: r.updatedAt.toISOString(),
}));
}
export async function getContainer(id: string): Promise<ContainerDetailDto | null> {
const { household } = await getCurrentSession();
const [container] = await db
.select({
id: gardenContainers.id,
householdId: gardenContainers.householdId,
name: gardenContainers.name,
type: gardenContainers.type,
locationNotes: gardenContainers.locationNotes,
coverImageUrl: gardenContainers.coverImageUrl,
createdAt: gardenContainers.createdAt,
updatedAt: gardenContainers.updatedAt,
plantCount: sql<number>`(select count(*)::int from garden_plants where container_id = ${gardenContainers.id})`,
})
.from(gardenContainers)
.where(and(eq(gardenContainers.id, id), eq(gardenContainers.householdId, household.id)))
.limit(1);
if (!container) return null;
const plants = await db
.select({
id: gardenPlants.id,
name: gardenPlants.name,
scientificName: gardenPlants.scientificName,
healthStatus: gardenPlants.healthStatus,
primaryImageUrl: gardenPlants.primaryImageUrl,
category: gardenPlants.category,
})
.from(gardenPlants)
.where(eq(gardenPlants.containerId, id))
.orderBy(desc(gardenPlants.name));
return {
id: container.id,
householdId: container.householdId,
name: container.name,
type: container.type,
locationNotes: container.locationNotes,
coverImageUrl: container.coverImageUrl,
plantCount: container.plantCount ?? 0,
createdAt: container.createdAt.toISOString(),
updatedAt: container.updatedAt.toISOString(),
plants,
};
}
export async function canAccessContainer(id: string, householdId: string): Promise<boolean> {
const [row] = await db
.select({ id: gardenContainers.id })
.from(gardenContainers)
.where(and(eq(gardenContainers.id, id), eq(gardenContainers.householdId, householdId)))
.limit(1);
return !!row;
}
export async function searchContainers(query: string, householdId: string) {
const rows = await db
.select({ id: gardenContainers.id, name: gardenContainers.name })
.from(gardenContainers)
.where(
and(
eq(gardenContainers.householdId, householdId),
sql`${gardenContainers.name} ilike ${`%${query}%`}`,
),
)
.limit(10);
return rows.map((r) => ({
id: r.id,
title: r.name,
url: `/garden/containers/${r.id}`,
}));
}
@@ -0,0 +1,40 @@
import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { gardenContainers, gardenPlants } from "../schema";
export type ContainerShareData = {
id: string;
name: string;
type: string;
locationNotes: string | null;
coverImageUrl: string | null;
plants: { id: string; name: string; scientificName: string | null }[];
};
export async function loadContainerForShare(id: string): Promise<ContainerShareData | null> {
const [container] = await db
.select()
.from(gardenContainers)
.where(eq(gardenContainers.id, id))
.limit(1);
if (!container) return null;
const plants = await db
.select({
id: gardenPlants.id,
name: gardenPlants.name,
scientificName: gardenPlants.scientificName,
})
.from(gardenPlants)
.where(and(eq(gardenPlants.containerId, id)));
return {
id: container.id,
name: container.name,
type: container.type,
locationNotes: container.locationNotes,
coverImageUrl: container.coverImageUrl,
plants,
};
}
+31
View File
@@ -0,0 +1,31 @@
import { test, expect } from "@playwright/test";
test("garden containers happy path", async ({ page }) => {
await page.goto("/garden");
await expect(page.getByRole("heading", { name: "Garden" })).toBeVisible();
// Create a container
await page.getByRole("button", { name: /new container/i }).click();
await page.getByLabel("Name").fill("Living Room Shelf");
await page.getByLabel("Type").selectOption("shelf");
await page.getByRole("button", { name: /save|create/i }).click();
// Verify it appears in the list
await expect(page.getByText("Living Room Shelf")).toBeVisible();
// Open the container detail
await page.getByText("Living Room Shelf").click();
await expect(page.getByRole("heading", { name: "Living Room Shelf" })).toBeVisible();
// Edit the container
await page.getByRole("button", { name: /edit/i }).click();
await page.getByLabel("Name").fill("Living Room Shelf (Updated)");
await page.getByRole("button", { name: /save/i }).click();
await expect(page.getByRole("heading", { name: "Living Room Shelf (Updated)" })).toBeVisible();
// Delete the container
await page.getByRole("button", { name: /delete/i }).click();
await page.getByRole("button", { name: /confirm|yes/i }).click();
await expect(page).toHaveURL(/\/garden/);
await expect(page.getByText("Living Room Shelf")).toBeHidden();
});