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 prep-list link, remove and asked actions, and guard question deletion

Khuram Niaz83d2f9fb1c32
diff --git a/__tests__/jobStagePrep.spec.ts b/__tests__/jobStagePrep.spec.ts
new file mode 100644
index 0000000..b5e5527
--- /dev/null
+++ b/__tests__/jobStagePrep.spec.ts
@@ -0,0 +1,181 @@
+import {
+ addStagePrepQuestions,
+ removeStagePrepQuestion,
+ setPrepQuestionAsked,
+} from "@/actions/jobStage.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import prisma from "@/lib/db";
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ jobStage: { findFirst: vi.fn() },
+ question: { count: vi.fn() },
+ jobStagePrepQuestion: {
+ createMany: vi.fn(),
+ findMany: vi.fn(),
+ deleteMany: vi.fn(),
+ updateMany: vi.fn(),
+ findFirst: vi.fn(),
+ },
+ },
+}));
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+
+const db = prisma as any;
+const user = { id: "user-1" };
+
+const interviewStage = {
+ id: "st1",
+ jobId: "j1",
+ occurredAt: null,
+ isCurrent: true,
+ StageType: {
+ id: "t-int",
+ label: "Final / Onsite Interview",
+ statusId: "s-int",
+ Status: { value: "interview" },
+ },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(user);
+ db.jobStage.findFirst.mockResolvedValue(interviewStage);
+ db.question.count.mockResolvedValue(2);
+ db.jobStagePrepQuestion.createMany.mockResolvedValue({ count: 2 });
+ db.jobStagePrepQuestion.findMany.mockResolvedValue([]);
+});
+
+describe("addStagePrepQuestions", () => {
+ // The question count must match the ids passed, or this fails on ownership
+ // and never reaches the gate it claims to test.
+ it("refuses a stage that is not an interview stage", async () => {
+ db.jobStage.findFirst.mockResolvedValue({
+ ...interviewStage,
+ StageType: { id: "t-app", label: "Applied", statusId: "s-app", Status: { value: "applied" } },
+ });
+ db.question.count.mockResolvedValue(1);
+
+ const res = await addStagePrepQuestions("st1", ["q1"]);
+
+ expect(res.success).toBe(false);
+ expect(res.message).toContain("not an interview stage");
+ expect(res.message).toContain("Applied");
+ expect(db.jobStagePrepQuestion.createMany).not.toHaveBeenCalled();
+ });
+
+ it("refuses when any question belongs to someone else", async () => {
+ db.question.count.mockResolvedValue(1);
+
+ const res = await addStagePrepQuestions("st1", ["q1", "someone-elses"]);
+
+ expect(res.success).toBe(false);
+ expect(db.jobStagePrepQuestion.createMany).not.toHaveBeenCalled();
+ });
+
+ it("links every question unasked", async () => {
+ const res = await addStagePrepQuestions("st1", ["q1", "q2"]);
+
+ expect(res.success).toBe(true);
+ expect(db.jobStagePrepQuestion.createMany).toHaveBeenCalledWith({
+ data: [
+ { stageId: "st1", questionId: "q1", asked: false },
+ { stageId: "st1", questionId: "q2", asked: false },
+ ],
+ });
+ });
+
+ // SQLite has no skipDuplicates, so the subtraction is ours to get right.
+ it("skips questions already on the stage's prep list", async () => {
+ db.jobStagePrepQuestion.findMany.mockResolvedValueOnce([
+ { questionId: "q1" },
+ ]);
+
+ await addStagePrepQuestions("st1", ["q1", "q2"]);
+
+ expect(db.jobStagePrepQuestion.createMany).toHaveBeenCalledWith({
+ data: [{ stageId: "st1", questionId: "q2", asked: false }],
+ });
+ });
+
+ it("writes nothing when every question is already linked", async () => {
+ db.jobStagePrepQuestion.findMany.mockResolvedValueOnce([
+ { questionId: "q1" },
+ { questionId: "q2" },
+ ]);
+
+ const res = await addStagePrepQuestions("st1", ["q1", "q2"]);
+
+ expect(res.success).toBe(true);
+ expect(db.jobStagePrepQuestion.createMany).not.toHaveBeenCalled();
+ });
+
+ it("rejects an empty selection", async () => {
+ const res = await addStagePrepQuestions("st1", []);
+
+ expect(res.success).toBe(false);
+ expect(db.jobStagePrepQuestion.createMany).not.toHaveBeenCalled();
+ });
+});
+
+describe("setPrepQuestionAsked", () => {
+ it("records askedAt when marking asked", async () => {
+ db.jobStagePrepQuestion.updateMany.mockResolvedValue({ count: 1 });
+ db.jobStagePrepQuestion.findFirst.mockResolvedValue({
+ id: "p1",
+ asked: true,
+ askedAt: new Date(),
+ });
+
+ const res = await setPrepQuestionAsked("p1", true);
+
+ expect(res.success).toBe(true);
+ const call = db.jobStagePrepQuestion.updateMany.mock.calls[0][0];
+ expect(call.where).toEqual({
+ id: "p1",
+ Stage: { Job: { userId: user.id } },
+ Question: { createdBy: user.id },
+ });
+ expect(call.data.asked).toBe(true);
+ expect(call.data.askedAt).toBeInstanceOf(Date);
+ });
+
+ it("clears askedAt when unmarking", async () => {
+ db.jobStagePrepQuestion.updateMany.mockResolvedValue({ count: 1 });
+ db.jobStagePrepQuestion.findFirst.mockResolvedValue({
+ id: "p1",
+ asked: false,
+ askedAt: null,
+ });
+
+ await setPrepQuestionAsked("p1", false);
+
+ expect(db.jobStagePrepQuestion.updateMany.mock.calls[0][0].data).toEqual({
+ asked: false,
+ askedAt: null,
+ });
+ });
+
+ it("fails when the row belongs to someone else", async () => {
+ db.jobStagePrepQuestion.updateMany.mockResolvedValue({ count: 0 });
+
+ const res = await setPrepQuestionAsked("someone-elses", true);
+
+ expect(res.success).toBe(false);
+ });
+});
+
+describe("removeStagePrepQuestion", () => {
+ it("deletes through both ownership chains", async () => {
+ db.jobStagePrepQuestion.deleteMany.mockResolvedValue({ count: 1 });
+
+ const res = await removeStagePrepQuestion("p1");
+
+ expect(res.success).toBe(true);
+ expect(db.jobStagePrepQuestion.deleteMany.mock.calls[0][0].where).toEqual({
+ id: "p1",
+ Stage: { Job: { userId: user.id } },
+ Question: { createdBy: user.id },
+ });
+ });
+});
diff --git a/__tests__/question.actions.spec.ts b/__tests__/question.actions.spec.ts
index 4ad1300..0f7a954 100644
--- a/__tests__/question.actions.spec.ts
+++ b/__tests__/question.actions.spec.ts
@@ -24,6 +24,9 @@ vi.mock("@prisma/client", () => {
tag: {
findMany: vi.fn(),
},
+ jobStagePrepQuestion: {
+ count: vi.fn(),
+ },
};
return { PrismaClient: vi.fn(function() { return mPrismaClient; }) };
});
@@ -47,6 +50,7 @@ describe("Question Actions", () => {
beforeEach(() => {
vi.clearAllMocks();
+ (prisma.jobStagePrepQuestion.count as any).mockResolvedValue(0);
});
// getQuestionsList
@@ -451,6 +455,28 @@ describe("Question Actions", () => {
expect(result).toEqual({ success: false, message: "DB error" });
});
+
+ it("blocks deleting a question that sits on a prep list, naming the count", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.jobStagePrepQuestion.count as any).mockResolvedValue(3);
+
+ const result = await deleteQuestion("q-1");
+
+ expect(result.success).toBe(false);
+ expect(result.message).toContain("3");
+ expect(prisma.question.delete).not.toHaveBeenCalled();
+ });
+
+ it("deletes a question that is on no prep list", async () => {
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ (prisma.jobStagePrepQuestion.count as any).mockResolvedValue(0);
+ (prisma.question.delete as any).mockResolvedValue(mockQuestion);
+
+ const result = await deleteQuestion("q-1");
+
+ expect(result.success).toBe(true);
+ expect(prisma.question.delete).toHaveBeenCalled();
+ });
});
// getTagsWithQuestionCounts
diff --git a/src/actions/jobStage.actions.ts b/src/actions/jobStage.actions.ts
index 74d771c..9ea1200 100644
--- a/src/actions/jobStage.actions.ts
+++ b/src/actions/jobStage.actions.ts
@@ -12,3 +12,8 @@ export {
linkStageInterviewer,
unlinkStageInterviewer,
} from "./jobStage/interviewers";
+export {
+ addStagePrepQuestions,
+ removeStagePrepQuestion,
+ setPrepQuestionAsked,
+} from "./jobStage/prep";
diff --git a/src/actions/jobStage/prep.ts b/src/actions/jobStage/prep.ts
new file mode 100644
index 0000000..626bf6e
--- /dev/null
+++ b/src/actions/jobStage/prep.ts
@@ -0,0 +1,99 @@
+"use server";
+import prisma from "@/lib/db";
+import { handleError } from "@/lib/utils";
+import { requireUser } from "../shared";
+import { assertInterviewStage, assertStageOwned } from "./shared";
+
+const PREP_INCLUDE = {
+ Question: { select: { id: true, question: true, tags: true } },
+};
+
+export const addStagePrepQuestions = async (
+ stageId: string,
+ questionIds: string[],
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ const ids = [...new Set(questionIds)].filter(Boolean);
+ if (ids.length === 0) throw new Error("Pick at least one question");
+
+ const [stage, owned] = await Promise.all([
+ assertStageOwned(stageId, user.id),
+ prisma.question.count({
+ where: { id: { in: ids }, createdBy: user.id },
+ }),
+ ]);
+ // Kind before ownership: the stage is already known to be the caller's,
+ // and "Applied is not an interview stage" is the message that helps.
+ assertInterviewStage(stage);
+ if (owned !== ids.length) throw new Error("Question not found");
+
+ // SQLite has no skipDuplicates, so the already-linked ids are subtracted
+ // here rather than left to the unique index.
+ const linked = await prisma.jobStagePrepQuestion.findMany({
+ where: { stageId, questionId: { in: ids } },
+ select: { questionId: true },
+ });
+ const alreadyLinked = new Set(linked.map((row) => row.questionId));
+ const fresh = ids.filter((id) => !alreadyLinked.has(id));
+ if (fresh.length > 0) {
+ await prisma.jobStagePrepQuestion.createMany({
+ data: fresh.map((questionId) => ({ stageId, questionId, asked: false })),
+ });
+ }
+
+ const data = await prisma.jobStagePrepQuestion.findMany({
+ where: { stageId },
+ include: PREP_INCLUDE,
+ orderBy: { createdAt: "asc" },
+ });
+ return { success: true, data };
+ } catch (error) {
+ return handleError(error, "Failed to add questions to the prep list.");
+ }
+};
+
+export const removeStagePrepQuestion = async (
+ linkId: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ const res = await prisma.jobStagePrepQuestion.deleteMany({
+ where: {
+ id: linkId,
+ Stage: { Job: { userId: user.id } },
+ Question: { createdBy: user.id },
+ },
+ });
+ if (res.count === 0) throw new Error("Prep question not found");
+ return { success: true };
+ } catch (error) {
+ return handleError(error, "Failed to remove the prep question.");
+ }
+};
+
+export const setPrepQuestionAsked = async (
+ linkId: string,
+ asked: boolean,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ const res = await prisma.jobStagePrepQuestion.updateMany({
+ where: {
+ id: linkId,
+ Stage: { Job: { userId: user.id } },
+ Question: { createdBy: user.id },
+ },
+ data: { asked, askedAt: asked ? new Date() : null },
+ });
+ if (res.count === 0) throw new Error("Prep question not found");
+
+ const data = await prisma.jobStagePrepQuestion.findFirst({
+ where: { id: linkId },
+ select: { id: true, asked: true, askedAt: true },
+ });
+ return { success: true, data };
+ } catch (error) {
+ return handleError(error, "Failed to update the prep question.");
+ }
+};
diff --git a/src/actions/question.actions.ts b/src/actions/question.actions.ts
index 24b5612..5d35f51 100644
--- a/src/actions/question.actions.ts
+++ b/src/actions/question.actions.ts
@@ -132,6 +132,17 @@ export const deleteQuestion = async (
try {
const user = await requireUser();
+ // Silently erasing the record that a question was asked in a real
+ // interview is worse than a delete that fails with a reason.
+ const prepRows = await prisma.jobStagePrepQuestion.count({
+ where: { questionId, Question: { createdBy: user.id } },
+ });
+ if (prepRows > 0) {
+ throw new Error(
+ `Question cannot be deleted: it is on the prep list of ${prepRows} interview stage${prepRows === 1 ? "" : "s"}. Remove it from those stages first.`,
+ );
+ }
+
await prisma.question.delete({
where: { id: questionId, createdBy: user.id },
});