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(cover-letter): save generated letter and link it to the job
Khuram Niaz30b153efecd2
diff --git a/__tests__/coverLetter.actions.spec.ts b/__tests__/coverLetter.actions.spec.tsindex e9a89fd..897646e 100644--- a/__tests__/coverLetter.actions.spec.ts+++ b/__tests__/coverLetter.actions.spec.ts@@ -3,6 +3,7 @@ import {createCoverLetter,updateCoverLetter,deleteCoverLetterById,+ generateCoverLetterForJob,} from "@/actions/coverLetter.actions";import { getCurrentUser } from "@/utils/user.utils";import { PrismaClient } from "@prisma/client";@@ -23,6 +24,11 @@ vi.mock("@prisma/client", () => {findFirst: vi.fn(),create: vi.fn(),},+ job: {+ findUnique: vi.fn(),+ update: vi.fn(),+ },+ $transaction: vi.fn(),};return { PrismaClient: vi.fn(function() { return mPrismaClient; }) };});@@ -348,3 +354,94 @@ describe("coverLetterActions", () => {});});});++const markdown = "Dear Hiring Manager,\n\nI build platforms.\n\nSincerely,\nK";++describe("generateCoverLetterForJob", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue({ id: "user-1" });+ (prisma.$transaction as any).mockImplementation(async (fn: any) =>+ fn(prisma),+ );+ (prisma.profile.findFirst as any).mockResolvedValue({ id: "profile-1" });+ (prisma.coverLetter.findMany as any).mockResolvedValue([]);+ (prisma.coverLetter.create as any).mockResolvedValue({+ id: "cl-1",+ title: "Senior Engineer - Acme",+ });+ (prisma.job.findUnique as any).mockResolvedValue({+ id: "job-1",+ JobTitle: { label: "Senior Engineer" },+ Company: { label: "Acme" },+ });+ });++ it("rejects when unauthenticated", async () => {+ (getCurrentUser as any).mockResolvedValue(null);+ const result = await generateCoverLetterForJob("job-1", markdown);+ expect(result.success).toBe(false);+ expect(prisma.coverLetter.create).not.toHaveBeenCalled();+ });++ it("scopes the job lookup by userId", async () => {+ await generateCoverLetterForJob("job-1", markdown);+ expect(prisma.job.findUnique).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { id: "job-1", userId: "user-1" },+ }),+ );+ });++ it("rejects a job the caller does not own", async () => {+ (prisma.job.findUnique as any).mockResolvedValue(null);+ const result = await generateCoverLetterForJob("job-1", markdown);+ expect(result.success).toBe(false);+ expect(prisma.coverLetter.create).not.toHaveBeenCalled();+ });++ it("rejects content that is too short", async () => {+ const result = await generateCoverLetterForJob("job-1", "hi");+ expect(result.success).toBe(false);+ expect(prisma.coverLetter.create).not.toHaveBeenCalled();+ });++ it("stores markdown converted to HTML", async () => {+ await generateCoverLetterForJob("job-1", markdown);+ const arg = (prisma.coverLetter.create as any).mock.calls[0][0];+ expect(arg.data.content).toContain("<p>");+ expect(arg.data.content).toContain("I build platforms.");+ expect(arg.data.profileId).toBe("profile-1");+ });++ it("escapes raw HTML from the model", async () => {+ await generateCoverLetterForJob(+ "job-1",+ "Dear Hiring Manager,\n\n<script>alert(1)</script>\n\nSincerely,",+ );+ const arg = (prisma.coverLetter.create as any).mock.calls[0][0];+ expect(arg.data.content).not.toContain("<script>");+ });++ it("titles from the job and uniquifies against existing letters", async () => {+ (prisma.coverLetter.findMany as any).mockResolvedValue([+ { title: "Senior Engineer - Acme" },+ ]);+ await generateCoverLetterForJob("job-1", markdown);+ const arg = (prisma.coverLetter.create as any).mock.calls[0][0];+ expect(arg.data.title).toBe("Senior Engineer - Acme (2)");+ });++ it("links the new letter to the job", async () => {+ await generateCoverLetterForJob("job-1", markdown);+ expect(prisma.job.update).toHaveBeenCalledWith({+ where: { id: "job-1", userId: "user-1" },+ data: { coverLetterId: "cl-1" },+ });+ });++ it("never updates an existing cover letter", async () => {+ await generateCoverLetterForJob("job-1", markdown);+ expect(prisma.coverLetter.update).not.toHaveBeenCalled();+ });+});diff --git a/src/actions/coverLetter.actions.ts b/src/actions/coverLetter.actions.tsindex 81a5730..5da0a9a 100644--- a/src/actions/coverLetter.actions.ts+++ b/src/actions/coverLetter.actions.ts@@ -1,8 +1,16 @@"use server";+import MarkdownIt from "markdown-it";import prisma from "@/lib/db";import { handleError } from "@/lib/utils";import { getCurrentUser } from "@/utils/user.utils";import { APP_CONSTANTS } from "@/lib/constants";+import { buildCoverLetterTitle } from "@/lib/coverLetterTitle";++// html:false escapes raw HTML in the model output before it is ever stored,+// so the saved document is the same shape a hand-written letter produces.+const md = new MarkdownIt({ html: false, linkify: false, breaks: true });++const MIN_CONTENT_LENGTH = 10;export const getCoverLetterList = async (page: number = 1,@@ -152,3 +160,67 @@ export const deleteCoverLetterById = async (return handleError(error, msg);}};++export const generateCoverLetterForJob = async (+ jobId: string,+ markdown: string+): Promise<any | undefined> => {+ try {+ const user = await getCurrentUser();+ if (!user) {+ throw new Error("Not authenticated");+ }++ if (!markdown || markdown.trim().length < MIN_CONTENT_LENGTH) {+ throw new Error("Generated cover letter was too short to save.");+ }++ const job = await prisma.job.findUnique({+ where: { id: jobId, userId: user.id },+ include: { JobTitle: true, Company: true },+ });++ if (!job) {+ throw new Error("Job not found");+ }++ const profile = await prisma.profile.findFirst({+ where: { userId: user.id },+ });++ if (!profile) {+ throw new Error("No profile found for this user.");+ }++ const existing = await prisma.coverLetter.findMany({+ where: { profile: { userId: user.id } },+ select: { title: true },+ });++ const title = buildCoverLetterTitle(+ job.JobTitle?.label ?? "Cover Letter",+ job.Company?.label ?? "",+ existing.map((letter) => letter.title)+ );++ const content = md.render(markdown);++ const created = await prisma.$transaction(async (tx) => {+ const letter = await tx.coverLetter.create({+ data: { profileId: profile.id, title, content },+ });++ await tx.job.update({+ where: { id: jobId, userId: user.id },+ data: { coverLetterId: letter.id },+ });++ return letter;+ });++ return { success: true, data: { id: created.id, title: created.title } };+ } catch (error) {+ const msg = "Failed to save generated cover letter.";+ return handleError(error, msg);+ }+};