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): make updateJobStatus and the Edit Job status field append a current stage, and stop re-stamping appliedDate

Khuram Niaze0bc248ff6ba
diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.ts
index 20703bf..7cb3d40 100644
--- a/__tests__/job.actions.spec.ts
+++ b/__tests__/job.actions.spec.ts
@@ -14,6 +14,7 @@ import {
import { getMockJobDetails, getMockJobsList } from "@/lib/mock.utils";
import { JobResponse } from "@/models/job.model";
import { getCurrentUser } from "@/utils/user.utils";
+import { resolveStageTypeForStatusId } from "@/lib/jobs/resolve";
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
@@ -52,7 +53,17 @@ vi.mock("@prisma/client", () => {
resume: { count: vi.fn() },
coverLetter: { count: vi.fn() },
tag: { count: vi.fn() },
+ jobStage: {
+ findFirst: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ updateMany: vi.fn(),
+ },
+ $transaction: vi.fn(),
};
+ (mPrismaClient.$transaction as any).mockImplementation((fn: any) =>
+ fn(mPrismaClient),
+ );
return {
PrismaClient: vi.fn(function () {
return mPrismaClient;
@@ -60,6 +71,13 @@ vi.mock("@prisma/client", () => {
};
});
+// Only the stage-type resolver is stubbed: the other resolvers in that module
+// are used by addJob and the reference-create actions in this same spec.
+vi.mock("@/lib/jobs/resolve", async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ resolveStageTypeForStatusId: vi.fn(),
+}));
+
vi.mock("@/utils/user.utils", () => ({
getCurrentUser: vi.fn(),
}));
@@ -103,6 +121,12 @@ describe("jobActions", () => {
for (const model of refModels) {
(prisma as any)[model].count.mockResolvedValue(1);
}
+ // Both status write paths now append a stage before updating the job.
+ (prisma as any).$transaction.mockImplementation((fn: any) => fn(prisma));
+ (prisma as any).job.count.mockResolvedValue(1);
+ (prisma as any).jobStage.create.mockResolvedValue({ id: "stage-id" });
+ (prisma as any).jobStage.updateMany.mockResolvedValue({ count: 1 });
+ (resolveStageTypeForStatusId as any).mockResolvedValue("stage-type-id");
});
describe("getStatusList", () => {
it("should return status list on successful query", async () => {
@@ -1212,6 +1236,18 @@ describe("jobActions", () => {
expect(result).toStrictEqual({ data: jobData, success: true });
expect(prisma.job.update).toHaveBeenCalledTimes(1);
});
+ it("appends a status stage when the Edit Job dialog changes the status", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.job.update as any).mockResolvedValue(jobData);
+ (prisma as any).jobStage.findFirst.mockResolvedValue({
+ id: "st-old",
+ StageType: { statusId: "s-old", Status: { value: "applied" } },
+ });
+
+ await updateJob({ ...jobData, status: "s-new" });
+
+ expect((prisma as any).jobStage.create).toHaveBeenCalled();
+ });
it("should handle unexpected errors", async () => {
(getCurrentUser as any).mockResolvedValue(mockUser);
diff --git a/__tests__/jobStatusStage.spec.ts b/__tests__/jobStatusStage.spec.ts
new file mode 100644
index 0000000..69cb021
--- /dev/null
+++ b/__tests__/jobStatusStage.spec.ts
@@ -0,0 +1,157 @@
+import { updateJobStatus } from "@/actions/job.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import prisma from "@/lib/db";
+import { resolveStageTypeForStatusId } from "@/lib/jobs/resolve";
+
+vi.mock("@/lib/db", () => {
+ const jobStage = {
+ findFirst: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ updateMany: vi.fn(),
+ };
+ const job = {
+ update: vi.fn(),
+ findFirst: vi.fn(),
+ count: vi.fn(),
+ };
+ const client = {
+ jobStage,
+ job,
+ $transaction: vi.fn(async (fn: any) => fn(client)),
+ };
+ return { default: client };
+});
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+vi.mock("@/lib/jobs/resolve", () => ({
+ resolveStageTypeForStatusId: vi.fn(),
+}));
+vi.mock("next/cache", () => ({ revalidatePath: vi.fn() }));
+
+const db = prisma as any;
+const user = { id: "user-1" };
+const interview = { id: "s-int", label: "Interview", value: "interview" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(user);
+ (resolveStageTypeForStatusId as any).mockResolvedValue("t-int");
+ db.job.count.mockResolvedValue(1);
+ db.job.findFirst.mockResolvedValue({ appliedDate: null });
+ db.job.update.mockResolvedValue({ id: "j1" });
+ db.jobStage.updateMany.mockResolvedValue({ count: 1 });
+});
+
+describe("updateJobStatus", () => {
+ // The comparison is on PARENT STATUS, not stage type: re-picking Interview
+ // while the current stage is "2nd Technical Interview" must append nothing,
+ // or the timeline reads as a step backwards into screening.
+ it("appends nothing when the current stage already carries that status", async () => {
+ db.jobStage.findFirst.mockResolvedValue({
+ id: "st-tech",
+ StageType: { statusId: "s-int", Status: { value: "interview" } },
+ });
+
+ const res = await updateJobStatus("j1", interview as any);
+
+ expect(res.success).toBe(true);
+ expect(db.jobStage.create).not.toHaveBeenCalled();
+ expect(db.job.update.mock.calls[0][0].data).toEqual({
+ statusId: "s-int",
+ applied: true,
+ });
+ });
+
+ it("appends an undated current stage when the status genuinely changes", async () => {
+ db.jobStage.findFirst.mockResolvedValue({
+ id: "st-app",
+ StageType: { statusId: "s-app", Status: { value: "applied" } },
+ });
+ db.jobStage.create.mockResolvedValue({ id: "st-new" });
+
+ const res = await updateJobStatus("j1", interview as any);
+
+ expect(res.success).toBe(true);
+ expect(db.jobStage.create.mock.calls[0][0].data).toEqual({
+ jobId: "j1",
+ stageTypeId: "t-int",
+ occurredAt: null,
+ isCurrent: false,
+ });
+ // D8: the helper scopes its own writes rather than trusting the caller.
+ expect(db.jobStage.updateMany).toHaveBeenCalledWith({
+ where: {
+ jobId: "j1",
+ isCurrent: true,
+ NOT: { id: "st-new" },
+ Job: { userId: user.id },
+ },
+ data: { isCurrent: false },
+ });
+ });
+
+ // D4: resolving writes through the base client, so it must not happen while
+ // the transaction holds SQLite's write lock.
+ it("resolves the stage type before opening the transaction", async () => {
+ db.jobStage.findFirst.mockResolvedValue(null);
+ db.jobStage.create.mockResolvedValue({ id: "st-first" });
+
+ await updateJobStatus("j1", interview as any);
+
+ const resolveOrder = (resolveStageTypeForStatusId as any).mock
+ .invocationCallOrder[0];
+ const txOrder = (db.$transaction as any).mock.invocationCallOrder[0];
+ expect(resolveOrder).toBeLessThan(txOrder);
+ });
+
+ it("appends a first stage for a stageless job without failing", async () => {
+ db.jobStage.findFirst.mockResolvedValue(null);
+ db.jobStage.create.mockResolvedValue({ id: "st-first" });
+
+ const res = await updateJobStatus("j1", interview as any);
+
+ expect(res.success).toBe(true);
+ expect(db.jobStage.create).toHaveBeenCalled();
+ });
+
+ it("refuses a job the caller does not own before writing a stage", async () => {
+ db.job.count.mockResolvedValue(0);
+
+ const res = await updateJobStatus("someone-elses", interview as any);
+
+ expect(res.success).toBe(false);
+ expect(db.jobStage.create).not.toHaveBeenCalled();
+ });
+
+ it("still writes applied and appliedDate for an Applied pick", async () => {
+ db.jobStage.findFirst.mockResolvedValue(null);
+ db.jobStage.create.mockResolvedValue({ id: "st-app" });
+
+ await updateJobStatus("j1", {
+ id: "s-app",
+ label: "Applied",
+ value: "applied",
+ } as any);
+
+ const data = db.job.update.mock.calls[0][0].data;
+ expect(data.applied).toBe(true);
+ expect(data.appliedDate).toBeInstanceOf(Date);
+ });
+
+ // D5: a deliberate change from today's behaviour, which re-stamped the date
+ // on every Applied pick and moved the job on the dashboard's weekly chart.
+ it("never moves an appliedDate the job already has", async () => {
+ const original = new Date("2026-09-03T00:00:00Z");
+ db.jobStage.findFirst.mockResolvedValue(null);
+ db.jobStage.create.mockResolvedValue({ id: "st-app" });
+ db.job.findFirst.mockResolvedValue({ appliedDate: original });
+
+ await updateJobStatus("j1", {
+ id: "s-app",
+ label: "Applied",
+ value: "applied",
+ } as any);
+
+ expect(db.job.update.mock.calls[0][0].data).not.toHaveProperty("appliedDate");
+ });
+});
diff --git a/src/actions/job/mutations.ts b/src/actions/job/mutations.ts
index 10ac08e..b08b6ff 100644
--- a/src/actions/job/mutations.ts
+++ b/src/actions/job/mutations.ts
@@ -6,6 +6,8 @@ import { AddJobFormSchema } from "@/models/addJobForm.schema";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { requireUser } from "../shared";
+import { appendStatusStage } from "./shared";
+import { resolveStageTypeForStatusId } from "@/lib/jobs/resolve";
type JobRefs = {
jobTitleId?: string | null;
@@ -184,30 +186,38 @@ export const updateJob = async (
tagIds: tagIds.filter((tagId) => !currentTagIds.has(tagId)),
});
- const job = await prisma.job.update({
- where: {
- id,
- userId: user.id,
- },
- data: {
- jobTitleId: title,
- companyId: company,
- locationId: location,
- statusId: status,
- jobSourceId: source,
- salaryRange: salaryRange || null,
- createdAt: new Date(),
- dueDate: dueDate,
- appliedDate: dateApplied,
- description: jobDescription,
- jobType: type,
- workplaceType,
- jobUrl,
- applied,
- resumeId: resume,
- coverLetterId: coverLetter,
- tags: { set: tagIds.map((id) => ({ id })) },
- },
+ // Same D4 rule: resolve before the transaction opens.
+ const stageTypeId = await resolveStageTypeForStatusId(status, user.id);
+
+ const job = await prisma.$transaction(async (tx: any) => {
+ // The Edit Job dialog's Status field is the fourth entry point into the
+ // timeline; without this a job and its stages go permanently out of step.
+ await appendStatusStage(tx, id, status, stageTypeId, user.id);
+ return tx.job.update({
+ where: {
+ id,
+ userId: user.id,
+ },
+ data: {
+ jobTitleId: title,
+ companyId: company,
+ locationId: location,
+ statusId: status,
+ jobSourceId: source,
+ salaryRange: salaryRange || null,
+ createdAt: new Date(),
+ dueDate: dueDate,
+ appliedDate: dateApplied,
+ description: jobDescription,
+ jobType: type,
+ workplaceType,
+ jobUrl,
+ applied,
+ resumeId: resume,
+ coverLetterId: coverLetter,
+ tags: { set: tagIds.map((id) => ({ id })) },
+ },
+ });
});
revalidatePath("/dashboard");
return { success: true, data: job };
diff --git a/src/actions/job/shared.ts b/src/actions/job/shared.ts
index 90fc294..5ebed15 100644
--- a/src/actions/job/shared.ts
+++ b/src/actions/job/shared.ts
@@ -1,6 +1,8 @@
// Not a "use server" module: job/queries.ts and company/queries.ts both map
// job rows through this, and exporting it from either would make it an action.
+import { promoteStage } from "@/actions/jobStage/shared";
+
// An automation job saved without LLM analysis carries only its keyword
// pre-rank in matchScore, which the list must not show as an AI match. The
// matchData body is dropped so the list payload stays small.
@@ -13,3 +15,36 @@ export function hideUnanalyzedScore<
} catch {}
return analyzed ? job : { ...job, matchScore: null };
}
+
+type StatusStageTx = Parameters<typeof promoteStage>[0] & {
+ jobStage: { findFirst: (args: any) => Promise<any>; create: (args: any) => Promise<any> };
+};
+
+// The status dropdowns' half of the derived-status invariant. Compares PARENT
+// STATUS, not stage type: re-picking Interview while the current stage is
+// "2nd Technical Interview" must append nothing (spec decision 16).
+//
+// stageTypeId is an argument, never resolved here: resolveStageTypeForStatusId
+// writes through the base prisma client, and calling it inside the caller's
+// transaction contends for SQLite's write lock (D4).
+export async function appendStatusStage(
+ tx: StatusStageTx,
+ jobId: string,
+ statusId: string,
+ stageTypeId: string,
+ userId: string,
+): Promise<void> {
+ const current = await tx.jobStage.findFirst({
+ where: { jobId, isCurrent: true, Job: { userId } },
+ select: {
+ id: true,
+ StageType: { select: { statusId: true, Status: { select: { value: true } } } },
+ },
+ });
+ if (current?.StageType.statusId === statusId) return;
+
+ const stage = await tx.jobStage.create({
+ data: { jobId, stageTypeId, occurredAt: null, isCurrent: false },
+ });
+ await promoteStage(tx, jobId, stage.id, userId);
+}
diff --git a/src/actions/job/status.ts b/src/actions/job/status.ts
index 41e996a..85e7716 100644
--- a/src/actions/job/status.ts
+++ b/src/actions/job/status.ts
@@ -4,6 +4,9 @@ import { handleError } from "@/lib/utils";
import { JobStatus } from "@/models/job.model";
import { revalidatePath } from "next/cache";
import { requireUser } from "../shared";
+import { appendStatusStage } from "./shared";
+import { jobFieldsForStage } from "../jobStage/shared";
+import { resolveStageTypeForStatusId } from "@/lib/jobs/resolve";
export const updateJobStatus = async (
jobId: string,
@@ -11,33 +14,33 @@ export const updateJobStatus = async (
): Promise<any | undefined> => {
try {
const user = await requireUser();
- const dataToUpdate = () => {
- switch (status.value) {
- case "applied":
- return {
- statusId: status.id,
- applied: true,
- appliedDate: new Date(),
- };
- case "interview":
- return {
- statusId: status.id,
- applied: true,
- };
- default:
- return {
- statusId: status.id,
- };
- }
- };
- const job = await prisma.job.update({
- where: {
- id: jobId,
- userId: user.id,
- },
- data: dataToUpdate(),
+ const owned = await prisma.job.count({
+ where: { id: jobId, userId: user.id },
});
+ if (owned === 0) throw new Error("Job not found");
+
+ // Outside the transaction on purpose: this resolve can create a row, and
+ // it writes through the base client (D4).
+ const stageTypeId = await resolveStageTypeForStatusId(status.id, user.id);
+
+ const job = await prisma.$transaction(async (tx: any) => {
+ await appendStatusStage(tx, jobId, status.id, stageTypeId, user.id);
+ const existing = await tx.job.findFirst({
+ where: { id: jobId, userId: user.id },
+ select: { appliedDate: true },
+ });
+ return tx.job.update({
+ where: { id: jobId, userId: user.id },
+ data: jobFieldsForStage(
+ status.value,
+ status.id,
+ null,
+ existing?.appliedDate ?? null,
+ ),
+ });
+ });
+
revalidatePath("/dashboard");
return { job, success: true };
} catch (error) {