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(contacts): reshape the Contact model, add ContactRole and JobContact, and seed default roles

Khuram Niazd92e83e7efda
diff --git a/__tests__/auth.actions.spec.ts b/__tests__/auth.actions.spec.ts
index 678a153..b0a9863 100644
--- a/__tests__/auth.actions.spec.ts
+++ b/__tests__/auth.actions.spec.ts
@@ -2,7 +2,8 @@ import { signup, authenticate } from "@/actions/auth.actions";
import { signIn } from "@/auth";
import prisma from "@/lib/db";
import bcrypt from "bcryptjs";
-import { JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";
+import { CONTACT_ROLES, JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";
+import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";
import { delay } from "@/utils/delay";
import { AuthError } from "next-auth";
@@ -16,6 +17,9 @@ vi.mock("@/lib/db", () => {
jobSource: {
createMany: vi.fn(),
},
+ contactRole: {
+ createMany: vi.fn(),
+ },
jobStatus: {
upsert: vi.fn(),
},
@@ -193,6 +197,32 @@ describe("Auth Actions", () => {
});
});
+ it("seeds the default contact roles for the new user", async () => {
+ (prisma.user.findUnique as any).mockResolvedValue(null);
+ (bcrypt.hash as any).mockResolvedValue("hashed");
+ (prisma.user.create as any).mockResolvedValue({ id: "new-user-id" });
+
+ await signup({
+ name: "Test",
+ email: "[email protected]",
+ password: "Password1!",
+ });
+
+ expect(prisma.contactRole.createMany).toHaveBeenCalledWith({
+ data: CONTACT_ROLES.map((role) => ({
+ label: role.label,
+ value: role.value,
+ createdBy: "new-user-id",
+ })),
+ });
+ });
+
+ it("uses the canonical form of each label as the role value", () => {
+ for (const role of CONTACT_ROLES) {
+ expect(role.value).toBe(canonicalizeEntityValue(role.label));
+ }
+ });
+
it("should create job sources with correct structure", async () => {
(prisma.user.findUnique as any).mockResolvedValue(null);
(bcrypt.hash as any).mockResolvedValue("hashed_password_123");
diff --git a/__tests__/backupExport.spec.ts b/__tests__/backupExport.spec.ts
index 7dc34f6..74255e7 100644
--- a/__tests__/backupExport.spec.ts
+++ b/__tests__/backupExport.spec.ts
@@ -16,7 +16,7 @@ vi.mock("@/lib/db", () => {
"profile", "file", "resume", "contactInfo", "summary", "resumeSection",
"workExperience", "education", "licenseOrCertification", "otherSection",
"skill", "coverLetter", "automation", "job", "note", "interview",
- "contact", "task", "activity", "question", "automationRun", "userSettings",
+ "contact", "contactRole", "jobContact", "task", "activity", "question", "automationRun", "userSettings",
]) {
mock[key] = delegate();
}
diff --git a/__tests__/backupImportGuards.spec.ts b/__tests__/backupImportGuards.spec.ts
index 9461fdd..7010483 100644
--- a/__tests__/backupImportGuards.spec.ts
+++ b/__tests__/backupImportGuards.spec.ts
@@ -27,7 +27,7 @@ vi.mock("@/lib/db", () => {
"profile", "file", "resume", "contactInfo", "summary", "resumeSection",
"workExperience", "education", "licenseOrCertification", "otherSection",
"skill", "coverLetter", "automation", "job", "note", "interview",
- "contact", "task", "activity", "question", "userSettings",
+ "contact", "contactRole", "jobContact", "task", "activity", "question", "userSettings",
"chatConversation",
]) {
mock[key] = counted();
diff --git a/__tests__/backupOrdering.spec.ts b/__tests__/backupOrdering.spec.ts
index 953da4d..59f92af 100644
--- a/__tests__/backupOrdering.spec.ts
+++ b/__tests__/backupOrdering.spec.ts
@@ -47,10 +47,37 @@ describe("backup ordering", () => {
expect(MODEL_SPECS.ContactInfo.fks).not.toHaveProperty("resumeSectionId");
});
- it("marks exactly the six lookup models, all owned by createdBy", () => {
+ it("inserts ContactRole before JobContact, and Contact after Company and Location", () => {
+ const at = (m: BackupModel) => INSERT_ORDER.indexOf(m);
+ expect(at("ContactRole")).toBeLessThan(at("JobContact"));
+ expect(at("Contact")).toBeLessThan(at("JobContact"));
+ expect(at("Company")).toBeLessThan(at("Contact"));
+ expect(at("Location")).toBeLessThan(at("Contact"));
+ });
+
+ it("scopes JobContact through the job, which is the only chain it has", () => {
+ expect(MODEL_SPECS.JobContact.scope("u1")).toEqual({ Job: { userId: "u1" } });
+ expect(MODEL_SPECS.JobContact.fks).toEqual({
+ jobId: "Job",
+ contactId: "Contact",
+ roleId: "ContactRole",
+ });
+ });
+
+ it("remaps both of Contact's company FKs, not just the current employer", () => {
+ expect(MODEL_SPECS.Contact.fks).toEqual({
+ interviewId: "Interview",
+ companyId: "Company",
+ locationId: "Location",
+ workedAtCompanyId: "Company",
+ });
+ });
+
+ it("marks exactly the seven lookup models, all owned by createdBy", () => {
expect([...LOOKUP_MODELS].sort()).toEqual([
"ActivityType",
"Company",
+ "ContactRole",
"JobSource",
"JobTitle",
"Location",
diff --git a/prisma/migrations/20260912131248_contacts/migration.sql b/prisma/migrations/20260912131248_contacts/migration.sql
new file mode 100644
index 0000000..f09542b
--- /dev/null
+++ b/prisma/migrations/20260912131248_contacts/migration.sql
@@ -0,0 +1,91 @@
+/*
+ Warnings:
+
+ - Added the required column `updatedAt` to the `Contact` table without a default value. This is not possible if the table is not empty.
+
+*/
+-- CreateTable
+CREATE TABLE "ContactRole" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "label" TEXT NOT NULL,
+ "value" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ CONSTRAINT "ContactRole_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateTable
+CREATE TABLE "JobContact" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "jobId" TEXT NOT NULL,
+ "contactId" TEXT NOT NULL,
+ "roleId" TEXT NOT NULL,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT "JobContact_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "Job" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "JobContact_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "Contact" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "JobContact_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "ContactRole" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- RedefineTables
+PRAGMA defer_foreign_keys=ON;
+PRAGMA foreign_keys=OFF;
+CREATE TABLE "new_Contact" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "title" TEXT,
+ "email" TEXT,
+ "phone" TEXT,
+ "linkedinUrl" TEXT,
+ "companyId" TEXT,
+ "locationId" TEXT,
+ "relationship" TEXT,
+ "workedAtCompanyId" TEXT,
+ "workedFrom" DATETIME,
+ "workedTo" DATETIME,
+ "notes" TEXT,
+ "lastContactedAt" DATETIME,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "interviewId" TEXT,
+ CONSTRAINT "Contact_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_locationId_fkey" FOREIGN KEY ("locationId") REFERENCES "Location" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_workedAtCompanyId_fkey" FOREIGN KEY ("workedAtCompanyId") REFERENCES "Company" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "Contact_interviewId_fkey" FOREIGN KEY ("interviewId") REFERENCES "Interview" ("id") ON DELETE SET NULL ON UPDATE CASCADE
+);
+INSERT INTO "new_Contact" ("createdAt", "createdBy", "email", "id", "interviewId", "name") SELECT "createdAt", "createdBy", "email", "id", "interviewId", "name" FROM "Contact";
+DROP TABLE "Contact";
+ALTER TABLE "new_Contact" RENAME TO "Contact";
+CREATE INDEX "Contact_createdBy_idx" ON "Contact"("createdBy");
+CREATE INDEX "Contact_companyId_idx" ON "Contact"("companyId");
+CREATE INDEX "Contact_workedAtCompanyId_idx" ON "Contact"("workedAtCompanyId");
+PRAGMA foreign_keys=ON;
+PRAGMA defer_foreign_keys=OFF;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "ContactRole_value_createdBy_key" ON "ContactRole"("value", "createdBy");
+
+-- CreateIndex
+CREATE INDEX "JobContact_contactId_idx" ON "JobContact"("contactId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "JobContact_jobId_contactId_roleId_key" ON "JobContact"("jobId", "contactId", "roleId");
+
+-- Seed the five default contact roles for existing users. New accounts get
+-- these from signup(); uuid() is client-side, so the id is generated here.
+INSERT INTO "ContactRole" ("id", "label", "value", "createdBy")
+SELECT lower(
+ substr(hex(randomblob(16)), 1, 8) || '-' ||
+ substr(hex(randomblob(16)), 1, 4) || '-' ||
+ substr(hex(randomblob(16)), 1, 4) || '-' ||
+ substr(hex(randomblob(16)), 1, 4) || '-' ||
+ substr(hex(randomblob(16)), 1, 12)
+), r."label", r."value", u."id"
+FROM "User" u
+CROSS JOIN (
+ SELECT 'Recruiter' AS "label", 'recruiter' AS "value"
+ UNION ALL SELECT 'Hiring Manager', 'hiring manager'
+ UNION ALL SELECT 'Interviewer', 'interviewer'
+ UNION ALL SELECT 'Referrer', 'referrer'
+ UNION ALL SELECT 'Reference', 'reference'
+) r;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 360717b..d2d8198 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -24,6 +24,7 @@ model User {
Company Company[]
JobSource JobSource[]
Contact Contact[]
+ ContactRole ContactRole[]
Profile Profile[]
Activity Activity[]
ActivityType ActivityType[]
@@ -207,14 +208,67 @@ model OtherSection {
}
model Contact {
- id String @id @default(uuid())
- name String
- email String
- createdAt DateTime
+ id String @id @default(uuid())
+ name String
+ title String?
+ email String?
+ phone String?
+ linkedinUrl String?
+
+ // Where they work now
+ companyId String?
+ Company Company? @relation("ContactCompany", fields: [companyId], references: [id])
+ locationId String?
+ Location Location? @relation(fields: [locationId], references: [id])
+
+ // Shared history — how you know them
+ relationship String?
+ workedAtCompanyId String?
+ WorkedAtCompany Company? @relation("ContactWorkedAt", fields: [workedAtCompanyId], references: [id])
+ workedFrom DateTime?
+ workedTo DateTime?
+
+ notes String?
+ lastContactedAt DateTime?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ createdBy String // userId
+ user User @relation(fields: [createdBy], references: [id])
+
+ Interview Interview? @relation(fields: [interviewId], references: [id])
+ interviewId String?
+
+ jobLinks JobContact[]
+
+ @@index([createdBy])
+ @@index([companyId])
+ @@index([workedAtCompanyId])
+}
+
+model ContactRole {
+ id String @id @default(uuid())
+ label String
+ value String
createdBy String // userId
- user User @relation(fields: [createdBy], references: [id])
- Interview Interview? @relation(fields: [interviewId], references: [id])
- interviewId String?
+ user User @relation(fields: [createdBy], references: [id])
+ jobContacts JobContact[]
+
+ @@unique([value, createdBy])
+}
+
+model JobContact {
+ id String @id @default(uuid())
+ jobId String
+ Job Job @relation(fields: [jobId], references: [id], onDelete: Cascade)
+ contactId String
+ Contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ roleId String
+ Role ContactRole @relation(fields: [roleId], references: [id])
+ createdAt DateTime @default(now())
+
+ @@unique([jobId, contactId, roleId])
+ @@index([contactId])
}
model JobTitle {
@@ -247,6 +301,7 @@ model Location {
user User @relation(fields: [createdBy], references: [id])
educations Education[]
workExperience WorkExperience[]
+ contacts Contact[]
@@unique([value, createdBy])
}
@@ -261,6 +316,9 @@ model Company {
user User @relation(fields: [createdBy], references: [id])
workExperiences WorkExperience[]
+ contacts Contact[] @relation("ContactCompany")
+ formerColleagues Contact[] @relation("ContactWorkedAt")
+
// Watch intent — independent of whether a board is linked
watched Boolean @default(false)
watchedAt DateTime?
@@ -329,6 +387,7 @@ model Job {
coverLetterId String?
Notes Note[]
tags Tag[]
+ contactLinks JobContact[]
// Automation discovery fields
automationId String?
diff --git a/src/actions/auth.actions.ts b/src/actions/auth.actions.ts
index c5608ae..47aa2b1 100644
--- a/src/actions/auth.actions.ts
+++ b/src/actions/auth.actions.ts
@@ -5,7 +5,7 @@ import { delay } from "@/utils/delay";
import prisma from "@/lib/db";
import bcrypt from "bcryptjs";
import { SignupFormSchema } from "@/models/signupForm.schema";
-import { JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";
+import { CONTACT_ROLES, JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";
export async function signup(formData: {
name: string;
@@ -41,6 +41,14 @@ export async function signup(formData: {
})),
});
+ await prisma.contactRole.createMany({
+ data: CONTACT_ROLES.map((role) => ({
+ label: role.label,
+ value: role.value,
+ createdBy: newUser.id,
+ })),
+ });
+
for (const status of JOB_STATUSES) {
await prisma.jobStatus.upsert({
where: { value: status.value },
diff --git a/src/lib/backup/ordering.ts b/src/lib/backup/ordering.ts
index dcb5f9e..0823af8 100644
--- a/src/lib/backup/ordering.ts
+++ b/src/lib/backup/ordering.ts
@@ -26,6 +26,8 @@ export type BackupModel =
| "Note"
| "Interview"
| "Contact"
+ | "ContactRole"
+ | "JobContact"
| "Task"
| "Activity"
| "Question"
@@ -141,9 +143,28 @@ export const MODEL_SPECS: Record<BackupModel, ModelSpec> = {
Contact: {
delegate: "contact",
owner: "createdBy",
- fks: { interviewId: "Interview" },
+ fks: {
+ interviewId: "Interview",
+ companyId: "Company",
+ locationId: "Location",
+ workedAtCompanyId: "Company",
+ },
scope: byCreatedBy,
},
+ // A lookup like every other (value, createdBy) reference table, so a restore
+ // into an account that already has the seeded roles does not double them.
+ ContactRole: {
+ delegate: "contactRole",
+ owner: "createdBy",
+ lookup: true,
+ fks: {},
+ scope: byCreatedBy,
+ },
+ JobContact: {
+ delegate: "jobContact",
+ fks: { jobId: "Job", contactId: "Contact", roleId: "ContactRole" },
+ scope: (userId) => ({ Job: { userId } }),
+ },
Task: {
delegate: "task",
owner: "userId",
@@ -172,6 +193,7 @@ export const INSERT_ORDER: BackupModel[] = [
"JobSource",
"Tag",
"ActivityType",
+ "ContactRole",
"Profile",
"File",
"Resume",
@@ -189,6 +211,7 @@ export const INSERT_ORDER: BackupModel[] = [
"Note",
"Interview",
"Contact",
+ "JobContact",
"Task",
"Activity",
"Question",
diff --git a/src/lib/backup/schema.ts b/src/lib/backup/schema.ts
index 635c22b..dcd7937 100644
--- a/src/lib/backup/schema.ts
+++ b/src/lib/backup/schema.ts
@@ -225,12 +225,37 @@ const Note = z.object({
const Interview = z.object({ id, createdAt: dt, jobId: id });
+// Everything past `interviewId` is `.optional()` as well as nullable: a backup
+// taken before the contacts feature has no such key, and undefined leaves
+// Prisma on the column default.
const Contact = z.object({
id,
name: str,
- email: str,
+ email: optStr,
createdAt: dt,
interviewId: optId,
+ title: optStr.optional(),
+ phone: optStr.optional(),
+ linkedinUrl: optStr.optional(),
+ companyId: optId.optional(),
+ locationId: optId.optional(),
+ relationship: optStr.optional(),
+ workedAtCompanyId: optId.optional(),
+ workedFrom: optDt.optional(),
+ workedTo: optDt.optional(),
+ notes: optStr.optional(),
+ lastContactedAt: optDt.optional(),
+ updatedAt: dt.optional(),
+});
+
+const ContactRole = z.object({ id, label: str, value: str });
+
+const JobContact = z.object({
+ id,
+ jobId: id,
+ contactId: id,
+ roleId: id,
+ createdAt: dt,
});
const Task = z.object({
@@ -304,6 +329,7 @@ export const BackupDataSchema = z.object({
JobSource: group(JobSource),
Tag: group(Tag),
ActivityType: group(ActivityType),
+ ContactRole: group(ContactRole),
Profile: group(Profile),
File: group(File),
Resume: group(Resume),
@@ -321,6 +347,7 @@ export const BackupDataSchema = z.object({
Note: group(Note),
Interview: group(Interview),
Contact: group(Contact),
+ JobContact: group(JobContact),
Task: group(Task),
Activity: group(Activity),
Question: group(Question),
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 6f1978e..9944fe3 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -279,6 +279,17 @@ export const JOB_SOURCES = [
{ label: "Other", value: "other" },
] as const;
+// Seeded per user at signup and backfilled by the contacts migration. `value`
+// must equal canonicalizeEntityValue(label) or the creatable role picker will
+// mint a duplicate instead of matching the seeded row.
+export const CONTACT_ROLES = [
+ { label: "Recruiter", value: "recruiter" },
+ { label: "Hiring Manager", value: "hiring manager" },
+ { label: "Interviewer", value: "interviewer" },
+ { label: "Referrer", value: "referrer" },
+ { label: "Reference", value: "reference" },
+] as const;
+
export const JOB_STATUSES = [
{ label: "New", value: "new" },
{ label: "Draft", value: "draft" },
diff --git a/src/models/contact.model.ts b/src/models/contact.model.ts
new file mode 100644
index 0000000..55579cd
--- /dev/null
+++ b/src/models/contact.model.ts
@@ -0,0 +1,74 @@
+// Shape returned by getContactList / getContactById, not the raw Prisma row:
+// the relation objects are narrowed to what the table and expanded row show.
+
+export interface ContactRole {
+ id: string;
+ label: string;
+ value: string;
+ createdBy: string;
+ _count?: { jobContacts: number };
+}
+
+export interface EntityRef {
+ id: string;
+ label: string;
+}
+
+// What the job-details tab and the expanded Library row need off the person —
+// deliberately not the full Contact, which the link queries do not select.
+export interface ContactSummary {
+ id: string;
+ name: string;
+ title: string | null;
+ email: string | null;
+ phone: string | null;
+ linkedinUrl: string | null;
+ Company: EntityRef | null;
+}
+
+export interface JobContactLink {
+ id: string;
+ jobId: string;
+ contactId: string;
+ roleId: string;
+ createdAt: Date;
+ Role: ContactRole;
+ Job?: {
+ id: string;
+ JobTitle: { label: string };
+ Company: { label: string };
+ };
+ Contact?: ContactSummary;
+}
+
+export interface Contact {
+ id: string;
+ name: string;
+ title: string | null;
+ email: string | null;
+ phone: string | null;
+ linkedinUrl: string | null;
+ companyId: string | null;
+ Company: EntityRef | null;
+ locationId: string | null;
+ Location: EntityRef | null;
+ relationship: string | null;
+ workedAtCompanyId: string | null;
+ WorkedAtCompany: EntityRef | null;
+ workedFrom: Date | null;
+ workedTo: Date | null;
+ notes: string | null;
+ lastContactedAt: Date | null;
+ createdAt: Date;
+ updatedAt: Date;
+ createdBy: string;
+ jobLinks?: JobContactLink[];
+ _count?: { jobLinks: number };
+}
+
+// What the job-tab ComboBox consumes: id/label/value, like every other picker.
+export interface ContactRef {
+ id: string;
+ label: string;
+ value: string;
+}