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): add updateJobFromNames patch helper
Khuram Niazeb5e49e6b932
diff --git a/__tests__/updateJobFromNames.spec.ts b/__tests__/updateJobFromNames.spec.tsnew file mode 100644index 0000000..6bafaee--- /dev/null+++ b/__tests__/updateJobFromNames.spec.ts@@ -0,0 +1,170 @@+import { updateJobFromNames } from "@/lib/jobs/updateJobFromNames";+import {+ resolveCompany,+ resolveJobTitle,+ resolveLocation,+ resolveJobSource,+ resolveJobType,+ resolveWorkplaceType,+ 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(), update: vi.fn() },+ };+ return { PrismaClient: vi.fn(function () { return mPrismaClient; }) };+});++vi.mock("@/lib/jobs/resolve", () => ({+ resolveCompany: vi.fn(),+ resolveJobTitle: vi.fn(),+ resolveLocation: vi.fn(),+ resolveJobSource: vi.fn(),+ resolveJobType: vi.fn(),+ resolveWorkplaceType: vi.fn(),+ resolveJobStatus: vi.fn(),+ resolveTags: vi.fn(),+}));++const userId = "user-1";+const words = (n: number) => Array.from({ length: n }, () => "word").join(" ");++describe("updateJobFromNames", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (prisma.job.findFirst as any).mockResolvedValue({+ id: "job-1",+ descriptionCompleteness: "title-only",+ });+ (prisma.job.update as any).mockResolvedValue({ id: "job-1" });+ (resolveCompany as any).mockResolvedValue({ id: "company-1", label: "Acme", created: false });+ (resolveJobTitle as any).mockResolvedValue({ id: "title-1", label: "Engineer", created: false });+ (resolveLocation as any).mockResolvedValue({ id: "loc-1", label: "Remote", created: true });+ (resolveJobSource as any).mockResolvedValue({ id: "src-1", label: "Indeed", created: false });+ (resolveJobStatus as any).mockResolvedValue("status-1");+ (resolveJobType as any).mockReturnValue("FT");+ (resolveWorkplaceType as any).mockReturnValue("REMOTE");+ (resolveTags as any).mockResolvedValue({ resolved: [], dropped: [] });+ });++ it("returns updated:false when the job is not the caller's MCP-created job", async () => {+ (prisma.job.findFirst as any).mockResolvedValue(null);++ const result = await updateJobFromNames({ jobId: "job-x" }, userId);++ expect(result.updated).toBe(false);+ expect(result.message).toContain("not found");+ expect(prisma.job.update).not.toHaveBeenCalled();+ });++ it("scopes the ownership lookup to userId and MCP-created jobs", async () => {+ await updateJobFromNames({ jobId: "job-1", salaryRange: "$1" }, userId);++ expect(prisma.job.findFirst).toHaveBeenCalledWith({+ where: { id: "job-1", userId, createdVia: { not: null } },+ select: { id: true, descriptionCompleteness: true },+ });+ });++ it("patches only the provided fields", async () => {+ await updateJobFromNames({ jobId: "job-1", salaryRange: "$150k" }, userId);++ const call = (prisma.job.update as any).mock.calls[0][0];+ expect(call.where).toEqual({ id: "job-1", userId, createdVia: { not: null } });+ expect(call.data).toEqual({ salaryRange: "$150k" });+ });++ it("re-renders the description and reclassifies completeness", async () => {+ const result = await updateJobFromNames(+ { jobId: "job-1", jobDescription: words(200) },+ userId,+ );++ const data = (prisma.job.update as any).mock.calls[0][0].data;+ expect(data.description).toContain("<p>");+ expect(data.descriptionCompleteness).toBe("full");+ expect(result.descriptionChanged).toBe(true);+ expect(result.descriptionCompleteness).toBe("full");+ });++ it("reports descriptionChanged:false and the stored completeness when description is untouched", async () => {+ const result = await updateJobFromNames(+ { jobId: "job-1", status: "applied" },+ userId,+ );++ expect(result.descriptionChanged).toBe(false);+ expect(result.descriptionCompleteness).toBe("title-only");+ });++ it("resolves name-based fields to ids and reports them", async () => {+ const result = await updateJobFromNames(+ { jobId: "job-1", company: "Acme", jobTitle: "Engineer", location: "Remote" },+ userId,+ );++ const data = (prisma.job.update as any).mock.calls[0][0].data;+ expect(data).toEqual({+ companyId: "company-1",+ jobTitleId: "title-1",+ locationId: "loc-1",+ });+ expect(result.message).toContain("Created Remote");+ expect(result.message).toContain("Matched Acme");+ });++ it("replaces tags wholesale when tags are provided", async () => {+ (resolveTags as any).mockResolvedValue({+ resolved: [{ id: "tag-1", label: "React", created: false }],+ dropped: [],+ });++ await updateJobFromNames({ jobId: "job-1", tags: ["React"] }, userId);++ const data = (prisma.job.update as any).mock.calls[0][0].data;+ expect(data.tags).toEqual({ set: [{ id: "tag-1" }] });+ });++ it("normalizes a supplied jobUrl", async () => {+ await updateJobFromNames(+ { jobId: "job-1", jobUrl: "https://example.com/job/1?utm_source=x" },+ userId,+ );++ const data = (prisma.job.update as any).mock.calls[0][0].data;+ expect(data.jobUrl).not.toContain("utm_source");+ });++ it("defaults appliedDate to now when applied flips true without a date", async () => {+ await updateJobFromNames({ jobId: "job-1", applied: true }, userId);++ const data = (prisma.job.update as any).mock.calls[0][0].data;+ expect(data.applied).toBe(true);+ expect(data.appliedDate).toBeInstanceOf(Date);+ });++ it("returns updated:false with a not-found message on P2025", async () => {+ (prisma.job.update as any).mockRejectedValue({ code: "P2025" });++ const result = await updateJobFromNames(+ { jobId: "job-1", salaryRange: "$1" },+ userId,+ );++ expect(result.updated).toBe(false);+ expect(result.message).toContain("not found");+ });++ it("reports a no-op when no updatable field is supplied", async () => {+ const result = await updateJobFromNames({ jobId: "job-1" }, userId);++ expect(result.updated).toBe(false);+ expect(result.message).toContain("No fields to update");+ expect(prisma.job.update).not.toHaveBeenCalled();+ });+});diff --git a/src/lib/jobs/updateJobFromNames.ts b/src/lib/jobs/updateJobFromNames.tsnew file mode 100644index 0000000..7fdb878--- /dev/null+++ b/src/lib/jobs/updateJobFromNames.ts@@ -0,0 +1,205 @@+import MarkdownIt from "markdown-it";+import prisma from "@/lib/db";+import { APP_CONSTANTS } from "@/lib/constants";+import { normalizeJobUrl } from "@/lib/scraper/utils";+import { classifyDescriptionCompleteness } from "@/lib/jobs/descriptionCompleteness";+import type { DescriptionCompleteness } from "@/models/job.model";+import {+ resolveCompany,+ resolveJobTitle,+ resolveLocation,+ resolveJobSource,+ resolveJobType,+ resolveWorkplaceType,+ resolveJobStatus,+ resolveTags,+ type ResolvedEntity,+} from "./resolve";++// Same renderer config as createJobFromNames — html:false escapes raw HTML.+const md = new MarkdownIt({ html: false, linkify: false, breaks: true });++export interface UpdateJobFromNamesInput {+ jobId: string;+ company?: string;+ jobTitle?: string;+ jobDescription?: string;+ location?: string;+ source?: string;+ jobType?: string;+ workplaceType?: string;+ status?: string;+ // Not `| null`: McpUpdateJobSchema's transform can only produce+ // Date | undefined, never null, so there's no reachable "clear the date"+ // path via MCP — a nullable type here would be dead code.+ dueDate?: Date;+ applied?: boolean;+ appliedDate?: Date;+ jobUrl?: string;+ salaryRange?: string;+ tags?: string[];+}++export interface UpdateJobFromNamesResult {+ updated: boolean;+ jobId: string;+ descriptionChanged: boolean;+ descriptionCompleteness: DescriptionCompleteness | null;+ resolutions: ResolvedEntity[];+ message: string;+}++const NOT_FOUND_MESSAGE =+ "Job not found, not owned by this token's user, or not eligible for " ++ "updates via MCP (only jobs created through MCP can be updated).";++export async function updateJobFromNames(+ input: UpdateJobFromNamesInput,+ userId: string,+): Promise<UpdateJobFromNamesResult> {+ const { jobId } = input;++ // Ownership + eligibility gate, identical to the update `where` below, so a+ // caller learns "not found" before any entity is created as a side effect.+ const existing = await prisma.job.findFirst({+ where: { id: jobId, userId, createdVia: { not: null } },+ select: { id: true, descriptionCompleteness: true },+ });+ if (!existing) {+ return {+ updated: false,+ jobId,+ descriptionChanged: false,+ descriptionCompleteness: null,+ resolutions: [],+ message: NOT_FOUND_MESSAGE,+ };+ }++ // Validate synchronously before any async resolution starts, matching+ // createJobFromNames — an invalid enum must not orphan in-flight promises.+ const jobTypeValue =+ input.jobType !== undefined ? resolveJobType(input.jobType) : undefined;+ const workplaceTypeValue =+ input.workplaceType !== undefined+ ? resolveWorkplaceType(input.workplaceType)+ : undefined;++ const [+ resolvedCompany,+ resolvedTitle,+ resolvedLocation,+ resolvedSource,+ resolvedTagsResult,+ statusId,+ ] = await Promise.all([+ input.company !== undefined ? resolveCompany(input.company, userId) : null,+ input.jobTitle !== undefined ? resolveJobTitle(input.jobTitle, userId) : null,+ input.location !== undefined ? resolveLocation(input.location, userId) : null,+ input.source !== undefined ? resolveJobSource(input.source, userId) : null,+ input.tags !== undefined+ ? resolveTags(input.tags, userId, APP_CONSTANTS.MAX_JOB_TAGS)+ : null,+ input.status !== undefined ? resolveJobStatus(input.status) : null,+ ]);++ const resolutions: ResolvedEntity[] = [+ ...(resolvedCompany ? [resolvedCompany] : []),+ ...(resolvedTitle ? [resolvedTitle] : []),+ ...(resolvedLocation ? [resolvedLocation] : []),+ ...(resolvedSource ? [resolvedSource] : []),+ ...(resolvedTagsResult ? resolvedTagsResult.resolved : []),+ ];++ const data: Record<string, unknown> = {};+ if (resolvedCompany) data.companyId = resolvedCompany.id;+ if (resolvedTitle) data.jobTitleId = resolvedTitle.id;+ if (resolvedLocation) data.locationId = resolvedLocation.id;+ if (resolvedSource) data.jobSourceId = resolvedSource.id;+ if (statusId) data.statusId = statusId;+ if (jobTypeValue !== undefined) data.jobType = jobTypeValue;+ if (workplaceTypeValue !== undefined) data.workplaceType = workplaceTypeValue;+ if (input.salaryRange !== undefined) data.salaryRange = input.salaryRange;+ if (input.dueDate !== undefined) data.dueDate = input.dueDate;+ if (input.jobUrl !== undefined) data.jobUrl = normalizeJobUrl(input.jobUrl);+ if (input.applied !== undefined) data.applied = input.applied;+ if (input.appliedDate !== undefined) data.appliedDate = input.appliedDate;+ if (input.applied === true && input.appliedDate === undefined) {+ data.appliedDate = new Date();+ }+ if (resolvedTagsResult) {+ data.tags = { set: resolvedTagsResult.resolved.map((t) => ({ id: t.id })) };+ }++ let descriptionCompleteness: DescriptionCompleteness | null =+ (existing.descriptionCompleteness as DescriptionCompleteness | null) ?? null;+ const descriptionChanged = input.jobDescription !== undefined;+ if (input.jobDescription !== undefined) {+ descriptionCompleteness = classifyDescriptionCompleteness(input.jobDescription);+ data.description = md.render(input.jobDescription);+ data.descriptionCompleteness = descriptionCompleteness;+ }++ if (Object.keys(data).length === 0) {+ return {+ updated: false,+ jobId,+ descriptionChanged: false,+ descriptionCompleteness,+ resolutions,+ message: `No fields to update for job ${jobId}.`,+ };+ }++ try {+ await prisma.job.update({+ where: { id: jobId, userId, createdVia: { not: null } },+ data,+ });+ } catch (error: any) {+ if (error?.code === "P2025") {+ return {+ updated: false,+ jobId,+ descriptionChanged: false,+ descriptionCompleteness,+ resolutions,+ message: NOT_FOUND_MESSAGE,+ };+ }+ throw error;+ }++ return {+ updated: true,+ jobId,+ descriptionChanged,+ descriptionCompleteness,+ resolutions,+ message: buildUpdateMessage(+ jobId,+ Object.keys(data),+ resolutions,+ resolvedTagsResult?.dropped ?? [],+ ),+ };+}++function buildUpdateMessage(+ jobId: string,+ changedFields: string[],+ resolutions: ResolvedEntity[],+ droppedTags: string[],+): string {+ let msg = `Job ${jobId} updated. Fields changed: ${changedFields.join(", ")}.`;+ if (resolutions.length > 0) {+ const parts = resolutions.map(+ (r) => `${r.created ? "Created" : "Matched"} ${r.label}`,+ );+ msg += ` ${parts.join("; ")}.`;+ }+ if (droppedTags.length > 0) {+ msg += ` Dropped tags exceeding limit: ${droppedTags.join(", ")}.`;+ }+ return msg;+}