feat: garden plants crud (task 72)

- perenual species lookup with 24h db cache (api key optional)
- /api/garden/species-search route handler
- createPlant / updatePlant / deletePlant server actions
- addPlantImage / removePlantImage / setPrimaryImage actions (max 10)
- listPlants query grouped by container with last-watered subquery
- getPlant query with care log summary and active schedules
- plant-form client component with species autofill and image upload
- plant-list server component grouped by container with unassigned bucket
- plant-detail client component with info/gallery/care tabs
- species-search debounced combobox component
- /garden/plants/new, /[id], /[id]/edit pages
- garden.plant entity registered with search and share support
- /garden page updated to containers/plants tabs (default: containers)
This commit is contained in:
ginnoir
2026-06-01 20:13:20 -05:00
parent a86f5471ce
commit f3e38c576c
14 changed files with 1598 additions and 8 deletions
@@ -0,0 +1,259 @@
"use client";
import { useState, useTransition } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { deletePlant, addPlantImage, removePlantImage, setPrimaryImage } from "../server/actions";
import type { PlantDetailDto } from "../server/queries";
type Tab = "info" | "gallery" | "care";
type Props = { plant: PlantDetailDto };
function InfoRow({
label,
value,
children,
}: {
label: string;
value?: string | null;
children?: React.ReactNode;
}) {
if (!value && !children) return null;
return (
<div className="flex gap-3">
<span className="text-sm text-[var(--ink-mute)] w-28 shrink-0">{label}</span>
<span className="text-sm">{children ?? value}</span>
</div>
);
}
function healthBadgeClass(status: string): string {
if (status === "healthy") return "badge-success";
if (status === "sick") return "badge-danger";
return "badge-warning";
}
export function PlantDetail({ plant }: Props) {
const [tab, setTab] = useState<Tab>("info");
const [confirming, setConfirming] = useState(false);
const [isPending, startTransition] = useTransition();
const [galleryError, setGalleryError] = useState<string | null>(null);
const [uploadingImage, setUploadingImage] = useState(false);
const router = useRouter();
function handleDelete() {
startTransition(async () => {
await deletePlant({ id: plant.id });
router.push("/garden");
router.refresh();
});
}
async function handleImageUpload(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0];
if (!file) return;
setGalleryError(null);
setUploadingImage(true);
try {
const fd = new FormData();
fd.append("file", file);
const res = await fetch("/api/uploads", { method: "POST", body: fd });
if (!res.ok) throw new Error("Upload failed");
const data = (await res.json()) as { url: string };
await addPlantImage({ id: plant.id, url: data.url });
router.refresh();
} catch {
setGalleryError("Image upload failed.");
} finally {
setUploadingImage(false);
e.target.value = "";
}
}
function handleRemoveImage(url: string) {
startTransition(async () => {
await removePlantImage({ id: plant.id, url });
router.refresh();
});
}
function handleSetPrimary(url: string) {
startTransition(async () => {
await setPrimaryImage({ id: plant.id, url });
router.refresh();
});
}
return (
<div className="flex flex-col gap-5">
{/* Header */}
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-4">
{plant.primaryImageUrl && (
<img
src={plant.primaryImageUrl}
alt=""
className="w-16 h-16 rounded-lg object-cover shrink-0"
/>
)}
<div>
<h1 className="text-2xl font-bold">{plant.name}</h1>
{plant.scientificName && (
<p className="text-sm text-[var(--ink-mute)] italic mt-0.5">{plant.scientificName}</p>
)}
<div className="flex flex-wrap gap-2 mt-1">
<span className={`text-xs badge ${healthBadgeClass(plant.healthStatus)}`}>
{plant.healthStatus}
</span>
{plant.growthStage && (
<span className="text-xs badge badge-outline capitalize">{plant.growthStage}</span>
)}
</div>
</div>
</div>
<div className="flex gap-2 shrink-0">
<Link href={`/garden/plants/${plant.id}/edit`} className="btn btn-ghost btn-sm">
Edit
</Link>
{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>
{/* Tabs */}
<div className="flex gap-6 border-b border-[var(--ink-faint)]">
{(["info", "gallery", "care"] as Tab[]).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={`pb-2 text-sm font-medium capitalize transition-colors ${
tab === t
? "border-b-2 border-[var(--ink)] text-[var(--ink)]"
: "text-[var(--ink-mute)]"
}`}
>
{t}
</button>
))}
</div>
{/* Info */}
{tab === "info" && (
<div className="flex flex-col gap-2">
<InfoRow label="Category" value={plant.category} />
{plant.containerName && (
<InfoRow label="Container">
<Link href={`/garden/containers/${plant.containerId}`} className="underline">
{plant.containerName}
</Link>
</InfoRow>
)}
<InfoRow label="Acquired" value={plant.acquisitionDate} />
<InfoRow label="Sunlight" value={plant.sunlight} />
<InfoRow label="Watering" value={plant.wateringNotes} />
<InfoRow label="Fertilizing" value={plant.fertilizingNotes} />
<InfoRow label="Notes" value={plant.notes} />
{plant.recentCareLogs.length > 0 && (
<div className="mt-2">
<p className="text-xs font-semibold text-[var(--ink-mute)] uppercase tracking-wide mb-1">
Recent care
</p>
<ul className="text-sm space-y-1">
{plant.recentCareLogs.map((log) => (
<li key={log.id} className="flex gap-2 flex-wrap">
<span className="capitalize">{log.careType}</span>
<span className="text-[var(--ink-mute)]">
{new Date(log.performedAt).toLocaleDateString()}
</span>
{log.notes && <span className="text-[var(--ink-mute)]"> {log.notes}</span>}
</li>
))}
</ul>
</div>
)}
</div>
)}
{/* Gallery */}
{tab === "gallery" && (
<div className="flex flex-col gap-4">
{plant.images.length === 0 ? (
<p className="text-sm text-[var(--ink-mute)]">No photos yet.</p>
) : (
<div className="grid grid-cols-3 gap-2">
{plant.images.map((url) => (
<div key={url} className="relative group">
<img src={url} alt="" className="w-full aspect-square object-cover rounded-lg" />
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 rounded-lg flex items-center justify-center gap-3 transition-opacity">
<button
onClick={() => handleSetPrimary(url)}
disabled={isPending}
title="Set as primary"
className={`text-lg leading-none ${url === plant.primaryImageUrl ? "text-yellow-400" : "text-white"}`}
>
</button>
<button
onClick={() => handleRemoveImage(url)}
disabled={isPending}
title="Remove"
className="text-white text-lg leading-none"
>
</button>
</div>
{url === plant.primaryImageUrl && (
<span className="absolute top-1 left-1 text-xs px-1 bg-black/60 text-yellow-300 rounded">
Primary
</span>
)}
</div>
))}
</div>
)}
{galleryError && <p className="text-sm text-red-500">{galleryError}</p>}
<div className="flex items-center gap-3">
{plant.images.length < 10 && (
<label className="btn btn-ghost btn-sm cursor-pointer">
{uploadingImage ? "Uploading…" : "Upload photo"}
<input
type="file"
accept="image/*"
className="hidden"
onChange={handleImageUpload}
disabled={uploadingImage}
/>
</label>
)}
<span className="text-xs text-[var(--ink-mute)]">{plant.images.length}/10 photos</span>
</div>
</div>
)}
{/* Care */}
{tab === "care" && (
<p className="text-sm text-[var(--ink-mute)]">Care tracking coming soon.</p>
)}
</div>
);
}
@@ -0,0 +1,367 @@
"use client";
import { useState, useTransition, useRef } from "react";
import { useRouter } from "next/navigation";
import { createPlant, updatePlant } from "../server/actions";
import { SpeciesSearch } from "./species-search";
import type { PlantDetailDto, ContainerDto } from "../server/queries";
import type { SpeciesSuggestion } from "../server/species-lookup";
const CATEGORIES = [
{ value: "vegetable", label: "Vegetable" },
{ value: "fruit", label: "Fruit" },
{ value: "herb", label: "Herb" },
{ value: "flower", label: "Flower" },
{ value: "succulent", label: "Succulent" },
{ value: "cactus", label: "Cactus" },
{ value: "tropical", label: "Tropical" },
{ value: "tree", label: "Tree" },
{ value: "shrub", label: "Shrub" },
{ value: "other", label: "Other" },
];
const HEALTH_STATUSES = [
{ value: "healthy", label: "Healthy" },
{ value: "needs-attention", label: "Needs attention" },
{ value: "sick", label: "Sick" },
{ value: "dormant", label: "Dormant" },
];
const GROWTH_STAGES = [
{ value: "", label: "Unknown" },
{ value: "seedling", label: "Seedling" },
{ value: "sprout", label: "Sprout" },
{ value: "vegetative", label: "Vegetative" },
{ value: "budding", label: "Budding" },
{ value: "flowering", label: "Flowering" },
{ value: "ripening", label: "Ripening" },
{ value: "dormant", label: "Dormant" },
];
type Props = {
existingPlant?: PlantDetailDto;
defaultContainerId?: string | null;
containers: ContainerDto[];
};
export function PlantForm({ existingPlant, defaultContainerId, containers }: Props) {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const [images, setImages] = useState<string[]>(existingPlant?.images ?? []);
const [uploading, setUploading] = useState(false);
const [selectedSpeciesId, setSelectedSpeciesId] = useState(existingPlant?.speciesId ?? "");
const scientificNameRef = useRef<HTMLInputElement>(null);
const sunlightRef = useRef<HTMLInputElement>(null);
const wateringNotesRef = useRef<HTMLTextAreaElement>(null);
function handleSpeciesSelect(species: SpeciesSuggestion) {
setSelectedSpeciesId(species.id);
if (scientificNameRef.current) scientificNameRef.current.value = species.scientific_name;
if (sunlightRef.current) sunlightRef.current.value = species.sunlight.join(", ");
if (wateringNotesRef.current) wateringNotesRef.current.value = species.watering;
}
async function handleImageSelect(e: React.ChangeEvent<HTMLInputElement>) {
const files = Array.from(e.target.files ?? []);
if (images.length >= 10) {
setError("Maximum 10 images allowed.");
return;
}
setUploading(true);
setError(null);
try {
const urls: string[] = [];
for (const file of files) {
if (images.length + urls.length >= 10) break;
const fd = new FormData();
fd.append("file", file);
const res = await fetch("/api/uploads", { method: "POST", body: fd });
if (!res.ok) throw new Error("Upload failed");
const data = (await res.json()) as { url: string };
urls.push(data.url);
}
setImages((prev) => [...prev, ...urls]);
} catch {
setError("Image upload failed. Please try again.");
} finally {
setUploading(false);
e.target.value = "";
}
}
function handleRemoveImage(url: string) {
setImages((prev) => prev.filter((u) => u !== url));
}
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const fd = new FormData(e.currentTarget);
const input = {
name: fd.get("name") as string,
category: (fd.get("category") as string) || "other",
containerId: (fd.get("containerId") as string) || null,
healthStatus: (fd.get("healthStatus") as string) || "healthy",
growthStage: (fd.get("growthStage") as string) || null,
scientificName: scientificNameRef.current?.value || null,
speciesId: selectedSpeciesId || null,
sunlight: sunlightRef.current?.value || null,
wateringNotes: wateringNotesRef.current?.value || null,
fertilizingNotes: (fd.get("fertilizingNotes") as string) || null,
notes: (fd.get("notes") as string) || null,
acquisitionDate: (fd.get("acquisitionDate") as string) || null,
images,
primaryImageUrl: existingPlant?.primaryImageUrl ?? images[0] ?? null,
};
setError(null);
startTransition(async () => {
try {
if (existingPlant) {
await updatePlant({ id: existingPlant.id, ...input });
router.push(`/garden/plants/${existingPlant.id}`);
router.refresh();
} else {
const plant = await createPlant(input);
router.push(`/garden/plants/${plant.id}`);
}
} catch {
setError("Something went wrong. Please try again.");
}
});
}
return (
<form onSubmit={handleSubmit} className="flex flex-col gap-4 max-w-xl">
<div className="flex flex-col gap-1">
<label htmlFor="plant-name" className="text-sm font-medium">
Name <span className="text-red-500">*</span>
</label>
<input
id="plant-name"
name="name"
required
maxLength={120}
defaultValue={existingPlant?.name}
className="input"
/>
</div>
<div className="flex flex-col gap-1">
<label className="text-sm font-medium">Species lookup (optional)</label>
<SpeciesSearch
onSelect={handleSpeciesSelect}
initialValue={existingPlant?.scientificName ?? ""}
/>
<p className="text-xs text-[var(--ink-mute)]">
Search Perenual to auto-fill scientific name and care notes.
</p>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-scientific-name" className="text-sm font-medium">
Scientific name
</label>
<input
id="plant-scientific-name"
name="scientificName"
ref={scientificNameRef}
maxLength={200}
defaultValue={existingPlant?.scientificName ?? ""}
className="input"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1">
<label htmlFor="plant-category" className="text-sm font-medium">
Category
</label>
<select
id="plant-category"
name="category"
defaultValue={existingPlant?.category ?? "other"}
>
{CATEGORIES.map((c) => (
<option key={c.value} value={c.value}>
{c.label}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-container" className="text-sm font-medium">
Container
</label>
<select
id="plant-container"
name="containerId"
defaultValue={existingPlant?.containerId ?? defaultContainerId ?? ""}
>
<option value="">None</option>
{containers.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
</option>
))}
</select>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1">
<label htmlFor="plant-health" className="text-sm font-medium">
Health status
</label>
<select
id="plant-health"
name="healthStatus"
defaultValue={existingPlant?.healthStatus ?? "healthy"}
>
{HEALTH_STATUSES.map((h) => (
<option key={h.value} value={h.value}>
{h.label}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-stage" className="text-sm font-medium">
Growth stage
</label>
<select
id="plant-stage"
name="growthStage"
defaultValue={existingPlant?.growthStage ?? ""}
>
{GROWTH_STAGES.map((g) => (
<option key={g.value} value={g.value}>
{g.label}
</option>
))}
</select>
</div>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-acquired" className="text-sm font-medium">
Acquisition date
</label>
<input
id="plant-acquired"
type="date"
name="acquisitionDate"
defaultValue={existingPlant?.acquisitionDate ?? ""}
className="input"
/>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-sunlight" className="text-sm font-medium">
Sunlight requirements
</label>
<input
id="plant-sunlight"
name="sunlight"
ref={sunlightRef}
maxLength={200}
defaultValue={existingPlant?.sunlight ?? ""}
placeholder="e.g. full sun, part shade"
className="input"
/>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-watering" className="text-sm font-medium">
Watering notes
</label>
<textarea
id="plant-watering"
name="wateringNotes"
ref={wateringNotesRef}
maxLength={2000}
rows={2}
defaultValue={existingPlant?.wateringNotes ?? ""}
className="input"
/>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-fertilizing" className="text-sm font-medium">
Fertilizing notes
</label>
<textarea
id="plant-fertilizing"
name="fertilizingNotes"
maxLength={2000}
rows={2}
defaultValue={existingPlant?.fertilizingNotes ?? ""}
className="input"
/>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="plant-notes" className="text-sm font-medium">
General notes
</label>
<textarea
id="plant-notes"
name="notes"
maxLength={2000}
rows={3}
defaultValue={existingPlant?.notes ?? ""}
className="input"
/>
</div>
<div className="flex flex-col gap-2">
<label className="text-sm font-medium">Photos ({images.length}/10)</label>
{images.length > 0 && (
<div className="grid grid-cols-4 gap-2">
{images.map((url) => (
<div key={url} className="relative group">
<img src={url} alt="" className="w-full aspect-square object-cover rounded" />
<button
type="button"
onClick={() => handleRemoveImage(url)}
className="absolute top-0.5 right-0.5 bg-black/60 text-white rounded text-xs px-1 opacity-0 group-hover:opacity-100"
>
</button>
</div>
))}
</div>
)}
{images.length < 10 && (
<label className="btn btn-ghost btn-sm w-fit cursor-pointer">
{uploading ? "Uploading…" : "Add photos"}
<input
type="file"
accept="image/*"
multiple
className="hidden"
onChange={handleImageSelect}
disabled={uploading}
/>
</label>
)}
</div>
{error && <p className="text-sm text-red-500">{error}</p>}
<div className="flex gap-2 justify-end">
<a
href={existingPlant ? `/garden/plants/${existingPlant.id}` : "/garden"}
className="btn btn-ghost"
>
Cancel
</a>
<button type="submit" className="btn btn-primary" disabled={isPending || uploading}>
{isPending ? "Saving…" : existingPlant ? "Save" : "Create"}
</button>
</div>
</form>
);
}
@@ -0,0 +1,106 @@
import Link from "next/link";
import type { PlantListItemDto } from "../server/queries";
type Props = {
plants: PlantListItemDto[];
};
function daysAgo(isoString: string): string {
const diff = Date.now() - new Date(isoString).getTime();
const days = Math.floor(diff / 86_400_000);
if (days === 0) return "today";
if (days === 1) return "yesterday";
return `${days}d ago`;
}
function healthBadgeClass(status: string): string {
if (status === "healthy") return "badge-success";
if (status === "sick") return "badge-danger";
return "badge-warning";
}
export function PlantList({ plants }: Props) {
if (plants.length === 0) {
return (
<div className="flex flex-col items-center gap-3 py-8 text-center">
<p className="text-sm text-[var(--ink-mute)]">No plants yet.</p>
<Link href="/garden/plants/new" className="btn btn-primary btn-sm">
Add your first plant
</Link>
</div>
);
}
const groups = new Map<string | null, { name: string | null; items: PlantListItemDto[] }>();
for (const plant of plants) {
const key = plant.containerId;
if (!groups.has(key)) groups.set(key, { name: plant.containerName, items: [] });
groups.get(key)!.items.push(plant);
}
const entries = [...groups.entries()].sort(([a], [b]) => {
if (a === null) return 1;
if (b === null) return -1;
return 0;
});
return (
<div className="flex flex-col gap-6">
<div className="flex items-center justify-between">
<span className="text-sm text-[var(--ink-mute)]">
{plants.length} {plants.length === 1 ? "plant" : "plants"}
</span>
<Link href="/garden/plants/new" className="btn btn-primary btn-sm">
Add plant
</Link>
</div>
{entries.map(([containerId, group]) => (
<div key={containerId ?? "_unassigned"}>
<h3 className="text-xs font-semibold text-[var(--ink-mute)] uppercase tracking-wider mb-2">
{group.name ?? "Unassigned"}
</h3>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{group.items.map((plant) => (
<Link
key={plant.id}
href={`/garden/plants/${plant.id}`}
className="card p-3 hover:bg-[var(--surface-2)] transition-colors"
>
<div className="flex items-center gap-3">
{plant.primaryImageUrl ? (
<img
src={plant.primaryImageUrl}
alt=""
className="w-12 h-12 rounded-lg object-cover shrink-0"
/>
) : (
<div className="w-12 h-12 rounded-lg bg-[var(--surface-2)] shrink-0 flex items-center justify-center text-xl">
🌱
</div>
)}
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">{plant.name}</p>
<div className="flex items-center gap-2 mt-0.5 flex-wrap">
<span className={`text-xs badge ${healthBadgeClass(plant.healthStatus)}`}>
{plant.healthStatus}
</span>
{plant.lastWateredAt && (
<span className="text-xs text-[var(--ink-mute)]">
Watered {daysAgo(plant.lastWateredAt)}
</span>
)}
</div>
{plant.hasOverdueCare && (
<p className="text-xs text-amber-600 mt-0.5">Care overdue</p>
)}
</div>
</div>
</Link>
))}
</div>
</div>
))}
</div>
);
}
@@ -0,0 +1,107 @@
"use client";
import { useState, useEffect, useRef } from "react";
import type { SpeciesSuggestion } from "../server/species-lookup";
type Props = {
onSelect: (species: SpeciesSuggestion) => void;
initialValue?: string;
};
export function SpeciesSearch({ onSelect, initialValue = "" }: Props) {
const [query, setQuery] = useState(initialValue);
const [results, setResults] = useState<SpeciesSuggestion[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(
async () => {
if (!query.trim()) {
setResults([]);
setIsOpen(false);
return;
}
setIsLoading(true);
try {
const res = await fetch(`/api/garden/species-search?q=${encodeURIComponent(query)}`);
const data = (await res.json()) as SpeciesSuggestion[];
setResults(Array.isArray(data) ? data : []);
setIsOpen(Array.isArray(data) && data.length > 0);
} catch {
setResults([]);
} finally {
setIsLoading(false);
}
},
query.trim() ? 500 : 0,
);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [query]);
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setIsOpen(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
function handleSelect(species: SpeciesSuggestion) {
onSelect(species);
setQuery(species.common_name);
setIsOpen(false);
setResults([]);
}
return (
<div ref={containerRef} className="relative">
<div className="relative">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => results.length > 0 && setIsOpen(true)}
placeholder="Search by common or scientific name…"
className="input w-full"
autoComplete="off"
/>
{isLoading && (
<span className="absolute right-2 top-1/2 -translate-y-1/2 text-xs text-[var(--ink-mute)]">
</span>
)}
</div>
{isOpen && results.length > 0 && (
<ul className="absolute z-50 w-full mt-1 bg-[var(--surface-1)] border border-[var(--ink-faint)] rounded-md shadow-lg max-h-52 overflow-auto">
{results.map((s) => (
<li key={s.id}>
<button
type="button"
onClick={() => handleSelect(s)}
className="w-full text-left px-3 py-2 hover:bg-[var(--surface-2)] text-sm"
>
<span className="font-medium">{s.common_name}</span>
{s.scientific_name && (
<span className="text-[var(--ink-mute)] italic ml-2 text-xs">
{s.scientific_name}
</span>
)}
</button>
</li>
))}
</ul>
)}
</div>
);
}