feat: garden calendar + lists integrations (task 74)
- calendar-bridge.ts and lists-bridge.ts isolate cross-module deps
- scheduleOnCalendar action: creates event from care schedule with 30-min
slot, title convention (Water/Fertilize/Repot/Prune/custom), reminder opt
- pushOverdueToTaskList action: inserts one task per overdue (plant+schedule)
pair into the default task list, skips duplicate text entries
- CareScheduleEditor: per-row calendar 📅 button opens inline form with
calendar select + optional reminder minutes + success link to /calendar
- Garden page header: PushOverdueButton with auto-dismissing feedback toast
This commit is contained in:
@@ -2,6 +2,7 @@ import Link from "next/link";
|
||||
import { listContainers, listPlants } from "@/modules/garden/server/queries";
|
||||
import { ContainerList } from "@/modules/garden/components/container-list";
|
||||
import { PlantList } from "@/modules/garden/components/plant-list";
|
||||
import { PushOverdueButton } from "@/modules/garden/components/push-overdue-button";
|
||||
|
||||
type Props = {
|
||||
searchParams: Promise<{ tab?: string }>;
|
||||
@@ -18,7 +19,10 @@ export default async function GardenPage({ searchParams }: Props) {
|
||||
|
||||
return (
|
||||
<div className="page-content">
|
||||
<h1 className="page-title">Garden</h1>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<h1 className="page-title mb-0">Garden</h1>
|
||||
<PushOverdueButton />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-6 border-b border-[var(--ink-faint)] mb-6">
|
||||
<Link
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { listCalendars } from "@/modules/garden/server/calendar-bridge";
|
||||
import { getCareLogs, getCareSchedules, 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, careLogs, careSchedules] = await Promise.all([
|
||||
const [plant, careLogs, careSchedules, calendars] = await Promise.all([
|
||||
getPlant(id),
|
||||
getCareLogs(id),
|
||||
getCareSchedules(id),
|
||||
listCalendars(),
|
||||
]);
|
||||
if (!plant) notFound();
|
||||
|
||||
return (
|
||||
<div className="page-content">
|
||||
<PlantDetail plant={plant} careLogs={careLogs} careSchedules={careSchedules} />
|
||||
<PlantDetail
|
||||
plant={plant}
|
||||
careLogs={careLogs}
|
||||
careSchedules={careSchedules}
|
||||
calendars={calendars}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState, useTransition } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { deleteCareSchedule, toggleCareSchedule, upsertCareSchedule } from "../server/actions";
|
||||
import {
|
||||
deleteCareSchedule,
|
||||
scheduleOnCalendar,
|
||||
toggleCareSchedule,
|
||||
upsertCareSchedule,
|
||||
} from "../server/actions";
|
||||
import type { CalendarDto } from "../server/calendar-bridge";
|
||||
import type { CareScheduleDto } from "../server/queries";
|
||||
|
||||
const CARE_TYPES = ["watering", "fertilizing", "repotting", "pruning", "pest-control", "other"];
|
||||
@@ -10,6 +17,7 @@ const CARE_TYPES = ["watering", "fertilizing", "repotting", "pruning", "pest-con
|
||||
type Props = {
|
||||
plantId: string;
|
||||
schedules: CareScheduleDto[];
|
||||
calendars: CalendarDto[];
|
||||
};
|
||||
|
||||
function daysLabel(n: number | null): string {
|
||||
@@ -19,11 +27,15 @@ function daysLabel(n: number | null): string {
|
||||
return `Due in ${n} day${n !== 1 ? "s" : ""}`;
|
||||
}
|
||||
|
||||
export function CareScheduleEditor({ plantId, schedules }: Props) {
|
||||
export function CareScheduleEditor({ plantId, schedules, calendars }: Props) {
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [careType, setCareType] = useState("watering");
|
||||
const [intervalDays, setIntervalDays] = useState("7");
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [calendarOpenId, setCalendarOpenId] = useState<string | null>(null);
|
||||
const [selectedCalendarId, setSelectedCalendarId] = useState(calendars[0]?.id ?? "");
|
||||
const [reminderMinutes, setReminderMinutes] = useState("");
|
||||
const [calendarSuccess, setCalendarSuccess] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const router = useRouter();
|
||||
|
||||
@@ -62,6 +74,24 @@ export function CareScheduleEditor({ plantId, schedules }: Props) {
|
||||
});
|
||||
}
|
||||
|
||||
function handleScheduleOnCalendar(scheduleId: string) {
|
||||
if (!selectedCalendarId) return;
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await scheduleOnCalendar({
|
||||
scheduleId,
|
||||
calendarId: selectedCalendarId,
|
||||
reminderMinutesBefore: reminderMinutes ? parseInt(reminderMinutes, 10) : undefined,
|
||||
});
|
||||
setCalendarOpenId(null);
|
||||
setCalendarSuccess(scheduleId);
|
||||
setTimeout(() => setCalendarSuccess(null), 4000);
|
||||
} catch (err) {
|
||||
setFormError(err instanceof Error ? err.message : "Failed to add to calendar.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -128,42 +158,113 @@ export function CareScheduleEditor({ plantId, schedules }: Props) {
|
||||
)}
|
||||
|
||||
{schedules.map((s) => (
|
||||
<div
|
||||
key={s.id}
|
||||
className={`flex items-center justify-between gap-2 p-2 rounded-lg border ${
|
||||
s.isOverdue
|
||||
? "border-red-300 bg-red-50 dark:bg-red-950/20"
|
||||
: "border-[var(--ink-faint)]"
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium capitalize">{s.careType}</span>
|
||||
<span className="text-xs text-[var(--ink-mute)]">
|
||||
Every {s.intervalDays} days · {daysLabel(s.daysUntilDue)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<button
|
||||
onClick={() => handleToggle(s.id, !s.enabled)}
|
||||
disabled={isPending}
|
||||
title={s.enabled ? "Disable" : "Enable"}
|
||||
className={`text-xs px-2 py-0.5 rounded-full border transition-colors ${
|
||||
s.enabled
|
||||
? "border-green-400 text-green-700 dark:text-green-400"
|
||||
: "border-[var(--ink-faint)] text-[var(--ink-mute)]"
|
||||
}`}
|
||||
>
|
||||
{s.enabled ? "Active" : "Paused"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(s.id)}
|
||||
disabled={isPending}
|
||||
title="Delete schedule"
|
||||
className="text-[var(--ink-mute)] hover:text-red-500 text-xs"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
<div key={s.id} className="flex flex-col gap-1">
|
||||
<div
|
||||
className={`flex items-center justify-between gap-2 p-2 rounded-lg border ${
|
||||
s.isOverdue
|
||||
? "border-red-300 bg-red-50 dark:bg-red-950/20"
|
||||
: "border-[var(--ink-faint)]"
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium capitalize">{s.careType}</span>
|
||||
<span className="text-xs text-[var(--ink-mute)]">
|
||||
Every {s.intervalDays} days · {daysLabel(s.daysUntilDue)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{calendars.length > 0 && s.nextDueAt && (
|
||||
<button
|
||||
onClick={() => setCalendarOpenId(calendarOpenId === s.id ? null : s.id)}
|
||||
disabled={isPending}
|
||||
title="Add to calendar"
|
||||
className="text-xs text-[var(--ink-mute)] hover:text-[var(--ink)]"
|
||||
>
|
||||
📅
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => handleToggle(s.id, !s.enabled)}
|
||||
disabled={isPending}
|
||||
title={s.enabled ? "Disable" : "Enable"}
|
||||
className={`text-xs px-2 py-0.5 rounded-full border transition-colors ${
|
||||
s.enabled
|
||||
? "border-green-400 text-green-700 dark:text-green-400"
|
||||
: "border-[var(--ink-faint)] text-[var(--ink-mute)]"
|
||||
}`}
|
||||
>
|
||||
{s.enabled ? "Active" : "Paused"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(s.id)}
|
||||
disabled={isPending}
|
||||
title="Delete schedule"
|
||||
className="text-[var(--ink-mute)] hover:text-red-500 text-xs"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{calendarOpenId === s.id && (
|
||||
<div className="flex flex-col gap-2 p-3 bg-[var(--surface-2)] rounded-lg border border-[var(--ink-faint)] ml-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-col gap-1 flex-1">
|
||||
<label htmlFor={`cal-select-${s.id}`} className="text-xs font-medium">
|
||||
Calendar
|
||||
</label>
|
||||
<select
|
||||
id={`cal-select-${s.id}`}
|
||||
value={selectedCalendarId}
|
||||
onChange={(e) => setSelectedCalendarId(e.target.value)}
|
||||
className="input input-xs"
|
||||
>
|
||||
{calendars.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 w-28">
|
||||
<label htmlFor={`remind-${s.id}`} className="text-xs font-medium">
|
||||
Remind (min)
|
||||
</label>
|
||||
<input
|
||||
id={`remind-${s.id}`}
|
||||
type="number"
|
||||
min={0}
|
||||
max={1440}
|
||||
placeholder="optional"
|
||||
value={reminderMinutes}
|
||||
onChange={(e) => setReminderMinutes(e.target.value)}
|
||||
className="input input-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 items-center">
|
||||
<button
|
||||
onClick={() => handleScheduleOnCalendar(s.id)}
|
||||
disabled={isPending || !selectedCalendarId}
|
||||
className="btn btn-primary btn-xs"
|
||||
>
|
||||
{isPending ? "Scheduling…" : "Schedule"}
|
||||
</button>
|
||||
<button onClick={() => setCalendarOpenId(null)} className="btn btn-ghost btn-xs">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{calendarSuccess === s.id && (
|
||||
<p className="text-xs text-green-600 dark:text-green-400 ml-2">
|
||||
Event added to calendar.{" "}
|
||||
<Link href="/calendar" className="underline">
|
||||
View in calendar →
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ 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 { CalendarDto } from "../server/calendar-bridge";
|
||||
import type { CareLogDto, CareScheduleDto, PlantDetailDto } from "../server/queries";
|
||||
import { CareHistoryList } from "./care-history-list";
|
||||
import { CareLogForm } from "./care-log-form";
|
||||
@@ -15,6 +16,7 @@ type Props = {
|
||||
plant: PlantDetailDto;
|
||||
careLogs: CareLogDto[];
|
||||
careSchedules: CareScheduleDto[];
|
||||
calendars: CalendarDto[];
|
||||
};
|
||||
|
||||
function InfoRow({
|
||||
@@ -41,7 +43,7 @@ function healthBadgeClass(status: string): string {
|
||||
return "badge-warning";
|
||||
}
|
||||
|
||||
export function PlantDetail({ plant, careLogs, careSchedules }: Props) {
|
||||
export function PlantDetail({ plant, careLogs, careSchedules, calendars }: Props) {
|
||||
const [tab, setTab] = useState<Tab>("info");
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
@@ -260,7 +262,7 @@ export function PlantDetail({ plant, careLogs, careSchedules }: Props) {
|
||||
{/* Care */}
|
||||
{tab === "care" && (
|
||||
<div className="flex flex-col gap-6">
|
||||
<CareScheduleEditor plantId={plant.id} schedules={careSchedules} />
|
||||
<CareScheduleEditor plantId={plant.id} schedules={careSchedules} calendars={calendars} />
|
||||
<div className="border-t border-[var(--ink-faint)] pt-4">
|
||||
<p className="text-sm font-semibold text-[var(--ink-mute)] uppercase tracking-wide mb-3">
|
||||
Log care
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useTransition } from "react";
|
||||
import { pushOverdueToTaskList } from "../server/actions";
|
||||
|
||||
export function PushOverdueButton() {
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [isError, setIsError] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
useEffect(() => {
|
||||
if (!message) return;
|
||||
const id = setTimeout(() => setMessage(null), 4000);
|
||||
return () => clearTimeout(id);
|
||||
}, [message]);
|
||||
|
||||
function handleClick() {
|
||||
setMessage(null);
|
||||
setIsError(false);
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const { added } = await pushOverdueToTaskList();
|
||||
setMessage(
|
||||
added === 0
|
||||
? "No overdue care tasks."
|
||||
: `Added ${added} task${added !== 1 ? "s" : ""} to your task list.`,
|
||||
);
|
||||
} catch {
|
||||
setIsError(true);
|
||||
setMessage("Failed to push tasks. Please try again.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<button onClick={handleClick} disabled={isPending} className="btn btn-ghost btn-sm">
|
||||
{isPending ? "Pushing…" : "Add overdue to task list"}
|
||||
</button>
|
||||
{message && (
|
||||
<span className={`text-xs ${isError ? "text-red-500" : "text-[var(--ink-mute)]"}`}>
|
||||
{message}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
"use server";
|
||||
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { and, eq, lte, sql } from "drizzle-orm";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
@@ -8,7 +8,9 @@ import { getCurrentSession } from "@/lib/session";
|
||||
import { logActivity } from "@/modules/_core/activity";
|
||||
import { cancelReminder, scheduleReminder } from "@/modules/_core/reminders";
|
||||
import { gardenCareLogs, gardenCareSchedules, gardenContainers, gardenPlants } from "../schema";
|
||||
import { createCalendarEvent } from "./calendar-bridge";
|
||||
import { updateScheduleAfterCare } from "./care-schedule";
|
||||
import { addListItem, getList, listLists } from "./lists-bridge";
|
||||
|
||||
const containerInput = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
@@ -481,3 +483,114 @@ export async function toggleCareSchedule(input: { id: string; enabled: boolean }
|
||||
|
||||
revalidatePath(`/garden/plants/${row.plantId}`);
|
||||
}
|
||||
|
||||
// ─── Calendar integration ─────────────────────────────────────────────────────
|
||||
|
||||
function buildCareTitle(careType: string, plantName: string): string {
|
||||
const verbs: Record<string, string> = {
|
||||
watering: "Water",
|
||||
fertilizing: "Fertilize",
|
||||
repotting: "Repot",
|
||||
pruning: "Prune",
|
||||
};
|
||||
const verb = verbs[careType];
|
||||
return verb ? `${verb} ${plantName}` : `${careType} — ${plantName}`;
|
||||
}
|
||||
|
||||
const scheduleOnCalendarInput = z.object({
|
||||
scheduleId: z.string().uuid(),
|
||||
calendarId: z.string().uuid(),
|
||||
reminderMinutesBefore: z.number().int().min(0).max(1440).optional(),
|
||||
});
|
||||
|
||||
export async function scheduleOnCalendar(input: z.input<typeof scheduleOnCalendarInput>) {
|
||||
const parsed = scheduleOnCalendarInput.parse(input);
|
||||
const { household } = await getCurrentSession();
|
||||
|
||||
const [row] = await db
|
||||
.select({
|
||||
nextDueAt: gardenCareSchedules.nextDueAt,
|
||||
careType: gardenCareSchedules.careType,
|
||||
plantName: gardenPlants.name,
|
||||
})
|
||||
.from(gardenCareSchedules)
|
||||
.innerJoin(gardenPlants, eq(gardenCareSchedules.plantId, gardenPlants.id))
|
||||
.where(
|
||||
and(
|
||||
eq(gardenCareSchedules.id, parsed.scheduleId),
|
||||
eq(gardenCareSchedules.householdId, household.id),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!row) throw new Error("Forbidden");
|
||||
if (!row.nextDueAt) throw new Error("This schedule has no upcoming due date set.");
|
||||
|
||||
const startAt = row.nextDueAt;
|
||||
const endAt = new Date(startAt.getTime() + 30 * 60 * 1000);
|
||||
const title = buildCareTitle(row.careType, row.plantName);
|
||||
|
||||
await createCalendarEvent({
|
||||
calendarId: parsed.calendarId,
|
||||
title,
|
||||
startAt,
|
||||
endAt,
|
||||
allDay: false,
|
||||
notes: `Scheduled from garden. Next due: ${startAt.toLocaleDateString()}`,
|
||||
remindMinutesBefore: parsed.reminderMinutesBefore ?? null,
|
||||
});
|
||||
|
||||
revalidatePath("/calendar");
|
||||
}
|
||||
|
||||
// ─── Lists integration ────────────────────────────────────────────────────────
|
||||
|
||||
export async function pushOverdueToTaskList(): Promise<{ added: number }> {
|
||||
const { household } = await getCurrentSession();
|
||||
|
||||
const overduePairs = await db
|
||||
.select({
|
||||
plantName: gardenPlants.name,
|
||||
careType: gardenCareSchedules.careType,
|
||||
nextDueAt: gardenCareSchedules.nextDueAt,
|
||||
})
|
||||
.from(gardenCareSchedules)
|
||||
.innerJoin(gardenPlants, eq(gardenCareSchedules.plantId, gardenPlants.id))
|
||||
.where(
|
||||
and(
|
||||
eq(gardenCareSchedules.householdId, household.id),
|
||||
eq(gardenCareSchedules.enabled, true),
|
||||
lte(gardenCareSchedules.nextDueAt, sql`now()`),
|
||||
),
|
||||
);
|
||||
|
||||
if (overduePairs.length === 0) return { added: 0 };
|
||||
|
||||
const taskLists = await listLists({ type: "task" });
|
||||
const taskList = taskLists[0];
|
||||
if (!taskList) return { added: 0 };
|
||||
|
||||
const listDetail = await getList(taskList.id);
|
||||
const existingTexts = new Set(listDetail.items.map((i) => i.text));
|
||||
|
||||
let added = 0;
|
||||
for (const pair of overduePairs) {
|
||||
const title = buildCareTitle(pair.careType, pair.plantName);
|
||||
if (existingTexts.has(title)) continue;
|
||||
|
||||
const daysOverdue = pair.nextDueAt
|
||||
? Math.abs(Math.floor((Date.now() - pair.nextDueAt.getTime()) / (1000 * 60 * 60 * 24)))
|
||||
: 0;
|
||||
|
||||
await addListItem({
|
||||
listId: taskList.id,
|
||||
text: title,
|
||||
notes: `Overdue by ${daysOverdue} day(s)`,
|
||||
dueAt: pair.nextDueAt,
|
||||
});
|
||||
existingTexts.add(title);
|
||||
added++;
|
||||
}
|
||||
|
||||
return { added };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export { createEvent as createCalendarEvent } from "@/modules/calendar/server/actions";
|
||||
export { listCalendars } from "@/modules/calendar/server/queries";
|
||||
export type { CalendarDto } from "@/modules/calendar/server/queries";
|
||||
@@ -0,0 +1,2 @@
|
||||
export { addItem as addListItem } from "@/modules/lists/server/actions";
|
||||
export { getList, listLists } from "@/modules/lists/server/queries";
|
||||
Reference in New Issue
Block a user