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.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat(library): add the Stages tab listing stage types with reorder, rename and a guarded delete
Khuram Niazef8f94f610ad
diff --git a/__tests__/AdminTabsContainer.spec.tsx b/__tests__/AdminTabsContainer.spec.tsxindex 854e5bb..334b2f7 100644--- a/__tests__/AdminTabsContainer.spec.tsx+++ b/__tests__/AdminTabsContainer.spec.tsx@@ -46,6 +46,13 @@ vi.mock("@/actions/contactRole.actions", () => ({deleteContactRoleById: vi.fn(),}));+vi.mock("@/actions/jobStageType.actions", () => ({+ getJobStageTypeList: vi.fn().mockResolvedValue({ data: [], total: 0 }),+ createJobStageType: vi.fn(),+ updateJobStageType: vi.fn(),+ deleteJobStageTypeById: vi.fn(),+}));+describe("AdminTabsContainer", () => {const user = userEvent.setup({ skipHover: true });@@ -70,6 +77,12 @@ describe("AdminTabsContainer", () => {expect(screen.getByRole("tab", { name: "Roles" })).toBeInTheDocument();});+ it("offers a Stages tab", () => {+ render(<AdminTabsContainer />);++ expect(screen.getByRole("tab", { name: "Stages" })).toBeInTheDocument();+ });+it("should default to companies tab", () => {render(<AdminTabsContainer />);diff --git a/__tests__/JobStagesContainer.spec.tsx b/__tests__/JobStagesContainer.spec.tsxnew file mode 100644index 0000000..337c5bc--- /dev/null+++ b/__tests__/JobStagesContainer.spec.tsx@@ -0,0 +1,117 @@+import JobStagesContainer from "@/components/admin/JobStagesContainer";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import {+ getJobStageTypeList,+ deleteJobStageTypeById,+ updateJobStageType,+} from "@/actions/jobStageType.actions";++vi.mock("@/actions/jobStageType.actions", () => ({+ getJobStageTypeList: vi.fn(),+ createJobStageType: vi.fn(),+ updateJobStageType: vi.fn(),+ deleteJobStageTypeById: vi.fn(),+}));++vi.mock("@/actions/job.actions", () => ({+ getStatusList: vi.fn().mockResolvedValue([]),+}));++vi.mock("@/lib/toast", () => ({+ toastSuccess: vi.fn(),+ toastError: vi.fn(),+ toastActionResult: vi.fn(),+}));++const types = [+ {+ id: "t-int",+ label: "Final / Onsite Interview",+ value: "final / onsite interview",+ sortOrder: 6,+ statusId: "s-int",+ Status: { id: "s-int", label: "Interview", value: "interview" },+ _count: { stages: 3 },+ },+ {+ id: "t-off",+ label: "Offer Received",+ value: "offer received",+ sortOrder: 9,+ statusId: "s-off",+ Status: { id: "s-off", label: "Offer", value: "offer" },+ _count: { stages: 0 },+ },+];++describe("JobStagesContainer", () => {+ const user = userEvent.setup({ skipHover: true });++ beforeEach(() => {+ vi.clearAllMocks();+ (getJobStageTypeList as any).mockResolvedValue({ data: types, total: 2 });+ });++ it("lists each stage type with its parent status, order and stage count", async () => {+ render(<JobStagesContainer />);++ expect(+ await screen.findByText("Final / Onsite Interview"),+ ).toBeInTheDocument();+ expect(screen.getByText("Interview")).toBeInTheDocument();+ expect(screen.getByText("6")).toBeInTheDocument();+ expect(screen.getByText("3")).toBeInTheDocument();+ });++ it("refuses to delete a type that is in use, naming the count", async () => {+ render(<JobStagesContainer />);+ await screen.findByText("Final / Onsite Interview");++ await user.click(screen.getAllByRole("button", { name: /toggle menu/i })[0]);+ await user.click(await screen.findByText("Delete"));++ expect(await screen.findByText(/used by 3 job stages/)).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: /^Delete$/ })).toBeNull();+ expect(deleteJobStageTypeById).not.toHaveBeenCalled();+ });++ it("moves a type down by swapping sort order with its neighbour", async () => {+ (updateJobStageType as any).mockResolvedValue({ success: true });+ render(<JobStagesContainer />);+ await screen.findByText("Final / Onsite Interview");++ await user.click(screen.getAllByRole("button", { name: /toggle menu/i })[0]);+ await user.click(await screen.findByText("Move Down"));++ await waitFor(() =>+ expect(updateJobStageType).toHaveBeenCalledWith(+ "t-int",+ "Final / Onsite Interview",+ "s-int",+ 9,+ ),+ );+ expect(updateJobStageType).toHaveBeenCalledWith(+ "t-off",+ "Offer Received",+ "s-off",+ 6,+ );+ });++ it("searches stage types by label", async () => {+ render(<JobStagesContainer />);+ await screen.findByText("Final / Onsite Interview");++ await user.type(screen.getByPlaceholderText("Search stages..."), "onsite");++ await waitFor(() =>+ expect(getJobStageTypeList).toHaveBeenCalledWith(+ 1,+ expect.any(Number),+ "onsite",+ ),+ );+ });+});diff --git a/src/components/admin/AddJobStageType.tsx b/src/components/admin/AddJobStageType.tsxnew file mode 100644index 0000000..31b4a97--- /dev/null+++ b/src/components/admin/AddJobStageType.tsx@@ -0,0 +1,168 @@+"use client";+import { useTransition, useEffect } from "react";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "../ui/dialog";+import { Loader } from "lucide-react";+import { z } from "zod";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "../ui/form";+import { Input } from "../ui/input";+import SelectFormCtrl from "../Select";+import { toastActionResult } from "@/lib/toast";+import { JobStageTypeRef } from "@/models/jobStage.model";+import { JobStatus } from "@/models/job.model";+import {+ createJobStageType,+ updateJobStageType,+} from "@/actions/jobStageType.actions";++const AddJobStageTypeFormSchema = z.object({+ label: z+ .string({ error: "Stage name is required." })+ .min(1, { message: "Stage name cannot be empty." })+ .max(80, { message: "Stage name must be 80 characters or fewer." }),+ statusId: z+ .string({ error: "Parent status is required." })+ .min(1, { message: "Pick the status this stage means." }),+});++type AddJobStageTypeProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ type: JobStageTypeRef | null;+ statuses: JobStatus[];+ reloadTypes: () => void;+};++function AddJobStageType({+ open,+ onOpenChange,+ type,+ statuses,+ reloadTypes,+}: AddJobStageTypeProps) {+ const [isPending, startTransition] = useTransition();++ const form = useForm<z.infer<typeof AddJobStageTypeFormSchema>>({+ resolver: zodResolver(AddJobStageTypeFormSchema),+ defaultValues: { label: "", statusId: "" },+ });++ const { reset } = form;++ // A custom stage is most often an interview round, so that is the default.+ useEffect(() => {+ if (!open) return;+ reset({+ label: type?.label ?? "",+ statusId:+ type?.statusId ??+ statuses.find((s) => s.value === "interview")?.id ??+ "",+ });+ }, [open, type, statuses, reset]);++ const onSubmit = (values: z.infer<typeof AddJobStageTypeFormSchema>) => {+ startTransition(async () => {+ const res = type+ ? await updateJobStageType(+ type.id,+ values.label,+ values.statusId,+ type.sortOrder,+ )+ : await createJobStageType(values.label, values.statusId);+ toastActionResult(res, {+ success: `Stage has been ${type ? "updated" : "added"} successfully.`,+ onSuccess: () => {+ onOpenChange(false);+ reset();+ reloadTypes();+ },+ });+ });+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {type ? "Edit Stage" : "Add New Stage"}+ </DialogTitle>+ <DialogDescription>+ Stages are the steps a job moves through — each one belongs to a+ status, which the job takes on when the stage becomes current.+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">+ <FormField+ control={form.control}+ name="label"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Stage Name</FormLabel>+ <FormControl>+ <Input+ placeholder="e.g. Take-home Exercise"+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="statusId"+ render={({ field }) => (+ <FormItem className="flex flex-col">+ <FormLabel>Parent Status</FormLabel>+ <SelectFormCtrl+ label="status"+ options={statuses}+ field={field}+ />+ <FormMessage />+ </FormItem>+ )}+ />+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button type="submit" disabled={isPending}>+ Save+ {isPending && (+ <Loader className="ml-2 h-4 w-4 shrink-0 spinner" />+ )}+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+}++export default AddJobStageType;diff --git a/src/components/admin/AdminTabsContainer.tsx b/src/components/admin/AdminTabsContainer.tsxindex 3a7ec32..f4e1595 100644--- a/src/components/admin/AdminTabsContainer.tsx+++ b/src/components/admin/AdminTabsContainer.tsx@@ -5,6 +5,7 @@ import ContactRolesContainer from "@/components/admin/ContactRolesContainer";import ContactsContainer from "@/components/admin/ContactsContainer";import JobLocationsContainer from "@/components/admin/JobLocationsContainer";import JobSourcesContainer from "@/components/admin/JobSourcesContainer";+import JobStagesContainer from "@/components/admin/JobStagesContainer";import JobTitlesContainer from "@/components/admin/JobTitlesContainer";import TagsContainer from "@/components/admin/TagsContainer";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";@@ -43,6 +44,7 @@ function AdminTabsContainer() {<TabsTrigger value="activity-types">Activity Types</TabsTrigger><TabsTrigger value="contacts">Contacts</TabsTrigger><TabsTrigger value="roles">Roles</TabsTrigger>+ <TabsTrigger value="stages">Stages</TabsTrigger></TabsList><TabsContent value="companies"><CompaniesContainer />@@ -68,6 +70,9 @@ function AdminTabsContainer() {<TabsContent value="roles"><ContactRolesContainer /></TabsContent>+ <TabsContent value="stages">+ <JobStagesContainer />+ </TabsContent></Tabs>);}diff --git a/src/components/admin/JobStagesContainer.tsx b/src/components/admin/JobStagesContainer.tsxnew file mode 100644index 0000000..8da7a8a--- /dev/null+++ b/src/components/admin/JobStagesContainer.tsx@@ -0,0 +1,140 @@+"use client";+import { useCallback, useEffect, useState } from "react";+import { Card, CardContent, CardTitle } from "../ui/card";+import { ResponsiveCardHeader } from "../ResponsiveCardHeader";+import { APP_CONSTANTS } from "@/lib/constants";+import { JobStageTypeRef } from "@/models/jobStage.model";+import { JobStatus } from "@/models/job.model";+import JobStagesTable from "./JobStagesTable";+import AddJobStageType from "./AddJobStageType";+import { getJobStageTypeList } from "@/actions/jobStageType.actions";+import { getStatusList } from "@/actions/job.actions";+import Loading from "../Loading";+import { Button } from "../ui/button";+import { PlusCircle } from "lucide-react";+import { RecordsCount } from "../RecordsCount";+import { SearchInput } from "../SearchInput";++function JobStagesContainer() {+ const [types, setTypes] = useState<JobStageTypeRef[]>([]);+ const [totalTypes, setTotalTypes] = useState<number>(0);+ const [statuses, setStatuses] = useState<JobStatus[]>([]);+ const [page, setPage] = useState<number>(1);+ const [loading, setLoading] = useState<boolean>(false);+ const [searchTerm, setSearchTerm] = useState<string>("");+ const [dialogOpen, setDialogOpen] = useState(false);+ const [editType, setEditType] = useState<JobStageTypeRef | null>(null);++ const loadTypes = useCallback(async (page: number, search?: string) => {+ setLoading(true);+ const { data, total } = await getJobStageTypeList(+ page,+ APP_CONSTANTS.RECORDS_PER_PAGE,+ search,+ );+ if (data) {+ setTypes((prev) => (page === 1 ? data : [...prev, ...data]));+ setTotalTypes(total);+ setPage(page);+ }+ setLoading(false);+ }, []);++ const reloadTypes = useCallback(+ async () => loadTypes(1, searchTerm || undefined),+ [loadTypes, searchTerm],+ );++ // One effect for mount and debounced search: both reset to page 1 and+ // replace the list, so a separate mount effect would double-fetch.+ useEffect(() => {+ const timer = setTimeout(+ () => loadTypes(1, searchTerm || undefined),+ searchTerm ? 300 : 0,+ );+ return () => clearTimeout(timer);+ }, [searchTerm, loadTypes]);++ useEffect(() => {+ getStatusList().then((list) => setStatuses(list ?? []));+ }, []);++ const openAdd = () => {+ setEditType(null);+ setDialogOpen(true);+ };++ const openEdit = (type: JobStageTypeRef) => {+ setEditType(type);+ setDialogOpen(true);+ };++ return (+ <div className="col-span-3">+ <Card x-chunk="dashboard-06-chunk-0">+ <ResponsiveCardHeader>+ <div className="flex items-baseline gap-2">+ <CardTitle>Job Stages</CardTitle>+ {!loading && totalTypes > 0 && (+ <RecordsCount+ count={types.length}+ total={totalTypes}+ label="stages"+ />+ )}+ </div>+ <div className="flex flex-wrap items-center justify-end gap-2 sm:ml-auto">+ <SearchInput+ value={searchTerm}+ onChange={setSearchTerm}+ placeholder="Search stages..."+ />+ <Button+ size="sm"+ variant="outline"+ className="h-8 gap-1"+ onClick={openAdd}+ >+ <PlusCircle className="h-3.5 w-3.5" />+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">+ New Stage+ </span>+ </Button>+ </div>+ </ResponsiveCardHeader>+ <CardContent>+ {loading && <Loading />}+ {types.length > 0 && (+ <JobStagesTable+ types={types}+ reloadTypes={reloadTypes}+ onEdit={openEdit}+ />+ )}+ {types.length < totalTypes && (+ <div className="flex justify-center p-4">+ <Button+ size="sm"+ variant="outline"+ onClick={() => loadTypes(page + 1, searchTerm || undefined)}+ disabled={loading}+ className="btn btn-primary"+ >+ {loading ? "Loading..." : "Load More"}+ </Button>+ </div>+ )}+ </CardContent>+ </Card>+ <AddJobStageType+ open={dialogOpen}+ onOpenChange={setDialogOpen}+ type={editType}+ statuses={statuses}+ reloadTypes={reloadTypes}+ />+ </div>+ );+}++export default JobStagesContainer;diff --git a/src/components/admin/JobStagesTable.tsx b/src/components/admin/JobStagesTable.tsxnew file mode 100644index 0000000..514ccbb--- /dev/null+++ b/src/components/admin/JobStagesTable.tsx@@ -0,0 +1,194 @@+"use client";+import { useState } from "react";+import { Button } from "../ui/button";++import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger,+} from "../ui/dropdown-menu";+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "../ui/table";+import { JobStageTypeRef } from "@/models/jobStage.model";+import { ArrowDown, ArrowUp, MoreVertical, Pencil, Trash } from "lucide-react";+import { AlertDialog } from "@/models/alertDialog.model";+import { DeleteAlertDialog } from "../DeleteAlertDialog";+import { StatusBadge } from "../StatusBadge";+import { getJobStatusBadgeColor } from "@/lib/badge-colors";+import {+ deleteJobStageTypeById,+ updateJobStageType,+} from "@/actions/jobStageType.actions";+import { toastSuccess, toastError } from "@/lib/toast";++type JobStagesTableProps = {+ types: JobStageTypeRef[];+ reloadTypes: () => void;+ onEdit: (type: JobStageTypeRef) => void;+};++function JobStagesTable({ types, reloadTypes, onEdit }: JobStagesTableProps) {+ const [alert, setAlert] = useState<AlertDialog>({+ openState: false,+ deleteAction: false,+ });++ const onDeleteType = (type: JobStageTypeRef) => {+ const stages = type._count?.stages ?? 0;+ if (stages > 0) {+ setAlert({+ openState: true,+ title: "Stage type is in use!",+ description: `This stage type is used by ${stages} job stage${+ stages === 1 ? "" : "s"+ }. Change or remove those stages before deleting the type.`,+ deleteAction: false,+ });+ } else {+ setAlert({ openState: true, deleteAction: true, itemId: type.id });+ }+ };++ const deleteType = async (typeId: string) => {+ if (typeId) {+ const { success, message } = await deleteJobStageTypeById(typeId);+ if (success) {+ toastSuccess("Stage type has been deleted successfully");+ reloadTypes();+ } else {+ toastError(message);+ }+ }+ };++ // Swap sortOrder with the adjacent row rather than renumbering the list:+ // a drag-and-drop reorder would need a new dependency.+ const move = async (index: number, direction: -1 | 1) => {+ const type = types[index];+ const neighbour = types[index + direction];+ if (!neighbour) return;++ const results = await Promise.all([+ updateJobStageType(+ type.id,+ type.label,+ type.statusId,+ neighbour.sortOrder,+ ),+ updateJobStageType(+ neighbour.id,+ neighbour.label,+ neighbour.statusId,+ type.sortOrder,+ ),+ ]);+ const failed = results.find((res) => !res?.success);+ if (failed) {+ toastError(failed.message);+ }+ reloadTypes();+ };++ return (+ <>+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Stage</TableHead>+ <TableHead>Parent Status</TableHead>+ <TableHead className="hidden sm:table-cell">Order</TableHead>+ <TableHead>Stages</TableHead>+ <TableHead>+ <span className="sr-only">Actions</span>+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {types.map((type: JobStageTypeRef, index: number) => {+ return (+ <TableRow key={type.id}>+ <TableCell className="font-medium">{type.label}</TableCell>+ <TableCell>+ {type.Status && (+ <StatusBadge+ label={type.Status.label}+ color={getJobStatusBadgeColor(type.Status.value)}+ />+ )}+ </TableCell>+ <TableCell className="font-medium hidden sm:table-cell">+ {type.sortOrder}+ </TableCell>+ <TableCell className="font-medium">+ {type._count?.stages ?? 0}+ </TableCell>+ <TableCell>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button aria-haspopup="true" size="icon" variant="ghost">+ <MoreVertical className="h-4 w-4" />+ <span className="sr-only">Toggle menu</span>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Actions</DropdownMenuLabel>+ <DropdownMenuItem+ className="cursor-pointer"+ onClick={() => onEdit(type)}+ >+ <Pencil className="mr-2 h-4 w-4" />+ Edit+ </DropdownMenuItem>+ <DropdownMenuItem+ className="cursor-pointer"+ disabled={index === 0}+ onClick={() => move(index, -1)}+ >+ <ArrowUp className="mr-2 h-4 w-4" />+ Move Up+ </DropdownMenuItem>+ <DropdownMenuItem+ className="cursor-pointer"+ disabled={index === types.length - 1}+ onClick={() => move(index, 1)}+ >+ <ArrowDown className="mr-2 h-4 w-4" />+ Move Down+ </DropdownMenuItem>+ <DropdownMenuItem+ className="text-red-600 cursor-pointer"+ onClick={() => onDeleteType(type)}+ >+ <Trash className="mr-2 h-4 w-4" />+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ <DeleteAlertDialog+ pageTitle="stage type"+ open={alert.openState}+ onOpenChange={() => setAlert({ openState: false, deleteAction: false })}+ onDelete={() => deleteType(alert.itemId!)}+ alertTitle={alert.title}+ alertDescription={alert.description}+ deleteAction={alert.deleteAction}+ />+ </>+ );+}++export default JobStagesTable;