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
test: Add unit test coverage for MCP tools and resume import feature
Khuram Niazc1b9ea191256
diff --git a/__tests__/createJobFromNames.spec.ts b/__tests__/createJobFromNames.spec.tsnew file mode 100644index 0000000..f705c6a--- /dev/null+++ b/__tests__/createJobFromNames.spec.ts@@ -0,0 +1,158 @@+import { createJobFromNames } from "@/lib/jobs/createJobFromNames";+import { createJobRecord } from "@/lib/jobs/createJobRecord";+import {+ resolveCompany,+ resolveJobTitle,+ resolveLocation,+ resolveJobSource,+ resolveJobType,+ resolveJobStatus,+ resolveTags,+} from "@/lib/jobs/resolve";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ job: { findFirst: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++vi.mock("@/lib/jobs/createJobRecord", () => ({+ createJobRecord: vi.fn(),+}));++vi.mock("@/lib/jobs/resolve", () => ({+ resolveCompany: vi.fn(),+ resolveJobTitle: vi.fn(),+ resolveLocation: vi.fn(),+ resolveJobSource: vi.fn(),+ resolveJobType: vi.fn(),+ resolveJobStatus: vi.fn(),+ resolveTags: vi.fn(),+}));++const baseInput = {+ company: "Acme",+ jobTitle: "Engineer",+ jobDescription: "Build things",+};++describe("createJobFromNames", () => {+ const userId = "user-1";++ beforeEach(() => {+ vi.clearAllMocks();+ (resolveCompany as any).mockResolvedValue({ id: "company-1", label: "Acme", created: true });+ (resolveJobTitle as any).mockResolvedValue({ id: "title-1", label: "Engineer", created: true });+ (resolveLocation as any).mockResolvedValue(null);+ (resolveJobSource as any).mockResolvedValue(null);+ (resolveJobType as any).mockReturnValue("Full-time");+ (resolveJobStatus as any).mockResolvedValue("status-1");+ (resolveTags as any).mockResolvedValue({ resolved: [], dropped: [] });+ (prisma.job.findFirst as any).mockResolvedValue(null);+ (createJobRecord as any).mockResolvedValue({ id: "job-1" });+ });++ it("creates a job and reports matched/created resolutions in the message", async () => {+ const result = await createJobFromNames(baseInput, userId);++ expect(result.created).toBe(true);+ expect(result.jobId).toBe("job-1");+ expect(result.message).toBe("Created Acme; Created Engineer. Job created (id: job-1).");+ expect(createJobRecord).toHaveBeenCalledWith(+ expect.objectContaining({+ companyId: "company-1",+ jobTitleId: "title-1",+ statusId: "status-1",+ jobType: "Full-time",+ userId,+ applied: false,+ appliedDate: null,+ }),+ );+ });++ it("defaults appliedDate to now when applied is true and no date given", async () => {+ const before = Date.now();+ await createJobFromNames({ ...baseInput, applied: true }, userId);+ const after = Date.now();++ const call = (createJobRecord as any).mock.calls[0][0];+ expect(call.applied).toBe(true);+ expect(call.appliedDate.getTime()).toBeGreaterThanOrEqual(before);+ expect(call.appliedDate.getTime()).toBeLessThanOrEqual(after);+ });++ it("uses the given appliedDate when provided", async () => {+ const appliedDate = new Date("2026-01-01T00:00:00Z");+ await createJobFromNames({ ...baseInput, applied: true, appliedDate }, userId);++ const call = (createJobRecord as any).mock.calls[0][0];+ expect(call.appliedDate).toBe(appliedDate);+ });++ it("appends dropped tags to the success message", async () => {+ (resolveTags as any).mockResolvedValue({+ resolved: [{ id: "tag-1", label: "React", created: false }],+ dropped: ["Extra1", "Extra2"],+ });++ const result = await createJobFromNames(baseInput, userId);++ expect(result.message).toContain("Dropped tags exceeding limit: Extra1, Extra2.");+ });++ it("skips duplicate detection when allowDuplicate is true", async () => {+ await createJobFromNames({ ...baseInput, allowDuplicate: true }, userId);++ expect(prisma.job.findFirst).not.toHaveBeenCalled();+ expect(createJobRecord).toHaveBeenCalled();+ });++ it("detects a duplicate by jobUrl and skips creation", async () => {+ (prisma.job.findFirst as any).mockResolvedValueOnce({+ id: "existing-job",+ JobTitle: { label: "Engineer" },+ Company: { label: "Acme" },+ });++ const result = await createJobFromNames(+ { ...baseInput, jobUrl: "https://example.com/job/1" },+ userId,+ );++ expect(result.created).toBe(false);+ expect(result.duplicateOf).toEqual({+ id: "existing-job",+ title: "Engineer",+ company: "Acme",+ });+ expect(result.message).toContain("Duplicate detected");+ expect(result.message).toContain("Pass allowDuplicate: true to force create");+ expect(createJobRecord).not.toHaveBeenCalled();+ });++ it("detects a duplicate by company+title within the window when no URL is given", async () => {+ (prisma.job.findFirst as any).mockResolvedValueOnce({+ id: "existing-job-2",+ JobTitle: { label: "Engineer" },+ Company: { label: "Acme" },+ });++ const result = await createJobFromNames(baseInput, userId);++ expect(result.created).toBe(false);+ expect(result.duplicateOf?.id).toBe("existing-job-2");+ expect(createJobRecord).not.toHaveBeenCalled();+ });++ it("creates the job when no duplicate is found", async () => {+ const result = await createJobFromNames(baseInput, userId);++ expect(result.created).toBe(true);+ expect(result.duplicateOf).toBeUndefined();+ });+});diff --git a/__tests__/createQuestionFromNames.spec.ts b/__tests__/createQuestionFromNames.spec.tsnew file mode 100644index 0000000..24c0f2e--- /dev/null+++ b/__tests__/createQuestionFromNames.spec.ts@@ -0,0 +1,113 @@+import { createQuestionFromNames } from "@/lib/questions/createQuestionFromNames";+import { resolveTags } from "@/lib/jobs/resolve";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ question: { create: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++vi.mock("@/lib/jobs/resolve", () => ({+ resolveTags: vi.fn(),+}));++describe("createQuestionFromNames", () => {+ const userId = "user-1";++ beforeEach(() => {+ vi.clearAllMocks();+ (resolveTags as any).mockResolvedValue({ resolved: [], dropped: [] });+ (prisma.question.create as any).mockResolvedValue({ id: "question-1" });+ });++ it("converts the markdown answer to HTML before storing", async () => {+ await createQuestionFromNames(+ { question: "What is closures?", answer: "**bold** answer" },+ userId,+ );++ expect(prisma.question.create).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ answer: expect.stringContaining("<strong>bold</strong>"),+ }),+ }),+ );+ });++ it("does not render raw HTML tags in the markdown input (html:false)", async () => {+ await createQuestionFromNames(+ { question: "XSS?", answer: "<script>alert(1)</script>" },+ userId,+ );++ const data = (prisma.question.create as any).mock.calls[0][0].data;+ expect(data.answer).not.toContain("<script>");+ });++ it("connects resolved tags and sets createdVia", async () => {+ (resolveTags as any).mockResolvedValue({+ resolved: [{ id: "tag-1", label: "React", created: false }],+ dropped: [],+ });++ await createQuestionFromNames(+ { question: "Q?", answer: "A", tags: ["React"], createdVia: "my-token" },+ userId,+ );++ expect(prisma.question.create).toHaveBeenCalledWith({+ data: expect.objectContaining({+ createdBy: userId,+ createdVia: "my-token",+ tags: { connect: [{ id: "tag-1" }] },+ }),+ });+ });++ it("builds a success message describing matched/created resolutions", async () => {+ (resolveTags as any).mockResolvedValue({+ resolved: [+ { id: "tag-1", label: "React", created: false },+ { id: "tag-2", label: "Hooks", created: true },+ ],+ dropped: [],+ });++ const result = await createQuestionFromNames(+ { question: "Q?", answer: "A", tags: ["React", "Hooks"] },+ userId,+ );++ expect(result.message).toBe(+ "Matched React; Created Hooks. Question created (id: question-1).",+ );+ });++ it("appends dropped tags to the message when tags exceed the limit", async () => {+ (resolveTags as any).mockResolvedValue({+ resolved: [],+ dropped: ["Extra1", "Extra2"],+ });++ const result = await createQuestionFromNames(+ { question: "Q?", answer: "A" },+ userId,+ );++ expect(result.message).toContain("Dropped tags exceeding limit: Extra1, Extra2.");+ });++ it("omits the resolutions clause from the message when there are no tags", async () => {+ const result = await createQuestionFromNames(+ { question: "Q?", answer: "A" },+ userId,+ );++ expect(result.message).toBe("Question created (id: question-1).");+ });+});diff --git a/__tests__/mcpAuth.spec.ts b/__tests__/mcpAuth.spec.tsnew file mode 100644index 0000000..7238075--- /dev/null+++ b/__tests__/mcpAuth.spec.ts@@ -0,0 +1,147 @@+import { resolveMcpToken } from "@/lib/mcp/auth";+import { hashToken } from "@/lib/mcp/tokens";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ mcpAccessToken: { findUnique: vi.fn(), update: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++// Build a minimal Request-like object rather than a real Headers instance,+// since Headers trims header values and would swallow the "Bearer " (empty+// token) case we need to exercise below.+function makeRequest(authHeader?: string): Request {+ return {+ headers: { get: (name: string) => (name === "authorization" ? authHeader ?? null : null) },+ } as unknown as Request;+}++describe("resolveMcpToken", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.mcpAccessToken.update as any).mockResolvedValue({});+ });++ it("rejects a missing Authorization header", async () => {+ const result = await resolveMcpToken(makeRequest());+ expect(result).toEqual({+ ok: false,+ status: 401,+ error: "Missing or malformed Authorization header",+ });+ expect(prisma.mcpAccessToken.findUnique).not.toHaveBeenCalled();+ });++ it("rejects a malformed Authorization header (no Bearer prefix)", async () => {+ const result = await resolveMcpToken(makeRequest("Basic abc123"));+ expect(result).toEqual({+ ok: false,+ status: 401,+ error: "Missing or malformed Authorization header",+ });+ });++ it("rejects an empty bearer token", async () => {+ const result = await resolveMcpToken(makeRequest("Bearer "));+ expect(result).toEqual({ ok: false, status: 401, error: "Empty token" });+ });++ it("rejects a token that doesn't match any record", async () => {+ (prisma.mcpAccessToken.findUnique as any).mockResolvedValue(null);++ const result = await resolveMcpToken(makeRequest("Bearer jsync_unknown"));++ expect(result).toEqual({ ok: false, status: 401, error: "Invalid token" });+ });++ it("rejects an expired token", async () => {+ (prisma.mcpAccessToken.findUnique as any).mockResolvedValue({+ id: "t-1",+ userId: "user-1",+ scopes: JSON.stringify(["jobs:write"]),+ name: "my-token",+ expiresAt: new Date(Date.now() - 1000),+ });++ const result = await resolveMcpToken(makeRequest("Bearer jsync_expired"));++ expect(result).toEqual({ ok: false, status: 401, error: "Token expired" });+ });++ it("rejects a token with malformed scopes JSON", async () => {+ (prisma.mcpAccessToken.findUnique as any).mockResolvedValue({+ id: "t-1",+ userId: "user-1",+ scopes: "{not-json",+ name: "my-token",+ expiresAt: new Date(Date.now() + 1000 * 60 * 60),+ });++ const result = await resolveMcpToken(makeRequest("Bearer jsync_bad-scopes"));++ expect(result).toEqual({+ ok: false,+ status: 401,+ error: "Malformed token scopes",+ });+ });++ it("accepts a valid token and looks it up by its hash", async () => {+ const plaintext = "jsync_valid-token";+ (prisma.mcpAccessToken.findUnique as any).mockResolvedValue({+ id: "t-1",+ userId: "user-1",+ scopes: JSON.stringify(["jobs:write", "questions:write"]),+ name: "my-token",+ expiresAt: new Date(Date.now() + 1000 * 60 * 60),+ });++ const result = await resolveMcpToken(makeRequest(`Bearer ${plaintext}`));++ expect(result).toEqual({+ ok: true,+ userId: "user-1",+ scopes: ["jobs:write", "questions:write"],+ tokenName: "my-token",+ });+ expect(prisma.mcpAccessToken.findUnique).toHaveBeenCalledWith({+ where: { tokenHash: hashToken(plaintext) },+ });+ });++ it("updates lastUsedAt fire-and-forget on a valid token", async () => {+ (prisma.mcpAccessToken.findUnique as any).mockResolvedValue({+ id: "t-1",+ userId: "user-1",+ scopes: JSON.stringify([]),+ name: "my-token",+ expiresAt: new Date(Date.now() + 1000 * 60 * 60),+ });++ await resolveMcpToken(makeRequest("Bearer jsync_valid"));++ expect(prisma.mcpAccessToken.update).toHaveBeenCalledWith({+ where: { id: "t-1" },+ data: { lastUsedAt: expect.any(Date) },+ });+ });++ it("does not reject the request if the lastUsedAt update fails", async () => {+ (prisma.mcpAccessToken.findUnique as any).mockResolvedValue({+ id: "t-1",+ userId: "user-1",+ scopes: JSON.stringify([]),+ name: "my-token",+ expiresAt: new Date(Date.now() + 1000 * 60 * 60),+ });+ (prisma.mcpAccessToken.update as any).mockRejectedValue(new Error("db down"));++ const result = await resolveMcpToken(makeRequest("Bearer jsync_valid"));++ expect(result.ok).toBe(true);+ });+});diff --git a/__tests__/mcpRateLimit.spec.ts b/__tests__/mcpRateLimit.spec.tsnew file mode 100644index 0000000..9835150--- /dev/null+++ b/__tests__/mcpRateLimit.spec.ts@@ -0,0 +1,65 @@+import { checkMcpRateLimit } from "@/lib/mcp/rate-limit";+import { APP_CONSTANTS } from "@/lib/constants";++describe("checkMcpRateLimit", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("allows the first request and reports MAX - 1 remaining", () => {+ const result = checkMcpRateLimit("user-fresh-1");+ expect(result).toEqual({+ allowed: true,+ remaining: APP_CONSTANTS.MCP_RATE_LIMIT_MAX - 1,+ resetIn: APP_CONSTANTS.MCP_RATE_LIMIT_WINDOW_MS,+ });+ });++ it("decrements remaining on each subsequent call within the window", () => {+ const userId = "user-fresh-2";+ checkMcpRateLimit(userId);+ const second = checkMcpRateLimit(userId);+ expect(second.allowed).toBe(true);+ expect(second.remaining).toBe(APP_CONSTANTS.MCP_RATE_LIMIT_MAX - 2);+ });++ it("denies once the count reaches MAX", () => {+ const userId = "user-fresh-3";+ for (let i = 0; i < APP_CONSTANTS.MCP_RATE_LIMIT_MAX; i++) {+ checkMcpRateLimit(userId);+ }+ const result = checkMcpRateLimit(userId);+ expect(result.allowed).toBe(false);+ expect(result.remaining).toBe(0);+ expect(result.resetIn).toBeGreaterThan(0);+ });++ it("resets the count after the window elapses", () => {+ const userId = "user-fresh-4";+ for (let i = 0; i < APP_CONSTANTS.MCP_RATE_LIMIT_MAX; i++) {+ checkMcpRateLimit(userId);+ }+ expect(checkMcpRateLimit(userId).allowed).toBe(false);++ vi.advanceTimersByTime(APP_CONSTANTS.MCP_RATE_LIMIT_WINDOW_MS + 1);++ const result = checkMcpRateLimit(userId);+ expect(result.allowed).toBe(true);+ expect(result.remaining).toBe(APP_CONSTANTS.MCP_RATE_LIMIT_MAX - 1);+ });++ it("tracks separate users independently", () => {+ const a = "user-fresh-5a";+ const b = "user-fresh-5b";+ for (let i = 0; i < APP_CONSTANTS.MCP_RATE_LIMIT_MAX; i++) {+ checkMcpRateLimit(a);+ }+ expect(checkMcpRateLimit(a).allowed).toBe(false);+ expect(checkMcpRateLimit(b).allowed).toBe(true);+ });+});diff --git a/__tests__/mcpTokens.spec.ts b/__tests__/mcpTokens.spec.tsnew file mode 100644index 0000000..808d3ab--- /dev/null+++ b/__tests__/mcpTokens.spec.ts@@ -0,0 +1,44 @@+import { createHash } from "crypto";+import { generateToken, hashToken } from "@/lib/mcp/tokens";++describe("hashToken", () => {+ it("returns the sha256 hex digest of the input", () => {+ const plaintext = "jsync_abc123";+ expect(hashToken(plaintext)).toBe(+ createHash("sha256").update(plaintext).digest("hex"),+ );+ });++ it("is deterministic for the same input", () => {+ expect(hashToken("same-value")).toBe(hashToken("same-value"));+ });++ it("produces different hashes for different inputs", () => {+ expect(hashToken("value-a")).not.toBe(hashToken("value-b"));+ });+});++describe("generateToken", () => {+ it("prefixes the plaintext with jsync_", () => {+ const { plaintext } = generateToken();+ expect(plaintext.startsWith("jsync_")).toBe(true);+ });++ it("returns a hash matching hashToken(plaintext)", () => {+ const { plaintext, hash } = generateToken();+ expect(hash).toBe(hashToken(plaintext));+ });++ it("returns a prefix that is the first 12 characters of the plaintext", () => {+ const { plaintext, prefix } = generateToken();+ expect(prefix).toBe(plaintext.slice(0, 12));+ expect(prefix).toHaveLength(12);+ });++ it("generates unique plaintext/hash on each call", () => {+ const first = generateToken();+ const second = generateToken();+ expect(first.plaintext).not.toBe(second.plaintext);+ expect(first.hash).not.toBe(second.hash);+ });+});diff --git a/__tests__/resolveTags.spec.ts b/__tests__/resolveTags.spec.tsnew file mode 100644index 0000000..8dcbeda--- /dev/null+++ b/__tests__/resolveTags.spec.ts@@ -0,0 +1,88 @@+import { resolveTags } from "@/lib/jobs/resolve";+import { PrismaClient } from "@prisma/client";++const prisma = new PrismaClient();++vi.mock("@prisma/client", () => {+ const mPrismaClient = {+ tag: { findUnique: vi.fn(), create: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++describe("resolveTags", () => {+ const userId = "user-1";++ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.tag.findUnique as any).mockResolvedValue(null);+ (prisma.tag.create as any).mockImplementation(({ data }: any) =>+ Promise.resolve({+ id: `tag-${data.value}`,+ label: data.label,+ value: data.value,+ createdBy: data.createdBy,+ }),+ );+ });++ it("resolves each unique label to a tag", async () => {+ const result = await resolveTags(["React", "TypeScript"], userId, 10);++ expect(result.resolved).toHaveLength(2);+ expect(result.resolved.map((r) => r.label)).toEqual(["React", "TypeScript"]);+ expect(result.dropped).toEqual([]);+ });++ it("dedupes case-insensitively and trims whitespace", async () => {+ const result = await resolveTags([" React ", "react", "REACT"], userId, 10);++ expect(prisma.tag.findUnique).toHaveBeenCalledTimes(1);+ expect(result.resolved).toHaveLength(1);+ expect(result.resolved[0].label).toBe("React");+ });++ it("drops empty/whitespace-only labels", async () => {+ const result = await resolveTags(["React", "", " "], userId, 10);++ expect(result.resolved).toHaveLength(1);+ expect(result.resolved[0].label).toBe("React");+ });++ it("caps resolution at maxTags and reports the rest as dropped", async () => {+ const result = await resolveTags(["A", "B", "C", "D"], userId, 2);++ expect(result.resolved).toHaveLength(2);+ expect(result.resolved.map((r) => r.label)).toEqual(["A", "B"]);+ expect(result.dropped).toEqual(["C", "D"]);+ expect(prisma.tag.create).toHaveBeenCalledTimes(2);+ });++ it("reuses an existing tag instead of creating a duplicate", async () => {+ (prisma.tag.findUnique as any).mockResolvedValue({+ id: "existing-tag",+ label: "React",+ value: "react",+ createdBy: userId,+ });++ const result = await resolveTags(["React"], userId, 10);++ expect(prisma.tag.create).not.toHaveBeenCalled();+ expect(result.resolved[0]).toEqual({+ id: "existing-tag",+ label: "React",+ value: "react",+ createdBy: userId,+ created: false,+ });+ });++ it("returns empty resolved/dropped for an empty input array", async () => {+ const result = await resolveTags([], userId, 10);++ expect(result.resolved).toEqual([]);+ expect(result.dropped).toEqual([]);+ expect(prisma.tag.findUnique).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/resumeImport.actions.spec.ts b/__tests__/resumeImport.actions.spec.tsindex 9983eda..fba7260 100644--- a/__tests__/resumeImport.actions.spec.ts+++ b/__tests__/resumeImport.actions.spec.ts@@ -1,5 +1,7 @@import { resolveImportCard } from "@/actions/resumeImport.actions";import { getCurrentUser } from "@/utils/user.utils";+import { createJobTitle } from "@/actions/jobtitle.actions";+import { createLocation } from "@/actions/job.actions";import { PrismaClient } from "@prisma/client";import { APP_CONSTANTS } from "@/lib/constants";@@ -7,8 +9,10 @@ const prisma = new PrismaClient();vi.mock("@prisma/client", () => {const mPrismaClient = {- resume: { findUnique: vi.fn() },+ resume: { findUnique: vi.fn(), update: vi.fn() },resumeSection: { create: vi.fn(), findFirst: vi.fn(), update: vi.fn() },+ summary: { update: vi.fn() },+ company: { findFirst: vi.fn(), create: vi.fn() },skill: { createMany: vi.fn() },tag: { findUnique: vi.fn(), create: vi.fn() },};@@ -20,6 +24,8 @@ vi.mock("@prisma/client", () => {});vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));+vi.mock("@/actions/jobtitle.actions", () => ({ createJobTitle: vi.fn() }));+vi.mock("@/actions/job.actions", () => ({ createLocation: vi.fn() }));describe("resolveImportCard — skills", () => {const mockUser = { id: "user-1" };@@ -177,3 +183,409 @@ describe("resolveImportCard — skills", () => {expect(rows[0].tagId).toBe("existing-tag");});});++describe("resolveImportCard — contactInfo", () => {+ const mockUser = { id: "user-1" };++ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.resume.findUnique as any).mockResolvedValue({ id: "resume-1" });+ (prisma.resume.update as any).mockResolvedValue({});+ });++ it("connects or creates ContactInfo with the given fields", async () => {+ const result = await resolveImportCard("resume-1", {+ type: "contactInfo",+ data: {+ firstName: "Jane",+ lastName: "Doe",+ headline: "Engineer",+ email: "[email protected]",+ phone: "555-1234",+ address: "123 Main St",+ },+ } as any);++ expect(result).toEqual({ success: true, status: "saved" });+ expect(prisma.resume.update).toHaveBeenCalledWith({+ where: { id: "resume-1", profile: { userId: mockUser.id } },+ data: {+ ContactInfo: {+ connectOrCreate: {+ where: { resumeId: "resume-1" },+ create: {+ firstName: "Jane",+ lastName: "Doe",+ headline: "Engineer",+ email: "[email protected]",+ phone: "555-1234",+ address: "123 Main St",+ },+ },+ },+ },+ });+ });++ it("defaults missing string fields to empty strings", async () => {+ await resolveImportCard("resume-1", { type: "contactInfo", data: {} } as any);++ const call = (prisma.resume.update as any).mock.calls[0][0];+ expect(call.data.ContactInfo.connectOrCreate.create).toEqual(+ expect.objectContaining({+ firstName: "",+ lastName: "",+ headline: "",+ email: "",+ phone: "",+ }),+ );+ });++ it("rejects when the resume is not owned by the user", async () => {+ (prisma.resume.findUnique as any).mockResolvedValue(null);++ const result = await resolveImportCard("resume-1", {+ type: "contactInfo",+ data: {},+ } as any);++ expect(result.success).toBe(false);+ expect(prisma.resume.update).not.toHaveBeenCalled();+ });+});++describe("resolveImportCard — summary", () => {+ const mockUser = { id: "user-1" };++ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.resume.findUnique as any).mockResolvedValue({ id: "resume-1" });+ });++ it("creates a new SUMMARY section and summary when none exists", async () => {+ (prisma.resumeSection.findFirst as any).mockResolvedValue(null);+ (prisma.resumeSection.create as any).mockResolvedValue({ id: "section-1" });+ (prisma.resumeSection.update as any).mockResolvedValue({});++ const result = await resolveImportCard("resume-1", {+ type: "summary",+ data: "Experienced engineer.",+ } as any);++ expect(result).toEqual({ success: true, status: "saved" });+ expect(prisma.resumeSection.create).toHaveBeenCalledWith({+ data: { resumeId: "resume-1", sectionTitle: "Summary", sectionType: "summary" },+ });+ expect(prisma.resumeSection.update).toHaveBeenCalledWith({+ where: { id: "section-1" },+ data: { summary: { create: { content: "<p>Experienced engineer.</p>" } } },+ });+ });++ it("updates the existing summary when a SUMMARY section already exists", async () => {+ (prisma.resumeSection.findFirst as any).mockResolvedValue({+ id: "section-1",+ summaryId: "summary-1",+ });+ (prisma.summary.update as any).mockResolvedValue({});++ await resolveImportCard("resume-1", {+ type: "summary",+ data: "Updated summary.",+ } as any);++ expect(prisma.summary.update).toHaveBeenCalledWith({+ where: { id: "summary-1" },+ data: { content: "<p>Updated summary.</p>" },+ });+ expect(prisma.resumeSection.create).not.toHaveBeenCalled();+ });++ it("HTML-escapes summary text and splits multiple lines into paragraphs", async () => {+ (prisma.resumeSection.findFirst as any).mockResolvedValue(null);+ (prisma.resumeSection.create as any).mockResolvedValue({ id: "section-1" });+ (prisma.resumeSection.update as any).mockResolvedValue({});++ await resolveImportCard("resume-1", {+ type: "summary",+ data: "Line one <b>\nLine two",+ } as any);++ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.summary.create.content).toBe(+ "<p>Line one <b></p><p>Line two</p>",+ );+ });++ it("rejects when the resume is not owned by the user", async () => {+ (prisma.resume.findUnique as any).mockResolvedValue(null);++ const result = await resolveImportCard("resume-1", {+ type: "summary",+ data: "Some summary",+ } as any);++ expect(result.success).toBe(false);+ expect(prisma.resumeSection.findFirst).not.toHaveBeenCalled();+ });+});++describe("resolveImportCard — experience", () => {+ const mockUser = { id: "user-1" };++ beforeEach(() => {+ vi.resetAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.resume.findUnique as any).mockResolvedValue({ id: "resume-1" });+ (prisma.company.findFirst as any).mockResolvedValue(null);+ (prisma.company.create as any).mockImplementation(({ data }: any) =>+ Promise.resolve({ id: "company-1", ...data }),+ );+ (createJobTitle as any).mockResolvedValue({ id: "title-1" });+ (createLocation as any).mockResolvedValue({ data: { id: "location-1" }, success: true });+ (prisma.resumeSection.findFirst as any).mockResolvedValue(null);+ (prisma.resumeSection.create as any).mockResolvedValue({ id: "section-1" });+ (prisma.resumeSection.update as any).mockResolvedValue({});+ });++ it("resolves company/jobTitle/location and creates a work experience", async () => {+ const result = await resolveImportCard("resume-1", {+ type: "experience",+ data: {+ company: "Acme",+ jobTitle: "Engineer",+ location: "Remote",+ startDate: "Jan 2020",+ endDate: "present",+ description: "Built things.",+ },+ } as any);++ expect(result).toEqual({ success: true, status: "saved" });+ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.workExperiences.create).toEqual(+ expect.objectContaining({+ jobTitleId: "title-1",+ locationId: "location-1",+ startDate: new Date("Jan 1, 2020"),+ endDate: undefined,+ description: "<p>Built things.</p>",+ }),+ );+ });++ it("reuses an existing EXPERIENCE section instead of creating a new one", async () => {+ (prisma.resumeSection.findFirst as any).mockResolvedValue({ id: "existing-section" });++ await resolveImportCard("resume-1", {+ type: "experience",+ data: { company: "Acme", jobTitle: "Engineer" },+ } as any);++ expect(prisma.resumeSection.create).not.toHaveBeenCalled();+ expect(prisma.resumeSection.update).toHaveBeenCalledWith(+ expect.objectContaining({ where: expect.objectContaining({ id: "existing-section" }) }),+ );+ });++ it("falls back to a placeholder location when none is provided", async () => {+ (createLocation as any).mockResolvedValue({+ data: { id: "fallback-location" },+ success: true,+ });++ await resolveImportCard("resume-1", {+ type: "experience",+ data: { company: "Acme", jobTitle: "Engineer" },+ } as any);++ expect(createLocation).toHaveBeenLastCalledWith("Not specified");+ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.workExperiences.create.locationId).toBe("fallback-location");+ });++ it("defaults startDate to Jan 1 2000 when unparsable/missing", async () => {+ await resolveImportCard("resume-1", {+ type: "experience",+ data: { company: "Acme", jobTitle: "Engineer" },+ } as any);++ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.workExperiences.create.startDate).toEqual(new Date(2000, 0, 1));+ });++ it("rejects when the resume is not owned by the user", async () => {+ (prisma.resume.findUnique as any).mockResolvedValue(null);++ const result = await resolveImportCard("resume-1", {+ type: "experience",+ data: { company: "Acme", jobTitle: "Engineer" },+ } as any);++ expect(result.success).toBe(false);+ expect(createJobTitle).not.toHaveBeenCalled();+ });+});++describe("resolveImportCard — education", () => {+ const mockUser = { id: "user-1" };++ beforeEach(() => {+ vi.resetAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.resume.findUnique as any).mockResolvedValue({ id: "resume-1" });+ (createLocation as any).mockResolvedValue({ data: { id: "location-1" }, success: true });+ (prisma.resumeSection.findFirst as any).mockResolvedValue(null);+ (prisma.resumeSection.create as any).mockResolvedValue({ id: "section-1" });+ (prisma.resumeSection.update as any).mockResolvedValue({});+ });++ it("creates an education entry with resolved location and parsed dates", async () => {+ const result = await resolveImportCard("resume-1", {+ type: "education",+ data: {+ institution: "State University",+ degree: "BSc",+ fieldOfStudy: "Computer Science",+ location: "Somewhere",+ startDate: "2016",+ endDate: "2020",+ description: "Graduated with honors.",+ },+ } as any);++ expect(result).toEqual({ success: true, status: "saved" });+ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.educations.create).toEqual(+ expect.objectContaining({+ institution: "State University",+ degree: "BSc",+ fieldOfStudy: "Computer Science",+ locationId: "location-1",+ startDate: new Date(2016, 0, 1),+ endDate: new Date(2020, 0, 1),+ description: "<p>Graduated with honors.</p>",+ }),+ );+ });++ it("falls back to a placeholder location when none is provided or resolvable", async () => {+ (createLocation as any).mockResolvedValue({+ data: { id: "fallback-location" },+ success: true,+ });++ await resolveImportCard("resume-1", {+ type: "education",+ data: { institution: "State University" },+ } as any);++ expect(createLocation).toHaveBeenLastCalledWith("Not specified");+ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.educations.create.locationId).toBe("fallback-location");+ });++ it("defaults degree/fieldOfStudy to empty strings when omitted", async () => {+ await resolveImportCard("resume-1", {+ type: "education",+ data: { institution: "State University" },+ } as any);++ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.educations.create).toEqual(+ expect.objectContaining({ degree: "", fieldOfStudy: "" }),+ );+ });++ it("rejects when the resume is not owned by the user", async () => {+ (prisma.resume.findUnique as any).mockResolvedValue(null);++ const result = await resolveImportCard("resume-1", {+ type: "education",+ data: { institution: "State University" },+ } as any);++ expect(result.success).toBe(false);+ expect(prisma.resumeSection.create).not.toHaveBeenCalled();+ });+});++describe("resolveImportCard — certification", () => {+ const mockUser = { id: "user-1" };++ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(mockUser);+ (prisma.resume.findUnique as any).mockResolvedValue({ id: "resume-1" });+ (prisma.resumeSection.findFirst as any).mockResolvedValue(null);+ (prisma.resumeSection.create as any).mockResolvedValue({ id: "section-1" });+ (prisma.resumeSection.update as any).mockResolvedValue({});+ });++ it("creates a certification entry with parsed issue/expiration dates", async () => {+ const result = await resolveImportCard("resume-1", {+ type: "certification",+ data: {+ title: "AWS Certified",+ organization: "Amazon",+ issueDate: "Jun 2021",+ expirationDate: "Jun 2024",+ credentialUrl: "https://example.com/cred",+ },+ } as any);++ expect(result).toEqual({ success: true, status: "saved" });+ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.licenseOrCertifications.create).toEqual(+ expect.objectContaining({+ title: "AWS Certified",+ organization: "Amazon",+ issueDate: new Date("Jun 1, 2021"),+ expirationDate: new Date("Jun 1, 2024"),+ credentialUrl: "https://example.com/cred",+ }),+ );+ });++ it("reuses an existing CERTIFICATION section instead of creating a new one", async () => {+ (prisma.resumeSection.findFirst as any).mockResolvedValue({ id: "existing-section" });++ await resolveImportCard("resume-1", {+ type: "certification",+ data: { title: "AWS Certified" },+ } as any);++ expect(prisma.resumeSection.create).not.toHaveBeenCalled();+ });++ it("defaults organization to an empty string and dates to undefined when omitted", async () => {+ await resolveImportCard("resume-1", {+ type: "certification",+ data: { title: "AWS Certified" },+ } as any);++ const call = (prisma.resumeSection.update as any).mock.calls[0][0];+ expect(call.data.licenseOrCertifications.create).toEqual(+ expect.objectContaining({+ organization: "",+ issueDate: undefined,+ expirationDate: undefined,+ }),+ );+ });++ it("rejects when the resume is not owned by the user", async () => {+ (prisma.resume.findUnique as any).mockResolvedValue(null);++ const result = await resolveImportCard("resume-1", {+ type: "certification",+ data: { title: "AWS Certified" },+ } as any);++ expect(result.success).toBe(false);+ expect(prisma.resumeSection.create).not.toHaveBeenCalled();+ });+});