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-type list, create, rename and guarded delete actions

Khuram Niaz3e53d1e683b0
diff --git a/__tests__/jobStageType.actions.spec.ts b/__tests__/jobStageType.actions.spec.ts
new file mode 100644
index 0000000..97e9564
--- /dev/null
+++ b/__tests__/jobStageType.actions.spec.ts
@@ -0,0 +1,104 @@
+import {
+ getAllJobStageTypes,
+ getJobStageTypeList,
+ createJobStageType,
+ deleteJobStageTypeById,
+} from "@/actions/jobStageType.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import prisma from "@/lib/db";
+import { resolveJobStageType } from "@/lib/jobs/resolve";
+
+vi.mock("@/lib/db", () => ({
+ default: {
+ jobStageType: {
+ findMany: vi.fn(),
+ count: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ },
+ jobStage: { count: vi.fn() },
+ jobStatus: { count: vi.fn() },
+ },
+}));
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+vi.mock("@/lib/jobs/resolve", () => ({ resolveJobStageType: vi.fn() }));
+
+const db = prisma as any;
+const user = { id: "user-1" };
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(user);
+ db.jobStage.count.mockResolvedValue(0);
+ db.jobStatus.count.mockResolvedValue(1);
+});
+
+describe("getAllJobStageTypes", () => {
+ it("scopes to the caller and orders by sortOrder then label", async () => {
+ db.jobStageType.findMany.mockResolvedValue([]);
+
+ await getAllJobStageTypes();
+
+ const args = db.jobStageType.findMany.mock.calls[0][0];
+ expect(args.where).toEqual({ createdBy: user.id });
+ expect(args.orderBy).toEqual([{ sortOrder: "asc" }, { label: "asc" }]);
+ expect(args.include).toEqual({ Status: true });
+ });
+});
+
+describe("getJobStageTypeList", () => {
+ // getReferenceEntityList groups by an FK on Job, and a stage type reaches
+ // Job only through JobStage — so this is a dedicated read, like roles.
+ it("counts stages through the relation, not through a job groupBy", async () => {
+ db.jobStageType.findMany.mockResolvedValue([]);
+ db.jobStageType.count.mockResolvedValue(0);
+
+ await getJobStageTypeList(1, 25);
+
+ const args = db.jobStageType.findMany.mock.calls[0][0];
+ expect(args.include._count).toEqual({ select: { stages: true } });
+ });
+});
+
+describe("createJobStageType", () => {
+ it("refuses a status that does not exist", async () => {
+ db.jobStatus.count.mockResolvedValue(0);
+
+ const res = await createJobStageType("Panel", "nope");
+
+ expect(res.success).toBe(false);
+ expect(resolveJobStageType).not.toHaveBeenCalled();
+ });
+
+ it("delegates to the resolver so canonical-equal names collapse", async () => {
+ (resolveJobStageType as any).mockResolvedValue({ id: "t1", label: "Panel", created: true });
+
+ const res = await createJobStageType(" Panel ", "s-int");
+
+ expect(res.success).toBe(true);
+ expect(resolveJobStageType).toHaveBeenCalledWith(" Panel ", user.id, "s-int");
+ });
+});
+
+describe("deleteJobStageTypeById", () => {
+ it("blocks the delete with a counted message when stages use the type", async () => {
+ db.jobStage.count.mockResolvedValue(4);
+
+ const res = await deleteJobStageTypeById("t1");
+
+ expect(res.success).toBe(false);
+ expect(res.message).toContain("4");
+ expect(db.jobStageType.delete).not.toHaveBeenCalled();
+ });
+
+ it("deletes an unused type, scoped to the caller", async () => {
+ db.jobStageType.delete.mockResolvedValue({ id: "t1" });
+
+ const res = await deleteJobStageTypeById("t1");
+
+ expect(res.success).toBe(true);
+ expect(db.jobStageType.delete).toHaveBeenCalledWith({
+ where: { id: "t1", createdBy: user.id },
+ });
+ });
+});
diff --git a/src/actions/jobStageType.actions.ts b/src/actions/jobStageType.actions.ts
new file mode 100644
index 0000000..80e2cea
--- /dev/null
+++ b/src/actions/jobStageType.actions.ts
@@ -0,0 +1,116 @@
+"use server";
+import prisma from "@/lib/db";
+import { handleError } from "@/lib/utils";
+import { requireUser } from "./shared";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { resolveJobStageType } from "@/lib/jobs/resolve";
+
+export const getAllJobStageTypes = async (): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ return await prisma.jobStageType.findMany({
+ where: { createdBy: user.id },
+ include: { Status: true },
+ orderBy: [{ sortOrder: "asc" }, { label: "asc" }],
+ });
+ } catch (error) {
+ return handleError(error, "Failed to fetch stage types. ");
+ }
+};
+
+// Not getReferenceEntityList: that helper counts jobs grouped by an FK on Job,
+// and a stage type reaches Job only through JobStage.
+export const getJobStageTypeList = async (
+ page: number = 1,
+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,
+ search?: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ const whereClause: any = { createdBy: user.id };
+ if (search) {
+ whereClause.label = { contains: search };
+ }
+
+ const [data, total] = await Promise.all([
+ prisma.jobStageType.findMany({
+ where: whereClause,
+ skip: (page - 1) * limit,
+ take: limit,
+ include: { Status: true, _count: { select: { stages: true } } },
+ orderBy: [{ sortOrder: "asc" }, { label: "asc" }],
+ }),
+ prisma.jobStageType.count({ where: whereClause }),
+ ]);
+
+ return { data, total };
+ } catch (error) {
+ return handleError(error, "Failed to fetch stage type list. ");
+ }
+};
+
+const assertStatusExists = async (statusId: string) => {
+ const status = await prisma.jobStatus.count({ where: { id: statusId } });
+ if (status === 0) throw new Error("Job status not found");
+};
+
+export const createJobStageType = async (
+ label: string,
+ statusId: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ await assertStatusExists(statusId);
+ const data = await resolveJobStageType(label, user.id, statusId);
+ return { success: true, data };
+ } catch (error) {
+ return handleError(error, "Failed to create stage type.");
+ }
+};
+
+export const updateJobStageType = async (
+ id: string,
+ label: string,
+ statusId: string,
+ sortOrder: number,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+ await assertStatusExists(statusId);
+ // value is left alone on rename: it is the reverse-lookup key that a
+ // status resolves through, and rewriting it would orphan the mapping.
+ await prisma.jobStageType.update({
+ where: { id, createdBy: user.id },
+ data: { label: label.trim(), statusId, sortOrder },
+ });
+ return { success: true };
+ } catch (error) {
+ return handleError(error, "Failed to update stage type.");
+ }
+};
+
+export const deleteJobStageTypeById = async (
+ id: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await requireUser();
+
+ // JobStage.stageTypeId is required, so the database already refuses via
+ // the default Restrict; this turns that into a readable message.
+ const stages = await prisma.jobStage.count({
+ where: { stageTypeId: id, Job: { userId: user.id } },
+ });
+ if (stages > 0) {
+ throw new Error(
+ `Stage type cannot be deleted due to ${stages} job stage${stages === 1 ? "" : "s"} using it! `,
+ );
+ }
+
+ const res = await prisma.jobStageType.delete({
+ where: { id, createdBy: user.id },
+ });
+ return { res, success: true };
+ } catch (error) {
+ return handleError(error, "Failed to delete stage type.");
+ }
+};