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
refactor(toast): consolidate success/error toasts into shared helpers
Khuram Niazfe254731488a
diff --git a/__tests__/AddJob.spec.tsx b/__tests__/AddJob.spec.tsxindex dbb6d31..9a78b2f 100644--- a/__tests__/AddJob.spec.tsx+++ b/__tests__/AddJob.spec.tsx@@ -446,7 +446,7 @@ describe("AddJob Component - Error Handling", () => {expect(toast).toHaveBeenCalledWith(expect.objectContaining({variant: "destructive",- title: "Error!",+ title: "Error",description: "Failed to save job",}),);diff --git a/__tests__/job.actions.spec.ts b/__tests__/job.actions.spec.tsindex e1ce9eb..9a3dbf5 100644--- a/__tests__/job.actions.spec.ts+++ b/__tests__/job.actions.spec.ts@@ -888,7 +888,7 @@ describe("jobActions", () => {const result = await addJob(jobData);- expect(result).toStrictEqual({ job: jobData, success: true });+ expect(result).toStrictEqual({ data: jobData, success: true });expect(prisma.job.create).toHaveBeenCalledTimes(1);expect(prisma.job.create).toHaveBeenCalledWith({data: {@@ -938,7 +938,7 @@ describe("jobActions", () => {resumeId: jobData.resume,},});- expect(result).toEqual({ job: jobData, success: true });+ expect(result).toEqual({ data: jobData, success: true });});it("should handle unexpected errors", async () => {(getCurrentUser as any).mockResolvedValue(mockUser);@@ -968,7 +968,7 @@ describe("jobActions", () => {const result = await updateJob(jobData);- expect(result).toStrictEqual({ job: jobData, success: true });+ expect(result).toStrictEqual({ data: jobData, success: true });expect(prisma.job.update).toHaveBeenCalledTimes(1);});it("should handle unexpected errors", async () => {diff --git a/__tests__/toast.spec.ts b/__tests__/toast.spec.tsnew file mode 100644index 0000000..a95a550--- /dev/null+++ b/__tests__/toast.spec.ts@@ -0,0 +1,117 @@+import { toast } from "@/components/ui/use-toast";+import { toastSuccess, toastError, toastActionResult } from "@/lib/toast";++vi.mock("@/components/ui/use-toast", () => ({+ toast: vi.fn(),+}));++beforeEach(() => {+ vi.clearAllMocks();+});++describe("toastSuccess", () => {+ it("toasts a success variant with the given description", () => {+ toastSuccess("Job has been created successfully");+ expect(toast).toHaveBeenCalledWith({+ variant: "success",+ title: undefined,+ description: "Job has been created successfully",+ });+ });++ it("accepts an optional title", () => {+ toastSuccess("Saved", "Nice");+ expect(toast).toHaveBeenCalledWith({+ variant: "success",+ title: "Nice",+ description: "Saved",+ });+ });+});++describe("toastError", () => {+ it("defaults the title to 'Error'", () => {+ toastError("Failed to save job");+ expect(toast).toHaveBeenCalledWith({+ variant: "destructive",+ title: "Error",+ description: "Failed to save job",+ });+ });++ it("falls back to a generic message when no description is given", () => {+ toastError();+ expect(toast).toHaveBeenCalledWith({+ variant: "destructive",+ title: "Error",+ description: "Something went wrong. Please try again.",+ });+ });++ it("allows overriding the title", () => {+ toastError("Nope", "Custom Title");+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({ title: "Custom Title" }),+ );+ });+});++describe("toastActionResult", () => {+ it("toasts success and calls onSuccess with the result data on success", () => {+ const onSuccess = vi.fn();+ toastActionResult(+ { success: true, data: { id: "1" } },+ { success: "Job has been created successfully", onSuccess },+ );++ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ variant: "success",+ description: "Job has been created successfully",+ }),+ );+ expect(onSuccess).toHaveBeenCalledWith({ id: "1" });+ });++ it("does not call onSuccess on failure and toasts result.message", () => {+ const onSuccess = vi.fn();+ toastActionResult(+ { success: false, message: "Failed to save job" },+ { success: "Job has been created successfully", onSuccess },+ );++ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ variant: "destructive",+ title: "Error",+ description: "Failed to save job",+ }),+ );+ expect(onSuccess).not.toHaveBeenCalled();+ });++ it("toasts the fallback error when result is undefined", () => {+ toastActionResult(undefined, {+ success: "Job has been created successfully",+ error: "Could not create job",+ });++ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ variant: "destructive",+ title: "Error",+ description: "Could not create job",+ }),+ );+ });++ it("falls back to the generic message when result is undefined and no error override is given", () => {+ toastActionResult(undefined, { success: "Job has been created successfully" });++ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({+ description: "Something went wrong. Please try again.",+ }),+ );+ });+});diff --git a/src/actions/job.actions.ts b/src/actions/job.actions.tsindex f9d9c4d..79babc3 100644--- a/src/actions/job.actions.ts+++ b/src/actions/job.actions.ts@@ -372,7 +372,7 @@ export const addJob = async (tagIds: tags ?? [],});revalidatePath("/dashboard");- return { job, success: true };+ return { success: true, data: job };} catch (error) {const msg = "Failed to create job. ";return handleError(error, msg);@@ -440,7 +440,7 @@ export const updateJob = async (},});revalidatePath("/dashboard");- return { job, success: true };+ return { success: true, data: job };} catch (error) {const msg = "Failed to update job. ";return handleError(error, msg);diff --git a/src/components/admin/AddCompany.tsx b/src/components/admin/AddCompany.tsxindex eddfa22..4949b6c 100644--- a/src/components/admin/AddCompany.tsx+++ b/src/components/admin/AddCompany.tsx@@ -23,7 +23,7 @@ import {FormMessage,} from "../ui/form";import { Input } from "../ui/input";-import { toast } from "../ui/use-toast";+import { toastActionResult } from "@/lib/toast";import { addCompany, updateCompany } from "@/actions/company.actions";import { Company } from "@/models/job.model";@@ -87,23 +87,14 @@ function AddCompany({const res = editCompany? await updateCompany(data): await addCompany(data);- if (!res?.success) {- toast({- variant: "destructive",- title: "Error!",- description: res?.message,- });- } else {- reset();- setDialogOpen(false);- reloadCompanies();- toast({- variant: "success",- description: `Company has been ${- editCompany ? "updated" : "created"- } successfully`,- });- }+ toastActionResult(res, {+ success: `Company has been ${editCompany ? "updated" : "created"} successfully`,+ onSuccess: () => {+ reset();+ setDialogOpen(false);+ reloadCompanies();+ },+ });});};diff --git a/src/components/myjobs/AddJob.tsx b/src/components/myjobs/AddJob.tsxindex bf7b086..ac6c628 100644--- a/src/components/myjobs/AddJob.tsx+++ b/src/components/myjobs/AddJob.tsx@@ -27,7 +27,7 @@ import {} from "@/models/job.model";import { addDays } from "date-fns";import { z } from "zod";-import { toast } from "../ui/use-toast";+import { toastActionResult } from "@/lib/toast";import {Form,FormControl,@@ -184,25 +184,15 @@ export function AddJob({function onSubmit(data: z.infer<typeof AddJobFormSchema>) {startTransition(async () => {- const { success, message } = editJob- ? await updateJob(data)- : await addJob(data);- reset();- setDialogOpen(false);- if (!success) {- toast({- variant: "destructive",- title: "Error!",- description: message,- });- }- redirect(redirectPath ?? "/dashboard/myjobs");- });- toast({- variant: "success",- description: `Job has been ${- editJob ? "updated" : "created"- } successfully`,+ const result = editJob ? await updateJob(data) : await addJob(data);+ toastActionResult(result, {+ success: `Job has been ${editJob ? "updated" : "created"} successfully`,+ onSuccess: () => {+ reset();+ setDialogOpen(false);+ redirect(redirectPath ?? "/dashboard/myjobs");+ },+ });});}diff --git a/src/components/myjobs/NotesSection.tsx b/src/components/myjobs/NotesSection.tsxindex a55a28a..9c5e8af 100644--- a/src/components/myjobs/NotesSection.tsx+++ b/src/components/myjobs/NotesSection.tsx@@ -13,7 +13,7 @@ import {CollapsibleContent,CollapsibleTrigger,} from "../ui/collapsible";-import { toast } from "../ui/use-toast";+import { toastActionResult } from "@/lib/toast";type NotesSectionProps = {jobId: string;@@ -52,19 +52,10 @@ export function NotesSection({ jobId, openTrigger }: NotesSectionProps) {const handleDelete = async () => {const result = await deleteNote(noteIdToDelete);- if (result.success) {- toast({- variant: "success",- description: "Note deleted successfully",- });- loadNotes();- } else {- toast({- variant: "destructive",- title: "Error!",- description: result.message,- });- }+ toastActionResult(result, {+ success: "Note deleted successfully",+ onSuccess: () => loadNotes(),+ });};const handleAddNote = () => {diff --git a/src/components/questions/QuestionsContainer.tsx b/src/components/questions/QuestionsContainer.tsxindex 3fc74ce..20824a1 100644--- a/src/components/questions/QuestionsContainer.tsx+++ b/src/components/questions/QuestionsContainer.tsx@@ -15,7 +15,7 @@ import {getQuestionById,getQuestionsList,} from "@/actions/question.actions";-import { toast } from "../ui/use-toast";+import { toastActionResult, toastError } from "@/lib/toast";import { Question } from "@/models/question.model";import { Tag } from "@/models/job.model";import { RecordsCount } from "../RecordsCount";@@ -60,11 +60,7 @@ function QuestionsContainer({setTotalQuestions(result.total);setPage(pageNum);} else {- toast({- variant: "destructive",- title: "Error!",- description: result?.message || "Failed to load questions.",- });+ toastError(result?.message || "Failed to load questions.");}setLoading(false);},@@ -77,30 +73,17 @@ function QuestionsContainer({}, [loadQuestions, filterKey, searchTerm, onQuestionsChanged]);const onDeleteQuestion = async (questionId: string) => {- const { success, message } = await deleteQuestion(questionId);- if (success) {- toast({- variant: "success",- description: "Question has been deleted successfully",- });- reloadQuestions();- } else {- toast({- variant: "destructive",- title: "Error!",- description: message,- });- }+ const result = await deleteQuestion(questionId);+ toastActionResult(result, {+ success: "Question has been deleted successfully",+ onSuccess: () => reloadQuestions(),+ });};const onEditQuestion = async (question: Question) => {const { data, success, message } = await getQuestionById(question.id);if (!success) {- toast({- variant: "destructive",- title: "Error!",- description: message,- });+ toastError(message);return;}setEditQuestion(data);diff --git a/src/components/tasks/TaskForm.tsx b/src/components/tasks/TaskForm.tsxindex abea7fb..927b2d3 100644--- a/src/components/tasks/TaskForm.tsx+++ b/src/components/tasks/TaskForm.tsx@@ -17,7 +17,7 @@ import { AddTaskFormSchema } from "@/models/addTaskForm.schema";import { zodResolver } from "@hookform/resolvers/zod";import { Task, TASK_STATUSES, TaskStatus } from "@/models/task.model";import { z } from "zod";-import { toast } from "../ui/use-toast";+import { toastActionResult } from "@/lib/toast";import {Form,FormControl,@@ -104,26 +104,16 @@ export function TaskForm({function onSubmit(data: z.infer<typeof AddTaskFormSchema>) {startTransition(async () => {- const { success, message } = editTask- ? await updateTask(data)- : await createTask(data);-- if (success) {- toast({- variant: "success",- description: `Task has been ${editTask ? "updated" : "created"} successfully`,- });- reset();- setDialogOpen(false);- resetEditTask();- onTaskSaved();- } else {- toast({- variant: "destructive",- title: "Error!",- description: message,- });- }+ const result = editTask ? await updateTask(data) : await createTask(data);+ toastActionResult(result, {+ success: `Task has been ${editTask ? "updated" : "created"} successfully`,+ onSuccess: () => {+ reset();+ setDialogOpen(false);+ resetEditTask();+ onTaskSaved();+ },+ });});}diff --git a/src/lib/toast.ts b/src/lib/toast.tsnew file mode 100644index 0000000..b3d365c--- /dev/null+++ b/src/lib/toast.ts@@ -0,0 +1,27 @@+import { toast } from "@/components/ui/use-toast";+import type { ActionResult } from "@/models/action.model";++export function toastSuccess(description: string, title?: string) {+ toast({ variant: "success", title, description });+}++export function toastError(description?: string, title = "Error") {+ toast({+ variant: "destructive",+ title,+ description: description ?? "Something went wrong. Please try again.",+ });+}++// Collapses the repeated success/error branch into one call.+export function toastActionResult<T>(+ result: ActionResult<T> | undefined,+ opts: { success: string; onSuccess?: (data: T | undefined) => void; error?: string },+) {+ if (result?.success) {+ toastSuccess(opts.success);+ opts.onSuccess?.(result.data);+ } else {+ toastError(result?.message ?? opts.error);+ }+}diff --git a/src/lib/utils.ts b/src/lib/utils.tsindex 8387c0c..44ae6b8 100644--- a/src/lib/utils.ts+++ b/src/lib/utils.ts@@ -56,6 +56,7 @@ export function handleError(error: unknown, msg = "Server Error.") {}return { success: false, message: error.message || msg };}+ return { success: false, message: msg };}export function getTimestampedFileName(originalName: string): string {diff --git a/src/models/action.model.ts b/src/models/action.model.tsnew file mode 100644index 0000000..fa471d2--- /dev/null+++ b/src/models/action.model.ts@@ -0,0 +1,3 @@+export type ActionResult<T = unknown> =+ | { success: true; data?: T }+ | { success: false; message: string };