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:
@@ -0,0 +1,17 @@
|
|||||||
|
import { NextResponse } from "next/server";
|
||||||
|
import { getCurrentSession } from "@/lib/session";
|
||||||
|
import { searchSpecies } from "@/modules/garden/server/species-lookup";
|
||||||
|
|
||||||
|
export async function GET(request: Request) {
|
||||||
|
try {
|
||||||
|
await getCurrentSession();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const q = searchParams.get("q") ?? "";
|
||||||
|
|
||||||
|
const results = await searchSpecies(q);
|
||||||
|
return NextResponse.json(results);
|
||||||
|
}
|
||||||
+39
-4
@@ -1,12 +1,47 @@
|
|||||||
import { listContainers } from "@/modules/garden/server/queries";
|
import Link from "next/link";
|
||||||
|
import { listContainers, listPlants } from "@/modules/garden/server/queries";
|
||||||
import { ContainerList } from "@/modules/garden/components/container-list";
|
import { ContainerList } from "@/modules/garden/components/container-list";
|
||||||
|
import { PlantList } from "@/modules/garden/components/plant-list";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
searchParams: Promise<{ tab?: string }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default async function GardenPage({ searchParams }: Props) {
|
||||||
|
const { tab = "containers" } = await searchParams;
|
||||||
|
const isPlants = tab === "plants";
|
||||||
|
|
||||||
|
const [containers, plants] = await Promise.all([
|
||||||
|
listContainers(),
|
||||||
|
isPlants ? listPlants() : Promise.resolve([]),
|
||||||
|
]);
|
||||||
|
|
||||||
export default async function GardenPage() {
|
|
||||||
const containers = await listContainers();
|
|
||||||
return (
|
return (
|
||||||
<div className="page-content">
|
<div className="page-content">
|
||||||
<h1 className="page-title">Garden</h1>
|
<h1 className="page-title">Garden</h1>
|
||||||
<ContainerList containers={containers} />
|
|
||||||
|
<div className="flex gap-6 border-b border-[var(--ink-faint)] mb-6">
|
||||||
|
<Link
|
||||||
|
href="/garden?tab=containers"
|
||||||
|
className={`pb-2 text-sm font-medium transition-colors ${
|
||||||
|
!isPlants
|
||||||
|
? "border-b-2 border-[var(--ink)] text-[var(--ink)]"
|
||||||
|
: "text-[var(--ink-mute)]"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Containers
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
href="/garden?tab=plants"
|
||||||
|
className={`pb-2 text-sm font-medium transition-colors ${
|
||||||
|
isPlants ? "border-b-2 border-[var(--ink)] text-[var(--ink)]" : "text-[var(--ink-mute)]"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Plants
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isPlants ? <PlantList plants={plants} /> : <ContainerList containers={containers} />}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { getPlant, listContainers } from "@/modules/garden/server/queries";
|
||||||
|
import { PlantForm } from "@/modules/garden/components/plant-form";
|
||||||
|
|
||||||
|
export default async function EditPlantPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const [plant, containers] = await Promise.all([getPlant(id), listContainers()]);
|
||||||
|
if (!plant) notFound();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-content max-w-xl">
|
||||||
|
<h1 className="page-title">Edit Plant</h1>
|
||||||
|
<PlantForm existingPlant={plant} containers={containers} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { getPlant } from "@/modules/garden/server/queries";
|
||||||
|
import { PlantDetail } from "@/modules/garden/components/plant-detail";
|
||||||
|
|
||||||
|
export default async function PlantPage({ params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const { id } = await params;
|
||||||
|
const plant = await getPlant(id);
|
||||||
|
if (!plant) notFound();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-content">
|
||||||
|
<PlantDetail plant={plant} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { listContainers } from "@/modules/garden/server/queries";
|
||||||
|
import { PlantForm } from "@/modules/garden/components/plant-form";
|
||||||
|
|
||||||
|
export default async function NewPlantPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ containerId?: string }>;
|
||||||
|
}) {
|
||||||
|
const params = await searchParams;
|
||||||
|
const containers = await listContainers();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-content max-w-xl">
|
||||||
|
<h1 className="page-title">Add Plant</h1>
|
||||||
|
<PlantForm containers={containers} defaultContainerId={params.containerId ?? null} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,12 +1,81 @@
|
|||||||
import type { ModuleManifest } from "../_core/module";
|
import type { ModuleManifest } from "../_core/module";
|
||||||
import { loadContainerForShare, type ContainerShareData } from "./server/share-queries";
|
import {
|
||||||
import { searchContainers } from "./server/queries";
|
loadContainerForShare,
|
||||||
|
loadPlantForShare,
|
||||||
|
type ContainerShareData,
|
||||||
|
type PlantShareData,
|
||||||
|
} from "./server/share-queries";
|
||||||
|
import { searchContainers, searchPlants } from "./server/queries";
|
||||||
|
|
||||||
const gardenManifest: ModuleManifest = {
|
const gardenManifest: ModuleManifest = {
|
||||||
id: "garden",
|
id: "garden",
|
||||||
name: "Garden",
|
name: "Garden",
|
||||||
nav: { href: "/garden", label: "Garden", icon: "sprout" },
|
nav: { href: "/garden", label: "Garden", icon: "sprout" },
|
||||||
entities: [
|
entities: [
|
||||||
|
{
|
||||||
|
type: "garden.plant",
|
||||||
|
label: { singular: "Plant", plural: "Plants" },
|
||||||
|
share: { canShare: true, defaultCapabilities: ["read"] },
|
||||||
|
search: { search: searchPlants },
|
||||||
|
resolveUrl: (id) => `/garden/plants/${id}`,
|
||||||
|
loadForShare: (id) => loadPlantForShare(id),
|
||||||
|
renderSharedView: ({ data }) => {
|
||||||
|
const d = data as PlantShareData;
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
{d.primaryImageUrl && (
|
||||||
|
<img
|
||||||
|
src={d.primaryImageUrl}
|
||||||
|
alt=""
|
||||||
|
className="w-full max-h-48 object-cover rounded-lg"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<h2 className="text-xl font-bold">{d.name}</h2>
|
||||||
|
{d.scientificName && (
|
||||||
|
<p className="text-sm italic text-[var(--ink-mute)]">{d.scientificName}</p>
|
||||||
|
)}
|
||||||
|
<p className="text-sm capitalize">
|
||||||
|
{d.healthStatus} · {d.category}
|
||||||
|
</p>
|
||||||
|
{d.wateringNotes && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-semibold uppercase text-[var(--ink-mute)] mb-1">
|
||||||
|
Watering
|
||||||
|
</p>
|
||||||
|
<p className="text-sm">{d.wateringNotes}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{d.fertilizingNotes && (
|
||||||
|
<div>
|
||||||
|
<p className="text-xs font-semibold uppercase text-[var(--ink-mute)] mb-1">
|
||||||
|
Fertilizing
|
||||||
|
</p>
|
||||||
|
<p className="text-sm">{d.fertilizingNotes}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{d.notes && <p className="text-sm">{d.notes}</p>}
|
||||||
|
{d.images.length > 1 && (
|
||||||
|
<div className="grid grid-cols-3 gap-2 mt-1">
|
||||||
|
{d.images.slice(1).map((url) => (
|
||||||
|
<img
|
||||||
|
key={url}
|
||||||
|
src={url}
|
||||||
|
alt=""
|
||||||
|
className="w-full aspect-square object-cover rounded"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
renderActivity: (entry) => {
|
||||||
|
const name = entry.payload?.name as string | undefined;
|
||||||
|
if (entry.action === "create") return `Added plant${name ? ` "${name}"` : ""}`;
|
||||||
|
if (entry.action === "delete") return `Removed plant${name ? ` "${name}"` : ""}`;
|
||||||
|
return `Updated${name ? ` "${name}"` : " plant"}`;
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
type: "garden.container",
|
type: "garden.container",
|
||||||
label: { singular: "Container", plural: "Containers" },
|
label: { singular: "Container", plural: "Containers" },
|
||||||
@@ -51,6 +120,12 @@ const gardenManifest: ModuleManifest = {
|
|||||||
],
|
],
|
||||||
dashboardWidgets: [],
|
dashboardWidgets: [],
|
||||||
quickAdds: [
|
quickAdds: [
|
||||||
|
{
|
||||||
|
id: "garden.add-plant",
|
||||||
|
label: "Add plant",
|
||||||
|
icon: "sprout",
|
||||||
|
url: "/garden/plants/new",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "garden.add-container",
|
id: "garden.add-container",
|
||||||
label: "Add container",
|
label: "Add container",
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
|||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getCurrentSession } from "@/lib/session";
|
import { getCurrentSession } from "@/lib/session";
|
||||||
import { logActivity } from "@/modules/_core/activity";
|
import { logActivity } from "@/modules/_core/activity";
|
||||||
import { gardenContainers } from "../schema";
|
import { gardenContainers, gardenPlants } from "../schema";
|
||||||
|
|
||||||
const containerInput = z.object({
|
const containerInput = z.object({
|
||||||
name: z.string().trim().min(1).max(120),
|
name: z.string().trim().min(1).max(120),
|
||||||
@@ -95,3 +95,213 @@ async function assertCanAccessContainer(id: string, householdId: string) {
|
|||||||
|
|
||||||
if (!row) throw new Error("Forbidden");
|
if (!row) throw new Error("Forbidden");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Plant actions ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const plantInput = z.object({
|
||||||
|
name: z.string().trim().min(1).max(120),
|
||||||
|
category: z.string().trim().min(1).max(40).default("other"),
|
||||||
|
containerId: z.string().uuid().nullable().optional(),
|
||||||
|
healthStatus: z.string().trim().min(1).max(40).default("healthy"),
|
||||||
|
growthStage: z.string().trim().max(40).nullable().optional(),
|
||||||
|
scientificName: z.string().trim().max(200).nullable().optional(),
|
||||||
|
speciesId: z.string().trim().max(100).nullable().optional(),
|
||||||
|
sunlight: z.string().trim().max(200).nullable().optional(),
|
||||||
|
wateringNotes: z.string().trim().max(2000).nullable().optional(),
|
||||||
|
fertilizingNotes: z.string().trim().max(2000).nullable().optional(),
|
||||||
|
notes: z.string().trim().max(2000).nullable().optional(),
|
||||||
|
acquisitionDate: z.string().nullable().optional(),
|
||||||
|
images: z.array(z.string().url()).max(10).default([]),
|
||||||
|
primaryImageUrl: z.string().url().nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function createPlant(input: z.input<typeof plantInput>) {
|
||||||
|
const parsed = plantInput.parse(input);
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
|
||||||
|
if (parsed.containerId) {
|
||||||
|
await assertCanAccessContainer(parsed.containerId, household.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [plant] = await db
|
||||||
|
.insert(gardenPlants)
|
||||||
|
.values({
|
||||||
|
householdId: household.id,
|
||||||
|
name: parsed.name,
|
||||||
|
category: parsed.category ?? "other",
|
||||||
|
containerId: parsed.containerId ?? null,
|
||||||
|
healthStatus: parsed.healthStatus ?? "healthy",
|
||||||
|
growthStage: parsed.growthStage ?? null,
|
||||||
|
scientificName: parsed.scientificName ?? null,
|
||||||
|
speciesId: parsed.speciesId ?? null,
|
||||||
|
sunlight: parsed.sunlight ?? null,
|
||||||
|
wateringNotes: parsed.wateringNotes ?? null,
|
||||||
|
fertilizingNotes: parsed.fertilizingNotes ?? null,
|
||||||
|
notes: parsed.notes ?? null,
|
||||||
|
acquisitionDate: parsed.acquisitionDate ?? null,
|
||||||
|
images: parsed.images,
|
||||||
|
primaryImageUrl: parsed.primaryImageUrl ?? parsed.images[0] ?? null,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (!plant) throw new Error("Plant was not created");
|
||||||
|
|
||||||
|
await logActivity({
|
||||||
|
entityType: "garden.plant",
|
||||||
|
entityId: plant.id,
|
||||||
|
action: "create",
|
||||||
|
payload: { name: plant.name },
|
||||||
|
});
|
||||||
|
revalidatePath("/garden");
|
||||||
|
return plant;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updatePlant(input: { id: string } & Partial<z.input<typeof plantInput>>) {
|
||||||
|
const parsed = z.object({ id: z.string().uuid() }).and(plantInput.partial()).parse(input);
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
await assertCanAccessPlant(parsed.id, household.id);
|
||||||
|
|
||||||
|
if (parsed.containerId) {
|
||||||
|
await assertCanAccessContainer(parsed.containerId, household.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(gardenPlants)
|
||||||
|
.set({
|
||||||
|
name: parsed.name,
|
||||||
|
category: parsed.category,
|
||||||
|
containerId: parsed.containerId === undefined ? undefined : (parsed.containerId ?? null),
|
||||||
|
healthStatus: parsed.healthStatus,
|
||||||
|
growthStage: parsed.growthStage === undefined ? undefined : (parsed.growthStage ?? null),
|
||||||
|
scientificName:
|
||||||
|
parsed.scientificName === undefined ? undefined : (parsed.scientificName ?? null),
|
||||||
|
speciesId: parsed.speciesId === undefined ? undefined : (parsed.speciesId ?? null),
|
||||||
|
sunlight: parsed.sunlight === undefined ? undefined : (parsed.sunlight ?? null),
|
||||||
|
wateringNotes:
|
||||||
|
parsed.wateringNotes === undefined ? undefined : (parsed.wateringNotes ?? null),
|
||||||
|
fertilizingNotes:
|
||||||
|
parsed.fertilizingNotes === undefined ? undefined : (parsed.fertilizingNotes ?? null),
|
||||||
|
notes: parsed.notes === undefined ? undefined : (parsed.notes ?? null),
|
||||||
|
acquisitionDate:
|
||||||
|
parsed.acquisitionDate === undefined ? undefined : (parsed.acquisitionDate ?? null),
|
||||||
|
images: parsed.images,
|
||||||
|
primaryImageUrl:
|
||||||
|
parsed.primaryImageUrl === undefined ? undefined : (parsed.primaryImageUrl ?? null),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
})
|
||||||
|
.where(eq(gardenPlants.id, parsed.id));
|
||||||
|
|
||||||
|
await logActivity({
|
||||||
|
entityType: "garden.plant",
|
||||||
|
entityId: parsed.id,
|
||||||
|
action: "update",
|
||||||
|
payload: { name: parsed.name },
|
||||||
|
});
|
||||||
|
revalidatePath("/garden");
|
||||||
|
revalidatePath(`/garden/plants/${parsed.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePlant(input: { id: string }) {
|
||||||
|
const parsed = z.object({ id: z.string().uuid() }).parse(input);
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
await assertCanAccessPlant(parsed.id, household.id);
|
||||||
|
|
||||||
|
const [plant] = await db
|
||||||
|
.select({ name: gardenPlants.name })
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(eq(gardenPlants.id, parsed.id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
await logActivity({
|
||||||
|
entityType: "garden.plant",
|
||||||
|
entityId: parsed.id,
|
||||||
|
action: "delete",
|
||||||
|
payload: { name: plant?.name },
|
||||||
|
});
|
||||||
|
await db.delete(gardenPlants).where(eq(gardenPlants.id, parsed.id));
|
||||||
|
revalidatePath("/garden");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addPlantImage(input: { id: string; url: string }) {
|
||||||
|
const parsed = z.object({ id: z.string().uuid(), url: z.string().url() }).parse(input);
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
await assertCanAccessPlant(parsed.id, household.id);
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.select({ images: gardenPlants.images })
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(eq(gardenPlants.id, parsed.id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!row) throw new Error("Plant not found");
|
||||||
|
if (row.images.length >= 10) throw new Error("Maximum 10 images allowed");
|
||||||
|
|
||||||
|
const newImages = [...row.images, parsed.url];
|
||||||
|
await db
|
||||||
|
.update(gardenPlants)
|
||||||
|
.set({
|
||||||
|
images: newImages,
|
||||||
|
primaryImageUrl: row.images.length === 0 ? parsed.url : undefined,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
})
|
||||||
|
.where(eq(gardenPlants.id, parsed.id));
|
||||||
|
|
||||||
|
revalidatePath(`/garden/plants/${parsed.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removePlantImage(input: { id: string; url: string }) {
|
||||||
|
const parsed = z.object({ id: z.string().uuid(), url: z.string() }).parse(input);
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
await assertCanAccessPlant(parsed.id, household.id);
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.select({ images: gardenPlants.images, primaryImageUrl: gardenPlants.primaryImageUrl })
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(eq(gardenPlants.id, parsed.id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!row) throw new Error("Plant not found");
|
||||||
|
|
||||||
|
const newImages = row.images.filter((u) => u !== parsed.url);
|
||||||
|
const wasPrimary = row.primaryImageUrl === parsed.url;
|
||||||
|
const newPrimary = wasPrimary ? (newImages[0] ?? null) : row.primaryImageUrl;
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(gardenPlants)
|
||||||
|
.set({ images: newImages, primaryImageUrl: newPrimary, updatedAt: new Date() })
|
||||||
|
.where(eq(gardenPlants.id, parsed.id));
|
||||||
|
|
||||||
|
revalidatePath(`/garden/plants/${parsed.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setPrimaryImage(input: { id: string; url: string }) {
|
||||||
|
const parsed = z.object({ id: z.string().uuid(), url: z.string() }).parse(input);
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
await assertCanAccessPlant(parsed.id, household.id);
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.select({ images: gardenPlants.images })
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(eq(gardenPlants.id, parsed.id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!row) throw new Error("Plant not found");
|
||||||
|
if (!row.images.includes(parsed.url)) throw new Error("Image not in plant gallery");
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(gardenPlants)
|
||||||
|
.set({ primaryImageUrl: parsed.url, updatedAt: new Date() })
|
||||||
|
.where(eq(gardenPlants.id, parsed.id));
|
||||||
|
|
||||||
|
revalidatePath(`/garden/plants/${parsed.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function assertCanAccessPlant(id: string, householdId: string) {
|
||||||
|
const [row] = await db
|
||||||
|
.select({ id: gardenPlants.id })
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(and(eq(gardenPlants.id, id), eq(gardenPlants.householdId, householdId)))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!row) throw new Error("Forbidden");
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { and, desc, eq, sql } from "drizzle-orm";
|
import { and, desc, eq, sql } from "drizzle-orm";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getCurrentSession } from "@/lib/session";
|
import { getCurrentSession } from "@/lib/session";
|
||||||
import { gardenContainers, gardenPlants } from "../schema";
|
import { gardenCareLogs, gardenCareSchedules, gardenContainers, gardenPlants } from "../schema";
|
||||||
|
|
||||||
export type ContainerDto = {
|
export type ContainerDto = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -133,3 +133,215 @@ export async function searchContainers(query: string, householdId: string) {
|
|||||||
url: `/garden/containers/${r.id}`,
|
url: `/garden/containers/${r.id}`,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Plant queries ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export type PlantListItemDto = {
|
||||||
|
id: string;
|
||||||
|
containerId: string | null;
|
||||||
|
containerName: string | null;
|
||||||
|
name: string;
|
||||||
|
healthStatus: string;
|
||||||
|
primaryImageUrl: string | null;
|
||||||
|
category: string;
|
||||||
|
lastWateredAt: string | null;
|
||||||
|
hasOverdueCare: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CareLogSummaryDto = {
|
||||||
|
id: string;
|
||||||
|
careType: string;
|
||||||
|
notes: string | null;
|
||||||
|
performedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CareScheduleSummaryDto = {
|
||||||
|
id: string;
|
||||||
|
careType: string;
|
||||||
|
intervalDays: number;
|
||||||
|
nextDueAt: string | null;
|
||||||
|
enabled: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PlantDetailDto = {
|
||||||
|
id: string;
|
||||||
|
householdId: string;
|
||||||
|
containerId: string | null;
|
||||||
|
containerName: string | null;
|
||||||
|
name: string;
|
||||||
|
scientificName: string | null;
|
||||||
|
speciesId: string | null;
|
||||||
|
category: string;
|
||||||
|
notes: string | null;
|
||||||
|
acquisitionDate: string | null;
|
||||||
|
growthStage: string | null;
|
||||||
|
healthStatus: string;
|
||||||
|
sunlight: string | null;
|
||||||
|
wateringNotes: string | null;
|
||||||
|
fertilizingNotes: string | null;
|
||||||
|
primaryImageUrl: string | null;
|
||||||
|
images: string[];
|
||||||
|
recentCareLogs: CareLogSummaryDto[];
|
||||||
|
activeSchedules: CareScheduleSummaryDto[];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function listPlants({ containerId }: { containerId?: string } = {}): Promise<
|
||||||
|
PlantListItemDto[]
|
||||||
|
> {
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
|
||||||
|
const filter = containerId
|
||||||
|
? and(eq(gardenPlants.householdId, household.id), eq(gardenPlants.containerId, containerId))
|
||||||
|
: eq(gardenPlants.householdId, household.id);
|
||||||
|
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
id: gardenPlants.id,
|
||||||
|
containerId: gardenPlants.containerId,
|
||||||
|
containerName: gardenContainers.name,
|
||||||
|
name: gardenPlants.name,
|
||||||
|
healthStatus: gardenPlants.healthStatus,
|
||||||
|
primaryImageUrl: gardenPlants.primaryImageUrl,
|
||||||
|
category: gardenPlants.category,
|
||||||
|
lastWateredAt: sql<string | null>`(
|
||||||
|
select performed_at::text from garden_care_logs
|
||||||
|
where plant_id = ${gardenPlants.id}
|
||||||
|
and care_type = 'watering'
|
||||||
|
order by performed_at desc
|
||||||
|
limit 1
|
||||||
|
)`,
|
||||||
|
hasOverdueCare: sql<boolean>`exists(
|
||||||
|
select 1 from garden_care_schedules
|
||||||
|
where plant_id = ${gardenPlants.id}
|
||||||
|
and enabled = true
|
||||||
|
and next_due_at < now()
|
||||||
|
)`,
|
||||||
|
})
|
||||||
|
.from(gardenPlants)
|
||||||
|
.leftJoin(gardenContainers, eq(gardenPlants.containerId, gardenContainers.id))
|
||||||
|
.where(filter)
|
||||||
|
.orderBy(gardenContainers.name, gardenPlants.name);
|
||||||
|
|
||||||
|
return rows.map((r) => ({
|
||||||
|
...r,
|
||||||
|
containerName: r.containerName ?? null,
|
||||||
|
lastWateredAt: r.lastWateredAt ?? null,
|
||||||
|
hasOverdueCare: !!r.hasOverdueCare,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPlant(id: string): Promise<PlantDetailDto | null> {
|
||||||
|
const { household } = await getCurrentSession();
|
||||||
|
|
||||||
|
const [row] = await db
|
||||||
|
.select({
|
||||||
|
id: gardenPlants.id,
|
||||||
|
householdId: gardenPlants.householdId,
|
||||||
|
containerId: gardenPlants.containerId,
|
||||||
|
containerName: gardenContainers.name,
|
||||||
|
name: gardenPlants.name,
|
||||||
|
scientificName: gardenPlants.scientificName,
|
||||||
|
speciesId: gardenPlants.speciesId,
|
||||||
|
category: gardenPlants.category,
|
||||||
|
notes: gardenPlants.notes,
|
||||||
|
acquisitionDate: gardenPlants.acquisitionDate,
|
||||||
|
growthStage: gardenPlants.growthStage,
|
||||||
|
healthStatus: gardenPlants.healthStatus,
|
||||||
|
sunlight: gardenPlants.sunlight,
|
||||||
|
wateringNotes: gardenPlants.wateringNotes,
|
||||||
|
fertilizingNotes: gardenPlants.fertilizingNotes,
|
||||||
|
primaryImageUrl: gardenPlants.primaryImageUrl,
|
||||||
|
images: gardenPlants.images,
|
||||||
|
createdAt: gardenPlants.createdAt,
|
||||||
|
updatedAt: gardenPlants.updatedAt,
|
||||||
|
})
|
||||||
|
.from(gardenPlants)
|
||||||
|
.leftJoin(gardenContainers, eq(gardenPlants.containerId, gardenContainers.id))
|
||||||
|
.where(and(eq(gardenPlants.id, id), eq(gardenPlants.householdId, household.id)))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!row) return null;
|
||||||
|
|
||||||
|
const careLogs = await db
|
||||||
|
.select({
|
||||||
|
id: gardenCareLogs.id,
|
||||||
|
careType: gardenCareLogs.careType,
|
||||||
|
notes: gardenCareLogs.notes,
|
||||||
|
performedAt: gardenCareLogs.performedAt,
|
||||||
|
})
|
||||||
|
.from(gardenCareLogs)
|
||||||
|
.where(eq(gardenCareLogs.plantId, id))
|
||||||
|
.orderBy(desc(gardenCareLogs.performedAt))
|
||||||
|
.limit(5);
|
||||||
|
|
||||||
|
const schedules = await db
|
||||||
|
.select({
|
||||||
|
id: gardenCareSchedules.id,
|
||||||
|
careType: gardenCareSchedules.careType,
|
||||||
|
intervalDays: gardenCareSchedules.intervalDays,
|
||||||
|
nextDueAt: gardenCareSchedules.nextDueAt,
|
||||||
|
enabled: gardenCareSchedules.enabled,
|
||||||
|
})
|
||||||
|
.from(gardenCareSchedules)
|
||||||
|
.where(and(eq(gardenCareSchedules.plantId, id), eq(gardenCareSchedules.enabled, true)));
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
householdId: row.householdId,
|
||||||
|
containerId: row.containerId,
|
||||||
|
containerName: row.containerName ?? null,
|
||||||
|
name: row.name,
|
||||||
|
scientificName: row.scientificName,
|
||||||
|
speciesId: row.speciesId,
|
||||||
|
category: row.category,
|
||||||
|
notes: row.notes,
|
||||||
|
acquisitionDate: row.acquisitionDate,
|
||||||
|
growthStage: row.growthStage,
|
||||||
|
healthStatus: row.healthStatus,
|
||||||
|
sunlight: row.sunlight,
|
||||||
|
wateringNotes: row.wateringNotes,
|
||||||
|
fertilizingNotes: row.fertilizingNotes,
|
||||||
|
primaryImageUrl: row.primaryImageUrl,
|
||||||
|
images: row.images,
|
||||||
|
recentCareLogs: careLogs.map((l) => ({
|
||||||
|
id: l.id,
|
||||||
|
careType: l.careType,
|
||||||
|
notes: l.notes,
|
||||||
|
performedAt: l.performedAt.toISOString(),
|
||||||
|
})),
|
||||||
|
activeSchedules: schedules.map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
careType: s.careType,
|
||||||
|
intervalDays: s.intervalDays,
|
||||||
|
nextDueAt: s.nextDueAt?.toISOString() ?? null,
|
||||||
|
enabled: s.enabled,
|
||||||
|
})),
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchPlants(query: string, householdId: string) {
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
id: gardenPlants.id,
|
||||||
|
name: gardenPlants.name,
|
||||||
|
scientificName: gardenPlants.scientificName,
|
||||||
|
})
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(gardenPlants.householdId, householdId),
|
||||||
|
sql`(${gardenPlants.name} || ' ' || coalesce(${gardenPlants.scientificName}, '')) ilike ${`%${query}%`}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(10);
|
||||||
|
|
||||||
|
return rows.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
title: r.name + (r.scientificName ? ` (${r.scientificName})` : ""),
|
||||||
|
url: `/garden/plants/${r.id}`,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,45 @@ export type ContainerShareData = {
|
|||||||
plants: { id: string; name: string; scientificName: string | null }[];
|
plants: { id: string; name: string; scientificName: string | null }[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type PlantShareData = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
scientificName: string | null;
|
||||||
|
primaryImageUrl: string | null;
|
||||||
|
images: string[];
|
||||||
|
healthStatus: string;
|
||||||
|
growthStage: string | null;
|
||||||
|
category: string;
|
||||||
|
wateringNotes: string | null;
|
||||||
|
fertilizingNotes: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
sunlight: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function loadPlantForShare(id: string): Promise<PlantShareData | null> {
|
||||||
|
const [plant] = await db
|
||||||
|
.select({
|
||||||
|
id: gardenPlants.id,
|
||||||
|
name: gardenPlants.name,
|
||||||
|
scientificName: gardenPlants.scientificName,
|
||||||
|
primaryImageUrl: gardenPlants.primaryImageUrl,
|
||||||
|
images: gardenPlants.images,
|
||||||
|
healthStatus: gardenPlants.healthStatus,
|
||||||
|
growthStage: gardenPlants.growthStage,
|
||||||
|
category: gardenPlants.category,
|
||||||
|
wateringNotes: gardenPlants.wateringNotes,
|
||||||
|
fertilizingNotes: gardenPlants.fertilizingNotes,
|
||||||
|
notes: gardenPlants.notes,
|
||||||
|
sunlight: gardenPlants.sunlight,
|
||||||
|
})
|
||||||
|
.from(gardenPlants)
|
||||||
|
.where(eq(gardenPlants.id, id))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!plant) return null;
|
||||||
|
return plant;
|
||||||
|
}
|
||||||
|
|
||||||
export async function loadContainerForShare(id: string): Promise<ContainerShareData | null> {
|
export async function loadContainerForShare(id: string): Promise<ContainerShareData | null> {
|
||||||
const [container] = await db
|
const [container] = await db
|
||||||
.select()
|
.select()
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { and, eq, gt } from "drizzle-orm";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { gardenSpeciesCache } from "../schema";
|
||||||
|
|
||||||
|
export type SpeciesSuggestion = {
|
||||||
|
id: string;
|
||||||
|
common_name: string;
|
||||||
|
scientific_name: string;
|
||||||
|
watering: string;
|
||||||
|
sunlight: string[];
|
||||||
|
cycle: string;
|
||||||
|
default_image_url: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const BASE_URL = "https://perenual.com";
|
||||||
|
|
||||||
|
function parseItem(item: Record<string, unknown>): SpeciesSuggestion {
|
||||||
|
const rawNames = item.scientific_name;
|
||||||
|
const scientificName = Array.isArray(rawNames) && rawNames.length > 0 ? String(rawNames[0]) : "";
|
||||||
|
|
||||||
|
const sunlight = Array.isArray(item.sunlight) ? item.sunlight.map(String) : [];
|
||||||
|
|
||||||
|
const defaultImage = item.default_image as Record<string, unknown> | null | undefined;
|
||||||
|
const rawImageUrl = defaultImage?.regular_url ?? defaultImage?.medium_url ?? null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: String(item.id),
|
||||||
|
common_name: String(item.common_name ?? ""),
|
||||||
|
scientific_name: scientificName,
|
||||||
|
watering: String(item.watering ?? ""),
|
||||||
|
sunlight,
|
||||||
|
cycle: String(item.cycle ?? ""),
|
||||||
|
default_image_url: rawImageUrl ? String(rawImageUrl) : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchSpecies(query: string): Promise<SpeciesSuggestion[]> {
|
||||||
|
const apiKey = process.env.PERENUAL_API_KEY;
|
||||||
|
if (!apiKey) return [];
|
||||||
|
if (!query.trim()) return [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `${BASE_URL}/api/species-list?key=${encodeURIComponent(apiKey)}&q=${encodeURIComponent(query)}`;
|
||||||
|
const res = await fetch(url, { cache: "no-store" });
|
||||||
|
if (!res.ok) throw new Error(`Perenual API error: ${res.status}`);
|
||||||
|
|
||||||
|
const json = (await res.json()) as { data?: unknown[] };
|
||||||
|
if (!Array.isArray(json.data)) return [];
|
||||||
|
|
||||||
|
const results = json.data.map((item) => parseItem(item as Record<string, unknown>));
|
||||||
|
|
||||||
|
await Promise.allSettled(
|
||||||
|
results.map((r) =>
|
||||||
|
db
|
||||||
|
.insert(gardenSpeciesCache)
|
||||||
|
.values({
|
||||||
|
speciesId: r.id,
|
||||||
|
data: r as unknown as Record<string, unknown>,
|
||||||
|
cachedAt: new Date(),
|
||||||
|
})
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: gardenSpeciesCache.speciesId,
|
||||||
|
set: { data: r as unknown as Record<string, unknown>, cachedAt: new Date() },
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return results;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[species-lookup] searchSpecies failed", err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSpeciesById(id: string): Promise<SpeciesSuggestion | null> {
|
||||||
|
const cutoff = new Date(Date.now() - CACHE_TTL_MS);
|
||||||
|
const [cached] = await db
|
||||||
|
.select()
|
||||||
|
.from(gardenSpeciesCache)
|
||||||
|
.where(and(eq(gardenSpeciesCache.speciesId, id), gt(gardenSpeciesCache.cachedAt, cutoff)))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (cached) return cached.data as unknown as SpeciesSuggestion;
|
||||||
|
|
||||||
|
const apiKey = process.env.PERENUAL_API_KEY;
|
||||||
|
if (!apiKey) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = `${BASE_URL}/api/species/details/${encodeURIComponent(id)}?key=${encodeURIComponent(apiKey)}`;
|
||||||
|
const res = await fetch(url, { cache: "no-store" });
|
||||||
|
if (!res.ok) return null;
|
||||||
|
|
||||||
|
const item = (await res.json()) as Record<string, unknown>;
|
||||||
|
const result = parseItem(item);
|
||||||
|
|
||||||
|
await db
|
||||||
|
.insert(gardenSpeciesCache)
|
||||||
|
.values({
|
||||||
|
speciesId: result.id,
|
||||||
|
data: result as unknown as Record<string, unknown>,
|
||||||
|
cachedAt: new Date(),
|
||||||
|
})
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: gardenSpeciesCache.speciesId,
|
||||||
|
set: { data: result as unknown as Record<string, unknown>, cachedAt: new Date() },
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[species-lookup] getSpeciesById failed", err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user