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(jobs): replace the preset filter with a multi-facet filter popover with live counts, URL-synced filters and a Filtered-by chip row; keep filters on reload; update the jobs help page and status-filter e2e
Khuram Niaz9138a9a8d89e
diff --git a/__tests__/JobsContainer.spec.tsx b/__tests__/JobsContainer.spec.tsxindex 77e0091..179c29e 100644--- a/__tests__/JobsContainer.spec.tsx+++ b/__tests__/JobsContainer.spec.tsx@@ -3,11 +3,13 @@ import { screen, render, waitFor, act } from "@testing-library/react";import userEvent from "@testing-library/user-event";import {getJobsList,+ getJobFilterCounts,getJobDetails,deleteJobById,updateJobStatus,} from "@/actions/job.actions";import { useRouter, usePathname, useSearchParams } from "next/navigation";+import { EMPTY_JOB_FACETS } from "@/lib/jobs/jobFacets";vi.mock("next-auth", () => {const mockAuth = vi.fn();@@ -41,6 +43,7 @@ vi.mock("next-auth/providers/credentials", () => ({vi.mock("@/actions/job.actions", () => ({getJobsList: vi.fn(),+ getJobFilterCounts: vi.fn(),getJobDetails: vi.fn(),deleteJobById: vi.fn(),updateJobStatus: vi.fn(),@@ -219,6 +222,10 @@ describe("JobsContainer Search Functionality", () => {(useRouter as any).mockReturnValue(mockRouter);(usePathname as any).mockReturnValue("/dashboard/myjobs");(useSearchParams as any).mockReturnValue(mockSearchParams);+ (getJobFilterCounts as any).mockResolvedValue({+ success: true,+ data: { total: 2, statusCounts: {}, acceptedDiscovered: 0 },+ });});afterEach(() => {@@ -401,153 +408,123 @@ describe("JobsContainer Search Functionality", () => {});});- describe("Search with Filters", () => {- it("should combine search with status filter", async () => {- (getJobsList as any).mockResolvedValue({- success: true,- data: mockJobs,- total: 2,- });+ describe("Popover filters", () => {+ const U = undefined;++ it("passes facets from the URL to getJobsList", async () => {+ (useSearchParams as any).mockReturnValue(+ new URLSearchParams("status=applied,interview&type=FT"),+ );+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });renderComponent();await waitFor(() => {- expect(- screen.getByPlaceholderText("Search jobs..."),- ).toBeInTheDocument();- });-- // Type in search- const searchInput = screen.getByPlaceholderText("Search jobs...");- await act(async () => {- await user.type(searchInput, "Developer");+ expect(getJobsList).toHaveBeenCalledWith(+ 1, 25,+ { ...EMPTY_JOB_FACETS, statuses: ["applied", "interview"], jobTypes: ["FT"] },+ U, U, U, U, U, U, U,+ );});+ });- await act(async () => {- vi.advanceTimersByTime(300);- });+ it("combines URL facets with search", async () => {+ (useSearchParams as any).mockReturnValue(new URLSearchParams("status=applied"));+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined, undefined);- });+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));- // Now change filter- const filterTrigger = screen.getByRole("combobox");await act(async () => {- await user.click(filterTrigger);+ await user.type(screen.getByPlaceholderText("Search jobs..."), "Developer");});-- const appliedOption = screen.getByRole("option", { name: "Applied" });await act(async () => {- await user.click(appliedOption);+ vi.advanceTimersByTime(300);});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", "Developer", undefined, undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenLastCalledWith(+ 1, 25, { ...EMPTY_JOB_FACETS, statuses: ["applied"] },+ "Developer", U, U, U, U, U, U,+ );});});- it("should preserve search when changing filter", async () => {- (getJobsList as any).mockResolvedValue({- success: true,- data: mockJobs,- total: 2,- });+ it("writes applied facets to the URL, keeping deep-link params", async () => {+ (useSearchParams as any).mockReturnValue(+ new URLSearchParams("company=google&applied=true"),+ );+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });renderComponent();+ await user.click(screen.getByRole("button", { name: /^Filter jobs/ }));+ await user.click(screen.getByRole("checkbox", { name: "Interview" }));+ await user.click(screen.getByRole("button", { name: /^Show / }));- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledTimes(1);- });-- // Type in search- const searchInput = screen.getByPlaceholderText("Search jobs...");- await act(async () => {- await user.type(searchInput, "Amazon");- });-- await act(async () => {- vi.advanceTimersByTime(300);- });+ expect(mockRouter.push).toHaveBeenCalledWith(+ "/dashboard/myjobs?company=google&applied=true&status=interview",+ );+ });- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Amazon", undefined, undefined, undefined, undefined, undefined, undefined);- });+ it("shows a chip per active section and clears one on its ×", async () => {+ (useSearchParams as any).mockReturnValue(+ new URLSearchParams("status=applied&workplace=REMOTE"),+ );+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });- // Change filter- const filterTrigger = screen.getByRole("combobox");- await act(async () => {- await user.click(filterTrigger);- });+ renderComponent();- const interviewOption = screen.getByRole("option", { name: "Interview" });- await act(async () => {- await user.click(interviewOption);- });+ expect(screen.getByText("Filtered by")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Remove Workplace filter" }));+ expect(mockRouter.push).toHaveBeenCalledWith("/dashboard/myjobs?status=applied");+ });- // Search term should still be present- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "interview", "Amazon", undefined, undefined, undefined, undefined, undefined, undefined);- });+ it("hides the chip row when no facets are active", async () => {+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));+ expect(screen.queryByText("Filtered by")).not.toBeInTheDocument();});- it("should clear filter but preserve search when selecting None filter", async () => {- (getJobsList as any).mockResolvedValue({- success: true,- data: mockJobs,- total: 2,- });+ it("keeps facets and search on reload", async () => {+ (useSearchParams as any).mockReturnValue(new URLSearchParams("status=draft"));+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));+ await user.click(screen.getByRole("button", { name: "Reload jobs" }));await waitFor(() => {- expect(getJobsList).toHaveBeenCalledTimes(1);- });-- // First type in search- const searchInput = screen.getByPlaceholderText("Search jobs...");- await act(async () => {- await user.type(searchInput, "Developer");+ expect(getJobsList).toHaveBeenLastCalledWith(+ 1, 25, { ...EMPTY_JOB_FACETS, statuses: ["draft"] }, U, U, U, U, U, U, U,+ );});+ });- await act(async () => {- vi.advanceTimersByTime(300);- });+ it("does not blame the filters when the list failed to load", async () => {+ (useSearchParams as any).mockReturnValue(new URLSearchParams("status=rejected"));+ (getJobsList as any).mockResolvedValue({ success: false, message: "boom" });- // Set a filter- const filterTrigger = screen.getByRole("combobox");- await act(async () => {- await user.click(filterTrigger);- });+ renderComponent();- const appliedOption = screen.getByRole("option", { name: "Applied" });- await act(async () => {- await user.click(appliedOption);- });+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));+ await act(async () => {});+ expect(screen.queryByText("No jobs match these filters.")).not.toBeInTheDocument();+ });- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", "Developer", undefined, undefined, undefined, undefined, undefined, undefined);- });+ it("explains an empty filtered list and offers Clear all", async () => {+ (useSearchParams as any).mockReturnValue(new URLSearchParams("status=rejected"));+ (getJobsList as any).mockResolvedValue({ success: true, data: [], total: 0 });- // Now clear filter by selecting None- await act(async () => {- await user.click(filterTrigger);- });-- const noneOption = screen.getByRole("option", {- name: "All (Except Dismissed)",- });- await act(async () => {- await user.click(noneOption);- });+ renderComponent();- // Filter should be cleared but search preserved- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined, undefined);- });+ expect(await screen.findByText("No jobs match these filters.")).toBeInTheDocument();+ await user.click(screen.getAllByRole("button", { name: "Clear all" })[0]);+ expect(mockRouter.push).toHaveBeenCalledWith("/dashboard/myjobs");});});+describe("Search Results Display", () => {it("should display filtered jobs after search", async () => {const amazonJob = [mockJobs[0]];@@ -823,33 +800,19 @@ describe("JobsContainer Search Functionality", () => {expect(googleButtons).toHaveLength(0);});- it("should combine company filter with status filter", async () => {- const companySearchParams = new URLSearchParams("company=google&applied=true");- (useSearchParams as any).mockReturnValue(companySearchParams);- (getJobsList as any).mockResolvedValue({- success: true,- data: mockJobs,- total: 2,- });+ it("should combine company filter with status facets", async () => {+ (useSearchParams as any).mockReturnValue(+ new URLSearchParams("company=google&applied=true&status=applied"),+ );+ (getJobsList as any).mockResolvedValue({ success: true, data: mockJobs, total: 2 });renderComponent();await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, "google", true, undefined, undefined, undefined, undefined);- });-- const filterTrigger = screen.getByRole("combobox");- await act(async () => {- await user.click(filterTrigger);- });-- const appliedOption = screen.getByRole("option", { name: "Applied" });- await act(async () => {- await user.click(appliedOption);- });-- await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", undefined, "google", true, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(+ 1, 25, { ...EMPTY_JOB_FACETS, statuses: ["applied"] },+ undefined, "google", true, undefined, undefined, undefined, undefined,+ );});});});diff --git a/__tests__/JobsFilterPopover.spec.tsx b/__tests__/JobsFilterPopover.spec.tsxnew file mode 100644index 0000000..dfdfb6e--- /dev/null+++ b/__tests__/JobsFilterPopover.spec.tsx@@ -0,0 +1,211 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { JobsFilterPopover } from "@/components/myjobs/jobs-container/JobsFilterPopover";+import { getJobFilterCounts } from "@/actions/job.actions";+import { EMPTY_JOB_FACETS } from "@/lib/jobs/jobFacets";++vi.mock("@/actions/job.actions", () => ({+ getJobFilterCounts: vi.fn(),+}));++const statuses = [+ { id: "s-rejected", label: "Rejected", value: "rejected" },+ { id: "s-applied", label: "Applied", value: "applied" },+ { id: "s-interview", label: "Interview", value: "interview" },+];++const counts = (total: number) => ({+ success: true,+ data: {+ total,+ statusCounts: { "s-applied": 11, "s-interview": 4, "s-rejected": 21 },+ acceptedDiscovered: 7,+ },+});++describe("JobsFilterPopover", () => {+ const user = userEvent.setup({ delay: null });+ const onApply = vi.fn();++ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ (getJobFilterCounts as any).mockResolvedValue(counts(18));+ });++ afterEach(() => vi.useRealTimers());++ const renderPopover = (facets = EMPTY_JOB_FACETS) =>+ render(+ <JobsFilterPopover+ statuses={statuses}+ facets={facets}+ search=""+ scope={{}}+ onApply={onApply}+ />,+ );++ const open = async () => {+ await user.click(screen.getByRole("button", { name: /^Filter jobs/ }));+ await act(async () => {+ vi.advanceTimersByTime(300);+ });+ };++ it("lists statuses in JOB_STATUSES order with their counts", async () => {+ renderPopover();+ await open();+ const labels = screen+ .getAllByRole("checkbox")+ .map((box) => box.getAttribute("aria-label"));+ expect(labels.slice(0, 3)).toEqual(["Applied", "Interview", "Rejected"]);+ expect(labels).toContain("Accepted (discovered)");+ expect(labels).toContain("Include dismissed discovered jobs");+ await waitFor(() => expect(screen.getByText("21")).toBeInTheDocument());+ });++ it("shows the live total on the apply button", async () => {+ renderPopover();+ await open();+ expect(+ await screen.findByRole("button", { name: "Show 18 jobs" }),+ ).toBeInTheDocument();+ });++ it("applies the draft only on Show N jobs", async () => {+ renderPopover();+ await open();+ await user.click(screen.getByRole("checkbox", { name: "Applied" }));+ await user.click(screen.getByRole("button", { name: "Remote" }));+ expect(onApply).not.toHaveBeenCalled();++ await act(async () => {+ vi.advanceTimersByTime(300);+ });+ await user.click(await screen.findByRole("button", { name: /^Show \d+ jobs?$/ }));+ expect(onApply).toHaveBeenCalledWith({+ ...EMPTY_JOB_FACETS,+ statuses: ["applied"],+ workplaces: ["REMOTE"],+ });+ });++ it("sends the draft, not the applied facets, to the count query", async () => {+ renderPopover();+ await open();+ await user.click(screen.getByRole("button", { name: "Contract" }));+ await act(async () => {+ vi.advanceTimersByTime(300);+ });+ await waitFor(() =>+ expect(getJobFilterCounts).toHaveBeenLastCalledWith(+ { ...EMPTY_JOB_FACETS, jobTypes: ["C"] },+ "",+ {},+ ),+ );+ });++ it("discards the draft when closed without applying", async () => {+ renderPopover();+ await open();+ await user.click(screen.getByRole("checkbox", { name: "Applied" }));+ await user.keyboard("{Escape}");+ await open();+ expect(screen.getByRole("checkbox", { name: "Applied" })).not.toBeChecked();+ expect(onApply).not.toHaveBeenCalled();+ });++ it("drops the old counts when reopened", async () => {+ renderPopover();+ await open();+ expect(+ await screen.findByRole("button", { name: "Show 18 jobs" }),+ ).toBeInTheDocument();+ await user.keyboard("{Escape}");+ await user.click(screen.getByRole("button", { name: /^Filter jobs/ }));+ expect(screen.getByRole("button", { name: "Show jobs" })).toBeInTheDocument();+ });++ it("drops a count reply that lands after the popover closed", async () => {+ let resolveLate: (value: unknown) => void = () => {};+ (getJobFilterCounts as any).mockReturnValueOnce(+ new Promise((resolve) => (resolveLate = resolve)),+ );+ renderPopover();+ await open();+ await user.keyboard("{Escape}");+ await act(async () => resolveLate(counts(42)));+ await user.click(screen.getByRole("button", { name: /^Filter jobs/ }));+ expect(screen.getByRole("button", { name: "Show jobs" })).toBeInTheDocument();+ });++ it("seeds the draft from the applied facets on open", async () => {+ renderPopover({ ...EMPTY_JOB_FACETS, statuses: ["interview"] });+ await open();+ expect(screen.getByRole("checkbox", { name: "Interview" })).toBeChecked();+ });++ it("Select all ticks every status row, then reads Clear", async () => {+ renderPopover();+ await open();+ await user.click(screen.getByRole("button", { name: "Select all" }));+ expect(screen.getByRole("checkbox", { name: "Applied" })).toBeChecked();+ expect(+ screen.getByRole("checkbox", { name: "Accepted (discovered)" }),+ ).toBeChecked();+ await user.click(screen.getByRole("button", { name: "Clear" }));+ expect(screen.getByRole("checkbox", { name: "Applied" })).not.toBeChecked();+ });++ it("Clear all in the footer empties the draft without applying", async () => {+ renderPopover({ ...EMPTY_JOB_FACETS, jobTypes: ["FT"] });+ await open();+ await user.click(screen.getByRole("button", { name: "Clear all" }));+ expect(screen.getByRole("button", { name: "Full-time" })).toHaveAttribute(+ "aria-pressed",+ "false",+ );+ expect(onApply).not.toHaveBeenCalled();+ });++ it("shows the active count on the trigger badge", () => {+ renderPopover({+ ...EMPTY_JOB_FACETS,+ statuses: ["applied", "interview"],+ jobTypes: ["FT"],+ workplaces: ["REMOTE"],+ });+ expect(+ screen.getByRole("button", { name: "Filter jobs, 4 active" }),+ ).toBeInTheDocument();+ });++ it("ignores a slower count for an older draft", async () => {+ let resolveOld: (value: unknown) => void = () => {};+ (getJobFilterCounts as any)+ .mockResolvedValueOnce(counts(18))+ .mockReturnValueOnce(new Promise((resolve) => (resolveOld = resolve)))+ .mockResolvedValueOnce(counts(3));+ renderPopover();+ await open();+ await user.click(screen.getByRole("checkbox", { name: "Applied" }));+ await act(async () => {+ vi.advanceTimersByTime(300);+ });+ await user.click(screen.getByRole("checkbox", { name: "Interview" }));+ await act(async () => {+ vi.advanceTimersByTime(300);+ });+ expect(await screen.findByRole("button", { name: "Show 3 jobs" })).toBeInTheDocument();+ await act(async () => resolveOld(counts(99)));+ expect(screen.getByRole("button", { name: "Show 3 jobs" })).toBeInTheDocument();+ });++ it("falls back to Show jobs when the count fails", async () => {+ (getJobFilterCounts as any).mockResolvedValue({ success: false, message: "x" });+ renderPopover();+ await open();+ expect(await screen.findByRole("button", { name: "Show jobs" })).toBeInTheDocument();+ });+});diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.tsindex 3de17ec..fa0fb5b 100644--- a/__tests__/job.actions.spec.ts+++ b/__tests__/job.actions.spec.ts@@ -5,6 +5,7 @@ import {deleteJobById,getJobDetails,getJobsList,+ getJobFilterCounts,getJobSourceList,getStatusList,saveJobMatchResult,@@ -12,6 +13,7 @@ import {updateJobStatus,} from "@/actions/job.actions";import { getMockJobDetails, getMockJobsList } from "@/lib/mock.utils";+import { EMPTY_JOB_FACETS } from "@/lib/jobs/jobFacets";import { JobResponse } from "@/models/job.model";import { getCurrentUser } from "@/utils/user.utils";import { resolveStageTypeForStatusId } from "@/lib/jobs/resolve";@@ -38,6 +40,7 @@ vi.mock("@prisma/client", () => {findUnique: vi.fn(),findFirst: vi.fn(),count: vi.fn(),+ groupBy: vi.fn(),create: vi.fn(),update: vi.fn(),delete: vi.fn(),@@ -329,6 +332,84 @@ describe("jobActions", () => {});});+ describe("facets", () => {+ const whereOf = () => (prisma.job.findMany as any).mock.calls[0][0].where;++ beforeEach(() => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.job.findMany as any).mockResolvedValue([]);+ (prisma.job.count as any).mockResolvedValue(0);+ });++ it("hides dismissed discovered jobs by default", async () => {+ await getJobsList(1, 10);+ expect(whereOf().AND).toEqual([+ {+ OR: [+ { discoveryStatus: null },+ { discoveryStatus: { not: "dismissed" } },+ ],+ },+ ]);+ });++ it("ORs statuses with accepted-discovered inside one AND entry", async () => {+ await getJobsList(1, 10, {+ ...EMPTY_JOB_FACETS,+ statuses: ["applied", "interview"],+ acceptedDiscovered: true,+ });+ expect(whereOf().AND).toContainEqual({+ OR: [+ { Status: { value: { in: ["applied", "interview"] } } },+ { discoveryStatus: "accepted" },+ ],+ });+ });++ it("ANDs job type and workplace as `in` lists", async () => {+ await getJobsList(1, 10, {+ ...EMPTY_JOB_FACETS,+ jobTypes: ["FT", "C"],+ workplaces: ["REMOTE"],+ });+ expect(whereOf().AND).toEqual(+ expect.arrayContaining([+ { jobType: { in: ["FT", "C"] } },+ { workplaceType: { in: ["REMOTE"] } },+ ]),+ );+ });++ it("drops the dismissed exclusion when dismissed jobs are included", async () => {+ await getJobsList(1, 10, { ...EMPTY_JOB_FACETS, includeDismissed: true });+ expect(whereOf().AND).toEqual([]);+ });++ it("keeps the search OR alongside the status OR", async () => {+ await getJobsList(1, 10, { ...EMPTY_JOB_FACETS, statuses: ["applied"] }, "Developer");+ const where = whereOf();+ expect(where.OR).toContainEqual({ description: { contains: "Developer" } });+ expect(where.AND).toContainEqual({+ OR: [{ Status: { value: { in: ["applied"] } } }],+ });+ });++ it("ignores values outside the whitelist", async () => {+ await getJobsList(1, 10, {+ ...EMPTY_JOB_FACETS,+ statuses: ["bogus"],+ jobTypes: ["fulltime"],+ });+ expect(whereOf().AND).toHaveLength(1);+ });++ it("always scopes by the current user", async () => {+ await getJobsList(1, 10, { ...EMPTY_JOB_FACETS, statuses: ["applied"] });+ expect(whereOf().userId).toBe(mockUser.id);+ });+ });+describe("search functionality", () => {it("should build OR clause when search parameter is provided", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);@@ -460,14 +541,21 @@ describe("jobActions", () => {(prisma.job.findMany as any).mockResolvedValue([]);(prisma.job.count as any).mockResolvedValue(0);- await getJobsList(1, 10, "applied", "Developer");+ await getJobsList(+ 1,+ 10,+ { ...EMPTY_JOB_FACETS, statuses: ["applied"] },+ "Developer",+ );const findManyCall = (prisma.job.findMany as any).mock.calls[0][0];expect(findManyCall.where).toMatchObject({userId: mockUser.id,- Status: { value: "applied" },OR: expect.any(Array),});+ expect(findManyCall.where.AND).toContainEqual({+ OR: [{ Status: { value: { in: ["applied"] } } }],+ });});it("should not include OR clause when search is undefined", async () => {@@ -518,14 +606,21 @@ describe("jobActions", () => {(prisma.job.findMany as any).mockResolvedValue([]);(prisma.job.count as any).mockResolvedValue(0);- await getJobsList(1, 10, "PT", "Developer");+ await getJobsList(+ 1,+ 10,+ { ...EMPTY_JOB_FACETS, jobTypes: ["PT"] },+ "Developer",+ );const findManyCall = (prisma.job.findMany as any).mock.calls[0][0];expect(findManyCall.where).toMatchObject({userId: mockUser.id,- jobType: "PT",OR: expect.any(Array),});+ expect(findManyCall.where.AND).toContainEqual({+ jobType: { in: ["PT"] },+ });});});@@ -596,15 +691,24 @@ describe("jobActions", () => {(prisma.job.findMany as any).mockResolvedValue([]);(prisma.job.count as any).mockResolvedValue(0);- await getJobsList(1, 10, "applied", undefined, "google", true);+ await getJobsList(+ 1,+ 10,+ { ...EMPTY_JOB_FACETS, statuses: ["applied"] },+ undefined,+ "google",+ true,+ );const findManyCall = (prisma.job.findMany as any).mock.calls[0][0];expect(findManyCall.where).toMatchObject({userId: mockUser.id,- Status: { value: "applied" },Company: { value: "google" },applied: true,});+ expect(findManyCall.where.AND).toContainEqual({+ OR: [{ Status: { value: { in: ["applied"] } } }],+ });});it("should not add Company or applied when params are undefined", async () => {@@ -869,6 +973,77 @@ describe("jobActions", () => {});});});+ describe("getJobFilterCounts", () => {+ // Queued per test, not in beforeEach: clearMocks keeps unused Once values,+ // so the unauthenticated test would leak them into later describes.+ const queueCounts = () =>+ (prisma.job.count as any)+ .mockResolvedValueOnce(18)+ .mockResolvedValueOnce(7);++ beforeEach(() => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.job.groupBy as any).mockResolvedValue([+ { statusId: "s-applied", _count: { _all: 11 } },+ { statusId: "s-interview", _count: { _all: 4 } },+ ]);+ });++ it("returns the total, per-status counts and the accepted count", async () => {+ queueCounts();+ const result = await getJobFilterCounts({+ ...EMPTY_JOB_FACETS,+ statuses: ["applied"],+ });+ expect(result).toEqual({+ success: true,+ data: {+ total: 18,+ statusCounts: { "s-applied": 11, "s-interview": 4 },+ acceptedDiscovered: 7,+ },+ });+ });++ it("counts statuses without the Status section but with the others", async () => {+ queueCounts();+ await getJobFilterCounts({+ ...EMPTY_JOB_FACETS,+ statuses: ["applied"],+ jobTypes: ["FT"],+ });+ const where = (prisma.job.groupBy as any).mock.calls[0][0].where;+ expect(where.AND).toContainEqual({ jobType: { in: ["FT"] } });+ expect(JSON.stringify(where)).not.toContain('"applied"');+ expect((prisma.job.groupBy as any).mock.calls[0][0].by).toEqual(["statusId"]);+ });++ it("scopes counts by the deep-link filters and search", async () => {+ queueCounts();+ await getJobFilterCounts(EMPTY_JOB_FACETS, "Dev", {+ companyValue: "google",+ appliedOnly: true,+ });+ const totalWhere = (prisma.job.count as any).mock.calls[0][0].where;+ expect(totalWhere).toMatchObject({+ userId: mockUser.id,+ Company: { value: "google" },+ applied: true,+ });+ expect(totalWhere.OR).toContainEqual({ description: { contains: "Dev" } });+ const acceptedWhere = (prisma.job.count as any).mock.calls[1][0].where;+ expect(acceptedWhere.AND[1]).toEqual({ discoveryStatus: "accepted" });+ expect(acceptedWhere.AND[0].userId).toBe(mockUser.id);+ });++ it("returns Not authenticated without a session", async () => {+ (getCurrentUser as any).mockResolvedValue(null);+ const result = await getJobFilterCounts(EMPTY_JOB_FACETS);+ expect(result).toEqual({ success: false, message: "Not authenticated" });+ });+ });++describe("getJobDetails", () => {it("should throw error when jobId is not provided", async () => {await expect(getJobDetails("")).resolves.toStrictEqual({diff --git a/__tests__/jobFacets.spec.ts b/__tests__/jobFacets.spec.tsnew file mode 100644index 0000000..068ca9f--- /dev/null+++ b/__tests__/jobFacets.spec.ts@@ -0,0 +1,102 @@+import {+ EMPTY_JOB_FACETS,+ countJobFacets,+ hasJobFacets,+ normalizeJobFacets,+ parseJobFacets,+ writeJobFacets,+} from "@/lib/jobs/jobFacets";++describe("jobFacets", () => {+ describe("parseJobFacets", () => {+ it("returns empty facets for a bare URL", () => {+ expect(parseJobFacets(new URLSearchParams())).toEqual(EMPTY_JOB_FACETS);+ });++ it("reads every facet param", () => {+ const params = new URLSearchParams(+ "status=applied,interview&accepted=1&type=FT,C&workplace=REMOTE&dismissed=1",+ );+ expect(parseJobFacets(params)).toEqual({+ statuses: ["applied", "interview"],+ acceptedDiscovered: true,+ jobTypes: ["FT", "C"],+ workplaces: ["REMOTE"],+ includeDismissed: true,+ });+ });++ it("drops unknown and duplicate values", () => {+ const params = new URLSearchParams(+ "status=bogus,applied,applied&type=fulltime&workplace=REMOTE,REMOTE&accepted=yes",+ );+ expect(parseJobFacets(params)).toEqual({+ ...EMPTY_JOB_FACETS,+ statuses: ["applied"],+ workplaces: ["REMOTE"],+ });+ });++ it("reads comma lists that were percent-encoded", () => {+ const params = new URLSearchParams("status=applied%2Cinterview");+ expect(parseJobFacets(params).statuses).toEqual(["applied", "interview"]);+ });+ });++ describe("normalizeJobFacets", () => {+ it("orders values canonically so equal picks compare equal", () => {+ const a = normalizeJobFacets({ statuses: ["interview", "applied"] });+ const b = normalizeJobFacets({ statuses: ["applied", "interview"] });+ expect(a).toEqual(b);+ });++ it("fills missing keys from empty", () => {+ expect(normalizeJobFacets(undefined)).toEqual(EMPTY_JOB_FACETS);+ });+ });++ describe("writeJobFacets", () => {+ it("keeps unrelated params and removes cleared facets", () => {+ const before = new URLSearchParams(+ "company=google&applied=true&status=draft&dismissed=1",+ );+ const after = writeJobFacets(before, {+ ...EMPTY_JOB_FACETS,+ workplaces: ["HYBRID"],+ });+ expect(after.get("company")).toBe("google");+ expect(after.get("applied")).toBe("true");+ expect(after.get("workplace")).toBe("HYBRID");+ expect(after.has("status")).toBe(false);+ expect(after.has("dismissed")).toBe(false);+ expect(before.get("status")).toBe("draft");+ });++ it("round-trips through parseJobFacets", () => {+ const facets = {+ statuses: ["applied", "offer"],+ acceptedDiscovered: true,+ jobTypes: ["PT"],+ workplaces: ["REMOTE", "ONSITE"],+ includeDismissed: false,+ };+ const params = writeJobFacets(new URLSearchParams(), facets);+ expect(parseJobFacets(params)).toEqual(facets);+ });+ });++ describe("countJobFacets", () => {+ it("counts values, with one each for the two flags", () => {+ expect(+ countJobFacets({+ statuses: ["applied", "interview"],+ acceptedDiscovered: true,+ jobTypes: ["FT"],+ workplaces: ["REMOTE"],+ includeDismissed: true,+ }),+ ).toBe(6);+ expect(hasJobFacets(EMPTY_JOB_FACETS)).toBe(false);+ });+ });+});diff --git a/e2e/add-job.spec.ts b/e2e/add-job.spec.tsindex 99ff60c..c9cbb00 100644--- a/e2e/add-job.spec.ts+++ b/e2e/add-job.spec.ts@@ -289,12 +289,17 @@ test.describe("Add New Job", () => {await createNewJob(page, jobText, cleanup);await expect(page.getByRole("row", { name: jobText }).first()).toBeVisible();- await page.getByTestId("job-filter-select").click();- await page.getByRole("option", { name: "Rejected", exact: true }).click();+ await page.getByTestId("job-filter-button").click();+ await page.getByRole("checkbox", { name: "Rejected", exact: true }).check();+ await page.getByRole("button", { name: /^Show (\d+ )?jobs?$/ }).click();+ await expect(page).toHaveURL(/status=rejected/);await expect(page.getByRole("row", { name: jobText })).not.toBeVisible();- await page.getByTestId("job-filter-select").click();- await page.getByRole("option", { name: "Draft", exact: true }).click();+ await page.getByTestId("job-filter-button").click();+ await page.getByRole("checkbox", { name: "Rejected", exact: true }).uncheck();+ await page.getByRole("checkbox", { name: "Draft", exact: true }).check();+ await page.getByRole("button", { name: /^Show (\d+ )?jobs?$/ }).click();+ await expect(page).toHaveURL(/status=draft/);await expect(page.getByRole("row", { name: jobText }).first()).toBeVisible();});diff --git a/src/actions/job.actions.ts b/src/actions/job.actions.tsindex d47eb3f..f1e445f 100644--- a/src/actions/job.actions.ts+++ b/src/actions/job.actions.ts@@ -4,6 +4,7 @@export {getJobsList,+ getJobFilterCounts,getJobsIterator,getJobDetails,} from "./job/queries";diff --git a/src/actions/job/queries.ts b/src/actions/job/queries.tsindex b453aec..5afc181 100644--- a/src/actions/job/queries.ts+++ b/src/actions/job/queries.ts@@ -1,7 +1,13 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { JOB_TYPES, JobSortField } from "@/models/job.model";+import {+ JOB_TYPES,+ JobFacets,+ JobListScope,+ JobSortField,+} from "@/models/job.model";+import { normalizeJobFacets } from "@/lib/jobs/jobFacets";import type { SortState } from "@/models/sort.model";import { findManySorted, planListSort, SortFieldSpec } from "@/lib/listSort";import { APP_CONSTANTS } from "@/lib/constants";@@ -79,19 +85,13 @@ const JOB_DETAILS_INCLUDE = {stages: { include: STAGE_DETAIL_INCLUDE },};-type JobsListFilters = {- filter?: string;+type JobsListFilters = JobListScope & {+ facets?: JobFacets;search?: string;- companyValue?: string;- appliedOnly?: boolean;- titleValue?: string;- locationValue?: string;- sourceValue?: string;};const buildJobsWhereClause = (userId: string, filters: JobsListFilters) => {const {- filter,search,companyValue,appliedOnly,@@ -99,38 +99,36 @@ const buildJobsWhereClause = (userId: string, filters: JobsListFilters) => {locationValue,sourceValue,} = filters;+ const facets = normalizeJobFacets(filters.facets);+ const and: Record<string, any>[] = [];- const filterBy = filter- ? filter === Object.keys(JOB_TYPES)[1]- ? {- jobType: filter,- }- : filter === "accepted" || filter === "dismissed"- ? {- discoveryStatus: filter,- }- : {- Status: {- value: filter,- },- }- : {};+ // Dismissed discovered jobs are kept only for dedup and shouldn't+ // clutter the tracked jobs list unless explicitly included.+ if (!facets.includeDismissed) {+ and.push({+ OR: [{ discoveryStatus: null }, { discoveryStatus: { not: "dismissed" } }],+ });+ }- const whereClause: any = {- userId,- ...filterBy,- };+ // Accepted (discovered) sits in the Status list, so it ORs with statuses.+ const statusOr: Record<string, any>[] = [];+ if (facets.statuses.length) {+ statusOr.push({ Status: { value: { in: facets.statuses } } });+ }+ if (facets.acceptedDiscovered) {+ statusOr.push({ discoveryStatus: "accepted" });+ }+ if (statusOr.length) and.push({ OR: statusOr });- // Dismissed discovered jobs are kept only for dedup and shouldn't- // clutter the tracked jobs list unless explicitly filtered for.- if (filter !== "dismissed") {- whereClause.AND = [- {- OR: [{ discoveryStatus: null }, { discoveryStatus: { not: "dismissed" } }],- },- ];+ if (facets.jobTypes.length) {+ and.push({ jobType: { in: facets.jobTypes } });+ }+ if (facets.workplaces.length) {+ and.push({ workplaceType: { in: facets.workplaces } });}+ const whereClause: any = { userId, AND: and };+if (companyValue) {whereClause.Company = { value: companyValue };}@@ -226,7 +224,7 @@ const JOB_SORT_SPECS: Record<JobSortField, SortFieldSpec> = {export const getJobsList = async (page: number = 1,limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,- filter?: string,+ facets?: JobFacets,search?: string,companyValue?: string,appliedOnly?: boolean,@@ -240,7 +238,7 @@ export const getJobsList = async (const skip = (page - 1) * limit;const whereClause = buildJobsWhereClause(user.id, {- filter,+ facets,search,companyValue,appliedOnly,@@ -261,6 +259,47 @@ export const getJobsList = async (}};+export const getJobFilterCounts = async (+ facets: JobFacets,+ search?: string,+ scope: JobListScope = {},+): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ const applied = normalizeJobFacets(facets);+ // Status counts ignore the Status section itself, so ticking one status+ // never zeroes the others.+ const statusFree = { ...applied, statuses: [], acceptedDiscovered: false };+ const where = buildJobsWhereClause(user.id, { ...scope, search, facets: applied });+ const statusFreeWhere = buildJobsWhereClause(user.id, {+ ...scope,+ search,+ facets: statusFree,+ });++ const [total, grouped, acceptedDiscovered] = await Promise.all([+ prisma.job.count({ where }),+ prisma.job.groupBy({+ by: ["statusId"],+ where: statusFreeWhere,+ _count: { _all: true },+ }),+ prisma.job.count({+ where: { AND: [statusFreeWhere, { discoveryStatus: "accepted" }] },+ }),+ ]);++ const statusCounts = Object.fromEntries(+ grouped.map((row) => [row.statusId, row._count._all]),+ );+ return { success: true, data: { total, statusCounts, acceptedDiscovered } };+ } catch (error) {+ const msg = "Failed to count jobs. ";+ return handleError(error, msg);+ }+};++export async function* getJobsIterator(filter?: string, pageSize = 200) {const user = await requireUser();let page = 1;diff --git a/src/components/myjobs/JobsContainer.tsx b/src/components/myjobs/JobsContainer.tsxindex 8b10e58..0920c82 100644--- a/src/components/myjobs/JobsContainer.tsx+++ b/src/components/myjobs/JobsContainer.tsx@@ -27,6 +27,8 @@ import { useJobFilters } from "./jobs-container/useJobFilters";import { useJobsList } from "./jobs-container/useJobsList";import { downloadJobsList } from "./jobs-container/downloadJobsCsv";import { JobsToolbar } from "./jobs-container/JobsToolbar";+import { EMPTY_JOB_FACETS, hasJobFacets } from "@/lib/jobs/jobFacets";+import { Button } from "../ui/button";type MyJobsProps = {statuses: JobStatus[];@@ -65,6 +67,8 @@ function JobsContainer({clearTitleFilter,clearLocationFilter,clearSourceFilter,+ facets,+ applyFacets,} = useJobFilters({ companies, titles, locations, sources });const { sort, toggleSort } = useSort(JOB_SORT_FIELDS);@@ -74,14 +78,13 @@ function JobsContainer({viewMode,onChangeViewMode,totalJobs,- filterKey,searchTerm,setSearchTerm,initialLoading,+ listLoaded,loadingMore,loadJobs,reloadJobs,- onFilterChange,sentinelRef,} = useJobsList({companyFilter,@@ -89,6 +92,7 @@ function JobsContainer({titleFilter,locationFilter,sourceFilter,+ facets,sort,});@@ -148,11 +152,18 @@ function JobsContainer({onClearLocationFilter={clearLocationFilter}sourceLabel={sourceLabel}onClearSourceFilter={clearSourceFilter}- onReload={() => loadJobs(1, filterKey, searchTerm || undefined)}+ onReload={() => loadJobs(1, searchTerm || undefined)}searchTerm={searchTerm}onSearchTermChange={setSearchTerm}- filterKey={filterKey}- onFilterChange={onFilterChange}+ facets={facets}+ onApplyFacets={applyFacets}+ scope={{+ companyValue: companyFilter || undefined,+ appliedOnly: appliedFilter || undefined,+ titleValue: titleFilter || undefined,+ locationValue: locationFilter || undefined,+ sourceValue: sourceFilter || undefined,+ }}onDownload={downloadJobsList}statuses={statuses}companies={companies}@@ -166,6 +177,21 @@ function JobsContainer({/><CardContent>{initialLoading && <Loading />}+ {!initialLoading &&+ listLoaded &&+ jobs.length === 0 &&+ hasJobFacets(facets) && (+ <div className="flex flex-col items-center gap-2 py-10 text-sm text-muted-foreground">+ <p>No jobs match these filters.</p>+ <Button+ size="sm"+ variant="outline"+ onClick={() => applyFacets(EMPTY_JOB_FACETS)}+ >+ Clear all+ </Button>+ </div>+ )}{jobs.length > 0 &&(viewMode === "cards" ? (<MyJobsGriddiff --git a/src/components/myjobs/jobs-container/JobsFilterChips.tsx b/src/components/myjobs/jobs-container/JobsFilterChips.tsxnew file mode 100644index 0000000..434ec71--- /dev/null+++ b/src/components/myjobs/jobs-container/JobsFilterChips.tsx@@ -0,0 +1,80 @@+"use client";+import { X } from "lucide-react";+import { EMPTY_JOB_FACETS, hasJobFacets } from "@/lib/jobs/jobFacets";+import {+ JobFacets,+ JobStatus,+ getJobTypeLabel,+ getWorkplaceTypeLabel,+} from "@/models/job.model";++// "Filtered by" row for the popover facets; deep-link chips stay in the+// header (D6), so Clear all here leaves company/title/location/source alone.+export function JobsFilterChips({+ statuses,+ facets,+ onChange,+}: {+ statuses: JobStatus[];+ facets: JobFacets;+ onChange: (facets: JobFacets) => void;+}) {+ if (!hasJobFacets(facets)) return null;++ const statusLabels = [+ ...facets.statuses.map(+ (value) => statuses.find((s) => s.value === value)?.label ?? value,+ ),+ ...(facets.acceptedDiscovered ? ["Accepted (discovered)"] : []),+ ];++ const chips = [+ {+ name: "Status",+ value: statusLabels.join(", "),+ clear: { statuses: [], acceptedDiscovered: false },+ },+ {+ name: "Job type",+ value: facets.jobTypes.map((c) => getJobTypeLabel(c)).join(", "),+ clear: { jobTypes: [] },+ },+ {+ name: "Workplace",+ value: facets.workplaces.map((c) => getWorkplaceTypeLabel(c)).join(", "),+ clear: { workplaces: [] },+ },+ {+ name: "Dismissed",+ value: facets.includeDismissed ? "Included" : "",+ clear: { includeDismissed: false },+ },+ ].filter((chip) => chip.value);++ return (+ <div className="flex w-full flex-wrap items-center gap-2">+ <span className="mr-0.5 text-xs text-muted-foreground">Filtered by</span>+ {chips.map((chip) => (+ <button+ key={chip.name}+ type="button"+ aria-label={`Remove ${chip.name} filter`}+ title={chip.value}+ onClick={() => onChange({ ...facets, ...chip.clear })}+ className="inline-flex h-7 max-w-[280px] items-center gap-1.5 rounded-md bg-muted pl-2.5 pr-2 text-[13px] hover:bg-muted/70"+ >+ <span className="text-muted-foreground">{chip.name}</span>+ <span className="truncate font-medium">{chip.value}</span>+ <X className="h-3 w-3 shrink-0" />+ </button>+ ))}+ <button+ type="button"+ className="h-7 px-2 text-[13px] text-muted-foreground underline hover:text-foreground"+ onClick={() => onChange(EMPTY_JOB_FACETS)}+ >+ Clear all+ </button>+ </div>+ );+}diff --git a/src/components/myjobs/jobs-container/JobsFilterPopover.tsx b/src/components/myjobs/jobs-container/JobsFilterPopover.tsxnew file mode 100644index 0000000..1609513--- /dev/null+++ b/src/components/myjobs/jobs-container/JobsFilterPopover.tsx@@ -0,0 +1,244 @@+"use client";+import { useState } from "react";+import { SlidersHorizontal } from "lucide-react";+import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";+import { Toggle } from "../../ui/toggle";+import { Button } from "../../ui/button";+import { cn } from "@/lib/utils";+import { JOB_STATUSES } from "@/lib/constants";+import {+ EMPTY_JOB_FACETS,+ countJobFacets,+ normalizeJobFacets,+} from "@/lib/jobs/jobFacets";+import {+ JOB_TYPES,+ JobFacets,+ JobListScope,+ JobStatus,+ WORKPLACE_TYPES,+} from "@/models/job.model";+import { useJobFilterCounts } from "./useJobFilterCounts";++const STATUS_ORDER: string[] = JOB_STATUSES.map((s) => s.value);+const ACCEPTED_LABEL = "Accepted (discovered)";+const SECTION_LABEL =+ "text-xs font-semibold uppercase tracking-wide text-muted-foreground";++const toggleIn = (list: string[], value: string) =>+ list.includes(value) ? list.filter((v) => v !== value) : [...list, value];++// Draft-until-apply filter popover for the Jobs list (see D1 in the plan).+export function JobsFilterPopover({+ statuses,+ facets,+ search,+ scope,+ onApply,+}: {+ statuses: JobStatus[];+ facets: JobFacets;+ search: string;+ scope: JobListScope;+ onApply: (facets: JobFacets) => void;+}) {+ const [open, setOpen] = useState(false);+ const [draft, setDraft] = useState<JobFacets>(facets);+ const normalized = normalizeJobFacets(draft);+ const counts = useJobFilterCounts({+ enabled: open,+ facets: normalized,+ search,+ scope,+ });+ const active = countJobFacets(facets);++ const orderedStatuses = [...statuses].sort(+ (a, b) => STATUS_ORDER.indexOf(a.value) - STATUS_ORDER.indexOf(b.value),+ );+ const allStatusesPicked =+ orderedStatuses.every((s) => draft.statuses.includes(s.value)) &&+ draft.acceptedDiscovered;++ const onOpenChange = (next: boolean) => {+ // Re-seed on every open so a closed-without-apply draft is discarded.+ if (next) setDraft(facets);+ setOpen(next);+ };++ const apply = () => {+ onApply(normalized);+ setOpen(false);+ };++ const toggleAllStatuses = () =>+ setDraft((d) =>+ allStatusesPicked+ ? { ...d, statuses: [], acceptedDiscovered: false }+ : {+ ...d,+ statuses: orderedStatuses.map((s) => s.value),+ acceptedDiscovered: true,+ },+ );++ const total = counts?.total;+ const applyLabel =+ total === undefined+ ? "Show jobs"+ : `Show ${total} ${total === 1 ? "job" : "jobs"}`;++ const segmented = (+ options: Record<string, string>,+ picked: string[],+ onToggle: (code: string) => void,+ ) => (+ <div className="flex gap-1.5">+ {Object.entries(options).map(([code, label]) => (+ <Toggle+ key={code}+ variant="outline"+ size="sm"+ pressed={picked.includes(code)}+ onPressedChange={() => onToggle(code)}+ className="h-8 flex-1 data-[state=on]:bg-primary data-[state=on]:text-primary-foreground"+ >+ {label}+ </Toggle>+ ))}+ </div>+ );++ const statusRow = (+ key: string,+ label: string,+ checked: boolean,+ count: number | undefined,+ onChange: () => void,+ ) => (+ <label key={key} className="flex min-h-6 cursor-pointer items-center gap-2">+ <input+ type="checkbox"+ className="h-4 w-4 shrink-0"+ aria-label={label}+ checked={checked}+ onChange={onChange}+ />+ <span className="flex-1 truncate">{label}</span>+ <span className="text-xs text-muted-foreground">+ {counts ? (count ?? 0) : "–"}+ </span>+ </label>+ );++ return (+ <Popover open={open} onOpenChange={onOpenChange}>+ <PopoverTrigger asChild>+ <Button+ size="sm"+ variant="outline"+ data-testid="job-filter-button"+ aria-label={active ? `Filter jobs, ${active} active` : "Filter jobs"}+ className={cn(+ "relative h-8 w-8 p-0",+ active > 0 && "border-foreground ring-2 ring-foreground/10",+ )}+ >+ <SlidersHorizontal className="h-4 w-4" />+ {active > 0 && (+ <span className="absolute -right-2 -top-2 flex h-[18px] min-w-[18px] items-center justify-center rounded-full border-2 border-card bg-foreground px-1 text-[11px] font-semibold text-background">+ {active}+ </span>+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ collisionPadding={16}+ aria-label="Filter jobs"+ className="flex w-[min(380px,calc(100vw-32px))] flex-col p-0"+ >+ <div className="max-h-[min(70vh,560px)] overflow-y-auto">+ <div className="flex flex-col gap-2.5 border-b p-4 pb-3">+ <div className="flex items-center justify-between">+ <span className={SECTION_LABEL}>Status</span>+ <button+ type="button"+ className="text-xs text-muted-foreground hover:text-foreground"+ onClick={toggleAllStatuses}+ >+ {allStatusesPicked ? "Clear" : "Select all"}+ </button>+ </div>+ <div className="grid grid-cols-2 gap-x-4 gap-y-2 text-[13px]">+ {orderedStatuses.map((s) =>+ statusRow(+ s.id,+ s.label,+ draft.statuses.includes(s.value),+ counts?.statusCounts[s.id],+ () =>+ setDraft((d) => ({+ ...d,+ statuses: toggleIn(d.statuses, s.value),+ })),+ ),+ )}+ {statusRow(+ "accepted",+ ACCEPTED_LABEL,+ draft.acceptedDiscovered,+ counts?.acceptedDiscovered,+ () =>+ setDraft((d) => ({+ ...d,+ acceptedDiscovered: !d.acceptedDiscovered,+ })),+ )}+ </div>+ </div>+ <div className="flex flex-col gap-2.5 border-b px-4 py-3">+ <span className={SECTION_LABEL}>Job type</span>+ {segmented(JOB_TYPES, draft.jobTypes, (code) =>+ setDraft((d) => ({ ...d, jobTypes: toggleIn(d.jobTypes, code) })),+ )}+ </div>+ <div className="flex flex-col gap-2.5 border-b px-4 py-3">+ <span className={SECTION_LABEL}>Workplace</span>+ {segmented(WORKPLACE_TYPES, draft.workplaces, (code) =>+ setDraft((d) => ({+ ...d,+ workplaces: toggleIn(d.workplaces, code),+ })),+ )}+ </div>+ <label className="flex cursor-pointer items-center gap-2 border-b px-4 py-3 text-[13px]">+ <input+ type="checkbox"+ className="h-4 w-4 shrink-0"+ aria-label="Include dismissed discovered jobs"+ checked={draft.includeDismissed}+ onChange={() =>+ setDraft((d) => ({ ...d, includeDismissed: !d.includeDismissed }))+ }+ />+ <span>Include dismissed discovered jobs</span>+ </label>+ </div>+ <div className="flex items-center justify-between px-4 py-3">+ <Button+ size="sm"+ variant="ghost"+ className="text-muted-foreground"+ onClick={() => setDraft(EMPTY_JOB_FACETS)}+ >+ Clear all+ </Button>+ <Button size="sm" onClick={apply}>+ {applyLabel}+ </Button>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/src/components/myjobs/jobs-container/JobsToolbar.tsx b/src/components/myjobs/jobs-container/JobsToolbar.tsxindex bde2e46..ca9260c 100644--- a/src/components/myjobs/jobs-container/JobsToolbar.tsx+++ b/src/components/myjobs/jobs-container/JobsToolbar.tsx@@ -1,23 +1,17 @@"use client";-import { File, ListFilter, RefreshCw, X } from "lucide-react";+import { File, RefreshCw, X } from "lucide-react";import { CardHeader, CardTitle } from "../../ui/card";import { Button } from "../../ui/button";import { SearchInput } from "../../SearchInput";-import {- Select,- SelectContent,- SelectGroup,- SelectItem,- SelectLabel,- SelectSeparator,- SelectTrigger,- SelectValue,-} from "../../ui/select";import { RecordsCount } from "../../RecordsCount";import { JobsViewToggle } from "../JobsViewToggle";import { AddJob } from "../AddJob";+import { JobsFilterPopover } from "./JobsFilterPopover";+import { JobsFilterChips } from "./JobsFilterChips";import {Company,+ JobFacets,+ JobListScope,JobLocation,JobResponse,JobSource,@@ -28,7 +22,7 @@ import {} from "@/models/job.model";// Presentational: the Jobs card header — title/count, active filter chips,-// view toggle, search, filter select, export and Add Job.+// view toggle, search, filter popover, export and Add Job.export function JobsToolbar({jobsCount,totalJobs,@@ -46,8 +40,9 @@ export function JobsToolbar({onReload,searchTerm,onSearchTermChange,- filterKey,- onFilterChange,+ facets,+ onApplyFacets,+ scope,onDownload,statuses,companies,@@ -75,8 +70,9 @@ export function JobsToolbar({onReload: () => void;searchTerm: string;onSearchTermChange: (value: string) => void;- filterKey: string;- onFilterChange: (filterBy: string) => void;+ facets: JobFacets;+ onApplyFacets: (facets: JobFacets) => void;+ scope: JobListScope;onDownload: () => void;statuses: JobStatus[];companies: Company[];@@ -152,29 +148,13 @@ export function JobsToolbar({onChange={onSearchTermChange}placeholder="Search jobs..."/>- <Select value={filterKey} onValueChange={onFilterChange}>- <SelectTrigger- className="w-[120px] h-8"- data-testid="job-filter-select"- >- <ListFilter className="h-3.5 w-3.5" />- <SelectValue placeholder="Filter" />- </SelectTrigger>- <SelectContent>- <SelectGroup>- <SelectLabel>Filter by</SelectLabel>- <SelectSeparator />- <SelectItem value="none">All (Except Dismissed)</SelectItem>- <SelectItem value="applied">Applied</SelectItem>- <SelectItem value="interview">Interview</SelectItem>- <SelectItem value="draft">Draft</SelectItem>- <SelectItem value="rejected">Rejected</SelectItem>- <SelectItem value="PT">Part-time</SelectItem>- <SelectItem value="accepted">Accepted (discovered)</SelectItem>- <SelectItem value="dismissed">Dismissed (discovered)</SelectItem>- </SelectGroup>- </SelectContent>- </Select>+ <JobsFilterPopover+ statuses={statuses}+ facets={facets}+ search={searchTerm}+ scope={scope}+ onApply={onApplyFacets}+ /><Buttonsize="sm"variant="outline"@@ -199,6 +179,11 @@ export function JobsToolbar({initialOpen={addJobInitialOpen}/></div>+ <JobsFilterChips+ statuses={statuses}+ facets={facets}+ onChange={onApplyFacets}+ /></CardHeader>);}diff --git a/src/components/myjobs/jobs-container/useJobFilterCounts.ts b/src/components/myjobs/jobs-container/useJobFilterCounts.tsnew file mode 100644index 0000000..bba6026--- /dev/null+++ b/src/components/myjobs/jobs-container/useJobFilterCounts.ts@@ -0,0 +1,43 @@+"use client";+import { useEffect, useRef, useState } from "react";+import { getJobFilterCounts } from "@/actions/job.actions";+import { JobFacets, JobFilterCounts, JobListScope } from "@/models/job.model";++// Live counts for the popover draft: debounced, and only the newest request+// may write so a slow reply can't label the button with an older draft.+export function useJobFilterCounts({+ enabled,+ facets,+ search,+ scope,+}: {+ enabled: boolean;+ facets: JobFacets;+ search: string;+ scope: JobListScope;+}): JobFilterCounts | null {+ const [counts, setCounts] = useState<JobFilterCounts | null>(null);+ const requestSeq = useRef(0);+ const key = JSON.stringify([facets, search, scope]);++ useEffect(() => {+ if (!enabled) {+ // A reopen must not show totals for the draft that was just discarded,+ // including a reply still in flight.+ requestSeq.current++;+ setCounts(null);+ return;+ }+ const timer = setTimeout(async () => {+ const request = ++requestSeq.current;+ const result = await getJobFilterCounts(facets, search, scope);+ if (request !== requestSeq.current) return;+ setCounts(result?.success ? result.data : null);+ }, 300);+ return () => clearTimeout(timer);+ // `key` stands in for the three objects, which are rebuilt every render.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [enabled, key]);++ return counts;+}diff --git a/src/components/myjobs/jobs-container/useJobFilters.ts b/src/components/myjobs/jobs-container/useJobFilters.tsindex c22fc6e..aa7fb68 100644--- a/src/components/myjobs/jobs-container/useJobFilters.ts+++ b/src/components/myjobs/jobs-container/useJobFilters.ts@@ -1,10 +1,16 @@"use client";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { usePathname, useRouter, useSearchParams } from "next/navigation";-import { Company, JobLocation, JobSource, JobTitle } from "@/models/job.model";+import { parseJobFacets, writeJobFacets } from "@/lib/jobs/jobFacets";+import {+ Company,+ JobFacets,+ JobLocation,+ JobSource,+ JobTitle,+} from "@/models/job.model";-// Owns the URL-synced job list filters (company/title/location/source/applied),-// their display labels, and the clear handlers.+// Owns the URL-synced job list filters: deep-link chips (company/title/location/source/applied) and the popover facets.export function useJobFilters({companies,titles,@@ -51,6 +57,18 @@ export function useJobFilters({? sources.find((s) => s.value === sourceFilter)?.label: null;+ // Parsed from the URL string so the object is stable between renders.+ const queryString = queryParams.toString();+ const facets = useMemo(+ () => parseJobFacets(new URLSearchParams(queryString)),+ [queryString],+ );++ const applyFacets = (next: JobFacets) => {+ const qs = writeJobFacets(new URLSearchParams(queryString), next).toString();+ router.push(qs ? `${pathname}?${qs}` : pathname);+ };+const clearCompanyFilter = () => {setCompanyFilter(null);setAppliedFilter(false);@@ -103,5 +121,7 @@ export function useJobFilters({clearTitleFilter,clearLocationFilter,clearSourceFilter,+ facets,+ applyFacets,};}diff --git a/src/components/myjobs/jobs-container/useJobsList.ts b/src/components/myjobs/jobs-container/useJobsList.tsindex de7faf3..5d44dd3 100644--- a/src/components/myjobs/jobs-container/useJobsList.ts+++ b/src/components/myjobs/jobs-container/useJobsList.ts@@ -2,7 +2,13 @@import { useCallback, useEffect, useRef, useState } from "react";import { getJobsList } from "@/actions/job.actions";import { toastError } from "@/lib/toast";-import { JobResponse, JobSortField, JobsViewMode } from "@/models/job.model";+import {+ JobFacets,+ JobResponse,+ JobSortField,+ JobsViewMode,+} from "@/models/job.model";+import { hasJobFacets } from "@/lib/jobs/jobFacets";import type { SortState } from "@/models/sort.model";import { APP_CONSTANTS } from "@/lib/constants";import {@@ -19,6 +25,7 @@ export function useJobsList({titleFilter,locationFilter,sourceFilter,+ facets,sort,}: {companyFilter: string | null;@@ -26,6 +33,7 @@ export function useJobsList({titleFilter: string | null;locationFilter: string | null;sourceFilter: string | null;+ facets: JobFacets;sort: SortState<JobSortField> | null;}) {const { jobWrites } = useAgentChat();@@ -33,9 +41,11 @@ export function useJobsList({const [viewMode, setViewMode] = useState<JobsViewMode>("table");const [page, setPage] = useState(1);const [totalJobs, setTotalJobs] = useState(0);- const [filterKey, setFilterKey] = useState<string>("none");const [searchTerm, setSearchTerm] = useState("");const [initialLoading, setInitialLoading] = useState(false);+ // False until page 1 has loaded, so an empty list isn't read as "no matches"+ // before the first fetch or after a failed one.+ const [listLoaded, setListLoaded] = useState(false);const [loadingMore, setLoadingMore] = useState(false);const hasSearched = useRef(false);const sentinelRef = useRef<HTMLDivElement>(null);@@ -61,7 +71,7 @@ export function useJobsList({const jobsPerPage = APP_CONSTANTS.RECORDS_PER_PAGE;const loadJobs = useCallback(- async (page: number, filter?: string, search?: string) => {+ async (page: number, search?: string) => {// Only the newest request may write: a slower response to an older// sort, search or page must not replace or extend the newer list.const request = ++requestSeq.current;@@ -70,7 +80,7 @@ export function useJobsList({const { success, data, total, message } = await getJobsList(page,jobsPerPage,- filter && filter !== "none" ? filter : undefined,+ hasJobFacets(facets) ? facets : undefined,search,companyFilter || undefined,appliedFilter || undefined,@@ -84,14 +94,17 @@ export function useJobsList({setJobs((prev) => (page === 1 ? data : [...prev, ...data]));setTotalJobs(total);setPage(page);+ setListLoaded(true);} else {toastError(message);+ if (page === 1) setListLoaded(false);}setInitialLoading(false);setLoadingMore(false);},[jobsPerPage,+ facets,companyFilter,appliedFilter,titleFilter,@@ -101,14 +114,14 @@ export function useJobsList({);const reloadJobs = useCallback(async () => {- await loadJobs(1, undefined, searchTerm || undefined);- if (filterKey !== "none") {- setFilterKey("none");- }- }, [loadJobs, filterKey, searchTerm]);+ await loadJobs(1, searchTerm || undefined);+ }, [loadJobs, searchTerm]);useEffect(() => {- (async () => await loadJobs(1))();+ (async () => await loadJobs(1, searchTerm || undefined))();+ // Search has its own debounced effect below; keying on it here too+ // would fire a second, undebounced request per keystroke.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [loadJobs]);// The agent saves server-side, so only this counter tells us a row appeared@@ -128,7 +141,7 @@ export function useJobsList({if (searchTerm === "" && !hasSearched.current) return;const timer = setTimeout(() => {- loadJobs(1, filterKey, searchTerm || undefined);+ loadJobs(1, searchTerm || undefined);}, 300);return () => clearTimeout(timer);// eslint-disable-next-line react-hooks/exhaustive-deps@@ -141,7 +154,7 @@ export function useJobsList({sortRef.current = sort;if (lastSort.current === sort) return;lastSort.current = sort;- loadJobs(1, filterKey, searchTerm || undefined);+ loadJobs(1, searchTerm || undefined);// eslint-disable-next-line react-hooks/exhaustive-deps}, [sort]);@@ -158,7 +171,7 @@ export function useJobsList({!loadingMore &&jobs.length < totalJobs) {- loadJobs(page + 1, filterKey, searchTerm || undefined);+ loadJobs(page + 1, searchTerm || undefined);}},{ threshold: APP_CONSTANTS.INTERSECTION_OBSERVER_THRESHOLD },@@ -170,32 +183,25 @@ export function useJobsList({jobs.length,totalJobs,page,- filterKey,searchTerm,initialLoading,loadingMore,loadJobs,]);- const onFilterChange = (filterBy: string) => {- setFilterKey(filterBy);- loadJobs(1, filterBy, searchTerm || undefined);- };-return {jobs,viewMode,onChangeViewMode,page,totalJobs,- filterKey,searchTerm,setSearchTerm,initialLoading,+ listLoaded,loadingMore,loadJobs,reloadJobs,- onFilterChange,sentinelRef,};}diff --git a/src/lib/jobs/jobFacets.ts b/src/lib/jobs/jobFacets.tsnew file mode 100644index 0000000..d8e68b5--- /dev/null+++ b/src/lib/jobs/jobFacets.ts@@ -0,0 +1,77 @@+import { JOB_STATUS_VALUES } from "@/lib/constants";+import { JOB_TYPES, JobFacets, WORKPLACE_TYPES } from "@/models/job.model";++export const EMPTY_JOB_FACETS: JobFacets = {+ statuses: [],+ acceptedDiscovered: false,+ jobTypes: [],+ workplaces: [],+ includeDismissed: false,+};++const PARAM = {+ statuses: "status",+ acceptedDiscovered: "accepted",+ jobTypes: "type",+ workplaces: "workplace",+ includeDismissed: "dismissed",+} as const;++const JOB_TYPE_CODES = Object.keys(JOB_TYPES);+const WORKPLACE_CODES = Object.keys(WORKPLACE_TYPES);++// Filtering the whitelist (not the input) dedupes and fixes the order.+const pick = (values: readonly string[] | undefined, allowed: string[]) =>+ allowed.filter((value) => values?.includes(value));++export function normalizeJobFacets(+ input?: Partial<JobFacets> | null,+): JobFacets {+ return {+ statuses: pick(input?.statuses, JOB_STATUS_VALUES),+ acceptedDiscovered: input?.acceptedDiscovered === true,+ jobTypes: pick(input?.jobTypes, JOB_TYPE_CODES),+ workplaces: pick(input?.workplaces, WORKPLACE_CODES),+ includeDismissed: input?.includeDismissed === true,+ };+}++const readList = (params: URLSearchParams, key: string) =>+ params.get(key)?.split(",") ?? [];++export function parseJobFacets(params: URLSearchParams): JobFacets {+ return normalizeJobFacets({+ statuses: readList(params, PARAM.statuses),+ acceptedDiscovered: params.get(PARAM.acceptedDiscovered) === "1",+ jobTypes: readList(params, PARAM.jobTypes),+ workplaces: readList(params, PARAM.workplaces),+ includeDismissed: params.get(PARAM.includeDismissed) === "1",+ });+}++export function writeJobFacets(+ params: URLSearchParams,+ facets: JobFacets,+): URLSearchParams {+ const next = new URLSearchParams(params);+ const setList = (key: string, values: string[]) =>+ values.length ? next.set(key, values.join(",")) : next.delete(key);+ const setFlag = (key: string, on: boolean) =>+ on ? next.set(key, "1") : next.delete(key);++ setList(PARAM.statuses, facets.statuses);+ setFlag(PARAM.acceptedDiscovered, facets.acceptedDiscovered);+ setList(PARAM.jobTypes, facets.jobTypes);+ setList(PARAM.workplaces, facets.workplaces);+ setFlag(PARAM.includeDismissed, facets.includeDismissed);+ return next;+}++export const countJobFacets = (facets: JobFacets) =>+ facets.statuses.length ++ facets.jobTypes.length ++ facets.workplaces.length ++ Number(facets.acceptedDiscovered) ++ Number(facets.includeDismissed);++export const hasJobFacets = (facets: JobFacets) => countJobFacets(facets) > 0;diff --git a/src/models/job.model.ts b/src/models/job.model.tsindex dd33c8c..979ec12 100644--- a/src/models/job.model.ts+++ b/src/models/job.model.ts@@ -164,6 +164,32 @@ export enum WORKPLACE_TYPES {ONSITE = "Onsite",}+// Jobs-page popover filters. Values are stored codes (FT, REMOTE) and status+// values; OR within a field, AND across fields.+export type JobFacets = {+ statuses: string[];+ acceptedDiscovered: boolean;+ jobTypes: string[];+ workplaces: string[];+ includeDismissed: boolean;+};++// Deep-link filters from the Library tables, kept separate from the popover.+export type JobListScope = {+ companyValue?: string;+ appliedOnly?: boolean;+ titleValue?: string;+ locationValue?: string;+ sourceValue?: string;+};++export type JobFilterCounts = {+ total: number;+ // Keyed by JobStatus.id.+ statusCounts: Record<string, number>;+ acceptedDiscovered: number;+};+// Matches free-text input against a fixed enum, ignoring case and separators,// and returns its [key, label] pair. These are closed sets, so — unlike// canonicalizeEntityValue, which keeps punctuation on purpose so "C++" anddiff --git a/wiki/jobs.md b/wiki/jobs.mdindex 1832274..ebaf7a2 100644--- a/wiki/jobs.md+++ b/wiki/jobs.md@@ -62,9 +62,9 @@ You can also act from the Jobs list without opening the job: each row has **Edit## How do I find a job in a long list?-The Jobs card header has three tools. The **search box** matches on job text. The **filter dropdown** narrows to a preset: All (Except Dismissed), Applied, Interview, Draft, Rejected, Part-time, Accepted (discovered) or Dismissed (discovered). Opening the list from a job count in **Library → Companies**, **Job Titles**, **Locations** or **Sources** narrows it to that entry and shows it as a filter chip next to the search box — click the chip's **×** to clear it.+The Jobs card header has three tools. The **search box** matches on job text. The **filter button** (the sliders icon) opens a panel where you can combine filters: tick one or more **Status** values — including **Accepted (discovered)** — pick any **Job type** (Full-time, Part-time, Contract) and **Workplace** (Remote, Hybrid, Onsite), and tick **Include dismissed discovered jobs** to bring back jobs you dismissed from an automation. Picks in the same group match any of them; different groups must all match. The number beside each status is how many jobs you'd get with your other filters, and the button at the bottom shows the total — nothing changes until you click **Show N jobs**, and closing the panel throws your picks away. Active filters show as chips under the header with a badge count on the filter button; click a chip's **×** to drop that group or **Clear all** to drop them all. Filters are kept in the page address, so refreshing, going back or sharing the link keeps them. Opening the list from a job count in **Library → Companies**, **Job Titles**, **Locations** or **Sources** narrows it to that entry and shows it as a filter chip next to the search box — click the chip's **×** to clear it.-In table view, click a column header — **Applied**, **Title**, **Company**, **Location**, **Match** or **Source** — to sort the whole list, not just the rows loaded so far. The first click puts the most useful end first (newest dates and highest match scores first; names A→Z), a second click reverses it, and a third returns to the default order, newest added first. Jobs with nothing in that column always stay at the bottom, and a discovered job that hasn't been AI-matched yet sorts with the unmatched ones. Status isn't sortable — use the filter dropdown instead. The sort resets when you leave the page; card view keeps whatever order the table is sorted in. On a narrow screen only the columns you can see can be clicked.+In table view, click a column header — **Applied**, **Title**, **Company**, **Location**, **Match** or **Source** — to sort the whole list, not just the rows loaded so far. The first click puts the most useful end first (newest dates and highest match scores first; names A→Z), a second click reverses it, and a third returns to the default order, newest added first. Jobs with nothing in that column always stay at the bottom, and a discovered job that hasn't been AI-matched yet sorts with the unmatched ones. Status isn't sortable — use the filter panel instead. The sort resets when you leave the page; card view keeps whatever order the table is sorted in. On a narrow screen only the columns you can see can be clicked.The list also has a view toggle for table or card layout, and a reload button that refetches without a full page refresh.