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): server-side column sorting on the jobs table via shared useSort, SortableTableHead and listSort helpers; update the jobs help page
Khuram Niazd8a3551de452
diff --git a/__tests__/JobsContainer.spec.tsx b/__tests__/JobsContainer.spec.tsxindex 443bded..af6ce03 100644--- a/__tests__/JobsContainer.spec.tsx+++ b/__tests__/JobsContainer.spec.tsx@@ -336,7 +336,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Amazon", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Amazon", undefined, undefined, undefined, undefined, undefined, undefined);});});@@ -354,7 +354,7 @@ describe("JobsContainer Search Functionality", () => {});// Initial call should not have search parameter- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined);});it("should trigger search when clearing search term after searching", async () => {@@ -382,7 +382,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Test", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Test", undefined, undefined, undefined, undefined, undefined, undefined);});// Clear the search input@@ -396,7 +396,7 @@ describe("JobsContainer Search Functionality", () => {// Should call with undefined when cleared after having searchedawait waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined);});});});@@ -428,7 +428,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined, undefined);});// Now change filter@@ -443,7 +443,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", "Developer", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", "Developer", undefined, undefined, undefined, undefined, undefined, undefined);});});@@ -471,7 +471,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Amazon", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Amazon", undefined, undefined, undefined, undefined, undefined, undefined);});// Change filter@@ -487,7 +487,7 @@ describe("JobsContainer Search Functionality", () => {// Search term should still be presentawait waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "interview", "Amazon", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, "interview", "Amazon", undefined, undefined, undefined, undefined, undefined, undefined);});});@@ -526,7 +526,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", "Developer", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", "Developer", undefined, undefined, undefined, undefined, undefined, undefined);});// Now clear filter by selecting None@@ -543,7 +543,7 @@ describe("JobsContainer Search Functionality", () => {// Filter should be cleared but search preservedawait waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined, undefined);});});});@@ -695,7 +695,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined, undefined);});// Simulate sentinel becoming visible@@ -708,7 +708,7 @@ describe("JobsContainer Search Functionality", () => {// Should include search term in infinite scroll callawait waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(2, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(2, 25, undefined, "Developer", undefined, undefined, undefined, undefined, undefined, undefined);});});});@@ -742,7 +742,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "test", undefined, undefined, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, "test", undefined, undefined, undefined, undefined, undefined, undefined);});});});@@ -760,7 +760,7 @@ describe("JobsContainer Search Functionality", () => {renderComponent();await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, "google", true, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, "google", true, undefined, undefined, undefined, undefined);});});@@ -835,7 +835,7 @@ describe("JobsContainer Search Functionality", () => {renderComponent();await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, "google", true, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, "google", true, undefined, undefined, undefined, undefined);});const filterTrigger = screen.getByRole("combobox");@@ -849,7 +849,7 @@ describe("JobsContainer Search Functionality", () => {});await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", undefined, "google", true, undefined, undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, "applied", undefined, "google", true, undefined, undefined, undefined, undefined);});});});@@ -867,7 +867,7 @@ describe("JobsContainer Search Functionality", () => {renderComponent();await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, true, "full stack developer", undefined, undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, true, "full stack developer", undefined, undefined, undefined);});});@@ -925,7 +925,7 @@ describe("JobsContainer Search Functionality", () => {renderComponent();await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, true, undefined, "remote", undefined);+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, true, undefined, "remote", undefined, undefined);});});@@ -983,7 +983,7 @@ describe("JobsContainer Search Functionality", () => {renderComponent();await waitFor(() => {- expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, true, undefined, undefined, "indeed");+ expect(getJobsList).toHaveBeenCalledWith(1, 25, undefined, undefined, undefined, true, undefined, undefined, "indeed", undefined);});});@@ -1112,4 +1112,108 @@ describe("JobsContainer Search Functionality", () => {expect(screen.queryByRole("table")).not.toBeInTheDocument();});});++ describe("Column sorting", () => {+ const U = undefined;++ beforeEach(() => {+ // An earlier "View mode" test persists "cards" to localStorage, which+ // otherwise carries into these tests and hides the table entirely.+ localStorage.clear();+ (getJobsList as any).mockResolvedValue({+ success: true,+ data: mockJobs,+ total: 2,+ });+ });++ it("reloads page 1 sorted when a header is clicked", async () => {+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));++ await user.click(screen.getByRole("button", { name: /^Company/ }));++ await waitFor(() => {+ expect(getJobsList).toHaveBeenLastCalledWith(+ 1, 25, U, U, U, U, U, U, U, { field: "company", dir: "asc" },+ );+ });+ });++ it("starts date and match columns descending", async () => {+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));++ await user.click(screen.getByRole("button", { name: /^Date Applied/ }));++ await waitFor(() => {+ expect(getJobsList).toHaveBeenLastCalledWith(+ 1, 25, U, U, U, U, U, U, U, { field: "appliedDate", dir: "desc" },+ );+ });+ });++ it("keeps the active search when sorting", async () => {+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));++ await user.type(screen.getByPlaceholderText("Search jobs..."), "Amazon");+ await act(async () => {+ vi.advanceTimersByTime(300);+ });+ await user.click(screen.getByRole("button", { name: /^Company/ }));++ await waitFor(() => {+ expect(getJobsList).toHaveBeenLastCalledWith(+ 1, 25, U, "Amazon", U, U, U, U, U, { field: "company", dir: "asc" },+ );+ });+ });++ it("cycles natural → reversed → off", async () => {+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));+ const header = () => screen.getByRole("columnheader", { name: /^Title/ });+ const button = () => screen.getByRole("button", { name: /^Title/ });++ await user.click(button());+ await waitFor(() => expect(header()).toHaveAttribute("aria-sort", "ascending"));++ await user.click(button());+ await waitFor(() => expect(header()).toHaveAttribute("aria-sort", "descending"));++ await user.click(button());+ await waitFor(() => expect(header()).not.toHaveAttribute("aria-sort"));+ expect(getJobsList).toHaveBeenLastCalledWith(1, 25, U, U, U, U, U, U, U, U);+ });++ it("ignores a slower response to an older sort", async () => {+ const deferred = () => {+ let resolve!: (v: unknown) => void;+ const promise = new Promise((r) => (resolve = r));+ return { promise, resolve };+ };+ renderComponent();+ await waitFor(() => expect(getJobsList).toHaveBeenCalledTimes(1));++ const older = deferred();+ const newer = deferred();+ (getJobsList as any)+ .mockReturnValueOnce(older.promise)+ .mockReturnValueOnce(newer.promise);++ await user.click(screen.getByRole("button", { name: /^Company/ }));+ await user.click(screen.getByRole("button", { name: /^Company/ }));++ await act(async () => {+ newer.resolve({ success: true, data: [mockJobs[1]], total: 1 });+ });+ await act(async () => {+ older.resolve({ success: true, data: [mockJobs[0]], total: 1 });+ });++ expect(screen.getByText("Frontend Developer")).toBeInTheDocument();+ expect(screen.queryByText("Full Stack Developer")).not.toBeInTheDocument();+ });+ });});diff --git a/__tests__/MyJobsTable.spec.tsx b/__tests__/MyJobsTable.spec.tsxindex 66281a2..b70682b 100644--- a/__tests__/MyJobsTable.spec.tsx+++ b/__tests__/MyJobsTable.spec.tsx@@ -56,6 +56,8 @@ function renderTable(jobs: JobResponse[], overrides: Partial<React.ComponentPropeditJob,onChangeJobStatus,onAddNote,+ sort: null,+ onSort: vi.fn(),...overrides,};const result = render(<MyJobsTable {...props} />);@@ -114,6 +116,8 @@ describe("MyJobsTable", () => {editJob={vi.fn()}onChangeJobStatus={vi.fn()}onAddNote={vi.fn()}+ sort={null}+ onSort={vi.fn()}/>,);expect(screen.getByRole("link", { name: /match/i })).toHaveAttribute(@@ -129,7 +133,11 @@ describe("MyJobsTable", () => {expect(screen.queryByRole("link", { name: /match/i }),).not.toBeInTheDocument();- expect(screen.getByRole("button", { name: /match/i })).toBeDisabled();+ // The sortable "Match" column header is also a button named /match/i now.+ const matchButtons = screen.getAllByRole("button", { name: /match/i });+ expect(matchButtons.some((b) => (b as HTMLButtonElement).disabled)).toBe(+ true,+ );} finally {chat.busy = false;}@@ -147,6 +155,8 @@ describe("MyJobsTable", () => {editJob={vi.fn()}onChangeJobStatus={vi.fn()}onAddNote={vi.fn()}+ sort={null}+ onSort={vi.fn()}/>,);expect(screen.queryByText("0")).not.toBeInTheDocument();diff --git a/__tests__/SortableTableHead.spec.tsx b/__tests__/SortableTableHead.spec.tsxnew file mode 100644index 0000000..ec06267--- /dev/null+++ b/__tests__/SortableTableHead.spec.tsx@@ -0,0 +1,42 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { SortableTableHead } from "@/components/SortableTableHead";++function renderHead(sort: { field: string; dir: "asc" | "desc" } | null) {+ const onSort = vi.fn();+ render(+ <table>+ <thead>+ <tr>+ <SortableTableHead field="company" sort={sort} onSort={onSort}>+ Company+ </SortableTableHead>+ </tr>+ </thead>+ </table>,+ );+ return { onSort, th: screen.getByRole("columnheader") };+}++describe("SortableTableHead", () => {+ it("calls onSort with its field when clicked", async () => {+ const { onSort } = renderHead(null);+ await userEvent.click(screen.getByRole("button", { name: "Company" }));+ expect(onSort).toHaveBeenCalledWith("company");+ });++ it("has no aria-sort when another column is sorted", () => {+ const { th } = renderHead({ field: "title", dir: "asc" });+ expect(th).not.toHaveAttribute("aria-sort");+ });++ it("reports ascending and descending on the active column", () => {+ const { th } = renderHead({ field: "company", dir: "asc" });+ expect(th).toHaveAttribute("aria-sort", "ascending");+ });++ it("reports descending", () => {+ const { th } = renderHead({ field: "company", dir: "desc" });+ expect(th).toHaveAttribute("aria-sort", "descending");+ });+});diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.tsindex 80bf347..4328ab6 100644--- a/__tests__/job.actions.spec.ts+++ b/__tests__/job.actions.spec.ts@@ -268,6 +268,64 @@ describe("jobActions", () => {});});+ describe("sorting", () => {+ const BASE = [{ createdAt: "desc" }, { id: "desc" }];+ const sortArgs = (sort: any) =>+ [1, 10, undefined, undefined, undefined, undefined, undefined, undefined, undefined, sort] as const;++ beforeEach(() => {+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.job.findMany as any).mockResolvedValue([]);+ (prisma.job.count as any).mockResolvedValue(0);+ });++ it("orders by newest added with an id tiebreaker by default", async () => {+ await getJobsList();+ expect(prisma.job.findMany).toHaveBeenCalledWith(+ expect.objectContaining({ orderBy: BASE }),+ );+ });++ it("sorts text columns on the canonical value", async () => {+ await getJobsList(...sortArgs({ field: "company", dir: "asc" }));+ expect(prisma.job.findMany).toHaveBeenCalledWith(+ expect.objectContaining({+ orderBy: [{ Company: { value: "asc" } }, ...BASE],+ }),+ );+ expect(prisma.job.count).toHaveBeenCalledTimes(1);+ });++ it("ignores a field outside the whitelist", async () => {+ await getJobsList(...sortArgs({ field: "userId", dir: "asc" }));+ expect(prisma.job.findMany).toHaveBeenCalledWith(+ expect.objectContaining({ orderBy: BASE }),+ );+ });++ it("pages real match scores first, then unscored jobs by newest", async () => {+ (prisma.job.count as any)+ .mockResolvedValueOnce(1)+ .mockResolvedValueOnce(1);+ (prisma.job.findMany as any)+ .mockResolvedValueOnce([{ id: "scored", matchScore: 80, matchData: "{}" }])+ .mockResolvedValueOnce([{ id: "unmatched", matchScore: null, matchData: null }]);++ const result = await getJobsList(...sortArgs({ field: "matchScore", dir: "desc" }));++ expect(result.total).toBe(2);+ expect(result.data.map((j: any) => j.id)).toEqual(["scored", "unmatched"]);+ const [valuedCall, blankCall] = (prisma.job.findMany as any).mock.calls;+ expect(valuedCall[0].orderBy).toEqual([{ matchScore: "desc" }, ...BASE]);+ expect(blankCall[0].orderBy).toEqual(BASE);+ // The dismissed-hiding AND survives, with the partition appended.+ expect(valuedCall[0].where.AND).toHaveLength(2);+ expect(valuedCall[0].where.AND[1]).toMatchObject({+ matchScore: { not: null },+ });+ });+ });+describe("search functionality", () => {it("should build OR clause when search parameter is provided", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);diff --git a/__tests__/listSort.spec.ts b/__tests__/listSort.spec.tsnew file mode 100644index 0000000..332aca2--- /dev/null+++ b/__tests__/listSort.spec.ts@@ -0,0 +1,108 @@+import { findManySorted, planListSort, SortFieldSpec } from "@/lib/listSort";++const hasValue = { v: { not: null } };+const noValue = { v: null };++const FIELDS: Record<string, SortFieldSpec> = {+ name: { orderBy: (dir) => ({ name: dir }) },+ v: { orderBy: (dir) => ({ v: dir }), blanks: { hasValue, noValue } },+};+const FALLBACK = [{ createdAt: "desc" }];+const BASE = [{ createdAt: "desc" }, { id: "desc" }];++describe("planListSort", () => {+ it("defaults to the fallback plus an id tiebreaker", () => {+ expect(planListSort(null, FIELDS, FALLBACK)).toEqual({ orderBy: BASE });+ });++ it("puts the chosen field before the fallback", () => {+ expect(planListSort({ field: "name", dir: "asc" }, FIELDS, FALLBACK)).toEqual({+ orderBy: [{ name: "asc" }, ...BASE],+ });+ });++ it("carries blanks with the fallback order for the blank half", () => {+ expect(planListSort({ field: "v", dir: "desc" }, FIELDS, FALLBACK)).toEqual({+ orderBy: [{ v: "desc" }, ...BASE],+ blanks: { hasValue, noValue, orderBy: BASE },+ });+ });++ it.each([+ { field: "userId", dir: "asc" },+ { field: "constructor", dir: "asc" },+ { field: "name", dir: "sideways" },+ ])("falls back on untrusted input %o", (sort) => {+ expect(planListSort(sort as any, FIELDS, FALLBACK)).toEqual({ orderBy: BASE });+ });+});++describe("findManySorted", () => {+ const valued = ["a", "b", "c"];+ const blank = ["x", "y"];++ // Stands in for Prisma: routes on which partition condition was appended.+ function fakeModel() {+ const rowsFor = (where: any) => {+ const last = where.AND?.[where.AND.length - 1];+ if (last === hasValue) return valued;+ if (last === noValue) return blank;+ return [...valued, ...blank];+ };+ return {+ findMany: vi.fn(async ({ where, skip, take }: any) =>+ rowsFor(where).slice(skip, skip + take),+ ),+ count: vi.fn(async ({ where }: any) => rowsFor(where).length),+ };+ }++ const plan = planListSort({ field: "v", dir: "desc" }, FIELDS, FALLBACK);++ it("uses one query and count when the field has no blanks", async () => {+ const model = fakeModel();+ const res = await findManySorted(+ model,+ { where: { userId: "u" }, skip: 0, take: 10 },+ planListSort(null, FIELDS, FALLBACK),+ );+ expect(model.findMany).toHaveBeenCalledTimes(1);+ expect(res.total).toBe(5);+ });++ it("pages concatenate to the full list with blanks last", async () => {+ const model = fakeModel();+ const pages = [];+ for (const skip of [0, 2, 4]) {+ const res = await findManySorted(+ model,+ { where: { userId: "u" }, skip, take: 2 },+ plan,+ );+ expect(res.total).toBe(5);+ pages.push(...res.data);+ }+ expect(pages).toEqual(["a", "b", "c", "x", "y"]);+ });++ it("orders the blank half by the fallback, not the sorted field", async () => {+ const model = fakeModel();+ await findManySorted(model, { where: {}, skip: 2, take: 2 }, plan);+ const blankCall = model.findMany.mock.calls[1][0];+ expect(blankCall.orderBy).toEqual(BASE);+ expect(blankCall.skip).toBe(0);+ });++ it("keeps an existing AND and passes select through", async () => {+ const model = fakeModel();+ const existing = { status: "open" };+ await findManySorted(+ model,+ { where: { AND: [existing] }, skip: 0, take: 2, select: { id: true } },+ plan,+ );+ const call = model.findMany.mock.calls[0][0];+ expect(call.where.AND).toEqual([existing, hasValue]);+ expect(call.select).toEqual({ id: true });+ });+});diff --git a/__tests__/persistDiscoveredJobStage.spec.ts b/__tests__/persistDiscoveredJobStage.spec.tsindex 6b022e7..261c4b5 100644--- a/__tests__/persistDiscoveredJobStage.spec.ts+++ b/__tests__/persistDiscoveredJobStage.spec.ts@@ -2,6 +2,7 @@ import { persistDiscoveredJob } from "@/lib/scraper/automation-run/persist";import { mapScrapedJobToJobRecord } from "@/lib/scraper/mapper";import db from "@/lib/db";import { resolveStageTypeForStatusId } from "@/lib/jobs/resolve";+import { UNANALYZED_MATCH_MARKER } from "@/actions/job/shared";vi.mock("@/lib/db", () => ({default: { job: { create: vi.fn() }, jobStage: { create: vi.fn() } },@@ -54,4 +55,15 @@ describe("persistDiscoveredJob", () => {expect(res.saved).toBe(false);});++ // The jobs list Match sort filters on this substring of matchData.+ it("writes the unanalysed marker the jobs list sort filters on", async () => {+ await persistDiscoveredJob(automation, job, 50, { analyzed: false }, []);++ expect(mapScrapedJobToJobRecord).toHaveBeenCalledWith(+ expect.objectContaining({+ matchData: expect.stringContaining(UNANALYZED_MATCH_MARKER),+ }),+ );+ });});diff --git a/__tests__/useSort.spec.tsx b/__tests__/useSort.spec.tsxnew file mode 100644index 0000000..820d245--- /dev/null+++ b/__tests__/useSort.spec.tsx@@ -0,0 +1,44 @@+import { act, renderHook } from "@testing-library/react";+import { nextSort, useSort } from "@/hooks/useSort";++describe("nextSort", () => {+ it("starts a new column in its natural direction", () => {+ expect(nextSort(null, "date", "desc")).toEqual({ field: "date", dir: "desc" });+ });++ it("reverses on the second click", () => {+ expect(nextSort({ field: "date", dir: "desc" }, "date", "desc")).toEqual({+ field: "date",+ dir: "asc",+ });+ });++ it("clears on the third click", () => {+ expect(nextSort({ field: "date", dir: "asc" }, "date", "desc")).toBeNull();+ });++ it("switching columns restarts at the new column's natural direction", () => {+ expect(nextSort({ field: "date", dir: "asc" }, "name", "asc")).toEqual({+ field: "name",+ dir: "asc",+ });+ });+});++describe("useSort", () => {+ const DIRS = { date: "desc", name: "asc" } as const;++ it("starts unsorted and cycles natural → reversed → off", () => {+ const { result } = renderHook(() => useSort(DIRS));+ expect(result.current.sort).toBeNull();++ act(() => result.current.toggleSort("date"));+ expect(result.current.sort).toEqual({ field: "date", dir: "desc" });++ act(() => result.current.toggleSort("date"));+ expect(result.current.sort).toEqual({ field: "date", dir: "asc" });++ act(() => result.current.toggleSort("date"));+ expect(result.current.sort).toBeNull();+ });+});diff --git a/src/actions/job/queries.ts b/src/actions/job/queries.tsindex a4eaaec..b453aec 100644--- a/src/actions/job/queries.ts+++ b/src/actions/job/queries.ts@@ -1,10 +1,12 @@"use server";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";-import { JOB_TYPES } from "@/models/job.model";+import { JOB_TYPES, JobSortField } from "@/models/job.model";+import type { SortState } from "@/models/sort.model";+import { findManySorted, planListSort, SortFieldSpec } from "@/lib/listSort";import { APP_CONSTANTS } from "@/lib/constants";import { requireUser } from "../shared";-import { hideUnanalyzedScore } from "./shared";+import { hideUnanalyzedScore, UNANALYZED_MATCH_MARKER } from "./shared";import { STAGE_DETAIL_INCLUDE } from "../jobStage/shared";const JOB_LIST_SELECT = {@@ -174,6 +176,53 @@ const buildJobsWhereClause = (userId: string, filters: JobsListFilters) => {return whereClause;};+// Text sorts use the canonical lowercase `value`, so order ignores case.+const JOB_SORT_SPECS: Record<JobSortField, SortFieldSpec> = {+ appliedDate: {+ orderBy: (dir) => ({ appliedDate: dir }),+ blanks: {+ hasValue: { appliedDate: { not: null } },+ noValue: { appliedDate: null },+ },+ },+ title: { orderBy: (dir) => ({ JobTitle: { value: dir } }) },+ company: { orderBy: (dir) => ({ Company: { value: dir } }) },+ location: {+ orderBy: (dir) => ({ Location: { value: dir } }),+ blanks: {+ hasValue: { locationId: { not: null } },+ noValue: { locationId: null },+ },+ },+ source: {+ orderBy: (dir) => ({ JobSource: { value: dir } }),+ blanks: {+ hasValue: { jobSourceId: { not: null } },+ noValue: { jobSourceId: null },+ },+ },+ // A hidden pre-rank is not a score, so those jobs sort with the unmatched.+ // The matchData: null branch keeps a scored row with no matchData visible.+ matchScore: {+ orderBy: (dir) => ({ matchScore: dir }),+ blanks: {+ hasValue: {+ matchScore: { not: null },+ OR: [+ { matchData: null },+ { NOT: { matchData: { contains: UNANALYZED_MATCH_MARKER } } },+ ],+ },+ noValue: {+ OR: [+ { matchScore: null },+ { matchData: { contains: UNANALYZED_MATCH_MARKER } },+ ],+ },+ },+ },+};+export const getJobsList = async (page: number = 1,limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,@@ -184,6 +233,7 @@ export const getJobsList = async (titleValue?: string,locationValue?: string,sourceValue?: string,+ sort?: SortState,): Promise<any | undefined> => {try {const user = await requireUser();@@ -199,21 +249,11 @@ export const getJobsList = async (sourceValue,});- const [data, total] = await Promise.all([- prisma.job.findMany({- where: whereClause,- skip,- take: limit,- select: JOB_LIST_SELECT,- orderBy: {- createdAt: "desc",- // appliedDate: "desc",- },- }),- prisma.job.count({- where: whereClause,- }),- ]);+ const { data, total } = await findManySorted(+ prisma.job,+ { where: whereClause, skip, take: limit, select: JOB_LIST_SELECT },+ planListSort(sort, JOB_SORT_SPECS, [{ createdAt: "desc" }]),+ );return { success: true, data: data.map(hideUnanalyzedScore), total };} catch (error) {const msg = "Failed to fetch jobs list. ";diff --git a/src/actions/job/shared.ts b/src/actions/job/shared.tsindex b6deb80..3625fe5 100644--- a/src/actions/job/shared.ts+++ b/src/actions/job/shared.ts@@ -3,6 +3,9 @@import { promoteStage } from "@/actions/jobStage/shared";+// persist.ts writes matchData with JSON.stringify, so this substring is exact.+export const UNANALYZED_MATCH_MARKER = '"analyzed":false';+// An automation job saved without LLM analysis carries only its keyword// pre-rank in matchScore, which the list must not show as an AI match. The// matchData body is dropped so the list payload stays small.diff --git a/src/components/SortableTableHead.tsx b/src/components/SortableTableHead.tsxnew file mode 100644index 0000000..e91fdfd--- /dev/null+++ b/src/components/SortableTableHead.tsx@@ -0,0 +1,49 @@+"use client";+import type { ReactNode } from "react";+import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";+import { TableHead } from "@/components/ui/table";+import { cn } from "@/lib/utils";+import type { SortState } from "@/models/sort.model";++type SortableTableHeadProps<F extends string> = {+ field: F;+ sort: SortState<F> | null;+ onSort: (field: F) => void;+ className?: string;+ children: ReactNode;+};++export function SortableTableHead<F extends string>({+ field,+ sort,+ onSort,+ className,+ children,+}: SortableTableHeadProps<F>) {+ const dir = sort?.field === field ? sort.dir : null;+ const Icon = dir === "asc" ? ArrowUp : dir === "desc" ? ArrowDown : ArrowUpDown;++ return (+ <TableHead+ className={className}+ aria-sort={+ dir === "asc" ? "ascending" : dir === "desc" ? "descending" : undefined+ }+ >+ <button+ type="button"+ onClick={() => onSort(field)}+ className={cn(+ "inline-flex items-center gap-1 hover:text-foreground",+ dir && "text-foreground",+ )}+ >+ {children}+ <Icon+ className={cn("h-3.5 w-3.5", !dir && "opacity-40")}+ aria-hidden+ />+ </button>+ </TableHead>+ );+}diff --git a/src/components/myjobs/JobsContainer.tsx b/src/components/myjobs/JobsContainer.tsxindex 856e02c..8b10e58 100644--- a/src/components/myjobs/JobsContainer.tsx+++ b/src/components/myjobs/JobsContainer.tsx@@ -10,12 +10,14 @@ import {import { toastError, toastSuccess } from "@/lib/toast";import {Company,+ JOB_SORT_FIELDS,JobLocation,JobSource,JobStatus,JobTitle,Tag,} from "@/models/job.model";+import { useSort } from "@/hooks/useSort";import Loading from "../Loading";import { useRouter } from "next/navigation";import MyJobsTable from "./MyJobsTable";@@ -65,6 +67,8 @@ function JobsContainer({clearSourceFilter,} = useJobFilters({ companies, titles, locations, sources });+ const { sort, toggleSort } = useSort(JOB_SORT_FIELDS);+const {jobs,viewMode,@@ -85,6 +89,7 @@ function JobsContainer({titleFilter,locationFilter,sourceFilter,+ sort,});const onDeleteJob = async (jobId: string) => {@@ -179,6 +184,8 @@ function JobsContainer({editJob={onEditJob}onChangeJobStatus={onChangeJobStatus}onAddNote={onAddNote}+ sort={sort}+ onSort={toggleSort}/>))}{jobs.length < totalJobs && (diff --git a/src/components/myjobs/MyJobsTable.tsx b/src/components/myjobs/MyJobsTable.tsxindex f93289c..8a52399 100644--- a/src/components/myjobs/MyJobsTable.tsx+++ b/src/components/myjobs/MyJobsTable.tsx@@ -14,10 +14,13 @@ import { format } from "date-fns";import { useState } from "react";import {JobResponse,+ JobSortField,JobStatus,getJobTypeLabel,getWorkplaceTypeLabel,} from "@/models/job.model";+import type { SortState } from "@/models/sort.model";+import { SortableTableHead } from "../SortableTableHead";import Link from "next/link";import { DeleteAlertDialog } from "../DeleteAlertDialog";import { CircularScore } from "@/components/CircularScore";@@ -34,6 +37,8 @@ type MyJobsTableProps = {editJob: (id: string) => void;onChangeJobStatus: (id: string, status: JobStatus) => void;onAddNote: (jobId: string) => void;+ sort: SortState<JobSortField> | null;+ onSort: (field: JobSortField) => void;};function MyJobsTable({@@ -43,6 +48,8 @@ function MyJobsTable({editJob,onChangeJobStatus,onAddNote,+ sort,+ onSort,}: MyJobsTableProps) {const [alertOpen, setAlertOpen] = useState(false);const [jobIdToDelete, setJobIdToDelete] = useState("");@@ -60,13 +67,25 @@ function MyJobsTable({<TableHead className="hidden w-[100px] sm:table-cell"><span className="sr-only">Company Logo</span></TableHead>- <TableHead className="hidden md:table-cell">Date Applied</TableHead>- <TableHead>Title</TableHead>- <TableHead>Company</TableHead>- <TableHead className="hidden md:table-cell">Location</TableHead>+ <SortableTableHead field="appliedDate" sort={sort} onSort={onSort} className="hidden md:table-cell">+ Date Applied+ </SortableTableHead>+ <SortableTableHead field="title" sort={sort} onSort={onSort}>+ Title+ </SortableTableHead>+ <SortableTableHead field="company" sort={sort} onSort={onSort}>+ Company+ </SortableTableHead>+ <SortableTableHead field="location" sort={sort} onSort={onSort} className="hidden md:table-cell">+ Location+ </SortableTableHead><TableHead>Status</TableHead>- <TableHead className="hidden md:table-cell text-center">Match</TableHead>- <TableHead className="hidden md:table-cell">Source</TableHead>+ <SortableTableHead field="matchScore" sort={sort} onSort={onSort} className="hidden md:table-cell text-center">+ Match+ </SortableTableHead>+ <SortableTableHead field="source" sort={sort} onSort={onSort} className="hidden md:table-cell">+ Source+ </SortableTableHead><TableHead><span className="sr-only">Actions</span></TableHead>diff --git a/src/components/myjobs/jobs-container/useJobsList.ts b/src/components/myjobs/jobs-container/useJobsList.tsindex 34a3c4b..de7faf3 100644--- a/src/components/myjobs/jobs-container/useJobsList.ts+++ b/src/components/myjobs/jobs-container/useJobsList.ts@@ -2,7 +2,8 @@import { useCallback, useEffect, useRef, useState } from "react";import { getJobsList } from "@/actions/job.actions";import { toastError } from "@/lib/toast";-import { JobResponse, JobsViewMode } from "@/models/job.model";+import { JobResponse, JobSortField, JobsViewMode } from "@/models/job.model";+import type { SortState } from "@/models/sort.model";import { APP_CONSTANTS } from "@/lib/constants";import {getFromLocalStorage,@@ -18,12 +19,14 @@ export function useJobsList({titleFilter,locationFilter,sourceFilter,+ sort,}: {companyFilter: string | null;appliedFilter: boolean;titleFilter: string | null;locationFilter: string | null;sourceFilter: string | null;+ sort: SortState<JobSortField> | null;}) {const { jobWrites } = useAgentChat();const [jobs, setJobs] = useState<JobResponse[]>([]);@@ -36,6 +39,9 @@ export function useJobsList({const [loadingMore, setLoadingMore] = useState(false);const hasSearched = useRef(false);const sentinelRef = useRef<HTMLDivElement>(null);+ const requestSeq = useRef(0);+ const sortRef = useRef(sort);+ const lastSort = useRef(sort);// Read after mount: localStorage is unavailable during SSR, so seeding the// initial state from it would cause a hydration mismatch.@@ -56,6 +62,9 @@ export function useJobsList({const loadJobs = useCallback(async (page: number, filter?: string, 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;if (page === 1) setInitialLoading(true);else setLoadingMore(true);const { success, data, total, message } = await getJobsList(@@ -68,7 +77,9 @@ export function useJobsList({titleFilter || undefined,locationFilter || undefined,sourceFilter || undefined,+ sortRef.current ?? undefined,);+ if (request !== requestSeq.current) return;if (success && data) {setJobs((prev) => (page === 1 ? data : [...prev, ...data]));setTotalJobs(total);@@ -123,6 +134,17 @@ export function useJobsList({// eslint-disable-next-line react-hooks/exhaustive-deps}, [searchTerm]);+ // Reload page 1 on a real sort change, keeping the filter and search. The+ // equality check skips mount (and StrictMode's re-run) — the mount effect+ // already loads.+ useEffect(() => {+ sortRef.current = sort;+ if (lastSort.current === sort) return;+ lastSort.current = sort;+ loadJobs(1, filterKey, searchTerm || undefined);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [sort]);+// Infinite scroll: auto-load next page when sentinel is visibleuseEffect(() => {const sentinel = sentinelRef.current;diff --git a/src/hooks/useSort.ts b/src/hooks/useSort.tsnew file mode 100644index 0000000..0c83c8d--- /dev/null+++ b/src/hooks/useSort.ts@@ -0,0 +1,30 @@+"use client";+import { useCallback, useState } from "react";+import type { SortDir, SortState } from "@/models/sort.model";++const flip = (dir: SortDir): SortDir => (dir === "asc" ? "desc" : "asc");++// The third click clears: with no sort dropdown, it is the only way back+// to the page's default order.+export function nextSort<F extends string>(+ prev: SortState<F> | null,+ field: F,+ natural: SortDir,+): SortState<F> | null {+ if (!prev || prev.field !== field) return { field, dir: natural };+ if (prev.dir === natural) return { field, dir: flip(natural) };+ return null;+}++export function useSort<F extends string>(+ naturalDirs: Readonly<Record<F, SortDir>>,+) {+ const [sort, setSort] = useState<SortState<F> | null>(null);++ const toggleSort = useCallback(+ (field: F) => setSort((prev) => nextSort(prev, field, naturalDirs[field])),+ [naturalDirs],+ );++ return { sort, toggleSort };+}diff --git a/src/lib/listSort.ts b/src/lib/listSort.tsnew file mode 100644index 0000000..acb29ab--- /dev/null+++ b/src/lib/listSort.ts@@ -0,0 +1,104 @@+import type { SortDir, SortState } from "@/models/sort.model";++// Not a "use server" module: it takes a Prisma delegate as an argument, so it+// must never become a callable server-action endpoint.++type Where = Record<string, unknown>;+type OrderBy = Record<string, unknown>;++export type ListSortDelegate = {+ findMany: (args: any) => Promise<any>;+ count: (args: any) => Promise<any>;+};++// `blanks` marks a column that can be empty. `hasValue` and `noValue` must be+// exact complements under the page's where clause.+export type SortFieldSpec = {+ orderBy: (dir: SortDir) => OrderBy;+ blanks?: { hasValue: Where; noValue: Where };+};++export type ListSortPlan = {+ orderBy: OrderBy[];+ blanks?: { hasValue: Where; noValue: Where; orderBy: OrderBy[] };+};++// Equal sort keys otherwise shuffle between pages under infinite scroll.+const ID_TIEBREAK: OrderBy = { id: "desc" };++export function planListSort(+ sort: SortState | null | undefined,+ fields: Record<string, SortFieldSpec>,+ fallback: OrderBy[],+): ListSortPlan {+ const base = [...fallback, ID_TIEBREAK];+ // Sort input comes from the client; "constructor" must not hit the prototype.+ const spec =+ sort && Object.prototype.hasOwnProperty.call(fields, sort.field)+ ? fields[sort.field]+ : undefined;+ if (!sort || !spec || (sort.dir !== "asc" && sort.dir !== "desc")) {+ return { orderBy: base };+ }+ return {+ orderBy: [spec.orderBy(sort.dir), ...base],+ ...(spec.blanks && { blanks: { ...spec.blanks, orderBy: base } }),+ };+}++const withCondition = (where: Where, extra: Where): Where => {+ const and = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : [];+ return { ...where, AND: [...and, extra] };+};++// SQLite has no NULLS LAST and Prisma's `nulls` option is unsupported there,+// so valued rows page first and the list continues into the blank ones.+export async function findManySorted(+ model: ListSortDelegate,+ query: { where: Where; skip: number; take: number; select?: unknown },+ plan: ListSortPlan,+): Promise<{ data: any[]; total: number }> {+ const { where, skip, take, ...shape } = query;++ if (!plan.blanks) {+ const [data, total] = await Promise.all([+ model.findMany({ where, skip, take, orderBy: plan.orderBy, ...shape }),+ model.count({ where }),+ ]);+ return { data, total };+ }++ const valuedWhere = withCondition(where, plan.blanks.hasValue);+ const blankWhere = withCondition(where, plan.blanks.noValue);+ // Summing the halves keeps the total equal to the rows scroll can reach.+ const [valuedTotal, blankTotal] = await Promise.all([+ model.count({ where: valuedWhere }),+ model.count({ where: blankWhere }),+ ]);++ const valuedTake = Math.min(take, Math.max(0, valuedTotal - skip));+ const valued =+ valuedTake > 0+ ? await model.findMany({+ where: valuedWhere,+ skip,+ take: valuedTake,+ orderBy: plan.orderBy,+ ...shape,+ })+ : [];++ const blankTake = take - valued.length;+ const blank =+ blankTake > 0 && blankTotal > 0+ ? await model.findMany({+ where: blankWhere,+ skip: Math.max(0, skip - valuedTotal),+ take: blankTake,+ orderBy: plan.blanks.orderBy,+ ...shape,+ })+ : [];++ return { data: [...valued, ...blank], total: valuedTotal + blankTotal };+}diff --git a/src/models/job.model.ts b/src/models/job.model.tsindex 8704112..dd33c8c 100644--- a/src/models/job.model.ts+++ b/src/models/job.model.ts@@ -4,6 +4,7 @@ import type { JobContactLink } from "./contact.model";// Type-only: jobStage.model.ts imports Tag from here and has a runtime export,// so a value import back would make a real module cycle.import type { JobStage } from "./jobStage.model";+import type { SortDir } from "./sort.model";export interface JobForm {id?: string;@@ -69,6 +70,19 @@ export interface JobResponse {export type JobsViewMode = "table" | "cards";+// First-click direction per sortable column. The keys are also the server's+// sort whitelist in getJobsList.+export const JOB_SORT_FIELDS = {+ appliedDate: "desc",+ title: "asc",+ company: "asc",+ location: "asc",+ matchScore: "desc",+ source: "asc",+} as const satisfies Record<string, SortDir>;++export type JobSortField = keyof typeof JOB_SORT_FIELDS;+export interface JobTitle {id: string;label: string;diff --git a/src/models/sort.model.ts b/src/models/sort.model.tsnew file mode 100644index 0000000..0575e12--- /dev/null+++ b/src/models/sort.model.ts@@ -0,0 +1,3 @@+export type SortDir = "asc" | "desc";++export type SortState<F extends string = string> = { field: F; dir: SortDir };diff --git a/wiki/jobs.md b/wiki/jobs.mdindex ce8c10b..7715717 100644--- a/wiki/jobs.md+++ b/wiki/jobs.md@@ -3,7 +3,7 @@ type: how-totitle: Jobsdescription: Adding jobs by hand or by pasting a posting into AI chat, moving them through the status workflow, and finding, editing, exporting or deleting them.feature: jobs-tags: [jobs, applications, add a job, status, applied, interview, offer, offer accepted, offer declined, rejected, csv, export, paste, filter, search, job details, tabs, notes, ai match, cover letter]+tags: [jobs, applications, add a job, status, applied, interview, offer, offer accepted, offer declined, rejected, csv, export, paste, filter, search, sort, job details, tabs, notes, ai match, cover letter]aliases: [job tracker, application tracker, my jobs, job board, track an application, job list]status: stablestale_after: 2027-08-31@@ -57,6 +57,8 @@ You can also act from the Jobs list without opening the job: each row has **EditThe 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.+In table view, click a column header — **Date 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.+The list also has a view toggle for table or card layout, and a reload button that refetches without a full page refresh.## How do I run an AI match from the jobs list?