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(stages): add stage schema and migration, Withdrawn status, stage-type resolver and signup seeding

Khuram Niazb23e7b8178ad
diff --git a/__tests__/auth.actions.spec.ts b/__tests__/auth.actions.spec.ts
index b0a9863..90a13a7 100644
--- a/__tests__/auth.actions.spec.ts
+++ b/__tests__/auth.actions.spec.ts
@@ -22,6 +22,10 @@ vi.mock("@/lib/db", () => {
},
jobStatus: {
upsert: vi.fn(),
+ findMany: vi.fn(),
+ },
+ jobStageType: {
+ createMany: vi.fn(),
},
};
return { default: mockPrisma };
@@ -61,6 +65,10 @@ vi.mock("next-auth", () => {
describe("Auth Actions", () => {
beforeEach(() => {
vi.clearAllMocks();
+ // Stage-type seeding reads the statuses back to map value -> id.
+ (prisma.jobStatus.findMany as any).mockResolvedValue(
+ JOB_STATUSES.map((s) => ({ id: `id-${s.value}`, value: s.value })),
+ );
});
describe("signup", () => {
@@ -217,6 +225,30 @@ describe("Auth Actions", () => {
});
});
+ it("seeds the fourteen stage types after the statuses exist", 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!",
+ });
+
+ const rows = (prisma.jobStageType.createMany as any).mock.calls[0][0].data;
+ expect(rows).toHaveLength(14);
+ expect(rows.every((r: any) => r.createdBy === "new-user-id")).toBe(true);
+ expect(rows.every((r: any) => typeof r.statusId === "string")).toBe(true);
+ expect(rows.find((r: any) => r.value === "offer accepted")).toBeTruthy();
+
+ const statusOrder = (prisma.jobStatus.upsert as any).mock
+ .invocationCallOrder[0];
+ const stageOrder = (prisma.jobStageType.createMany as any).mock
+ .invocationCallOrder[0];
+ expect(statusOrder).toBeLessThan(stageOrder);
+ });
+
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));
diff --git a/__tests__/jobStageConstants.spec.ts b/__tests__/jobStageConstants.spec.ts
new file mode 100644
index 0000000..d8baf84
--- /dev/null
+++ b/__tests__/jobStageConstants.spec.ts
@@ -0,0 +1,47 @@
+import { JOB_STAGES, JOB_STATUSES } from "@/lib/constants";
+import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";
+import { JOB_STATUS_BADGE_COLORS } from "@/lib/badge-colors";
+
+describe("JOB_STAGES", () => {
+ it("has fourteen entries with unique values and sequential sortOrder", () => {
+ expect(JOB_STAGES).toHaveLength(14);
+ const values = JOB_STAGES.map((s) => s.value);
+ expect(new Set(values).size).toBe(14);
+ expect(JOB_STAGES.map((s) => s.sortOrder)).toEqual(
+ JOB_STAGES.map((_, i) => i),
+ );
+ });
+
+ it("stores each value as the canonical form of its own label", () => {
+ for (const stage of JOB_STAGES) {
+ expect(stage.value).toBe(canonicalizeEntityValue(stage.label));
+ }
+ });
+
+ it("points every stage at a real JobStatus value", () => {
+ const statuses = new Set<string>(JOB_STATUSES.map((s) => s.value));
+ for (const stage of JOB_STAGES) {
+ expect(statuses.has(stage.status)).toBe(true);
+ }
+ });
+
+ // Decision 19: the mapping must be total in both directions, so every
+ // status has exactly one status-named stage type to resolve back to.
+ it("carries exactly one status-named stage per JobStatus", () => {
+ for (const status of JOB_STATUSES) {
+ const named = JOB_STAGES.filter(
+ (s) => s.value === canonicalizeEntityValue(status.label),
+ );
+ expect(named).toHaveLength(1);
+ expect(named[0].status).toBe(status.value);
+ }
+ });
+
+ it("adds withdrawn as an appended status with a slate badge", () => {
+ expect(JOB_STATUSES[JOB_STATUSES.length - 1]).toEqual({
+ label: "Withdrawn",
+ value: "withdrawn",
+ });
+ expect(JOB_STATUS_BADGE_COLORS.withdrawn).toBe("slate");
+ });
+});
diff --git a/__tests__/resolveJobStageType.spec.ts b/__tests__/resolveJobStageType.spec.ts
new file mode 100644
index 0000000..c4dc66c
--- /dev/null
+++ b/__tests__/resolveJobStageType.spec.ts
@@ -0,0 +1,143 @@
+import {
+ resolveJobStageType,
+ resolveStageTypeForStatusId,
+} from "@/lib/jobs/resolve";
+import prisma from "@/lib/db";
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ jobStageType: {
+ findUnique: vi.fn(),
+ create: vi.fn(),
+ aggregate: vi.fn(),
+ },
+ jobStatus: { findUnique: vi.fn() },
+ },
+}));
+
+const db = prisma as any;
+
+describe("resolveJobStageType", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ db.jobStageType.aggregate.mockResolvedValue({ _max: { sortOrder: 13 } });
+ });
+
+ it("matches an existing type on canonical value", async () => {
+ db.jobStageType.findUnique.mockResolvedValue({ id: "t1", label: "On-site" });
+
+ const res = await resolveJobStageType(" ON-SITE ", "u1", "s1");
+
+ expect(db.jobStageType.findUnique).toHaveBeenCalledWith({
+ where: { value_createdBy: { value: "on-site", createdBy: "u1" } },
+ });
+ expect(res).toEqual({ id: "t1", label: "On-site", created: false });
+ expect(db.jobStageType.create).not.toHaveBeenCalled();
+ });
+
+ // D7: canonicalizeEntityValue folds case, diacritics, commas and whitespace
+ // and nothing else, so "On-site" and "Onsite" are genuinely two types. This
+ // test pins the limit so nobody later reads the resolver as fuzzy matching.
+ it("does not fold hyphens, so On-site and Onsite are different types", async () => {
+ db.jobStageType.findUnique.mockResolvedValue(null);
+ db.jobStageType.create.mockResolvedValue({ id: "t9", label: "Onsite" });
+
+ await resolveJobStageType("Onsite", "u1", "s1");
+
+ expect(db.jobStageType.findUnique).toHaveBeenCalledWith({
+ where: { value_createdBy: { value: "onsite", createdBy: "u1" } },
+ });
+ expect(db.jobStageType.create).toHaveBeenCalled();
+ });
+
+ // Only `value` collapses internal whitespace; the label is stored trimmed
+ // but otherwise verbatim, exactly as resolveEntity does for the other five.
+ it("creates with the trimmed label, canonical value and the next sortOrder", async () => {
+ db.jobStageType.findUnique.mockResolvedValue(null);
+ db.jobStageType.create.mockResolvedValue({
+ id: "t2",
+ label: "Panel Interview",
+ });
+
+ const res = await resolveJobStageType(" Panel Interview ", "u1", "s9");
+
+ expect(db.jobStageType.create).toHaveBeenCalledWith({
+ data: {
+ label: "Panel Interview",
+ value: "panel interview",
+ statusId: "s9",
+ sortOrder: 14,
+ createdBy: "u1",
+ },
+ });
+ expect(res.created).toBe(true);
+ });
+
+ it("returns the winner's row when a concurrent create wins the unique race", async () => {
+ db.jobStageType.findUnique
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ id: "t3", label: "Panel" });
+ db.jobStageType.create.mockRejectedValue({ code: "P2002" });
+
+ const res = await resolveJobStageType("Panel", "u1", "s1");
+
+ expect(res).toEqual({ id: "t3", label: "Panel", created: false });
+ });
+
+ it("rejects an empty label", async () => {
+ await expect(resolveJobStageType(" ", "u1", "s1")).rejects.toThrow(
+ "A non-empty label is required",
+ );
+ });
+});
+
+describe("resolveStageTypeForStatusId", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ db.jobStageType.aggregate.mockResolvedValue({ _max: { sortOrder: 13 } });
+ });
+
+ // The two hyphenated offer statuses are why the key is the canonical LABEL
+ // and not status.value: "offer-accepted" would never match the seeded row.
+ it("looks the type up by the canonical form of the status label", async () => {
+ db.jobStatus.findUnique.mockResolvedValue({
+ id: "s-oa",
+ label: "Offer Accepted",
+ value: "offer-accepted",
+ });
+ db.jobStageType.findUnique.mockResolvedValue({
+ id: "t-oa",
+ label: "Offer Accepted",
+ });
+
+ const id = await resolveStageTypeForStatusId("s-oa", "u1");
+
+ expect(db.jobStageType.findUnique).toHaveBeenCalledWith({
+ where: { value_createdBy: { value: "offer accepted", createdBy: "u1" } },
+ });
+ expect(id).toBe("t-oa");
+ });
+
+ it("creates the status-named type when the user has deleted it", async () => {
+ db.jobStatus.findUnique.mockResolvedValue({
+ id: "s-w",
+ label: "Withdrawn",
+ value: "withdrawn",
+ });
+ db.jobStageType.findUnique.mockResolvedValue(null);
+ db.jobStageType.create.mockResolvedValue({ id: "t-w", label: "Withdrawn" });
+
+ const id = await resolveStageTypeForStatusId("s-w", "u1");
+
+ expect(id).toBe("t-w");
+ expect(db.jobStageType.create).toHaveBeenCalled();
+ });
+
+ it("throws when the status does not exist", async () => {
+ db.jobStatus.findUnique.mockResolvedValue(null);
+
+ await expect(resolveStageTypeForStatusId("nope", "u1")).rejects.toThrow(
+ "Job status not found",
+ );
+ });
+});
diff --git a/prisma/migrations/20260919144828_job_stages_timeline/migration.sql b/prisma/migrations/20260919144828_job_stages_timeline/migration.sql
new file mode 100644
index 0000000..53f449b
--- /dev/null
+++ b/prisma/migrations/20260919144828_job_stages_timeline/migration.sql
@@ -0,0 +1,237 @@
+/*
+ Warnings:
+
+ - You are about to drop the `Interview` table. If the table is not empty, all the data it contains will be lost.
+ - You are about to drop the column `interviewId` on the `Contact` table. All the data in the column will be lost.
+
+*/
+-- Data-only: JobStatus rows are seeded at signup, so existing databases need
+-- the new status inserted. Shape copied from 20260904000000_job_status_offer_outcomes.
+INSERT OR IGNORE INTO "JobStatus" ("id", "label", "value") VALUES
+ ('3f2b6c41-88d5-4a0e-9d0a-6a1c9f0b7e22', 'Withdrawn', 'withdrawn');
+
+-- CreateTable
+CREATE TABLE "JobStageType" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "label" TEXT NOT NULL,
+ "value" TEXT NOT NULL,
+ "statusId" TEXT NOT NULL,
+ "sortOrder" INTEGER NOT NULL DEFAULT 0,
+ "createdBy" TEXT NOT NULL,
+ CONSTRAINT "JobStageType_statusId_fkey" FOREIGN KEY ("statusId") REFERENCES "JobStatus" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "JobStageType_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateTable
+CREATE TABLE "JobStage" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "jobId" TEXT NOT NULL,
+ "stageTypeId" TEXT NOT NULL,
+ "occurredAt" DATETIME,
+ "isCurrent" BOOLEAN NOT NULL DEFAULT false,
+ "outcome" TEXT,
+ "notes" TEXT,
+ "durationMins" INTEGER,
+ "format" TEXT,
+ "location" TEXT,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ CONSTRAINT "JobStage_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "Job" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "JobStage_stageTypeId_fkey" FOREIGN KEY ("stageTypeId") REFERENCES "JobStageType" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateTable
+CREATE TABLE "JobStageInterviewer" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "stageId" TEXT NOT NULL,
+ "contactId" TEXT NOT NULL,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT "JobStageInterviewer_stageId_fkey" FOREIGN KEY ("stageId") REFERENCES "JobStage" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "JobStageInterviewer_contactId_fkey" FOREIGN KEY ("contactId") REFERENCES "Contact" ("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+-- CreateTable
+CREATE TABLE "JobStagePrepQuestion" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "stageId" TEXT NOT NULL,
+ "questionId" TEXT NOT NULL,
+ "asked" BOOLEAN NOT NULL DEFAULT false,
+ "askedAt" DATETIME,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT "JobStagePrepQuestion_stageId_fkey" FOREIGN KEY ("stageId") REFERENCES "JobStage" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "JobStagePrepQuestion_questionId_fkey" FOREIGN KEY ("questionId") REFERENCES "Question" ("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,
+ "roleId" TEXT,
+ "notes" TEXT,
+ "lastContactedAt" DATETIME,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ 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_roleId_fkey" FOREIGN KEY ("roleId") REFERENCES "ContactRole" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT "Contact_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+INSERT INTO "new_Contact" ("companyId", "createdAt", "createdBy", "email", "id", "lastContactedAt", "linkedinUrl", "locationId", "name", "notes", "phone", "relationship", "roleId", "title", "updatedAt", "workedAtCompanyId", "workedFrom", "workedTo") SELECT "companyId", "createdAt", "createdBy", "email", "id", "lastContactedAt", "linkedinUrl", "locationId", "name", "notes", "phone", "relationship", "roleId", "title", "updatedAt", "workedAtCompanyId", "workedFrom", "workedTo" 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");
+CREATE INDEX "Contact_roleId_idx" ON "Contact"("roleId");
+PRAGMA foreign_keys=ON;
+PRAGMA defer_foreign_keys=OFF;
+
+-- DropTable
+-- After the Contact redefinition: the old Contact still holds the interviewId
+-- FK into Interview until the rename completes.
+PRAGMA foreign_keys=off;
+DROP TABLE "Interview";
+PRAGMA foreign_keys=on;
+
+-- CreateIndex
+CREATE INDEX "JobStageType_createdBy_idx" ON "JobStageType"("createdBy");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "JobStageType_value_createdBy_key" ON "JobStageType"("value", "createdBy");
+
+-- CreateIndex
+CREATE INDEX "JobStage_jobId_idx" ON "JobStage"("jobId");
+
+-- CreateIndex
+CREATE INDEX "JobStage_stageTypeId_idx" ON "JobStage"("stageTypeId");
+
+-- Exactly one current stage per job. Partial index (not expressible in the
+-- Prisma DSL) so historical stages are unaffected. Same mechanism as
+-- 20260710000001_automation_run_single_active.
+CREATE UNIQUE INDEX "JobStage_jobId_current_key"
+ON "JobStage"("jobId")
+WHERE "isCurrent" = 1;
+
+-- CreateIndex
+CREATE INDEX "JobStageInterviewer_contactId_idx" ON "JobStageInterviewer"("contactId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "JobStageInterviewer_stageId_contactId_key" ON "JobStageInterviewer"("stageId", "contactId");
+
+-- CreateIndex
+CREATE INDEX "JobStagePrepQuestion_questionId_idx" ON "JobStagePrepQuestion"("questionId");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "JobStagePrepQuestion_stageId_questionId_key" ON "JobStagePrepQuestion"("stageId", "questionId");
+
+-- Seed the fourteen default stage types for existing users. New accounts get
+-- these from signup(). `value` is canonicalizeEntityValue(label), which is how
+-- a status resolves back to its stage type (no isDefaultForStatus column).
+INSERT INTO "JobStageType" ("id", "label", "value", "statusId", "sortOrder", "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)
+), t."label", t."value", s."id", t."sortOrder", u."id"
+FROM "User" u
+CROSS JOIN (
+ SELECT 'New' AS "label", 'new' AS "value", 'new' AS "status", 0 AS "sortOrder"
+ UNION ALL SELECT 'Draft', 'draft', 'draft', 1
+ UNION ALL SELECT 'Applied', 'applied', 'applied', 2
+ UNION ALL SELECT 'Interview', 'interview', 'interview', 3
+ UNION ALL SELECT '1st Screening Interview', '1st screening interview', 'interview', 4
+ UNION ALL SELECT '2nd Technical Interview', '2nd technical interview', 'interview', 5
+ UNION ALL SELECT 'Final / Onsite Interview', 'final / onsite interview', 'interview', 6
+ UNION ALL SELECT 'Offer', 'offer', 'offer', 7
+ UNION ALL SELECT 'Offer Accepted', 'offer accepted', 'offer-accepted', 8
+ UNION ALL SELECT 'Offer Declined', 'offer declined', 'offer-declined', 9
+ UNION ALL SELECT 'Rejected', 'rejected', 'rejected', 10
+ UNION ALL SELECT 'Expired', 'expired', 'expired', 11
+ UNION ALL SELECT 'Archived', 'archived', 'archived', 12
+ UNION ALL SELECT 'Withdrawn', 'withdrawn', 'withdrawn', 13
+) t
+JOIN "JobStatus" s ON s."value" = t."status";
+
+-- Backfill, part 1 of 4: a New stage at Job.createdAt for every job. The
+-- createdAt offsets below are deliberate: stages tiebreak on createdAt when
+-- occurredAt is null, and CURRENT_TIMESTAMP is constant within a statement.
+INSERT INTO "JobStage" ("id", "jobId", "stageTypeId", "occurredAt", "isCurrent", "createdAt", "updatedAt")
+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)
+), j."id", t."id", j."createdAt", 0,
+ datetime('now', '-3 seconds'), datetime('now', '-3 seconds')
+FROM "Job" j
+JOIN "JobStageType" t ON t."createdBy" = j."userId" AND t."value" = 'new';
+
+-- Backfill, part 2 of 4: an Applied stage at Job.appliedDate, only where the
+-- job is actually applied. appliedDate is taken verbatim — a null one leaves
+-- the stage undated rather than inventing a timestamp.
+INSERT INTO "JobStage" ("id", "jobId", "stageTypeId", "occurredAt", "isCurrent", "createdAt", "updatedAt")
+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)
+), j."id", t."id", j."appliedDate", 0,
+ datetime('now', '-2 seconds'), datetime('now', '-2 seconds')
+FROM "Job" j
+JOIN "JobStageType" t ON t."createdBy" = j."userId" AND t."value" = 'applied'
+WHERE j."applied" = 1;
+
+-- Backfill, part 3 of 4: an undated stage matching the job's current status,
+-- marked current. Skipped where it would repeat one of the two stages above —
+-- a job still at New, or at Applied with an Applied stage already written.
+-- The CASE is the status -> stage-type reverse lookup: canonical form of the
+-- status LABEL, which differs from status.value for the two offer outcomes.
+INSERT INTO "JobStage" ("id", "jobId", "stageTypeId", "occurredAt", "isCurrent", "createdAt", "updatedAt")
+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)
+), j."id", t."id", NULL, 1,
+ datetime('now', '-1 seconds'), datetime('now', '-1 seconds')
+FROM "Job" j
+JOIN "JobStatus" s ON s."id" = j."statusId"
+JOIN "JobStageType" t ON t."createdBy" = j."userId" AND t."value" = CASE s."value"
+ WHEN 'offer-accepted' THEN 'offer accepted'
+ WHEN 'offer-declined' THEN 'offer declined'
+ ELSE s."value"
+END
+WHERE s."value" <> 'new'
+ AND NOT (s."value" = 'applied' AND j."applied" = 1);
+
+-- Backfill, part 4 of 4: where part 3 was skipped, the already-written dated
+-- stage becomes the current one. Every backfilled job now has exactly one.
+UPDATE "JobStage" SET "isCurrent" = 1
+WHERE "id" IN (
+ SELECT st."id"
+ FROM "JobStage" st
+ JOIN "Job" j ON j."id" = st."jobId"
+ JOIN "JobStatus" s ON s."id" = j."statusId"
+ JOIN "JobStageType" t ON t."id" = st."stageTypeId"
+ WHERE (s."value" = 'new' AND t."value" = 'new')
+ OR (s."value" = 'applied' AND j."applied" = 1 AND t."value" = 'applied')
+);
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 17c4466..475c389 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -25,6 +25,7 @@ model User {
JobSource JobSource[]
Contact Contact[]
ContactRole ContactRole[]
+ JobStageType JobStageType[]
Profile Profile[]
Activity Activity[]
ActivityType ActivityType[]
@@ -241,10 +242,8 @@ model Contact {
createdBy String // userId
user User @relation(fields: [createdBy], references: [id])
- Interview Interview? @relation(fields: [interviewId], references: [id])
- interviewId String?
-
jobLinks JobContact[]
+ stageLinks JobStageInterviewer[]
@@index([createdBy])
@@index([companyId])
@@ -295,6 +294,7 @@ model JobStatus {
label String
value String @unique
jobs Job[]
+ stageTypes JobStageType[]
}
model Location {
@@ -356,12 +356,77 @@ model JobSource {
@@unique([value, createdBy])
}
-model Interview {
- id String @id @default(uuid())
- createdAt DateTime
- jobId String
- job Job? @relation(fields: [jobId], references: [id])
- interviewers Contact[]
+// The kind of stage. Mirrors ContactRole in ownership and resolution, and
+// JobSource in being user-extensible. statusId is both the derived-status
+// source and the interview-kind discriminator (spec decisions 3 and 10).
+model JobStageType {
+ id String @id @default(uuid())
+ label String
+ value String
+ statusId String
+ Status JobStatus @relation(fields: [statusId], references: [id])
+ sortOrder Int @default(0)
+ createdBy String // userId
+ user User @relation(fields: [createdBy], references: [id])
+ stages JobStage[]
+
+ @@unique([value, createdBy])
+ @@index([createdBy])
+}
+
+// One entry in a job's timeline. No ownership column: a stage has no meaning
+// apart from its job, so ownership traverses Job: { userId }.
+model JobStage {
+ id String @id @default(uuid())
+ jobId String
+ Job Job @relation(fields: [jobId], references: [id], onDelete: Cascade)
+ stageTypeId String
+ StageType JobStageType @relation(fields: [stageTypeId], references: [id])
+ occurredAt DateTime?
+ isCurrent Boolean @default(false)
+ outcome String?
+ notes String?
+ durationMins Int?
+ format String?
+ location String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ interviewers JobStageInterviewer[]
+ prepQuestions JobStagePrepQuestion[]
+
+ @@index([jobId])
+ @@index([stageTypeId])
+ // Also has a hand-written partial unique index (not expressible here):
+ // UNIQUE(jobId) WHERE isCurrent = 1
+ // See migrations/20260919000000_job_stages_timeline
+}
+
+model JobStageInterviewer {
+ id String @id @default(uuid())
+ stageId String
+ Stage JobStage @relation(fields: [stageId], references: [id], onDelete: Cascade)
+ contactId String
+ Contact Contact @relation(fields: [contactId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now())
+
+ @@unique([stageId, contactId])
+ @@index([contactId])
+}
+
+// questionId is deliberately NOT cascading: erasing the record that a question
+// was asked in a real interview is worse than a delete that fails loudly.
+model JobStagePrepQuestion {
+ id String @id @default(uuid())
+ stageId String
+ Stage JobStage @relation(fields: [stageId], references: [id], onDelete: Cascade)
+ questionId String
+ Question Question @relation(fields: [questionId], references: [id])
+ asked Boolean @default(false)
+ askedAt DateTime?
+ createdAt DateTime @default(now())
+
+ @@unique([stageId, questionId])
+ @@index([questionId])
}
model Job {
@@ -387,7 +452,6 @@ model Job {
salaryRange String?
Location Location? @relation(fields: [locationId], references: [id])
locationId String?
- Interview Interview[]
Resume Resume? @relation(fields: [resumeId], references: [id])
resumeId String?
CoverLetter CoverLetter? @relation(fields: [coverLetterId], references: [id])
@@ -395,6 +459,7 @@ model Job {
Notes Note[]
tags Tag[]
contactLinks JobContact[]
+ stages JobStage[]
// Automation discovery fields
automationId String?
@@ -589,6 +654,7 @@ model Question {
createdBy String
user User @relation(fields: [createdBy], references: [id])
tags Tag[]
+ prepLinks JobStagePrepQuestion[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdVia String? // MCP provenance: which agent/token created this, mirrors Job.createdVia
diff --git a/src/actions/auth.actions.ts b/src/actions/auth.actions.ts
index 47aa2b1..18e8cbc 100644
--- a/src/actions/auth.actions.ts
+++ b/src/actions/auth.actions.ts
@@ -5,7 +5,12 @@ import { delay } from "@/utils/delay";
import prisma from "@/lib/db";
import bcrypt from "bcryptjs";
import { SignupFormSchema } from "@/models/signupForm.schema";
-import { CONTACT_ROLES, JOB_SOURCES, JOB_STATUSES } from "@/lib/constants";
+import {
+ CONTACT_ROLES,
+ JOB_SOURCES,
+ JOB_STAGES,
+ JOB_STATUSES,
+} from "@/lib/constants";
export async function signup(formData: {
name: string;
@@ -57,6 +62,21 @@ export async function signup(formData: {
});
}
+ // Stage types point at JobStatus, so this must follow the upsert loop.
+ const statusRows = await prisma.jobStatus.findMany({
+ select: { id: true, value: true },
+ });
+ const statusIdByValue = new Map(statusRows.map((s) => [s.value, s.id]));
+ await prisma.jobStageType.createMany({
+ data: JOB_STAGES.map((stage) => ({
+ label: stage.label,
+ value: stage.value,
+ statusId: statusIdByValue.get(stage.status)!,
+ sortOrder: stage.sortOrder,
+ createdBy: newUser.id,
+ })),
+ });
+
return { success: true };
}
diff --git a/src/actions/mock.actions.ts b/src/actions/mock.actions.ts
index 03e014d..cd74816 100644
--- a/src/actions/mock.actions.ts
+++ b/src/actions/mock.actions.ts
@@ -611,7 +611,6 @@ export const clearMockJobsAction = async (): Promise<any> => {
// Delete related records first (FK constraints)
await prisma.note.deleteMany({ where: { jobId: { in: jobIds } } });
- await prisma.interview.deleteMany({ where: { jobId: { in: jobIds } } });
// Disconnect tags (M2M)
await Promise.all(
diff --git a/src/lib/badge-colors.ts b/src/lib/badge-colors.ts
index c6fdd61..e3bd808 100644
--- a/src/lib/badge-colors.ts
+++ b/src/lib/badge-colors.ts
@@ -29,6 +29,7 @@ export const JOB_STATUS_BADGE_COLORS: Record<JobStatusValue, BadgeColor> = {
rejected: "red",
expired: "amber",
archived: "slate",
+ withdrawn: "slate",
};
// job.Status.value is a plain string from the DB, not the literal union,
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 9944fe3..ec6cdce 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -301,6 +301,44 @@ export const JOB_STATUSES = [
{ label: "Rejected", value: "rejected" },
{ label: "Expired", value: "expired" },
{ label: "Archived", value: "archived" },
+ { label: "Withdrawn", value: "withdrawn" },
+] as const;
+
+// Seeded per user at signup and backfilled by the stages migration. `value`
+// must equal canonicalizeEntityValue(label): the status -> stage-type reverse
+// lookup keys on the status LABEL's canonical form, not on status.value, so
+// "Offer Accepted" cannot mint a second type beside "offer-accepted".
+export const JOB_STAGES = [
+ { label: "New", value: "new", status: "new", sortOrder: 0 },
+ { label: "Draft", value: "draft", status: "draft", sortOrder: 1 },
+ { label: "Applied", value: "applied", status: "applied", sortOrder: 2 },
+ { label: "Interview", value: "interview", status: "interview", sortOrder: 3 },
+ { label: "1st Screening Interview", value: "1st screening interview", status: "interview", sortOrder: 4 },
+ { label: "2nd Technical Interview", value: "2nd technical interview", status: "interview", sortOrder: 5 },
+ { label: "Final / Onsite Interview", value: "final / onsite interview", status: "interview", sortOrder: 6 },
+ { label: "Offer", value: "offer", status: "offer", sortOrder: 7 },
+ { label: "Offer Accepted", value: "offer accepted", status: "offer-accepted", sortOrder: 8 },
+ { label: "Offer Declined", value: "offer declined", status: "offer-declined", sortOrder: 9 },
+ { label: "Rejected", value: "rejected", status: "rejected", sortOrder: 10 },
+ { label: "Expired", value: "expired", status: "expired", sortOrder: 11 },
+ { label: "Archived", value: "archived", status: "archived", sortOrder: 12 },
+ { label: "Withdrawn", value: "withdrawn", status: "withdrawn", sortOrder: 13 },
+] as const;
+
+// Statuses whose stage types render greyed at the tail of the stepper when the
+// job has not reached them (D6). Offer alone: the greyed tail reads as what a
+// job is working toward, and rejected/withdrawn are alternative endings, not
+// next steps. Both stay one click away in Add Stage.
+export const TERMINAL_STAGE_STATUSES = ["offer"] as const;
+
+// The fixed outcome set a stage may carry (spec's JobStage.outcome).
+export const STAGE_OUTCOMES = [
+ { label: "Scheduled", value: "scheduled" },
+ { label: "Completed", value: "completed" },
+ { label: "Passed", value: "passed" },
+ { label: "Failed", value: "failed" },
+ { label: "No-show", value: "no-show" },
+ { label: "Cancelled", value: "cancelled" },
] as const;
// Zod's z.enum needs a non-empty tuple; JOB_STATUSES is the source of truth.
diff --git a/src/lib/data/jobStatusesData.ts b/src/lib/data/jobStatusesData.ts
index e8a04d7..414c97f 100644
--- a/src/lib/data/jobStatusesData.ts
+++ b/src/lib/data/jobStatusesData.ts
@@ -44,4 +44,9 @@ export const JOB_STATUSES = [
label: "Archived",
value: "archived",
},
+ {
+ id: "3f2b6c41-88d5-4a0e-9d0a-6a1c9f0b7e22",
+ label: "Withdrawn",
+ value: "withdrawn",
+ },
];
diff --git a/src/lib/jobs/resolve.ts b/src/lib/jobs/resolve.ts
index ee49334..b143b39 100644
--- a/src/lib/jobs/resolve.ts
+++ b/src/lib/jobs/resolve.ts
@@ -153,6 +153,66 @@ export async function resolveTags(
return { resolved, dropped };
}
+// Not resolveEntity: that delegate creates exactly { label, value, createdBy }
+// and cannot carry statusId and sortOrder, so the pattern is followed rather
+// than the function reused (spec decision 3).
+export async function resolveJobStageType(
+ label: string,
+ userId: string,
+ statusId: string,
+): Promise<ResolvedEntity> {
+ const trimmed = label.trim();
+ const value = canonicalizeEntityValue(trimmed);
+ if (!value) throw new Error("A non-empty label is required");
+
+ const existing = await prisma.jobStageType.findUnique({
+ where: { value_createdBy: { value, createdBy: userId } },
+ });
+ if (existing) return { id: existing.id, label: existing.label, created: false };
+
+ const max = await prisma.jobStageType.aggregate({
+ where: { createdBy: userId },
+ _max: { sortOrder: true },
+ });
+
+ try {
+ const created = await prisma.jobStageType.create({
+ data: {
+ label: trimmed,
+ value,
+ statusId,
+ sortOrder: (max._max.sortOrder ?? -1) + 1,
+ createdBy: userId,
+ },
+ });
+ return { id: created.id, label: created.label, created: true };
+ } catch (err: any) {
+ if (err?.code === "P2002") {
+ const winner = await prisma.jobStageType.findUnique({
+ where: { value_createdBy: { value, createdBy: userId } },
+ });
+ if (winner) return { id: winner.id, label: winner.label, created: false };
+ }
+ throw err;
+ }
+}
+
+// The status -> stage-type reverse lookup. Keyed on the canonical form of the
+// status LABEL, not status.value: canonicalizeEntityValue("Offer Accepted") is
+// "offer accepted", so keying on "offer-accepted" would mint a duplicate.
+export async function resolveStageTypeForStatusId(
+ statusId: string,
+ userId: string,
+): Promise<string> {
+ const status = await prisma.jobStatus.findUnique({
+ where: { id: statusId },
+ select: { id: true, label: true },
+ });
+ if (!status) throw new Error("Job status not found");
+ const resolved = await resolveJobStageType(status.label, userId, status.id);
+ return resolved.id;
+}
+
// Bucket B — resolve-ONLY, never create
// A caller-correctable bad value, as opposed to a database or programming