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.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(dashboard): cap the weekly Activities chart to top-3 + Other, matching the donut
Khuram Niaza11e42f166ba
diff --git a/__tests__/JobsActivityCard.spec.tsx b/__tests__/JobsActivityCard.spec.tsxindex 223b327..530face 100644--- a/__tests__/JobsActivityCard.spec.tsx+++ b/__tests__/JobsActivityCard.spec.tsx@@ -20,6 +20,11 @@ vi.mock("@nivo/pie", () => ({{props.data.map((slice: any) => (<div key={slice.id} data-testid={`slice-${slice.id}`}>{slice.label}:{slice.value}:{slice.color}+ {slice.breakdown?.length+ ? `:${slice.breakdown+ .map((a: any) => `${a.label}=${a.hours}`)+ .join(",")}`+ : ""}</div>))}</div>@@ -48,6 +53,10 @@ describe("JobsActivityCard", () => {{ label: "Side Project 1", hours: 9.2 },{ label: "Learning", hours: 8.6 },],+ otherActivities: [+ { label: "Networking", hours: 10.5 },+ { label: "Interviewing", hours: 7 },+ ],otherHours: 17.5,totalHours: 63.4,},@@ -58,6 +67,7 @@ describe("JobsActivityCard", () => {jobsApplied: 34,jobsTrend: -12,topActivities: [{ label: "Job Search", hours: 6.4 }],+ otherActivities: [],otherHours: 0,totalHours: 6.4,},@@ -89,7 +99,7 @@ describe("JobsActivityCard", () => {"Jobsync:28.1:#2a9d90",);expect(screen.getByTestId("slice-__other__")).toHaveTextContent(- "Other:17.5:#94a3b8",+ "Other:17.5:#94a3b8:Networking=10.5,Interviewing=7",);});@@ -162,6 +172,7 @@ describe("JobsActivityCard", () => {jobsApplied: 1,jobsTrend: 0,topActivities: [{ label: "Job Search", hours: 2 }],+ otherActivities: [],otherHours: 0,totalHours: 2,},@@ -183,6 +194,7 @@ describe("JobsActivityCard", () => {jobsApplied: 3,jobsTrend: 0,topActivities: [],+ otherActivities: [],otherHours: 0,totalHours: 0,},diff --git a/__tests__/dashboard.actions.spec.ts b/__tests__/dashboard.actions.spec.tsindex b132b05..c25ea81 100644--- a/__tests__/dashboard.actions.spec.ts+++ b/__tests__/dashboard.actions.spec.ts@@ -127,9 +127,10 @@ describe("Dashboard Actions", () => {const result = await getActivityDataForPeriod();- expect(Array.isArray(result)).toBe(true);- expect(result.length).toBe(7);- expect(result[0]).toHaveProperty("day");+ expect(Array.isArray(result.data)).toBe(true);+ expect(result.data.length).toBe(7);+ expect(result.data[0]).toHaveProperty("day");+ expect(result.keys).toEqual(["Applying", "Interviewing"]);expect(prisma.activity.findMany).toHaveBeenCalledTimes(1);});@@ -158,12 +159,60 @@ describe("Dashboard Actions", () => {const result = await getActivityDataForPeriod();- expect(result.length).toBe(7);- result.forEach((day: any) => {+ expect(result.data.length).toBe(7);+ result.data.forEach((day: any) => {expect(day).toHaveProperty("day");});});+ it("caps to the top three types and attaches a breakdown to the Other bucket", async () => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ const today = new Date();+ const mockActivities = [+ {+ startTime: today,+ duration: 600,+ activityType: { label: "Jobsync" },+ },+ {+ startTime: today,+ duration: 300,+ activityType: { label: "Learning" },+ },+ {+ startTime: today,+ duration: 180,+ activityType: { label: "Side Project 1" },+ },+ {+ startTime: today,+ duration: 120,+ activityType: { label: "Job Search" },+ },+ {+ startTime: today,+ duration: 60,+ activityType: { label: "Networking" },+ },+ ];+ (prisma.activity.findMany as any).mockResolvedValue(mockActivities);++ const result = await getActivityDataForPeriod();++ expect(result.keys).toEqual([+ "Jobsync",+ "Learning",+ "Side Project 1",+ "__other__",+ ]);+ const todayEntry = result.data[result.data.length - 1];+ expect(todayEntry["__other__"]).toBe(3);+ expect(todayEntry.otherBreakdown).toEqual([+ { label: "Job Search", hours: 2 },+ { label: "Networking", hours: 1 },+ ]);+ });+it("should handle activities with missing activityType", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);const mockActivities = [@@ -177,8 +226,8 @@ describe("Dashboard Actions", () => {const result = await getActivityDataForPeriod();- expect(Array.isArray(result)).toBe(true);- expect(result.length).toBe(7);+ expect(Array.isArray(result.data)).toBe(true);+ expect(result.data.length).toBe(7);});});@@ -372,6 +421,10 @@ describe("Dashboard Actions", () => {{ label: "Learning", hours: 5 },{ label: "Side Project 1", hours: 3 },]);+ expect(result.otherActivities).toEqual([+ { label: "Job Search", hours: 2 },+ { label: "Networking", hours: 1 },+ ]);expect(result.otherHours).toBe(3);expect(result.totalHours).toBe(21);});@@ -425,6 +478,7 @@ describe("Dashboard Actions", () => {jobsApplied: 0,jobsTrend: 0,topActivities: [],+ otherActivities: [],otherHours: 0,totalHours: 0,});diff --git a/__tests__/jobsActivityChart.spec.ts b/__tests__/jobsActivityChart.spec.tsindex a5ff72f..91ca757 100644--- a/__tests__/jobsActivityChart.spec.ts+++ b/__tests__/jobsActivityChart.spec.ts@@ -52,9 +52,34 @@ describe("buildDonutSlices", () => {label: "Other",value: 17.5,color: "#94a3b8",+ breakdown: [],});});+ it("attaches the leftover activities to the Other slice for the tooltip", () => {+ const otherActivities = [+ { label: "Networking", hours: 10.5 },+ { label: "Interviewing", hours: 7 },+ ];+ const slices = buildDonutSlices(+ activities,+ 17.5,+ "light",+ otherActivities,+ );++ expect(slices[3].breakdown).toEqual(otherActivities);+ });++ it("drops zero-hour entries from the Other slice's breakdown", () => {+ const slices = buildDonutSlices(activities, 17.5, "light", [+ { label: "Networking", hours: 17.5 },+ { label: "Unused", hours: 0 },+ ]);++ expect(slices[3].breakdown).toEqual([{ label: "Networking", hours: 17.5 }]);+ });+it("omits the Other slice when there are no leftover hours", () => {const slices = buildDonutSlices(activities, 0, "light");diff --git a/src/actions/dashboard/charts.ts b/src/actions/dashboard/charts.tsindex e8f60c2..54cc694 100644--- a/src/actions/dashboard/charts.ts+++ b/src/actions/dashboard/charts.ts@@ -1,10 +1,14 @@import prisma from "@/lib/db";import { getLast7Days } from "@/lib/utils";import { format, parseISO } from "date-fns";+import { OTHER_SLICE_ID } from "@/components/dashboard/jobsActivityChart";import { requireUser } from "../shared";-import { getLocalDayRange } from "./shared";+import { getLocalDayRange, roundToTenth } from "./shared";-export const getActivityDataForPeriod = async (): Promise<any | undefined> => {+export const getActivityDataForPeriod = async (): Promise<{+ data: any[];+ keys: string[];+}> => {try {const user = await requireUser();// Use local time for date range to match grouping and getLast7Days@@ -46,12 +50,55 @@ export const getActivityDataForPeriod = async (): Promise<any | undefined> => {return acc;}, {});++ // Cap to the top 3 activity types by total weekly hours, matching the+ // donut card's ranking, and fold the rest into "Other" per day.+ const totalsByLabel: Record<string, number> = {};+ for (const dayTotals of Object.values(groupedData) as Record<+ string,+ number+ >[]) {+ for (const [label, hours] of Object.entries(dayTotals)) {+ totalsByLabel[label] = (totalsByLabel[label] || 0) + hours;+ }+ }+ const topLabels = Object.entries(totalsByLabel)+ .sort((a, b) => b[1] - a[1])+ .slice(0, 3)+ .map(([label]) => label);+ const hasOther = Object.keys(totalsByLabel).some(+ (label) => !topLabels.includes(label),+ );+ const keys = hasOther ? [...topLabels, OTHER_SLICE_ID] : topLabels;+const last7Days = getLast7Days("yyyy-MM-dd");- const result = last7Days.map((dateStr) => ({- day: format(parseISO(dateStr), "EEE, MMM d"),- ...groupedData[dateStr],- }));- return result;+ const data = last7Days.map((dateStr) => {+ const dayTotals: Record<string, number> = groupedData[dateStr] || {};+ const entry: Record<string, any> = {+ day: format(parseISO(dateStr), "EEE, MMM d"),+ };+ for (const label of topLabels) {+ if (dayTotals[label]) entry[label] = dayTotals[label];+ }+ if (hasOther) {+ const otherBreakdown = Object.entries(dayTotals)+ .filter(([label]) => !topLabels.includes(label))+ .map(([label, hours]) => ({ label, hours: roundToTenth(hours) }))+ .filter((entry) => entry.hours > 0)+ .sort((a, b) => b.hours - a.hours);+ const otherHours = otherBreakdown.reduce(+ (sum, entry) => sum + entry.hours,+ 0,+ );+ if (otherHours) {+ entry[OTHER_SLICE_ID] = otherHours;+ entry.otherBreakdown = otherBreakdown;+ }+ }+ return entry;+ });++ return { data, keys };} catch (error) {const msg = "Failed to fetch activities data.";console.error(msg, error);diff --git a/src/actions/dashboard/shared.ts b/src/actions/dashboard/shared.tsindex 314a5cc..4fc8bcb 100644--- a/src/actions/dashboard/shared.ts+++ b/src/actions/dashboard/shared.ts@@ -1,3 +1,5 @@+export const roundToTenth = (hours: number) => Math.round(hours * 10) / 10;+// Local-time day range: start at 00:00 daysBack days ago, end today 23:59:59.999export const getLocalDayRange = (daysBack: number,diff --git a/src/actions/dashboard/stats.ts b/src/actions/dashboard/stats.tsindex 4c6f3d5..4ab1fdf 100644--- a/src/actions/dashboard/stats.ts+++ b/src/actions/dashboard/stats.ts@@ -1,7 +1,7 @@import prisma from "@/lib/db";import { calculatePercentageDifference } from "@/lib/utils";import { requireUser } from "../shared";-import { getLocalDayRange } from "./shared";+import { getLocalDayRange, roundToTenth } from "./shared";export interface TopActivityType {label: string;@@ -12,12 +12,11 @@ export interface JobsActivitySummary {jobsApplied: number;jobsTrend: number;topActivities: TopActivityType[];+ otherActivities: TopActivityType[];otherHours: number;totalHours: number;}-const roundToTenth = (hours: number) => Math.round(hours * 10) / 10;-// One read for the merged Jobs & Activity card. Both halves share// getLocalDayRange so "7d" means the same window on each; the retired// getJobsAppliedForPeriod counted a rolling 7x24h window instead.@@ -76,8 +75,13 @@ export const getJobsActivitySummary = async (const topActivities = sorted.slice(0, 3).map(({ label, hours }) => ({ label, hours: roundToTenth(hours) }));+ const otherActivities = sorted+ .slice(3)+ .map(({ label, hours }) => ({ label, hours: roundToTenth(hours) }));+ // Summed from the same rounded values as otherActivities so the donut's+ // "Other" slice and its tooltip breakdown never disagree.const otherHours = roundToTenth(- sorted.slice(3).reduce((sum, entry) => sum + entry.hours, 0),+ otherActivities.reduce((sum, entry) => sum + entry.hours, 0),);// Totalled from the rounded parts so the number in the donut's// center always equals the legend beside it.@@ -88,7 +92,14 @@ export const getJobsActivitySummary = async (const jobsTrend =calculatePercentageDifference(priorJobs, jobsApplied) ?? 0;- return { jobsApplied, jobsTrend, topActivities, otherHours, totalHours };+ return {+ jobsApplied,+ jobsTrend,+ topActivities,+ otherActivities,+ otherHours,+ totalHours,+ };} catch (error) {const msg = "Failed to fetch jobs and activity summary";console.error(msg, error);diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsxindex 1d1ef96..0697224 100644--- a/src/app/dashboard/page.tsx+++ b/src/app/dashboard/page.tsx@@ -37,14 +37,6 @@ export default async function Dashboard() {getActivityCalendarData(),]);const activityCalendarDataKeys = Object.keys(activityCalendarData);- const activitiesDataKeys = (data: string[]) =>- Array.from(- new Set(- data.flatMap((entry) =>- Object.keys(entry).filter((key) => key !== "day"),- ),- ),- );return (<><div className="@container grid grid-cols-1 auto-rows-max items-start gap-2 md:gap-2 @3xl/main:col-span-2">@@ -67,8 +59,8 @@ export default async function Dashboard() {},{label: "Activities",- data: activitiesData,- keys: activitiesDataKeys(activitiesData),+ data: activitiesData.data,+ keys: activitiesData.keys,groupMode: "stacked",axisLeftLegend: "TIME SPENT (Hours)",},diff --git a/src/components/dashboard/JobsActivityCard.tsx b/src/components/dashboard/JobsActivityCard.tsxindex edcab7f..df64b5c 100644--- a/src/components/dashboard/JobsActivityCard.tsx+++ b/src/components/dashboard/JobsActivityCard.tsx@@ -6,7 +6,10 @@ import { animated } from "@react-spring/web";import { useTheme } from "next-themes";import { TrendingDown, TrendingUp } from "lucide-react";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";-import { JobsActivitySummary } from "@/actions/dashboard.actions";+import {+ JobsActivitySummary,+ TopActivityType,+} from "@/actions/dashboard.actions";import { useElementWidth } from "@/hooks/useElementWidth";import { usePersistedTabIndex } from "@/hooks/usePersistedTabIndex";import { APP_CONSTANTS } from "@/lib/constants";@@ -79,9 +82,20 @@ export default function JobsActivityCard({ data }: JobsActivityCardProps) {const { resolvedTheme } = useTheme();const theme = resolvedTheme === "light" ? "light" : "dark";const current = data[activeIndex];- const { jobsApplied, jobsTrend, topActivities, otherHours, totalHours } =- current.summary;- const slices = buildDonutSlices(topActivities, otherHours, theme);+ const {+ jobsApplied,+ jobsTrend,+ topActivities,+ otherActivities,+ otherHours,+ totalHours,+ } = current.summary;+ const slices = buildDonutSlices(+ topActivities,+ otherHours,+ theme,+ otherActivities,+ );const layout = donutLayout(chartWidth);const roomyTotal = layout.holeDiameter >= FULL_TOTAL_HOLE;const maxLabelChars = useRef(layout.maxLabelChars);@@ -183,6 +197,11 @@ export default function JobsActivityCard({ data }: JobsActivityCardProps) {}}><strong>{datum.data.label}</strong> — {datum.value}h+ {datum.data.breakdown?.map((activity: TopActivityType) => (+ <div key={activity.label}>+ {activity.label} — {activity.hours}h+ </div>+ ))}</div>)}/>diff --git a/src/components/dashboard/WeeklyBarChartToggle.tsx b/src/components/dashboard/WeeklyBarChartToggle.tsxindex 80ba82a..3068665 100644--- a/src/components/dashboard/WeeklyBarChartToggle.tsx+++ b/src/components/dashboard/WeeklyBarChartToggle.tsx@@ -1,11 +1,18 @@"use client";-import { useState, useEffect } from "react";+import { useState, useEffect, useMemo } from "react";+import { useTheme } from "next-themes";import { ResponsiveBar } from "@nivo/bar";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";import { cn } from "@/lib/utils";import { APP_CONSTANTS } from "@/lib/constants";import { usePersistedTabIndex } from "@/hooks/usePersistedTabIndex";+import {+ SERIES_COLORS,+ OTHER_COLOR,+ OTHER_SLICE_ID,+ otherBucketLabel,+} from "./jobsActivityChart";type ChartConfig = {label: string;@@ -28,7 +35,21 @@ export default function WeeklyBarChartToggle({charts.map((chart) => chart.label),);const [isSmallScreen, setIsSmallScreen] = useState(false);+ const { resolvedTheme } = useTheme();+ const theme = resolvedTheme === "light" ? "light" : "dark";const current = charts[activeIndex];+ const activityColors = useMemo(+ () =>+ new Map(+ current.keys.map((key, index) => [+ key,+ key === OTHER_SLICE_ID+ ? OTHER_COLOR[theme]+ : SERIES_COLORS[theme][index],+ ]),+ ),+ [current.keys, theme],+ );useEffect(() => {const mq = window.matchMedia("(max-width: 640px)");@@ -130,7 +151,9 @@ export default function WeeklyBarChartToggle({padding={0.6}groupMode={current.groupMode}colors={- current.groupMode === "stacked" ? { scheme: "nivo" } : "#2a7ef0"+ current.groupMode === "stacked"+ ? (bar) => activityColors.get(String(bar.id)) ?? "#94a3b8"+ : "#2a7ef0"}enableTotals={current.groupMode === "stacked" ? true : false}valueFormat={(value) =>@@ -181,7 +204,7 @@ export default function WeeklyBarChartToggle({tickValues: intTickValues,}}motionConfig="gentle"- tooltip={({ id, value, indexValue, color }) => (+ tooltip={({ id, value, indexValue, color, data }) => (<divstyle={{background: "#1e293b",@@ -192,6 +215,7 @@ export default function WeeklyBarChartToggle({whiteSpace: "nowrap",}}>+ <div style={{ marginBottom: 4 }}>{indexValue}</div><spanstyle={{display: "inline-block",@@ -210,13 +234,26 @@ export default function WeeklyBarChartToggle({.replace(/\(.*\)/, "").trim().replace(/\b\w/g, (c) => c.toUpperCase())- : String(id)}{" "}- – {indexValue}:{" "}+ : String(id) === OTHER_SLICE_ID+ ? otherBucketLabel(+ current.keys.filter((key) => key !== OTHER_SLICE_ID),+ )+ : String(id)}+ :{" "}<strong>{current.label === "Activities"? Number(value).toFixed(1): value}</strong>+ {String(id) === OTHER_SLICE_ID &&+ (data as any).otherBreakdown?.length > 0 &&+ (data as any).otherBreakdown.map(+ (activity: { label: string; hours: number }) => (+ <div key={activity.label}>+ {activity.label} – {activity.hours}h+ </div>+ ),+ )}</div>)}/>diff --git a/src/components/dashboard/jobsActivityChart.ts b/src/components/dashboard/jobsActivityChart.tsindex f05bd46..71f9f27 100644--- a/src/components/dashboard/jobsActivityChart.ts+++ b/src/components/dashboard/jobsActivityChart.ts@@ -3,20 +3,33 @@ import { TopActivityType } from "@/actions/dashboard.actions";// Donut hues, validated for colorblind separation against each theme's// card surface. The app's own --chart-* tokens fail that check here:// light --chart-3 (#274754) reads as near-black grey in a donut.-const SERIES_COLORS = {+export const SERIES_COLORS = {light: ["#2a9d90", "#c97e22", "#6d4fc7"],dark: ["#16a89a", "#c08438", "#8b72e8"],} as const;-const OTHER_COLOR = { light: "#94a3b8", dark: "#64748b" } as const;+export const OTHER_COLOR = { light: "#94a3b8", dark: "#64748b" } as const;++// Matches the "Other" bucket key charts/dashboard.actions builds server-side.+export const OTHER_ACTIVITY_LABEL = "Other";export const OTHER_SLICE_ID = "__other__";+// A real activity type can itself be named "Other". When it is, the+// synthetic bucket needs a distinct display label so the two don't render+// as two identically-labeled slices/bars.+export function otherBucketLabel(topLabels: string[]): string {+ return topLabels.includes(OTHER_ACTIVITY_LABEL)+ ? "Other activity types"+ : OTHER_ACTIVITY_LABEL;+}+export interface DonutSlice {id: string;label: string;value: number;color: string;+ breakdown?: TopActivityType[];}// Hues are assigned by rank and never cycled, so a slice keeps its color@@ -25,6 +38,7 @@ export function buildDonutSlices(topActivities: TopActivityType[],otherHours: number,theme: "light" | "dark",+ otherActivities: TopActivityType[] = [],): DonutSlice[] {const slices: DonutSlice[] = topActivities.filter((activity) => activity.hours > 0)@@ -38,9 +52,10 @@ export function buildDonutSlices(if (otherHours > 0) {slices.push({id: OTHER_SLICE_ID,- label: "Other",+ label: otherBucketLabel(topActivities.map((activity) => activity.label)),value: otherHours,color: OTHER_COLOR[theme],+ breakdown: otherActivities.filter((activity) => activity.hours > 0),});}