Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat: replace activity time inputs with a TimePicker, fix start/end validation, and add specs

Khuram Niazebf62a4e70aa
diff --git a/__tests__/ActivityForm.spec.tsx b/__tests__/ActivityForm.spec.tsx
new file mode 100644
index 0000000..1a28692
--- /dev/null
+++ b/__tests__/ActivityForm.spec.tsx
@@ -0,0 +1,146 @@
+import { ActivityForm } from "@/components/activities/ActivityForm";
+import { render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import {
+ createActivity,
+ getAllActivityTypes,
+} from "@/actions/activity.actions";
+
+const activityTypes = [
+ { id: "type-1", label: "Development", value: "development" },
+ { id: "type-2", label: "Research", value: "research" },
+];
+
+vi.mock("@/actions/activity.actions", () => ({
+ getAllActivityTypes: vi.fn(),
+ createActivity: vi.fn(),
+ createActivityType: vi.fn(),
+}));
+
+vi.mock("@/actions/company.actions", () => ({ addCompany: vi.fn() }));
+vi.mock("@/actions/job.actions", () => ({
+ createLocation: vi.fn(),
+ createJobSource: vi.fn(),
+}));
+vi.mock("@/actions/jobtitle.actions", () => ({ createJobTitle: vi.fn() }));
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn(), info: vi.fn() },
+}));
+
+Element.prototype.scrollIntoView = vi.fn();
+
+// Tiptap measures selections through Range, which jsdom leaves unimplemented
+document.createRange = () => {
+ const range = new Range();
+ range.getBoundingClientRect = vi.fn().mockReturnValue({
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 0,
+ top: 0,
+ width: 0,
+ });
+ range.getClientRects = () => ({
+ item: () => null,
+ length: 0,
+ [Symbol.iterator]: vi.fn(),
+ });
+ return range;
+};
+
+const user = userEvent.setup({ skipHover: true });
+
+async function renderForm() {
+ const onClose = vi.fn();
+ const reloadActivities = vi.fn();
+ vi.mocked(getAllActivityTypes).mockResolvedValue(activityTypes);
+
+ render(<ActivityForm onClose={onClose} reloadActivities={reloadActivities} />);
+ await screen.findByText("Activity Name");
+
+ return { onClose, reloadActivities };
+}
+
+// The form pre-fills valid times, so only the name and type need filling
+async function fillRequiredFields() {
+ await user.type(
+ screen.getByPlaceholderText("Ex: Job Search, Learning skill, etc"),
+ "Applied to roles"
+ );
+ await user.click(screen.getByRole("combobox"));
+ await user.click(await screen.findByRole("option", { name: "Development" }));
+}
+
+async function setEndTimeToStartOfDay() {
+ // 12:00 AM is the earliest instant of the day, so it is always at or before
+ // the "now" default start — no dependence on when the suite runs
+ await user.click(screen.getByRole("button", { name: /^End Time/ }));
+
+ const column = (name: string) => within(screen.getByRole("group", { name }));
+ await user.click(column("Hour").getByRole("button", { name: "12" }));
+ await user.click(column("Minute").getByRole("button", { name: "00" }));
+ await user.click(column("AM/PM").getByRole("button", { name: "AM" }));
+ await user.keyboard("{Escape}");
+}
+
+describe("ActivityForm", () => {
+ it("saves the combined date/time and duration", async () => {
+ const { onClose, reloadActivities } = await renderForm();
+ vi.mocked(createActivity).mockResolvedValue({
+ activity: { id: "activity-1" },
+ success: true,
+ });
+
+ await fillRequiredFields();
+ await user.click(screen.getByTestId("save-activity-btn"));
+
+ await waitFor(() => expect(createActivity).toHaveBeenCalled());
+ const payload = vi.mocked(createActivity).mock.calls[0][0];
+ expect(payload.activityName).toBe("Applied to roles");
+ expect(payload.activityType).toBe("type-1");
+ expect(payload.duration).toBe(5);
+ expect(payload.endTime!.getTime() - payload.startTime.getTime()).toBe(
+ 5 * 60 * 1000
+ );
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled());
+ expect(reloadActivities).toHaveBeenCalled();
+ });
+
+ it("keeps the dialog open when the save fails", async () => {
+ const { onClose, reloadActivities } = await renderForm();
+ vi.mocked(createActivity).mockResolvedValue({
+ success: false,
+ message: "Failed to create activity. ",
+ });
+
+ await fillRequiredFields();
+ await user.click(screen.getByTestId("save-activity-btn"));
+
+ await waitFor(() => expect(createActivity).toHaveBeenCalled());
+ expect(onClose).not.toHaveBeenCalled();
+ expect(reloadActivities).not.toHaveBeenCalled();
+ });
+
+ it("recalculates the duration when the end time is stepped", async () => {
+ await renderForm();
+
+ // Start Time then End Time, in DOM order
+ const later = screen.getAllByRole("button", { name: "5 minutes later" });
+ await user.click(later[1]);
+
+ expect(await screen.findByText(/\(10 min\)/)).toBeInTheDocument();
+ });
+
+ it("flags an end time before the start time without submitting", async () => {
+ await renderForm();
+
+ await setEndTimeToStartOfDay();
+
+ expect(
+ await screen.findByText("End time must be after the start time")
+ ).toBeInTheDocument();
+ expect(createActivity).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/TimePicker.spec.tsx b/__tests__/TimePicker.spec.tsx
new file mode 100644
index 0000000..bd0da86
--- /dev/null
+++ b/__tests__/TimePicker.spec.tsx
@@ -0,0 +1,191 @@
+import { TimePicker } from "@/components/TimePicker";
+import { render, screen, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { useForm } from "react-hook-form";
+import { Form, FormField, FormItem } from "@/components/ui/form";
+
+// jsdom lacks scrollIntoView; the columns also read layout boxes on open
+Element.prototype.scrollIntoView = vi.fn();
+
+const user = userEvent.setup({ skipHover: true });
+
+// TimePicker renders a FormControl, so it only works inside a form context —
+// the same way it is used in ActivityForm.
+function Harness({
+ initialValue = "09:05 AM",
+ onChange = vi.fn(),
+}: {
+ initialValue?: string;
+ onChange?: (value: string) => void;
+}) {
+ const form = useForm({
+ defaultValues: { startTime: initialValue },
+ mode: "onTouched",
+ });
+ const isTouched = !!form.formState.touchedFields.startTime;
+
+ return (
+ <Form {...form}>
+ <FormField
+ control={form.control}
+ name="startTime"
+ render={({ field }) => (
+ <FormItem>
+ <TimePicker
+ field={{
+ ...field,
+ onChange: (value: string) => {
+ field.onChange(value);
+ onChange(value);
+ },
+ }}
+ />
+ <span data-testid="touched">{String(isTouched)}</span>
+ </FormItem>
+ )}
+ />
+ </Form>
+ );
+}
+
+const column = (name: string) => within(screen.getByRole("group", { name }));
+
+async function openPicker(initialValue?: string) {
+ const onChange = vi.fn();
+ render(<Harness initialValue={initialValue} onChange={onChange} />);
+ await user.click(
+ screen.getByRole("button", { name: initialValue === "" ? "Pick a time" : "09:05 AM" })
+ );
+ return { onChange };
+}
+
+describe("TimePicker", () => {
+ it("shows the current value on the trigger", () => {
+ render(<Harness />);
+
+ expect(
+ screen.getByRole("button", { name: "09:05 AM" })
+ ).toBeInTheDocument();
+ });
+
+ it("prompts when there is no value yet", () => {
+ render(<Harness initialValue="" />);
+
+ expect(
+ screen.getByRole("button", { name: "Pick a time" })
+ ).toBeInTheDocument();
+ });
+
+ it("marks the current parts as pressed when opened", async () => {
+ await openPicker();
+
+ expect(column("Hour").getByRole("button", { name: "09" })).toHaveAttribute(
+ "aria-pressed",
+ "true"
+ );
+ expect(column("Minute").getByRole("button", { name: "05" })).toHaveAttribute(
+ "aria-pressed",
+ "true"
+ );
+ expect(column("AM/PM").getByRole("button", { name: "AM" })).toHaveAttribute(
+ "aria-pressed",
+ "true"
+ );
+ });
+
+ it("keeps the minute and meridiem when the hour changes", async () => {
+ const { onChange } = await openPicker();
+
+ await user.click(column("Hour").getByRole("button", { name: "11" }));
+
+ expect(onChange).toHaveBeenCalledWith("11:05 AM");
+ });
+
+ it("keeps the hour and meridiem when the minute changes", async () => {
+ const { onChange } = await openPicker();
+
+ await user.click(column("Minute").getByRole("button", { name: "42" }));
+
+ expect(onChange).toHaveBeenCalledWith("09:42 AM");
+ });
+
+ it("keeps the hour and minute when the meridiem changes", async () => {
+ const { onChange } = await openPicker();
+
+ await user.click(column("AM/PM").getByRole("button", { name: "PM" }));
+
+ expect(onChange).toHaveBeenCalledWith("09:05 PM");
+ });
+
+ it("emits a padded value the schema regex accepts", async () => {
+ const { onChange } = await openPicker("");
+
+ await user.click(column("Hour").getByRole("button", { name: "03" }));
+
+ // Unset parts fall back to 12:00 AM rather than emitting a partial string
+ expect(onChange).toHaveBeenCalledWith("03:00 AM");
+ expect(onChange.mock.calls[0][0]).toMatch(
+ /^(0[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/
+ );
+ });
+
+ it("reflects the new value on the trigger", async () => {
+ await openPicker();
+
+ await user.click(column("AM/PM").getByRole("button", { name: "PM" }));
+ // The popover is modal, so the trigger stays aria-hidden until it closes
+ await user.keyboard("{Escape}");
+
+ expect(
+ screen.getByRole("button", { name: "09:05 PM" })
+ ).toBeInTheDocument();
+ });
+
+ it("steps the time forward and back by five minutes", async () => {
+ const onChange = vi.fn();
+ render(<Harness onChange={onChange} />);
+
+ await user.click(screen.getByRole("button", { name: "5 minutes later" }));
+ expect(onChange).toHaveBeenLastCalledWith("09:10 AM");
+
+ await user.click(screen.getByRole("button", { name: "5 minutes earlier" }));
+ expect(onChange).toHaveBeenLastCalledWith("09:05 AM");
+ });
+
+ it("wraps the clock when a step crosses midnight", async () => {
+ const onChange = vi.fn();
+ render(<Harness initialValue="11:58 PM" onChange={onChange} />);
+
+ await user.click(screen.getByRole("button", { name: "5 minutes later" }));
+
+ expect(onChange).toHaveBeenLastCalledWith("12:03 AM");
+ });
+
+ it("wraps backwards across midnight too", async () => {
+ const onChange = vi.fn();
+ render(<Harness initialValue="12:02 AM" onChange={onChange} />);
+
+ await user.click(screen.getByRole("button", { name: "5 minutes earlier" }));
+
+ expect(onChange).toHaveBeenLastCalledWith("11:57 PM");
+ });
+
+ it("steps from midnight when there is no value yet", async () => {
+ const onChange = vi.fn();
+ render(<Harness initialValue="" onChange={onChange} />);
+
+ await user.click(screen.getByRole("button", { name: "5 minutes later" }));
+
+ expect(onChange).toHaveBeenLastCalledWith("12:05 AM");
+ });
+
+ // The onTouched validation mode never arms unless the trigger forwards blur
+ it("marks the field touched once the trigger loses focus", async () => {
+ render(<Harness />);
+ expect(screen.getByTestId("touched")).toHaveTextContent("false");
+
+ await user.click(screen.getByRole("button", { name: "09:05 AM" }));
+
+ expect(screen.getByTestId("touched")).toHaveTextContent("true");
+ });
+});
diff --git a/__tests__/addActivityForm.schema.spec.ts b/__tests__/addActivityForm.schema.spec.ts
new file mode 100644
index 0000000..edeb409
--- /dev/null
+++ b/__tests__/addActivityForm.schema.spec.ts
@@ -0,0 +1,144 @@
+import { AddActivityFormSchema } from "@/models/addActivityForm.schema";
+
+// A picked calendar date is local midnight; an untouched default carries the
+// current time. Both shapes are exercised below.
+const NOW = new Date(2026, 7, 12, 9, 5, 30);
+const today = () => new Date(NOW);
+const yesterdayMidnight = () => new Date(2026, 7, 11);
+const todayMidnight = () => new Date(2026, 7, 12);
+const tomorrowMidnight = () => new Date(2026, 7, 13);
+
+const base = {
+ activityName: "Job Search",
+ activityType: "research",
+};
+
+const parse = (input: Record<string, unknown>) =>
+ AddActivityFormSchema.safeParse({ ...base, ...input });
+
+const errorFor = (result: ReturnType<typeof parse>, field: string) =>
+ result.success
+ ? undefined
+ : result.error.issues.find((issue) => issue.path[0] === field)?.message;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("AddActivityFormSchema", () => {
+ it("accepts the form defaults", () => {
+ const result = parse({
+ startDate: today(),
+ startTime: "09:05 AM",
+ endDate: today(),
+ endTime: "09:10 AM",
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it("names the field when the activity type is missing", () => {
+ const result = parse({
+ activityType: "",
+ startDate: today(),
+ startTime: "09:05 AM",
+ endDate: today(),
+ endTime: "09:10 AM",
+ });
+
+ expect(errorFor(result, "activityType")).toBe(
+ "Activity type is required."
+ );
+ });
+
+ it("accepts a same-day entry when the end date came from the calendar", () => {
+ const result = parse({
+ startDate: today(),
+ startTime: "09:05 AM",
+ endDate: todayMidnight(),
+ endTime: "09:10 AM",
+ });
+
+ expect(errorFor(result, "endDate")).toBeUndefined();
+ expect(result.success).toBe(true);
+ });
+
+ it("rejects an end time before the start time on the same day", () => {
+ const result = parse({
+ startDate: todayMidnight(),
+ startTime: "05:00 PM",
+ endDate: today(),
+ endTime: "09:00 AM",
+ });
+
+ expect(errorFor(result, "endTime")).toBe(
+ "End time must be after the start time"
+ );
+ });
+
+ it("rejects an end date before the start date", () => {
+ const result = parse({
+ startDate: tomorrowMidnight(),
+ startTime: "09:00 AM",
+ endDate: todayMidnight(),
+ endTime: "10:00 AM",
+ });
+
+ expect(errorFor(result, "endDate")).toBe(
+ "End date must be the same as or after the start date"
+ );
+ });
+
+ it("accepts an activity that runs past midnight", () => {
+ const result = parse({
+ startDate: yesterdayMidnight(),
+ startTime: "11:00 PM",
+ endDate: todayMidnight(),
+ endTime: "01:00 AM",
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it("rejects a duration longer than the maximum", () => {
+ const result = parse({
+ startDate: todayMidnight(),
+ startTime: "01:00 AM",
+ endDate: todayMidnight(),
+ endTime: "11:00 AM",
+ });
+
+ expect(errorFor(result, "endTime")).toContain("cannot exceed 8 hours");
+ });
+
+ it("rejects a duration shorter than the minimum", () => {
+ const result = parse({
+ startDate: todayMidnight(),
+ startTime: "09:00 AM",
+ endDate: todayMidnight(),
+ endTime: "09:01 AM",
+ });
+
+ expect(errorFor(result, "endTime")).toBe(
+ "An activity must be at least 2 minutes long"
+ );
+ });
+
+ it("rejects a start date/time in the future", () => {
+ const result = parse({
+ startDate: today(),
+ startTime: "09:06 AM",
+ endDate: today(),
+ endTime: "09:30 AM",
+ });
+
+ expect(errorFor(result, "startTime")).toBe(
+ "Start date/time cannot be in the future"
+ );
+ });
+});
diff --git a/src/components/TimePicker.tsx b/src/components/TimePicker.tsx
new file mode 100644
index 0000000..0ce4761
--- /dev/null
+++ b/src/components/TimePicker.tsx
@@ -0,0 +1,181 @@
+"use client";
+
+import { Clock, Minus, Plus } from "lucide-react";
+import { addMinutes, format, parse } from "date-fns";
+import { useEffect, useRef, useState } from "react";
+import { ControllerRenderProps } from "react-hook-form";
+
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { FormControl } from "./ui/form";
+
+const HOURS = Array.from({ length: 12 }, (_, i) =>
+ String(i + 1).padStart(2, "0")
+);
+const MINUTES = Array.from({ length: 60 }, (_, i) =>
+ String(i).padStart(2, "0")
+);
+const MERIDIEMS = ["AM", "PM"];
+
+const TIME_PATTERN = /^(0[1-9]|1[0-2]):([0-5][0-9]) (AM|PM)$/;
+
+const TIME_FORMAT = "hh:mm a";
+const FALLBACK_TIME = "12:00 AM";
+const STEP_MINUTES = 5;
+
+type TimeParts = {
+ hour: string | null;
+ minute: string | null;
+ meridiem: string | null;
+};
+
+function parseTime(value: unknown): TimeParts {
+ const match = typeof value === "string" ? value.match(TIME_PATTERN) : null;
+ return match
+ ? { hour: match[1], minute: match[2], meridiem: match[3] }
+ : { hour: null, minute: null, meridiem: null };
+}
+
+interface TimeColumnProps {
+ label: string;
+ options: string[];
+ selected: string | null;
+ onSelect: (option: string) => void;
+}
+
+function TimeColumn({ label, options, selected, onSelect }: TimeColumnProps) {
+ const listRef = useRef<HTMLDivElement>(null);
+ const selectedRef = useRef<HTMLButtonElement>(null);
+
+ // Popover content mounts on open, so this centres the active option once,
+ // via scrollTop rather than scrollIntoView, which would move the dialog too.
+ useEffect(() => {
+ const list = listRef.current;
+ const item = selectedRef.current;
+ if (!list || !item) return;
+ list.scrollTop =
+ item.offsetTop - list.clientHeight / 2 + item.clientHeight / 2;
+ }, []);
+
+ return (
+ <div
+ ref={listRef}
+ role="group"
+ aria-label={label}
+ className="h-[220px] w-16 overflow-y-auto rounded-md border p-1"
+ >
+ {options.map((option) => {
+ const isSelected = option === selected;
+ return (
+ <Button
+ key={option}
+ ref={isSelected ? selectedRef : undefined}
+ type="button"
+ aria-pressed={isSelected}
+ variant={isSelected ? "default" : "ghost"}
+ size="sm"
+ className={cn("w-full", !isSelected && "font-normal")}
+ onClick={() => onSelect(option)}
+ >
+ {option}
+ </Button>
+ );
+ })}
+ </div>
+ );
+}
+
+interface TimePickerProps {
+ field: ControllerRenderProps<any, any>;
+}
+
+export function TimePicker({ field }: TimePickerProps) {
+ const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);
+ const { hour, minute, meridiem } = parseTime(field.value);
+
+ const update = (parts: Partial<TimeParts>) => {
+ const next = {
+ hour: parts.hour ?? hour ?? "12",
+ minute: parts.minute ?? minute ?? "00",
+ meridiem: parts.meridiem ?? meridiem ?? "AM",
+ };
+ field.onChange(`${next.hour}:${next.minute} ${next.meridiem}`);
+ };
+
+ // Stepping past midnight wraps the clock only — the date fields own the day
+ const shift = (minutes: number) => {
+ const current = TIME_PATTERN.test(field.value)
+ ? field.value
+ : FALLBACK_TIME;
+ const stepped = addMinutes(parse(current, TIME_FORMAT, new Date()), minutes);
+ field.onChange(format(stepped, TIME_FORMAT));
+ };
+
+ return (
+ <div className="flex md:w-[240px] lg:w-[280px]">
+ <Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen} modal>
+ <PopoverTrigger asChild>
+ <FormControl>
+ <Button
+ type="button"
+ onBlur={field.onBlur}
+ variant={"outline"}
+ className={cn(
+ "flex-1 justify-start rounded-r-none text-left font-normal",
+ !field.value && "text-muted-foreground"
+ )}
+ >
+ <Clock className="mr-2 h-4 w-4" />
+ {field.value ? field.value : <span>Pick a time</span>}
+ </Button>
+ </FormControl>
+ </PopoverTrigger>
+ <PopoverContent className="flex w-auto gap-2 p-2" align="start">
+ <TimeColumn
+ label="Hour"
+ options={HOURS}
+ selected={hour}
+ onSelect={(value) => update({ hour: value })}
+ />
+ <TimeColumn
+ label="Minute"
+ options={MINUTES}
+ selected={minute}
+ onSelect={(value) => update({ minute: value })}
+ />
+ <TimeColumn
+ label="AM/PM"
+ options={MERIDIEMS}
+ selected={meridiem}
+ onSelect={(value) => update({ meridiem: value })}
+ />
+ </PopoverContent>
+ </Popover>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ aria-label={`${STEP_MINUTES} minutes earlier`}
+ className="shrink-0 rounded-none border-l-0"
+ onClick={() => shift(-STEP_MINUTES)}
+ >
+ <Minus className="h-4 w-4" />
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ aria-label={`${STEP_MINUTES} minutes later`}
+ className="shrink-0 rounded-l-none border-l-0"
+ onClick={() => shift(STEP_MINUTES)}
+ >
+ <Plus className="h-4 w-4" />
+ </Button>
+ </div>
+ );
+}
diff --git a/src/components/activities/ActivityForm.tsx b/src/components/activities/ActivityForm.tsx
index afb82b2..5399db8 100644
--- a/src/components/activities/ActivityForm.tsx
+++ b/src/components/activities/ActivityForm.tsx
@@ -22,6 +22,7 @@ import {
format,
} from "date-fns";
import { DatePicker } from "../DatePicker";
+import { TimePicker } from "../TimePicker";
import TiptapEditor from "../TiptapEditor";
import { Combobox } from "../ComboBox";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
@@ -31,6 +32,7 @@ import {
getAllActivityTypes,
} from "@/actions/activity.actions";
import { combineDateAndTime } from "@/lib/utils";
+import { toastActionResult, toastError } from "@/lib/toast";
interface ActivityFormProps {
onClose: () => void;
@@ -66,11 +68,13 @@ const ActivityFormComponent = ({
const form = useForm<z.infer<typeof AddActivityFormSchema>>({
resolver: zodResolver(AddActivityFormSchema),
defaultValues,
+ mode: "onTouched",
});
const {
reset,
getValues,
+ trigger,
watch,
formState: { errors, isValid },
} = form;
@@ -111,11 +115,14 @@ const ActivityFormComponent = ({
["startDate", "startTime", "endDate", "endTime"].includes(name || "")
) {
calculateDuration();
+ // Cross-field errors land on the end fields, so changing a start
+ // field would otherwise leave a stale error until submit
+ trigger(["startTime", "endDate", "endTime"]);
}
});
return () => subscription.unsubscribe();
- }, [calculateDuration, loadActivityTypes, watch]);
+ }, [calculateDuration, loadActivityTypes, trigger, watch]);
const onSubmit = async (data: z.infer<typeof AddActivityFormSchema>) => {
const { startDate, startTime, endDate, endTime, ...rest } = data;
@@ -133,10 +140,16 @@ const ActivityFormComponent = ({
duration: totalMinutes,
};
const response = await createActivity(payload);
- onClose();
- reloadActivities();
+ toastActionResult(response, {
+ success: "Activity has been created successfully",
+ onSuccess: () => {
+ onClose();
+ reloadActivities();
+ },
+ });
} catch (error) {
console.error("Error parsing date and time:", error);
+ toastError("Failed to create activity.");
}
};
return (
@@ -211,9 +224,7 @@ const ActivityFormComponent = ({
render={({ field }) => (
<FormItem>
<FormLabel>Start Time</FormLabel>
- <FormControl>
- <Input {...field} placeholder="hh:mm AM/PM" />
- </FormControl>
+ <TimePicker field={field} />
<FormMessage>
{errors.startTime && (
<span className="text-red-500">
@@ -265,9 +276,7 @@ const ActivityFormComponent = ({
)}
</span>
</FormLabel>
- <FormControl>
- <Input {...field} placeholder="hh:mm AM/PM" />
- </FormControl>
+ <TimePicker field={field} />
<FormMessage>
{errors.endTime && (
<span className="text-red-500">
diff --git a/src/models/addActivityForm.schema.ts b/src/models/addActivityForm.schema.ts
index a2f7163..96004f2 100644
--- a/src/models/addActivityForm.schema.ts
+++ b/src/models/addActivityForm.schema.ts
@@ -1,6 +1,6 @@
import { APP_CONSTANTS } from "@/lib/constants";
import { combineDateAndTime } from "@/lib/utils";
-import { differenceInMinutes } from "date-fns";
+import { differenceInMinutes, startOfDay } from "date-fns";
import { z } from "zod";
export const AddActivityFormSchema = z
@@ -14,7 +14,9 @@ export const AddActivityFormSchema = z
.min(2, {
message: "Activity name must be at least 2 characters.",
}),
- activityType: z.string().min(1),
+ activityType: z.string().min(1, {
+ message: "Activity type is required.",
+ }),
startDate: z.date(),
startTime: z
.string()
@@ -41,21 +43,22 @@ export const AddActivityFormSchema = z
})
.optional(),
})
+ // Compare calendar days only: a picked date is local midnight while an
+ // untouched default carries the current time, so raw Dates aren't comparable
.refine(
(data) => {
if (!data.endDate) return true; // Skip if no endDate
- return data.endDate >= data.startDate;
+ return startOfDay(data.endDate) >= startOfDay(data.startDate);
},
{
message: "End date must be the same as or after the start date",
path: ["endDate"], // Target the error message to `endDate`
}
)
- // Check if `endTime` is earlier than `startTime` when the `endDate` equals `startDate`
+ // Check if the end date/time is earlier than the start date/time
.refine(
(data) => {
if (!data.endDate || !data.endTime) return true; // Skip if no endDate or endTime
- if (data.endDate > data.startDate) return true; // Valid if endDate is after startDate
// Combine date and time to compare
const startDateTime = combineDateAndTime(data.startDate, data.startTime);
@@ -64,8 +67,7 @@ export const AddActivityFormSchema = z
return endDateTime > startDateTime; // Valid only if endDateTime is after startDateTime
},
{
- message:
- "End time must be after the start time when the end date is the same",
+ message: "End time must be after the start time",
path: ["endTime"],
}
)
@@ -85,4 +87,27 @@ export const AddActivityFormSchema = z
} hours`,
path: ["endTime"],
}
+ )
+ // Match the timer, which discards anything shorter than the minimum
+ .refine(
+ (data) => {
+ if (!data.endDate || !data.endTime) return true; // Skip if no endDate or endTime
+
+ const startDateTime = combineDateAndTime(data.startDate, data.startTime);
+ const endDateTime = combineDateAndTime(data.endDate, data.endTime);
+
+ const durationInMinutes = differenceInMinutes(endDateTime, startDateTime);
+ return durationInMinutes >= APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES;
+ },
+ {
+ message: `An activity must be at least ${APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES} minutes long`,
+ path: ["endTime"],
+ }
+ )
+ .refine(
+ (data) => combineDateAndTime(data.startDate, data.startTime) <= new Date(),
+ {
+ message: "Start date/time cannot be in the future",
+ path: ["startTime"],
+ }
);