Skip to content

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

feat: Save ai job match details

Khuram Niaz4926769dc841
diff --git a/__tests__/AiJobMatchSection.spec.tsx b/__tests__/AiJobMatchSection.spec.tsx
new file mode 100644
index 0000000..0a612dd
--- /dev/null
+++ b/__tests__/AiJobMatchSection.spec.tsx
@@ -0,0 +1,309 @@
+import React from "react";
+import { render, waitFor } from "@testing-library/react";
+import "@testing-library/jest-dom";
+import { AiJobMatchSection } from "@/components/profile/AiJobMatchSection";
+
+const mockSubmit = jest.fn();
+const mockStop = jest.fn();
+let mockUseObjectReturn = {
+ object: null as any,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+};
+
+jest.mock("@ai-sdk/react", () => ({
+ experimental_useObject: () => mockUseObjectReturn,
+}));
+
+const mockSaveJobMatchResult = jest.fn();
+jest.mock("@/actions/job.actions", () => ({
+ saveJobMatchResult: (...args: any[]) => mockSaveJobMatchResult(...args),
+}));
+
+jest.mock("@/actions/profile.actions", () => ({
+ getResumeList: jest.fn().mockResolvedValue({
+ success: true,
+ data: [{ id: "resume-1", title: "My Resume" }],
+ }),
+}));
+
+jest.mock("@/actions/userSettings.actions", () => ({
+ getUserSettings: jest.fn().mockResolvedValue({
+ success: true,
+ data: { settings: { ai: { provider: "openai", model: "gpt-4o" } } },
+ }),
+}));
+
+jest.mock("@/utils/ai.utils", () => ({
+ checkIfModelIsRunning: jest.fn().mockResolvedValue({ isRunning: false }),
+}));
+
+const mockToast = jest.fn();
+jest.mock("@/components/ui/use-toast", () => ({
+ toast: (...args: any[]) => mockToast(...args),
+}));
+
+jest.mock("@/components/profile/AiJobMatchResponseContent", () => ({
+ AiJobMatchResponseContent: () => <div data-testid="match-content" />,
+}));
+
+jest.mock("@/components/Loading", () => ({
+ __esModule: true,
+ default: () => <div data-testid="loading" />,
+}));
+
+// Mock Radix UI portals to render inline
+jest.mock("@/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: any) => (open ? <div>{children}</div> : null),
+ SheetPortal: ({ children }: any) => <div>{children}</div>,
+ SheetContent: ({ children }: any) => <div>{children}</div>,
+ SheetHeader: ({ children }: any) => <div>{children}</div>,
+ SheetTitle: ({ children }: any) => <div>{children}</div>,
+}));
+
+jest.mock("@/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: any) => <div>{children}</div>,
+ TooltipContent: ({ children }: any) => <div>{children}</div>,
+ TooltipProvider: ({ children }: any) => <div>{children}</div>,
+ TooltipTrigger: ({ children }: any) => <div>{children}</div>,
+}));
+
+jest.mock("@/components/ui/select", () => ({
+ Select: ({ children }: any) => <div>{children}</div>,
+ SelectContent: ({ children }: any) => <div>{children}</div>,
+ SelectGroup: ({ children }: any) => <div>{children}</div>,
+ SelectItem: ({ children }: any) => <div>{children}</div>,
+ SelectTrigger: ({ children }: any) => <div>{children}</div>,
+ SelectValue: () => null,
+}));
+
+const completedMatchObject = {
+ matchScore: 82,
+ recommendation: "good match" as const,
+ summary: "Strong frontend candidate",
+ requirements: { met: [], missing: [], partial: [] },
+ skills: { matched: [], missing: [], transferable: [], bonus: [] },
+ experience: {
+ levelMatch: "match",
+ yearsRequired: 3,
+ yearsApparent: 5,
+ relevance: "highly relevant",
+ },
+ keywords: { matched: [], missing: [], addToResume: [] },
+ dealBreakers: [],
+ tailoringTips: [],
+};
+
+describe("AiJobMatchSection – auto-save", () => {
+ const defaultProps = {
+ aISectionOpen: true,
+ triggerChange: jest.fn(),
+ jobId: "job-1",
+ onMatchSaved: jest.fn(),
+ };
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+ });
+
+ it("saves match result when streaming completes with valid data", async () => {
+ mockSaveJobMatchResult.mockResolvedValue({ success: true });
+
+ // Start with loading state
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: true,
+ stop: mockStop,
+ };
+
+ const { rerender } = render(<AiJobMatchSection {...defaultProps} />);
+
+ // Transition to completed with result
+ mockUseObjectReturn = {
+ object: completedMatchObject,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ rerender(<AiJobMatchSection {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockSaveJobMatchResult).toHaveBeenCalledTimes(1);
+ expect(mockSaveJobMatchResult).toHaveBeenCalledWith(
+ "job-1",
+ 82,
+ expect.stringContaining('"matchScore":82'),
+ );
+ });
+ });
+
+ it("calls onMatchSaved callback after successful save", async () => {
+ mockSaveJobMatchResult.mockResolvedValue({ success: true });
+
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: true,
+ stop: mockStop,
+ };
+
+ const { rerender } = render(<AiJobMatchSection {...defaultProps} />);
+
+ mockUseObjectReturn = {
+ object: completedMatchObject,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ rerender(<AiJobMatchSection {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(defaultProps.onMatchSaved).toHaveBeenCalledWith(
+ 82,
+ expect.stringContaining('"matchScore":82'),
+ );
+ });
+ });
+
+ it("shows success toast after save", async () => {
+ mockSaveJobMatchResult.mockResolvedValue({ success: true });
+
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: true,
+ stop: mockStop,
+ };
+
+ const { rerender } = render(<AiJobMatchSection {...defaultProps} />);
+
+ mockUseObjectReturn = {
+ object: completedMatchObject,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ rerender(<AiJobMatchSection {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockToast).toHaveBeenCalledWith({ title: "Match result saved" });
+ });
+ });
+
+ it("does not save when stream has no matchScore", async () => {
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: true,
+ stop: mockStop,
+ };
+
+ const { rerender } = render(<AiJobMatchSection {...defaultProps} />);
+
+ mockUseObjectReturn = {
+ object: { summary: "partial data" },
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ rerender(<AiJobMatchSection {...defaultProps} />);
+
+ // Give effect time to run
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockSaveJobMatchResult).not.toHaveBeenCalled();
+ expect(defaultProps.onMatchSaved).not.toHaveBeenCalled();
+ });
+
+ it("does not save when component mounts without prior loading", async () => {
+ mockUseObjectReturn = {
+ object: completedMatchObject,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ render(<AiJobMatchSection {...defaultProps} />);
+
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(mockSaveJobMatchResult).not.toHaveBeenCalled();
+ });
+
+ it("shows error toast when save fails", async () => {
+ mockSaveJobMatchResult.mockResolvedValue({
+ success: false,
+ message: "DB error",
+ });
+
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: true,
+ stop: mockStop,
+ };
+
+ const { rerender } = render(<AiJobMatchSection {...defaultProps} />);
+
+ mockUseObjectReturn = {
+ object: completedMatchObject,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ rerender(<AiJobMatchSection {...defaultProps} />);
+
+ await waitFor(() => {
+ expect(mockToast).toHaveBeenCalledWith({
+ variant: "destructive",
+ title: "Error!",
+ description: "DB error",
+ });
+ });
+
+ expect(defaultProps.onMatchSaved).not.toHaveBeenCalled();
+ });
+
+ it("includes resume metadata in saved matchData", async () => {
+ mockSaveJobMatchResult.mockResolvedValue({ success: true });
+
+ mockUseObjectReturn = {
+ object: null,
+ submit: mockSubmit,
+ isLoading: true,
+ stop: mockStop,
+ };
+
+ const { rerender } = render(<AiJobMatchSection {...defaultProps} />);
+
+ mockUseObjectReturn = {
+ object: completedMatchObject,
+ submit: mockSubmit,
+ isLoading: false,
+ stop: mockStop,
+ };
+
+ rerender(<AiJobMatchSection {...defaultProps} />);
+
+ await waitFor(() => {
+ const savedData = mockSaveJobMatchResult.mock.calls[0][2];
+ const parsed = JSON.parse(savedData);
+ expect(parsed).toHaveProperty("matchedAt");
+ expect(parsed.matchScore).toBe(82);
+ expect(parsed.summary).toBe("Strong frontend candidate");
+ });
+ });
+});
diff --git a/__tests__/JobDetails.spec.tsx b/__tests__/JobDetails.spec.tsx
index f0ece3d..c1dbd57 100644
--- a/__tests__/JobDetails.spec.tsx
+++ b/__tests__/JobDetails.spec.tsx
@@ -2,15 +2,19 @@ import React from "react";
import JobDetails from "@/components/myjobs/JobDetails";
import { JobResponse, Tag } from "@/models/job.model";
import "@testing-library/jest-dom";
-import { render, screen } from "@testing-library/react";
+import { render, screen, act } from "@testing-library/react";
jest.mock("next/navigation", () => ({
useRouter: jest.fn(() => ({ back: jest.fn() })),
}));
-// Stub heavy sub-components that are not under test
+let capturedOnMatchSaved: ((score: number, data: string) => void) | undefined;
+
jest.mock("@/components/profile/AiJobMatchSection", () => ({
- AiJobMatchSection: () => null,
+ AiJobMatchSection: (props: any) => {
+ capturedOnMatchSaved = props.onMatchSaved;
+ return null;
+ },
}));
jest.mock("@/components/myjobs/NotesSection", () => ({
@@ -22,7 +26,7 @@ jest.mock("@/components/TipTapContentViewer", () => ({
}));
jest.mock("@/components/automations/MatchDetails", () => ({
- MatchDetails: () => null,
+ MatchDetails: () => <div data-testid="match-details" />,
}));
jest.mock("@/components/profile/DownloadFileButton", () => ({
@@ -121,3 +125,71 @@ describe("JobDetails – skill badges", () => {
expect(screen.getAllByText("Vue")).toHaveLength(1);
});
});
+
+describe("JobDetails – match data display", () => {
+ beforeEach(() => {
+ capturedOnMatchSaved = undefined;
+ });
+
+ it("shows inline match analysis when job has matchData", () => {
+ const matchData = JSON.stringify({
+ matchScore: 85,
+ summary: "Good match",
+ });
+ render(<JobDetails job={makeJob({ matchScore: 85, matchData })} />);
+
+ expect(screen.getByText("AI Match Analysis")).toBeInTheDocument();
+ expect(screen.getByText("85% Match")).toBeInTheDocument();
+ expect(screen.getByTestId("match-details")).toBeInTheDocument();
+ });
+
+ it("does not show inline match section when job has no matchData", () => {
+ render(<JobDetails job={makeJob()} />);
+
+ expect(screen.queryByText("AI Match Analysis")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("match-details")).not.toBeInTheDocument();
+ });
+
+ it("updates inline match display when onMatchSaved is called", () => {
+ render(<JobDetails job={makeJob()} />);
+
+ // Initially no match section
+ expect(screen.queryByText("AI Match Analysis")).not.toBeInTheDocument();
+
+ // Simulate save callback from AiJobMatchSection
+ const newMatchData = JSON.stringify({
+ matchScore: 72,
+ summary: "Partial match",
+ });
+
+ act(() => {
+ capturedOnMatchSaved?.(72, newMatchData);
+ });
+
+ expect(screen.getByText("AI Match Analysis")).toBeInTheDocument();
+ expect(screen.getByText("72% Match")).toBeInTheDocument();
+ expect(screen.getByTestId("match-details")).toBeInTheDocument();
+ });
+
+ it("overwrites existing match data when onMatchSaved is called", () => {
+ const oldMatchData = JSON.stringify({
+ matchScore: 60,
+ summary: "Old match",
+ });
+ render(<JobDetails job={makeJob({ matchScore: 60, matchData: oldMatchData })} />);
+
+ expect(screen.getByText("60% Match")).toBeInTheDocument();
+
+ const newMatchData = JSON.stringify({
+ matchScore: 90,
+ summary: "New match",
+ });
+
+ act(() => {
+ capturedOnMatchSaved?.(90, newMatchData);
+ });
+
+ expect(screen.queryByText("60% Match")).not.toBeInTheDocument();
+ expect(screen.getByText("90% Match")).toBeInTheDocument();
+ });
+});
diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.ts
index 15588c0..4d07a71 100644
--- a/__tests__/job.actions.spec.ts
+++ b/__tests__/job.actions.spec.ts
@@ -6,6 +6,7 @@ import {
getJobsList,
getJobSourceList,
getStatusList,
+ saveJobMatchResult,
updateJob,
updateJobStatus,
} from "@/actions/job.actions";
@@ -684,4 +685,53 @@ describe("jobActions", () => {
});
});
});
+ describe("saveJobMatchResult", () => {
+ it("should return error when user is not authenticated", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ const result = await saveJobMatchResult("job-id", 85, '{"summary":"test"}');
+
+ expect(result).toStrictEqual({
+ success: false,
+ message: "Not authenticated",
+ });
+ expect(prisma.job.update).not.toHaveBeenCalled();
+ });
+
+ it("should save match score and data successfully", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.job.update as jest.Mock).mockResolvedValue({});
+
+ const matchData = JSON.stringify({
+ matchScore: 85,
+ summary: "Good match",
+ resumeId: "resume-1",
+ resumeTitle: "My Resume",
+ matchedAt: "2026-03-29T00:00:00.000Z",
+ });
+
+ const result = await saveJobMatchResult("job-id", 85, matchData);
+
+ expect(result).toStrictEqual({ success: true });
+ expect(prisma.job.update).toHaveBeenCalledTimes(1);
+ expect(prisma.job.update).toHaveBeenCalledWith({
+ where: { id: "job-id", userId: mockUser.id },
+ data: { matchScore: 85, matchData },
+ });
+ });
+
+ it("should handle database errors", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.job.update as jest.Mock).mockRejectedValue(
+ new Error("Record not found"),
+ );
+
+ const result = await saveJobMatchResult("job-id", 75, '{}');
+
+ expect(result).toStrictEqual({
+ success: false,
+ message: "Record not found",
+ });
+ });
+ });
});
diff --git a/src/actions/job.actions.ts b/src/actions/job.actions.ts
index e10ddaf..2f69d2a 100644
--- a/src/actions/job.actions.ts
+++ b/src/actions/job.actions.ts
@@ -438,6 +438,29 @@ export const updateJobStatus = async (
}
};
+export const saveJobMatchResult = async (
+ jobId: string,
+ matchScore: number,
+ matchData: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ await prisma.job.update({
+ where: { id: jobId, userId: user.id },
+ data: { matchScore, matchData },
+ });
+
+ return { success: true };
+ } catch (error) {
+ const msg = "Failed to save match result.";
+ return handleError(error, msg);
+ }
+};
+
export const deleteJobById = async (
jobId: string,
): Promise<any | undefined> => {
diff --git a/src/components/myjobs/JobDetails.tsx b/src/components/myjobs/JobDetails.tsx
index 8c7dc2d..5954c69 100644
--- a/src/components/myjobs/JobDetails.tsx
+++ b/src/components/myjobs/JobDetails.tsx
@@ -16,24 +16,34 @@ import { ArrowLeft, Sparkles } from "lucide-react";
import { useRouter } from "next/navigation";
import { AiJobMatchSection } from "../profile/AiJobMatchSection";
import { NotesSection } from "./NotesSection";
-import { useState, useMemo } from "react";
+import { useState, useMemo, useCallback } from "react";
import { DownloadFileButton } from "../profile/DownloadFileButton";
import { MatchDetails } from "../automations/MatchDetails";
import type { JobMatchResponse } from "@/models/ai.schemas";
function JobDetails({ job }: { job: JobResponse }) {
const [aiSectionOpen, setAiSectionOpen] = useState(false);
+ const [currentMatchScore, setCurrentMatchScore] = useState(job.matchScore);
+ const [currentMatchData, setCurrentMatchData] = useState(job.matchData);
const router = useRouter();
const goBack = () => router.back();
const parsedMatchData = useMemo(() => {
- if (!job.matchData) return null;
+ if (!currentMatchData) return null;
try {
- return JSON.parse(job.matchData) as JobMatchResponse;
+ return JSON.parse(currentMatchData) as JobMatchResponse;
} catch {
return null;
}
- }, [job.matchData]);
+ }, [currentMatchData]);
+
+ const handleMatchSaved = useCallback(
+ (matchScore: number, matchData: string) => {
+ setCurrentMatchScore(matchScore);
+ setCurrentMatchData(matchData);
+ },
+ [],
+ );
const getAiJobMatch = async () => {
setAiSectionOpen(true);
};
@@ -136,8 +146,8 @@ function JobDetails({ job }: { job: JobResponse }) {
<h4 className="font-medium mb-2 flex items-center gap-2">
<Sparkles className="h-4 w-4" />
AI Match Analysis
- {job.matchScore && (
- <Badge variant="default">{job.matchScore}% Match</Badge>
+ {currentMatchScore && (
+ <Badge variant="default">{currentMatchScore}% Match</Badge>
)}
</h4>
<MatchDetails matchData={parsedMatchData} />
@@ -151,6 +161,7 @@ function JobDetails({ job }: { job: JobResponse }) {
jobId={job?.id}
aISectionOpen={aiSectionOpen}
triggerChange={setAiSectionOpen}
+ onMatchSaved={handleMatchSaved}
/>
}
</>
diff --git a/src/components/profile/AiJobMatchSection.tsx b/src/components/profile/AiJobMatchSection.tsx
index ffeeaa7..5df3138 100644
--- a/src/components/profile/AiJobMatchSection.tsx
+++ b/src/components/profile/AiJobMatchSection.tsx
@@ -2,6 +2,7 @@
import { experimental_useObject as useObject } from "@ai-sdk/react";
import { getResumeList } from "@/actions/profile.actions";
+import { saveJobMatchResult } from "@/actions/job.actions";
import {
Sheet,
SheetContent,
@@ -38,12 +39,14 @@ interface AiSectionProps {
aISectionOpen: boolean;
triggerChange: (openState: boolean) => void;
jobId: string;
+ onMatchSaved?: (matchScore: number, matchData: string) => void;
}
export const AiJobMatchSection = ({
aISectionOpen,
triggerChange,
jobId,
+ onMatchSaved,
}: AiSectionProps) => {
const [selectedResumeId, setSelectedResumeId] = useState<string>();
const [runningModelName, setRunningModelName] = useState<string>("");
@@ -51,6 +54,7 @@ export const AiJobMatchSection = ({
const [selectedModel, setSelectedModel] = useState<AiModel>(defaultModel);
const [isLoadingSettings, setIsLoadingSettings] = useState(true);
const resumesRef = useRef<Resume[]>([]);
+ const wasLoadingRef = useRef(false);
useEffect(() => {
const fetchSettings = async () => {
@@ -85,6 +89,39 @@ export const AiJobMatchSection = ({
},
});
+ useEffect(() => {
+ if (isLoading) {
+ wasLoadingRef.current = true;
+ return;
+ }
+ if (!wasLoadingRef.current || !object?.matchScore) return;
+ wasLoadingRef.current = false;
+
+ const resumeTitle =
+ resumesRef.current.find((r) => r.id === selectedResumeId)?.title ??
+ "Unknown Resume";
+ const matchData = JSON.stringify({
+ ...object,
+ resumeId: selectedResumeId,
+ resumeTitle,
+ matchedAt: new Date().toISOString(),
+ });
+ const score = object.matchScore;
+
+ saveJobMatchResult(jobId, score, matchData).then((result) => {
+ if (result?.success) {
+ onMatchSaved?.(score, matchData);
+ toast({ title: "Match result saved" });
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Error!",
+ description: result?.message || "Failed to save match result",
+ });
+ }
+ });
+ }, [isLoading, object, jobId, selectedResumeId, onMatchSaved]);
+
const getResumes = async () => {
try {
const { data, success, message } = await getResumeList();