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(dashboard): store daily goal targets per month with carry-forward, and add the save action

Khuram Niaz59b2f42e00e0
diff --git a/__tests__/DailyGoalsCalendar.spec.tsx b/__tests__/DailyGoalsCalendar.spec.tsx
index dcdfc77..beb3c48 100644
--- a/__tests__/DailyGoalsCalendar.spec.tsx
+++ b/__tests__/DailyGoalsCalendar.spec.tsx
@@ -22,13 +22,20 @@ describe("DailyGoalsCalendar", () => {
const user = userEvent.setup();
const today = "2026-10-05";
- const renderCalendar = () =>
+ const renderCalendar = (targets: Record<string, any> = {}) =>
render(
<DailyGoalsCalendar
today={today}
- initialValues={{ "2026-10-01": { jobs: 3, hours: 2.5 } }}
+ initialData={{
+ values: { "2026-10-01": { jobs: 3, hours: 2.5 } },
+ targets,
+ }}
/>,
);
+ const ok = (values: object = {}, targets: object = {}) => ({
+ success: true,
+ data: { values, targets },
+ });
// [summary Card, calendar Card]; the calendar is always the last one
const cards = () =>
@@ -66,10 +73,9 @@ describe("DailyGoalsCalendar", () => {
});
it("fetches a month on first visit and caches it", async () => {
- (getDailyGoalValues as any).mockResolvedValue({
- success: true,
- data: { "2026-09-10": { jobs: 5, hours: 4 } },
- });
+ (getDailyGoalValues as any).mockResolvedValue(
+ ok({ "2026-09-10": { jobs: 5, hours: 4 } }),
+ );
renderCalendar();
await user.click(previous());
@@ -97,17 +103,17 @@ describe("DailyGoalsCalendar", () => {
expect(cards().at(-1)).toHaveAttribute("aria-busy", "true");
// September settles while August is on screen: the dim must stay
- await act(async () => sep.resolve({ success: true, data: {} }));
+ await act(async () => sep.resolve(ok()));
expect(cards().at(-1)).toHaveAttribute("aria-busy", "true");
- await act(async () => aug.resolve({ success: true, data: {} }));
+ await act(async () => aug.resolve(ok()));
expect(cards().at(-1)).not.toHaveAttribute("aria-busy");
});
it("toasts a failed month and retries on the next visit", async () => {
(getDailyGoalValues as any)
.mockResolvedValueOnce({ success: false, message: "Boom" })
- .mockResolvedValueOnce({ success: true, data: {} });
+ .mockResolvedValueOnce(ok());
renderCalendar();
await user.click(previous());
@@ -140,7 +146,7 @@ describe("DailyGoalsCalendar", () => {
});
it("moves the calendar when the summary navigates", async () => {
- (getDailyGoalValues as any).mockResolvedValue({ success: true, data: {} });
+ (getDailyGoalValues as any).mockResolvedValue(ok());
renderCalendar();
await user.click(
@@ -162,10 +168,7 @@ describe("DailyGoalsCalendar", () => {
expect(cards()[1]).toHaveAttribute("aria-busy", "true");
await act(async () =>
- sep.resolve({
- success: true,
- data: { "2026-09-01": { jobs: 5, hours: 4 } },
- }),
+ sep.resolve(ok({ "2026-09-01": { jobs: 5, hours: 4 } })),
);
expect(
summary().getByText("September 2026. Goal hit: Jobs applied 3%, Activity 3%"),
@@ -191,11 +194,41 @@ describe("DailyGoalsCalendar", () => {
});
it("shows no summary when the current month failed to load", () => {
- render(<DailyGoalsCalendar today={today} initialValues={null} />);
+ render(<DailyGoalsCalendar today={today} initialData={null} />);
expect(
summary().getByText("October 2026. Goal hit: no data"),
).toBeInTheDocument();
expect(summary().queryByText("Nothing logged")).not.toBeInTheDocument();
expect(getDailyGoalValues).not.toHaveBeenCalled();
});
+
+ it("judges the current month against its stored target", () => {
+ renderCalendar({ "2026-10": { jobs: 3, hours: 2 } });
+ expect(
+ calendar().getByText(/October 1: Jobs applied 3 of 3, Activity 2\.5 of 2 h\. All goals met\./),
+ ).toBeInTheDocument();
+ expect(calendar().getByText("2 h")).toBeInTheDocument();
+ });
+
+ it("keeps an earlier month on the target it had", async () => {
+ (getDailyGoalValues as any).mockResolvedValue(
+ ok({ "2026-09-10": { jobs: 4, hours: 4 } }, { "2026-10": { jobs: 3, hours: 4 } }),
+ );
+ renderCalendar({ "2026-10": { jobs: 3, hours: 4 } });
+
+ await user.click(previous());
+ expect(
+ await calendar().findByText(/September 10: Jobs applied 4 of 5, Activity 4 of 4 h$/),
+ ).toBeInTheDocument();
+ });
+
+ it("shows carried targets for a month still loading", async () => {
+ const sep = deferred<any>();
+ (getDailyGoalValues as any).mockReturnValueOnce(sep.promise);
+ renderCalendar({ "2026-03": { jobs: 2, hours: 7 } });
+
+ await user.click(previous());
+ // Sep has no entry: carried from March, not the 4 h default
+ expect(calendar().getByText("7 h")).toBeInTheDocument();
+ });
});
diff --git a/__tests__/dailyGoals.actions.spec.ts b/__tests__/dailyGoals.actions.spec.ts
index 7387acb..26572b6 100644
--- a/__tests__/dailyGoals.actions.spec.ts
+++ b/__tests__/dailyGoals.actions.spec.ts
@@ -1,4 +1,7 @@
-import { getDailyGoalValues } from "@/actions/dailyGoals.actions";
+import {
+ getDailyGoalValues,
+ updateGoalTargets,
+} from "@/actions/dailyGoals.actions";
import { getCurrentUser } from "@/utils/user.utils";
import { PrismaClient } from "@prisma/client";
@@ -8,6 +11,7 @@ vi.mock("@prisma/client", () => {
const mPrismaClient = {
job: { groupBy: vi.fn() },
activity: { findMany: vi.fn() },
+ userSettings: { findUnique: vi.fn(), upsert: vi.fn() },
};
return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };
});
@@ -25,6 +29,7 @@ describe("getDailyGoalValues", () => {
(getCurrentUser as any).mockResolvedValue(mockUser);
(prisma.job.groupBy as any).mockResolvedValue([]);
(prisma.activity.findMany as any).mockResolvedValue([]);
+ (prisma.userSettings.findUnique as any).mockResolvedValue(null);
});
afterEach(() => {
@@ -60,7 +65,48 @@ describe("getDailyGoalValues", () => {
});
expect(result).toEqual({
success: true,
- data: { "2026-09-02": { jobs: 3, hours: 2.5 } },
+ data: { values: { "2026-09-02": { jobs: 3, hours: 2.5 } }, targets: {} },
+ });
+ });
+
+ it("returns the parsed stored targets scoped to the user", async () => {
+ (prisma.userSettings.findUnique as any).mockResolvedValue({
+ settings: JSON.stringify({
+ ai: {},
+ goals: {
+ targets: {
+ "2026-08": { jobs: 3, hours: 2 },
+ "2026-13": { jobs: 3, hours: 2 },
+ },
+ },
+ }),
+ });
+
+ const result = await getDailyGoalValues("2026-10");
+
+ expect(prisma.userSettings.findUnique).toHaveBeenCalledWith({
+ where: { userId: "user-id" },
+ select: { settings: true },
+ });
+ expect(result).toEqual({
+ success: true,
+ data: { values: {}, targets: { "2026-08": { jobs: 3, hours: 2 } } },
+ });
+ });
+
+ it("still returns values when the settings JSON is malformed", async () => {
+ (prisma.job.groupBy as any).mockResolvedValue([
+ { appliedDate: new Date(2026, 9, 2, 9), _count: { _all: 2 } },
+ ]);
+ (prisma.userSettings.findUnique as any).mockResolvedValue({
+ settings: '{"ai":',
+ });
+
+ const result = await getDailyGoalValues("2026-10");
+
+ expect(result).toEqual({
+ success: true,
+ data: { values: { "2026-10-02": { jobs: 2, hours: 0 } }, targets: {} },
});
});
@@ -85,3 +131,117 @@ describe("getDailyGoalValues", () => {
expect(result).toEqual({ success: false, message: "Not authenticated" });
});
});
+
+describe("updateGoalTargets", () => {
+ const mockUser = { id: "user-id" };
+ const stored = (settings: object) =>
+ (prisma.userSettings.findUnique as any).mockResolvedValue({
+ settings: JSON.stringify(settings),
+ });
+ const written = () =>
+ JSON.parse((prisma.userSettings.upsert as any).mock.calls[0][0].update.settings);
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 9, 5, 12));
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.userSettings.findUnique as any).mockResolvedValue(null);
+ (prisma.userSettings.upsert as any).mockResolvedValue({});
+ (prisma.job.groupBy as any).mockResolvedValue([]);
+ (prisma.activity.findMany as any).mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("writes the current month and keeps the other settings", async () => {
+ stored({
+ ai: { provider: "ollama", model: "m" },
+ display: { theme: "dark" },
+ goals: { targets: { "2026-08": { jobs: 2, hours: 2 } } },
+ });
+
+ const result = await updateGoalTargets({ month: "2026-10", jobs: 3, hours: 6 });
+
+ const targets = {
+ "2026-08": { jobs: 2, hours: 2 },
+ "2026-10": { jobs: 3, hours: 6 },
+ };
+ expect(result).toEqual(
+ expect.objectContaining({ success: true, data: expect.objectContaining({ targets }) }),
+ );
+ expect((prisma.userSettings.upsert as any).mock.calls[0][0].where).toEqual({
+ userId: "user-id",
+ });
+ expect(written()).toEqual({
+ ai: { provider: "ollama", model: "m" },
+ display: { theme: "dark" },
+ goals: { targets },
+ });
+ });
+
+ it("creates the settings row with defaults when none exists", async () => {
+ await updateGoalTargets({ month: "2026-10", jobs: 3, hours: 6 });
+ const create = JSON.parse(
+ (prisma.userSettings.upsert as any).mock.calls[0][0].create.settings,
+ );
+ expect(create.goals).toEqual({ targets: { "2026-10": { jobs: 3, hours: 6 } } });
+ expect(create.display).toEqual({ theme: "system" });
+ expect((prisma.userSettings.upsert as any).mock.calls[0][0].create.userId).toBe(
+ "user-id",
+ );
+ });
+
+ it("overwrites an earlier save in the same month", async () => {
+ stored({ goals: { targets: { "2026-10": { jobs: 9, hours: 9 } } } });
+ await updateGoalTargets({ month: "2026-10", jobs: 3, hours: 6 });
+ expect(written().goals.targets).toEqual({ "2026-10": { jobs: 3, hours: 6 } });
+ });
+
+ it("drops invalid stored entries on save", async () => {
+ stored({ goals: { targets: { "2026-13": { jobs: 1, hours: 1 }, "2026-09": "x" } } });
+ await updateGoalTargets({ month: "2026-10", jobs: 3, hours: 6 });
+ expect(written().goals.targets).toEqual({ "2026-10": { jobs: 3, hours: 6 } });
+ });
+
+ it("refuses to save over malformed settings JSON", async () => {
+ (prisma.userSettings.findUnique as any).mockResolvedValue({
+ settings: '{"ai":',
+ });
+ const result = await updateGoalTargets({ month: "2026-10", jobs: 3, hours: 6 });
+ expect(result.success).toBe(false);
+ expect(prisma.userSettings.upsert).not.toHaveBeenCalled();
+ });
+
+ it.each(["2026-09", "2026-11", "bad"])(
+ "rejects a month that is no longer current (%s)",
+ async (month) => {
+ const result = await updateGoalTargets({ month, jobs: 3, hours: 6 });
+ expect(result).toEqual({
+ success: false,
+ message: "The month has changed — reload the page.",
+ });
+ expect(prisma.userSettings.upsert).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ { jobs: 0, hours: 4 },
+ { jobs: 51, hours: 4 },
+ { jobs: 2.5, hours: 4 },
+ { jobs: 3, hours: 0 },
+ { jobs: 3, hours: 25 },
+ { jobs: Number.NaN, hours: 4 },
+ ])("rejects out-of-range targets %o", async (targets) => {
+ const result = await updateGoalTargets({ month: "2026-10", ...targets });
+ expect(result).toEqual({ success: false, message: "Invalid goal targets." });
+ expect(prisma.userSettings.upsert).not.toHaveBeenCalled();
+ });
+
+ it("returns a failure when not signed in", async () => {
+ (getCurrentUser as any).mockResolvedValue(null);
+ const result = await updateGoalTargets({ month: "2026-10", jobs: 3, hours: 6 });
+ expect(result).toEqual({ success: false, message: "Not authenticated" });
+ });
+});
diff --git a/__tests__/dailyGoals.spec.ts b/__tests__/dailyGoals.spec.ts
index fe5b133..044e198 100644
--- a/__tests__/dailyGoals.spec.ts
+++ b/__tests__/dailyGoals.spec.ts
@@ -1,11 +1,14 @@
import { DAILY_GOALS } from "@/lib/constants";
import {
+ DEFAULT_GOAL_TARGETS,
buildGoalValues,
buildMonthSummary,
formatDays,
goalMonthRange,
isValidMonth,
monthBounds,
+ parseStoredTargets,
+ resolveTargets,
shiftMonth,
} from "@/lib/dailyGoals";
@@ -88,6 +91,7 @@ describe("dailyGoals helpers", () => {
describe("buildMonthSummary", () => {
const met = { jobs: 5, hours: 4 };
+ const T = { jobs: 5, hours: 4 };
const stat = (summary: ReturnType<typeof buildMonthSummary>, label: string) =>
summary.stats?.find((s) => s.label === label)?.value;
@@ -100,6 +104,7 @@ describe("dailyGoals helpers", () => {
"2026-09-03": { jobs: 0, hours: 4 },
},
"2026-10-05",
+ T,
);
expect(summary.rings).toEqual({ jobs: 2 / 30, hours: 2 / 30 });
expect(stat(summary, "Both goals met")).toBe("1 day");
@@ -111,6 +116,7 @@ describe("dailyGoals helpers", () => {
"2026-09",
{ "2026-09-01": { jobs: 9, hours: 3.9 } },
"2026-10-05",
+ T,
);
expect(summary.rings).toEqual({ jobs: 1 / 30, hours: 0 });
});
@@ -120,6 +126,7 @@ describe("dailyGoals helpers", () => {
"2026-10",
{ "2026-10-01": met, "2026-10-20": met },
"2026-10-05",
+ T,
);
// Oct 1–4 past, today not met
expect(summary.rings).toEqual({ jobs: 1 / 4, hours: 1 / 4 });
@@ -132,6 +139,7 @@ describe("dailyGoals helpers", () => {
"2026-10",
{ "2026-10-05": { jobs: 5, hours: 1 } },
"2026-10-05",
+ T,
);
expect(summary.rings).toEqual({ jobs: 1 / 5, hours: 0 / 4 });
expect(stat(summary, "Both goals met")).toBe("0 days");
@@ -142,18 +150,19 @@ describe("dailyGoals helpers", () => {
"2026-10",
{ "2026-10-05": met },
"2026-10-05",
+ T,
);
expect(summary.rings).toEqual({ jobs: 1 / 5, hours: 1 / 5 });
expect(stat(summary, "Both goals met")).toBe("1 day");
});
it("never counts today as nothing logged", () => {
- const summary = buildMonthSummary("2026-10", {}, "2026-10-05");
+ const summary = buildMonthSummary("2026-10", {}, "2026-10-05", T);
expect(stat(summary, "Nothing logged")).toBe("4 days");
});
it("first of the month with nothing met has no ring values", () => {
- const summary = buildMonthSummary("2026-10", {}, "2026-10-01");
+ const summary = buildMonthSummary("2026-10", {}, "2026-10-01", T);
expect(summary.rings).toEqual({});
expect(stat(summary, "Both goals met")).toBe("0 days");
expect(stat(summary, "Nothing logged")).toBe("0 days");
@@ -161,15 +170,15 @@ describe("dailyGoals helpers", () => {
it("uses the real month length", () => {
expect(
- stat(buildMonthSummary("2024-02", {}, "2026-10-05"), "Nothing logged"),
+ stat(buildMonthSummary("2024-02", {}, "2026-10-05", T), "Nothing logged"),
).toBe("29 days");
expect(
- stat(buildMonthSummary("2026-02", {}, "2026-10-05"), "Nothing logged"),
+ stat(buildMonthSummary("2026-02", {}, "2026-10-05", T), "Nothing logged"),
).toBe("28 days");
});
it("shows real zeros for a loaded month with no records", () => {
- const summary = buildMonthSummary("2026-08", {}, "2026-10-05");
+ const summary = buildMonthSummary("2026-08", {}, "2026-10-05", T);
expect(summary.rings).toEqual({ jobs: 0, hours: 0 });
expect(stat(summary, "Nothing logged")).toBe("31 days");
});
@@ -179,12 +188,13 @@ describe("dailyGoals helpers", () => {
"2026-09",
{ "2026-09-01": { jobs: 0, hours: 0 }, "2026-09-02": { jobs: 1, hours: 0 } },
"2026-10-05",
+ T,
);
expect(stat(summary, "Nothing logged")).toBe("29 days");
});
it("lists the four rows in order with placeholder streaks", () => {
- const summary = buildMonthSummary("2026-09", {}, "2026-10-05");
+ const summary = buildMonthSummary("2026-09", {}, "2026-10-05", T);
expect(summary.stats).toEqual([
{
label: "Current streak",
@@ -200,5 +210,69 @@ describe("dailyGoals helpers", () => {
{ label: "Nothing logged", value: "30 days", tone: "danger" },
]);
});
+
+ it("judges days against the targets passed in", () => {
+ const summary = buildMonthSummary(
+ "2026-09",
+ { "2026-09-01": { jobs: 3, hours: 2 } },
+ "2026-10-05",
+ { jobs: 3, hours: 2 },
+ );
+ expect(summary.rings).toEqual({ jobs: 1 / 30, hours: 1 / 30 });
+ expect(stat(summary, "Both goals met")).toBe("1 day");
+ });
+ });
+
+ describe("parseStoredTargets", () => {
+ it("keeps valid month entries", () => {
+ expect(
+ parseStoredTargets({ "2026-10": { jobs: 3, hours: 4 } }),
+ ).toEqual({ "2026-10": { jobs: 3, hours: 4 } });
+ });
+
+ it.each([undefined, null, "x", 5, []])("returns {} for %s", (raw) => {
+ expect(parseStoredTargets(raw)).toEqual({});
+ });
+
+ it("drops bad keys and out-of-range or non-numeric values", () => {
+ expect(
+ parseStoredTargets({
+ "2026-13": { jobs: 3, hours: 4 },
+ "2026-09": { jobs: "5", hours: 4 },
+ "2026-08": { jobs: 0, hours: 4 },
+ "2026-07": { jobs: 3, hours: 2.5 },
+ "2026-06": { jobs: 51, hours: 4 },
+ "2026-05": { jobs: 2, hours: 25 },
+ "2026-04": { jobs: 2, hours: 3 },
+ }),
+ ).toEqual({ "2026-04": { jobs: 2, hours: 3 } });
+ });
+ });
+
+ describe("resolveTargets", () => {
+ const stored = {
+ "2026-03": { jobs: 4, hours: 2 },
+ "2026-10": { jobs: 3, hours: 6 },
+ };
+
+ it("uses the month's own entry", () => {
+ expect(resolveTargets("2026-10", stored)).toEqual({ jobs: 3, hours: 6 });
+ });
+
+ it("carries the latest earlier entry forward", () => {
+ expect(resolveTargets("2026-09", stored)).toEqual({ jobs: 4, hours: 2 });
+ expect(resolveTargets("2027-02", stored)).toEqual({ jobs: 3, hours: 6 });
+ });
+
+ it("falls back to the defaults before any entry", () => {
+ expect(resolveTargets("2026-02", stored)).toEqual(DEFAULT_GOAL_TARGETS);
+ expect(resolveTargets("2026-10", {})).toEqual({ jobs: 5, hours: 4 });
+ });
+
+ it("compares months across years", () => {
+ expect(
+ resolveTargets("2026-01", { "2025-12": { jobs: 2, hours: 1 } }),
+ ).toEqual({ jobs: 2, hours: 1 });
+ });
});
});
diff --git a/src/actions/dailyGoals.actions.ts b/src/actions/dailyGoals.actions.ts
index 10c2f1e..c0e2380 100644
--- a/src/actions/dailyGoals.actions.ts
+++ b/src/actions/dailyGoals.actions.ts
@@ -9,14 +9,53 @@ import {
goalMonthRange,
isValidMonth,
monthBounds,
+ parseStoredTargets,
+ type GoalMonthData,
type GoalValues,
} from "@/lib/dailyGoals";
+import {
+ GoalTargetsSchema,
+ type GoalTargetsByMonth,
+} from "@/models/dailyGoals.model";
+import { defaultUserSettings } from "@/models/userSettings.model";
+
+type Failure = { success: false; message: string };
+
+async function loadGoalValues(
+ userId: string,
+ start: Date,
+ end: Date,
+): Promise<GoalValues> {
+ const range = { gte: start, lte: end };
+ const [jobs, activities] = await Promise.all([
+ prisma.job.groupBy({
+ by: "appliedDate",
+ _count: { _all: true },
+ where: { userId, applied: true, appliedDate: range },
+ }),
+ prisma.activity.findMany({
+ where: { userId, startTime: range, duration: { not: null } },
+ select: { startTime: true, duration: true },
+ }),
+ ]);
+ return buildGoalValues(jobs, activities);
+}
+
+async function loadStoredTargets(userId: string): Promise<{
+ settings: Record<string, any> | null;
+ targets: GoalTargetsByMonth;
+}> {
+ const row = await prisma.userSettings.findUnique({
+ where: { userId },
+ select: { settings: true },
+ });
+ const settings = row ? JSON.parse(row.settings) : null;
+ return { settings, targets: parseStoredTargets(settings?.goals?.targets) };
+}
export async function getDailyGoalValues(
month: string,
-): Promise<
- { success: true; data: GoalValues } | { success: false; message: string }
-> {
+): Promise<{ success: true; data: GoalMonthData } | Failure> {
try {
const user = await requireUser();
const { minMonth, maxMonth } = goalMonthRange(
@@ -27,26 +66,61 @@ export async function getDailyGoalValues(
return { success: false, message: "Invalid month." };
}
const { start, end } = monthBounds(month);
- const range = { gte: start, lte: end };
- const [jobs, activities] = await Promise.all([
- prisma.job.groupBy({
- by: "appliedDate",
- _count: { _all: true },
- where: { userId: user.id, applied: true, appliedDate: range },
- }),
- prisma.activity.findMany({
- where: {
- userId: user.id,
- startTime: range,
- duration: { not: null },
- },
- select: { startTime: true, duration: true },
+ const [values, { targets }] = await Promise.all([
+ loadGoalValues(user.id, start, end),
+ // Corrupt settings JSON must not hide the values; targets use defaults
+ loadStoredTargets(user.id).catch((error) => {
+ if (error instanceof SyntaxError) return { targets: {} };
+ throw error;
}),
]);
- return { success: true, data: buildGoalValues(jobs, activities) };
+ return { success: true, data: { values, targets } };
} catch (error) {
// handleError types success as boolean; re-wrap to keep the union narrow.
const { message } = handleError(error, "Failed to load daily goals.");
return { success: false, message };
}
}
+
+export async function updateGoalTargets(input: {
+ month: string;
+ jobs: number;
+ hours: number;
+}): Promise<
+ { success: true; data: { targets: GoalTargetsByMonth } } | Failure
+> {
+ try {
+ const user = await requireUser();
+ // Only the current month is writable, so history can't be edited
+ if (input.month !== format(new Date(), "yyyy-MM")) {
+ return {
+ success: false,
+ message: "The month has changed — reload the page.",
+ };
+ }
+ const parsed = GoalTargetsSchema.safeParse({
+ jobs: input.jobs,
+ hours: input.hours,
+ });
+ if (!parsed.success) {
+ return { success: false, message: "Invalid goal targets." };
+ }
+ const { settings, targets: current } = await loadStoredTargets(user.id);
+ const targets = { ...current, [input.month]: parsed.data };
+ const base = settings ?? defaultUserSettings;
+ // updateUserSettings only deep-merges ai/display, so merge goals here
+ const json = JSON.stringify({
+ ...base,
+ goals: { ...base.goals, targets },
+ });
+ await prisma.userSettings.upsert({
+ where: { userId: user.id },
+ update: { settings: json },
+ create: { userId: user.id, settings: json },
+ });
+ return { success: true, data: { targets } };
+ } catch (error) {
+ const { message } = handleError(error, "Failed to save daily goals.");
+ return { success: false, message };
+ }
+}
diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx
index 390764d..628c1ea 100644
--- a/src/app/dashboard/page.tsx
+++ b/src/app/dashboard/page.tsx
@@ -85,7 +85,7 @@ export default async function Dashboard() {
<div className="flex flex-col gap-2">
<DailyGoalsCalendar
today={today}
- initialValues={dailyGoals.success ? dailyGoals.data : null}
+ initialData={dailyGoals.success ? dailyGoals.data : null}
/>
</div>
<div className="w-full col-span-3">
diff --git a/src/components/dashboard/DailyGoalsCalendar.tsx b/src/components/dashboard/DailyGoalsCalendar.tsx
index 260c000..7c53840 100644
--- a/src/components/dashboard/DailyGoalsCalendar.tsx
+++ b/src/components/dashboard/DailyGoalsCalendar.tsx
@@ -8,52 +8,67 @@ import {
} from "react-goal-calendar";
import { getDailyGoalValues } from "@/actions/dailyGoals.actions";
import { Card } from "@/components/ui/card";
-import { DAILY_GOALS } from "@/lib/constants";
import {
GOAL_IDS,
buildMonthSummary,
goalMonthRange,
+ resolveTargets,
+ type GoalMonthData,
type GoalValues,
type MonthSummary,
} from "@/lib/dailyGoals";
import { toastError } from "@/lib/toast";
import { cn } from "@/lib/utils";
+import type {
+ GoalTargets,
+ GoalTargetsByMonth,
+} from "@/models/dailyGoals.model";
-const GOALS: GcGoal[] = [
- { id: GOAL_IDS.JOBS, label: "Jobs applied", target: DAILY_GOALS.JOBS_TARGET },
- {
- id: GOAL_IDS.HOURS,
- label: "Activity",
- target: DAILY_GOALS.HOURS_TARGET,
- unit: "h",
- },
+// The summary's rings need labels only; targets vary by month
+const RINGS = [
+ { id: GOAL_IDS.JOBS, label: "Jobs applied" },
+ { id: GOAL_IDS.HOURS, label: "Activity" },
+];
+
+const goalsFor = (targets: GoalTargets): GcGoal[] => [
+ { ...RINGS[0], target: targets.jobs },
+ { ...RINGS[1], target: targets.hours, unit: "h" },
];
interface DailyGoalsCalendarProps {
today: string;
- initialValues: GoalValues | null;
+ initialData: GoalMonthData | null;
}
export default function DailyGoalsCalendar({
today,
- initialValues,
+ initialData,
}: DailyGoalsCalendarProps) {
const { minMonth, maxMonth } = goalMonthRange(today);
const [month, setMonth] = useState(maxMonth);
// null = the server fetch failed: leave uncached so it shows "—"
const [valuesByMonth, setValuesByMonth] = useState<
Record<string, GoalValues>
- >(initialValues ? { [maxMonth]: initialValues } : {});
+ >(initialData ? { [maxMonth]: initialData.values } : {});
+ // null until any load succeeds; resolves every month, cached or not
+ const [storedTargets, setStoredTargets] =
+ useState<GoalTargetsByMonth | null>(initialData?.targets ?? null);
+ const targetsFor = (key: string) => resolveTargets(key, storedTargets ?? {});
const [loadingMonth, setLoadingMonth] = useState<string | null>(null);
// Only cached months get an entry; the rest show the package's "—"
const summaries = useMemo(() => {
const data: Record<string, MonthSummary> = {};
for (const [key, values] of Object.entries(valuesByMonth)) {
- data[key] = buildMonthSummary(key, values, today);
+ data[key] = buildMonthSummary(
+ key,
+ values,
+ today,
+ resolveTargets(key, storedTargets ?? {}),
+ );
}
return data;
- }, [valuesByMonth, today]);
+ }, [valuesByMonth, storedTargets, today]);
const handleMonthChange = async (next: string) => {
setMonth(next);
@@ -61,7 +76,9 @@ export default function DailyGoalsCalendar({
setLoadingMonth(next);
const result = await getDailyGoalValues(next);
if (result.success) {
- setValuesByMonth((prev) => ({ ...prev, [next]: result.data }));
+ setValuesByMonth((prev) => ({ ...prev, [next]: result.data.values }));
+ // Only fills a failed initial load; a save may be newer than this read
+ setStoredTargets((prev) => prev ?? result.data.targets);
} else {
toastError(result.message);
}
@@ -85,11 +102,11 @@ export default function DailyGoalsCalendar({
return (
<>
<Card {...cardProps}>
- <GcMonthSummary rings={GOALS} data={summaries} {...monthProps} />
+ <GcMonthSummary rings={RINGS} data={summaries} {...monthProps} />
</Card>
<Card {...cardProps}>
<GcMonthCalendar
- goals={GOALS}
+ goals={goalsFor(targetsFor(month))}
values={valuesByMonth[month]}
legend
{...monthProps}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 882dd65..b2ceb77 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -453,6 +453,10 @@ export const AI_USAGE_CONSTANTS = {
export const DAILY_GOALS = {
JOBS_TARGET: 5,
HOURS_TARGET: 4,
+ JOBS_MIN: 1,
+ JOBS_MAX: 50,
+ HOURS_MIN: 1,
+ HOURS_MAX: 24,
// Months browsable before the current one
MONTHS_BACK: 11,
// Shown until streaks are computed across months
diff --git a/src/lib/dailyGoals.ts b/src/lib/dailyGoals.ts
index 56b48ad..82cfbe8 100644
--- a/src/lib/dailyGoals.ts
+++ b/src/lib/dailyGoals.ts
@@ -1,6 +1,11 @@
import { format } from "date-fns";
import type { GcMonthSummaryProps } from "react-goal-calendar";
import { DAILY_GOALS } from "@/lib/constants";
+import {
+ GoalTargetsSchema,
+ type GoalTargets,
+ type GoalTargetsByMonth,
+} from "@/models/dailyGoals.model";
// Directive-free: imported by the server action and the client calendar.
@@ -8,12 +13,42 @@ export type GoalValues = Record<string, Record<string, number>>;
export const GOAL_IDS = { JOBS: "jobs", HOURS: "hours" } as const;
+export type GoalMonthData = { values: GoalValues; targets: GoalTargetsByMonth };
+
+export const DEFAULT_GOAL_TARGETS: GoalTargets = {
+ jobs: DAILY_GOALS.JOBS_TARGET,
+ hours: DAILY_GOALS.HOURS_TARGET,
+};
+
const MONTH_PATTERN = /^\d{4}-(0[1-9]|1[0-2])$/;
export function isValidMonth(month: unknown): month is string {
return typeof month === "string" && MONTH_PATTERN.test(month);
}
+// Settings JSON is not schema-checked by Prisma; ignore anything malformed
+export function parseStoredTargets(raw: unknown): GoalTargetsByMonth {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
+ const targets: GoalTargetsByMonth = {};
+ for (const [month, value] of Object.entries(raw)) {
+ const parsed = GoalTargetsSchema.safeParse(value);
+ if (isValidMonth(month) && parsed.success) targets[month] = parsed.data;
+ }
+ return targets;
+}
+
+export function resolveTargets(
+ month: string,
+ stored: GoalTargetsByMonth,
+): GoalTargets {
+ let from: string | undefined;
+ // "YYYY-MM" sorts as a string; only look backward so the past stays fixed
+ for (const key of Object.keys(stored)) {
+ if (key <= month && (!from || key > from)) from = key;
+ }
+ return from ? stored[from] : DEFAULT_GOAL_TARGETS;
+}
+
export function shiftMonth(month: string, delta: number): string {
const [year, monthIndex] = month.split("-").map(Number);
return format(new Date(year, monthIndex - 1 + delta, 1), "yyyy-MM");
@@ -72,18 +107,14 @@ export function formatDays(count: number): string {
return `${count} ${count === 1 ? "day" : "days"}`;
}
-// Typed wide: ids come from Object.keys, which yields string
-const TARGETS: Record<string, number> = {
- [GOAL_IDS.JOBS]: DAILY_GOALS.JOBS_TARGET,
- [GOAL_IDS.HOURS]: DAILY_GOALS.HOURS_TARGET,
-};
+const IDS = Object.values(GOAL_IDS);
export function buildMonthSummary(
month: string,
values: GoalValues,
today: string,
+ targets: GoalTargets,
): MonthSummary {
- const ids = Object.keys(TARGETS);
const hit: Record<string, number> = {};
const counted: Record<string, number> = {};
let bothMet = 0;
@@ -94,19 +125,19 @@ export function buildMonthSummary(
const key = `${month}-${String(d).padStart(2, "0")}`;
if (key > today) break;
const day = values[key] ?? {};
- const isMet = (id: string) => (day[id] ?? 0) >= TARGETS[id];
+ const isMet = (id: (typeof IDS)[number]) => (day[id] ?? 0) >= targets[id];
// Today counts only once met, so an unfinished day never drags it down
- for (const id of ids) {
+ for (const id of IDS) {
if (key === today && !isMet(id)) continue;
counted[id] = (counted[id] ?? 0) + 1;
if (isMet(id)) hit[id] = (hit[id] ?? 0) + 1;
}
- if (ids.every(isMet)) bothMet++;
- if (key < today && ids.every((id) => !day[id])) nothingLogged++;
+ if (IDS.every(isMet)) bothMet++;
+ if (key < today && IDS.every((id) => !day[id])) nothingLogged++;
}
const rings: Record<string, number> = {};
- for (const id of ids) {
+ for (const id of IDS) {
if (counted[id]) rings[id] = (hit[id] ?? 0) / counted[id];
}
diff --git a/src/models/dailyGoals.model.ts b/src/models/dailyGoals.model.ts
new file mode 100644
index 0000000..d4562cc
--- /dev/null
+++ b/src/models/dailyGoals.model.ts
@@ -0,0 +1,19 @@
+import { z } from "zod";
+import { DAILY_GOALS } from "@/lib/constants";
+
+const wholeNumber = (min: number, max: number) =>
+ z
+ .number({ error: "Enter a number." })
+ .int({ message: "Use a whole number." })
+ .min(min, { message: `Must be at least ${min}.` })
+ .max(max, { message: `Must be at most ${max}.` });
+
+export const GoalTargetsSchema = z.object({
+ jobs: wholeNumber(DAILY_GOALS.JOBS_MIN, DAILY_GOALS.JOBS_MAX),
+ hours: wholeNumber(DAILY_GOALS.HOURS_MIN, DAILY_GOALS.HOURS_MAX),
+});
+
+export type GoalTargets = z.infer<typeof GoalTargetsSchema>;
+
+// Keyed by "YYYY-MM"; a month with no entry carries the latest earlier one
+export type GoalTargetsByMonth = Record<string, GoalTargets>;
diff --git a/src/models/userSettings.model.ts b/src/models/userSettings.model.ts
index 73726a6..130ec71 100644
--- a/src/models/userSettings.model.ts
+++ b/src/models/userSettings.model.ts
@@ -1,4 +1,5 @@
import { AiProvider } from "./ai.model";
+import type { GoalTargetsByMonth } from "./dailyGoals.model";
export interface AiSettings {
provider: AiProvider;
@@ -9,9 +10,14 @@ export interface DisplaySettings {
theme: "light" | "dark" | "system";
}
+export interface GoalSettings {
+ targets: GoalTargetsByMonth;
+}
+
export interface UserSettingsData {
ai: AiSettings;
display: DisplaySettings;
+ goals?: GoalSettings;
}
export interface UserSettings {