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(contacts): add contact CRUD actions, the role-filtered list query and the contact form schema
Khuram Niaz93ceca1c9696
diff --git a/__tests__/addContactForm.schema.spec.ts b/__tests__/addContactForm.schema.spec.tsnew file mode 100644index 0000000..f4dcab4--- /dev/null+++ b/__tests__/addContactForm.schema.spec.ts@@ -0,0 +1,50 @@+import { AddContactFormSchema } from "@/models/addContactForm.schema";++const valid = { name: "Dave Patel" };++describe("AddContactFormSchema", () => {+ it("accepts a name on its own", () => {+ expect(AddContactFormSchema.safeParse(valid).success).toBe(true);+ });++ it("rejects an empty name", () => {+ expect(AddContactFormSchema.safeParse({ name: "" }).success).toBe(false);+ });++ it("accepts an empty email, because a panelist is often just a name", () => {+ expect(+ AddContactFormSchema.safeParse({ ...valid, email: "" }).success,+ ).toBe(true);+ });++ it("rejects a malformed email when one is given", () => {+ expect(+ AddContactFormSchema.safeParse({ ...valid, email: "not-an-email" }).success,+ ).toBe(false);+ });++ it("rejects a LinkedIn URL that is not http(s)", () => {+ expect(+ AddContactFormSchema.safeParse({ ...valid, linkedinUrl: "ftp://x.com" })+ .success,+ ).toBe(false);+ });++ it("rejects an overlap that ends before it starts", () => {+ const res = AddContactFormSchema.safeParse({+ ...valid,+ workedFrom: new Date("2021-01-01"),+ workedTo: new Date("2019-01-01"),+ });+ expect(res.success).toBe(false);+ });++ it("accepts an open-ended overlap", () => {+ expect(+ AddContactFormSchema.safeParse({+ ...valid,+ workedFrom: new Date("2019-01-01"),+ }).success,+ ).toBe(true);+ });+});diff --git a/__tests__/contact.actions.spec.ts b/__tests__/contact.actions.spec.tsnew file mode 100644index 0000000..e6a22e9--- /dev/null+++ b/__tests__/contact.actions.spec.ts@@ -0,0 +1,137 @@+import {+ getContactList,+ getAllContacts,+ createContact,+ updateContact,+ deleteContactById,+} from "@/actions/contact.actions";+import { getCurrentUser } from "@/utils/user.utils";+import prisma from "@/lib/db";++vi.mock("@/lib/db", () => ({+ default: {+ contact: {+ findMany: vi.fn(),+ count: vi.fn(),+ findFirst: vi.fn(),+ create: vi.fn(),+ updateMany: vi.fn(),+ deleteMany: vi.fn(),+ },+ },+}));++vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));++const db = prisma as any;+const user = { id: "user-1" };++describe("contact actions", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (getCurrentUser as any).mockResolvedValue(user);+ db.contact.findMany.mockResolvedValue([]);+ db.contact.count.mockResolvedValue(0);+ });++ describe("getContactList", () => {+ it("scopes to the user", async () => {+ await getContactList();+ expect(db.contact.findMany.mock.calls[0][0].where).toEqual({+ createdBy: user.id,+ });+ });++ it("searches name, email and title", async () => {+ await getContactList(1, 10, "pat");+ expect(db.contact.findMany.mock.calls[0][0].where.OR).toEqual([+ { name: { contains: "pat" } },+ { email: { contains: "pat" } },+ { title: { contains: "pat" } },+ ]);+ });++ it("filters on a role held through any job link", async () => {+ await getContactList(1, 10, undefined, "role-1");+ expect(db.contact.findMany.mock.calls[0][0].where.jobLinks).toEqual({+ some: { roleId: "role-1" },+ });+ });++ it("pages with skip and take", async () => {+ await getContactList(3, 10);+ const args = db.contact.findMany.mock.calls[0][0];+ expect(args.skip).toBe(20);+ expect(args.take).toBe(10);+ });+ });++ describe("getAllContacts", () => {+ it("returns picker rows whose value carries the email, so search finds it", async () => {+ db.contact.findMany.mockResolvedValue([+ { id: "c1", name: "Dave Patel", email: "[email protected]", Company: { label: "Shopify" } },+ ]);++ const res = await getAllContacts();++ expect(res).toEqual([+ { id: "c1", label: "Dave Patel", value: "dave patel [email protected] shopify" },+ ]);+ });+ });++ describe("createContact", () => {+ it("writes createdBy from the session, never from the payload", async () => {+ db.contact.create.mockResolvedValue({ id: "c1" });++ await createContact({ name: "Dave", createdBy: "attacker" } as any);++ const data = db.contact.create.mock.calls[0][0].data;+ expect(data.createdBy).toBe(user.id);+ expect(data.name).toBe("Dave");+ });++ it("stores empty optional text as null rather than an empty string", async () => {+ db.contact.create.mockResolvedValue({ id: "c1" });++ await createContact({ name: "Dave", email: "", title: "", company: "" } as any);++ const data = db.contact.create.mock.calls[0][0].data;+ expect(data.email).toBeNull();+ expect(data.title).toBeNull();+ expect(data.companyId).toBeNull();+ });+ });++ describe("updateContact", () => {+ it("scopes the update to the owner and reports a miss", async () => {+ db.contact.updateMany.mockResolvedValue({ count: 0 });++ const res = await updateContact({ id: "c1", name: "Dave" } as any);++ expect(db.contact.updateMany).toHaveBeenCalledWith(+ expect.objectContaining({ where: { id: "c1", createdBy: user.id } }),+ );+ expect(res.success).toBe(false);+ });+ });++ describe("deleteContactById", () => {+ it("deletes only the caller's contact", async () => {+ db.contact.deleteMany.mockResolvedValue({ count: 1 });++ const res = await deleteContactById("c1");++ expect(db.contact.deleteMany).toHaveBeenCalledWith({+ where: { id: "c1", createdBy: user.id },+ });+ expect(res.success).toBe(true);+ });++ it("reports a delete that matched nothing rather than claiming success", async () => {+ db.contact.deleteMany.mockResolvedValue({ count: 0 });+ const res = await deleteContactById("someone-elses");+ expect(res.success).toBe(false);+ });+ });+});diff --git a/src/actions/contact.actions.ts b/src/actions/contact.actions.tsnew file mode 100644index 0000000..f8441d0--- /dev/null+++ b/src/actions/contact.actions.ts@@ -0,0 +1,11 @@+export {+ getContactList,+ getAllContacts,+ getContactById,+} from "./contact/queries";++export {+ createContact,+ updateContact,+ deleteContactById,+} from "./contact/mutations";diff --git a/src/actions/contact/mutations.ts b/src/actions/contact/mutations.tsnew file mode 100644index 0000000..06e18a2--- /dev/null+++ b/src/actions/contact/mutations.ts@@ -0,0 +1,79 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { requireUser } from "../shared";+import type { ContactFormValues } from "@/models/addContactForm.schema";++// An untouched optional field arrives as "" from react-hook-form; storing that+// makes "has an email" untestable, so empty means null in the database.+const nullable = (value?: string | null) =>+ value && value.trim() ? value.trim() : null;++const toContactData = (values: ContactFormValues) => ({+ name: values.name.trim(),+ title: nullable(values.title),+ email: nullable(values.email),+ phone: nullable(values.phone),+ linkedinUrl: nullable(values.linkedinUrl),+ companyId: nullable(values.company),+ locationId: nullable(values.location),+ relationship: nullable(values.relationship),+ workedAtCompanyId: nullable(values.workedAtCompany),+ workedFrom: values.workedFrom ?? null,+ workedTo: values.workedTo ?? null,+ notes: nullable(values.notes),+ lastContactedAt: values.lastContactedAt ?? null,+});++export const createContact = async (+ values: ContactFormValues,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ const data = await prisma.contact.create({+ data: { ...toContactData(values), createdBy: user.id },+ });+ return { success: true, data };+ } catch (error) {+ return handleError(error, "Failed to create contact.");+ }+};++export const updateContact = async (+ values: ContactFormValues,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ if (!values.id) throw new Error("Please provide a contact id");++ // updateMany, not update: a unique-where cannot carry createdBy, and a+ // count of 0 is how a contact belonging to someone else surfaces.+ const res = await prisma.contact.updateMany({+ where: { id: values.id, createdBy: user.id },+ data: toContactData(values),+ });+ if (res.count === 0) throw new Error("Contact not found");++ return { success: true, data: { id: values.id } };+ } catch (error) {+ return handleError(error, "Failed to update contact.");+ }+};++export const deleteContactById = async (+ contactId: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ // JobContact cascades from Contact, so the links go with the person.+ const res = await prisma.contact.deleteMany({+ where: { id: contactId, createdBy: user.id },+ });+ if (res.count === 0) throw new Error("Contact not found");++ return { success: true };+ } catch (error) {+ return handleError(error, "Failed to delete contact.");+ }+};diff --git a/src/actions/contact/queries.ts b/src/actions/contact/queries.tsnew file mode 100644index 0000000..fe006e8--- /dev/null+++ b/src/actions/contact/queries.ts@@ -0,0 +1,114 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { requireUser } from "../shared";+import { APP_CONSTANTS } from "@/lib/constants";++// Narrowed to what the table row and the expanded row render. Not shared: only+// this module reads it.+const CONTACT_LIST_INCLUDE = {+ Company: { select: { id: true, label: true } },+ Location: { select: { id: true, label: true } },+ WorkedAtCompany: { select: { id: true, label: true } },+ jobLinks: {+ include: {+ Role: true,+ Job: {+ select: {+ id: true,+ JobTitle: { select: { label: true } },+ Company: { select: { label: true } },+ },+ },+ },+ orderBy: { createdAt: "asc" as const },+ },+ _count: { select: { jobLinks: true } },+};++// Contacts get their own query rather than getReferenceEntityList: that helper+// counts jobs grouped by an FK on Job, and a contact reaches Job only through+// JobContact. The role filter has no equivalent there either.+export const getContactList = async (+ page: number = 1,+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,+ search?: string,+ roleId?: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const where: any = { createdBy: user.id };+ if (search) {+ where.OR = [+ { name: { contains: search } },+ { email: { contains: search } },+ { title: { contains: search } },+ ];+ }+ if (roleId) {+ where.jobLinks = { some: { roleId } };+ }++ const [data, total] = await Promise.all([+ prisma.contact.findMany({+ where,+ skip: (page - 1) * limit,+ take: limit,+ include: CONTACT_LIST_INCLUDE,+ // Name only. The spec's cold-contact use for lastContactedAt implies a+ // sort, but a sortable header means an orderBy threaded through the+ // action and the list hook plus a nulls-last rule — deferred to v2.+ orderBy: [{ name: "asc" }],+ }),+ prisma.contact.count({ where }),+ ]);++ return { data, total };+ } catch (error) {+ return handleError(error, "Failed to fetch contact list. ");+ }+};++// The job-tab picker filters a preloaded array, so `value` carries everything+// worth searching on — name, email and employer.+export const getAllContacts = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ const rows = await prisma.contact.findMany({+ where: { createdBy: user.id },+ select: {+ id: true,+ name: true,+ email: true,+ Company: { select: { label: true } },+ },+ orderBy: { name: "asc" },+ });++ return rows.map((row) => ({+ id: row.id,+ label: row.name,+ value: [row.name, row.email, row.Company?.label]+ .filter(Boolean)+ .join(" ")+ .toLowerCase(),+ }));+ } catch (error) {+ return handleError(error, "Failed to fetch contacts. ");+ }+};++export const getContactById = async (+ contactId: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ return await prisma.contact.findFirst({+ where: { id: contactId, createdBy: user.id },+ include: CONTACT_LIST_INCLUDE,+ });+ } catch (error) {+ return handleError(error, "Failed to fetch contact. ");+ }+};diff --git a/src/models/addContactForm.schema.ts b/src/models/addContactForm.schema.tsnew file mode 100644index 0000000..ba4ea2d--- /dev/null+++ b/src/models/addContactForm.schema.ts@@ -0,0 +1,52 @@+import { z } from "zod";++const isValidHttpUrl = (url: string) => {+ try {+ return ["http:", "https:"].includes(new URL(url).protocol);+ } catch {+ return false;+ }+};++const optionalText = (max: number) => z.string().max(max).default("").optional();++export const AddContactFormSchema = z+ .object({+ id: z.string().optional(),+ name: z+ .string({ error: "Contact name is required." })+ .min(1, { message: "Contact name cannot be empty." })+ .max(120, { message: "Contact name must be 120 characters or fewer." }),+ title: optionalText(120),+ email: z+ .string()+ .default("")+ .optional()+ .refine(+ (v) => !v || z.email().safeParse(v).success,+ "Please enter a valid email address.",+ ),+ phone: optionalText(40),+ linkedinUrl: z+ .string()+ .default("")+ .optional()+ .refine(+ (url) => !url || isValidHttpUrl(url),+ "Please enter a full LinkedIn URL starting with https://",+ ),+ company: z.string().optional(),+ location: z.string().optional(),+ relationship: optionalText(120),+ workedAtCompany: z.string().optional(),+ workedFrom: z.date().nullable().optional(),+ workedTo: z.date().nullable().optional(),+ notes: optionalText(2000),+ lastContactedAt: z.date().nullable().optional(),+ })+ .refine(+ (v) => !v.workedFrom || !v.workedTo || v.workedTo >= v.workedFrom,+ { message: "The end date cannot be before the start date.", path: ["workedTo"] },+ );++export type ContactFormValues = z.infer<typeof AddContactFormSchema>;