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
"use client";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogOverlay,
DialogTitle,
DialogFooter,
} from "@/components/ui/dialog";
import { addJob, updateJob } from "@/actions/job.actions";
import { Loader, PlusCircle } from "lucide-react";
import { Button } from "../ui/button";
import { useForm } from "react-hook-form";
import {
useCallback,
useEffect,
useRef,
useState,
useTransition,
} from "react";
import { AddJobFormSchema } from "@/models/addJobForm.schema";
import { zodResolver } from "@hookform/resolvers/zod";
import {
Company,
JOB_TYPES,
JobLocation,
JobResponse,
JobSource,
JobStatus,
JobTitle,
Tag,
WORKPLACE_TYPES,
} from "@/models/job.model";
import { addDays } from "date-fns";
import { z } from "zod";
import { toastActionResult, toastError } from "@/lib/toast";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import { RadioGroup, RadioGroupItem } from "../ui/radio-group";
import SelectFormCtrl from "../Select";
import { DatePicker } from "../DatePicker";
import { SALARY_RANGES } from "@/lib/data/salaryRangeData";
import TiptapEditor from "../TiptapEditor";
import { Input } from "../ui/input";
import { redirect, useRouter, useSearchParams } from "next/navigation";
import { Combobox } from "../ComboBox";
import { NotesCollapsibleSection } from "./NotesCollapsibleSection";
import { CoverLetter, Resume } from "@/models/profile.model";
import CreateResume from "../profile/CreateResume";
import { getResumeList } from "@/actions/profile.actions";
import { getCoverLetterList } from "@/actions/coverLetter.actions";
import { TagInput } from "./TagInput";
import { IncompleteResumeHint } from "../IncompleteResumeHint";
import {
buildIncompleteResumeHint,
hasMinResumeSections,
} from "@/lib/resumeSections";
import { APP_CONSTANTS, APPLIED_STATUS_VALUES } from "@/lib/constants";
import {
getFromLocalStorage,
saveToLocalStorage,
} from "@/utils/localstorage.utils";
type AddJobProps = {
jobStatuses: JobStatus[];
companies: Company[];
jobTitles: JobTitle[];
locations: JobLocation[];
jobSources: JobSource[];
tags: Tag[];
editJob?: JobResponse | null;
resetEditJob: () => void;
initialOpen?: boolean;
hideTrigger?: boolean;
redirectPath?: string;
};
export function AddJob({
jobStatuses,
companies,
jobTitles,
locations,
jobSources,
tags,
editJob,
resetEditJob,
initialOpen,
hideTrigger,
redirectPath,
}: AddJobProps) {
const router = useRouter();
const searchParams = useSearchParams();
const [dialogOpen, setDialogOpen] = useState(initialOpen ?? false);
const [resumeDialogOpen, setResumeDialogOpen] = useState(false);
const [resumes, setResumes] = useState<Resume[]>([]);
const [coverLetters, setCoverLetters] = useState<CoverLetter[]>([]);
const [availableTags, setAvailableTags] = useState<Tag[]>(tags);
const [isPending, startTransition] = useTransition();
useEffect(() => {
if (!dialogOpen && searchParams.get("add-job") === "true") {
const params = new URLSearchParams(searchParams.toString());
params.delete("add-job");
const newPath = params.toString()
? `?${params.toString()}`
: window.location.pathname;
router.replace(newPath);
}
}, [dialogOpen, router, searchParams]);
// Pre-fill with the last-used location/source, but only if that entity
// still exists (handles deletion and cross-user localStorage collisions,
// since `locations`/`jobSources` are already scoped to the current user).
const lastLocationId = getFromLocalStorage(
APP_CONSTANTS.LAST_JOB_LOCATION_STORAGE_KEY,
null,
);
const lastSourceId = getFromLocalStorage(
APP_CONSTANTS.LAST_JOB_SOURCE_STORAGE_KEY,
null,
);
// By value, not position: the list's order is not guaranteed.
const draftStatusId = jobStatuses.find((s) => s.value === "draft")?.id;
const appliedStatusId = jobStatuses.find((s) => s.value === "applied")?.id;
const newStatusId = jobStatuses.find((s) => s.value === "new")?.id;
const newJobDefaultValues = {
type: Object.keys(JOB_TYPES)[0],
workplaceType: "ONSITE",
dueDate: addDays(new Date(), APP_CONSTANTS.DEFAULT_JOB_DUE_DAYS),
status: draftStatusId,
salaryRange: "",
jobUrl: "",
jobDescription: "N/A",
location: locations.find((l) => l.id === lastLocationId)?.id,
source: jobSources.find((s) => s.id === lastSourceId)?.id,
};
const form = useForm<z.infer<typeof AddJobFormSchema>>({
resolver: zodResolver(AddJobFormSchema) as any,
defaultValues: newJobDefaultValues,
});
const { setValue, reset } = form;
// The date the form filled in itself, so it can take it back again.
const autoFilledDate = useRef<Date | null>(null);
const loadResumes = useCallback(async () => {
try {
const resumes = await getResumeList(1, APP_CONSTANTS.RESUME_PICKER_LIMIT);
setResumes(resumes.data ?? []);
} catch (error) {
console.error("Failed to load resumes:", error);
}
}, [setResumes]);
const loadCoverLetters = useCallback(async () => {
try {
const result = await getCoverLetterList(1, 100);
setCoverLetters(result.data);
} catch (error) {
console.error("Failed to load cover letters:", error);
}
}, [setCoverLetters]);
useEffect(() => {
if (editJob) {
reset({
id: editJob.id,
userId: editJob.userId,
title: editJob.JobTitle.id,
company: editJob.Company.id,
location: editJob.Location?.id,
type: editJob.jobType,
workplaceType: editJob.workplaceType ?? undefined,
source: editJob.JobSource?.id,
status: editJob.Status.id,
dueDate: editJob.dueDate,
salaryRange: editJob.salaryRange ?? "",
jobDescription: editJob.description,
jobUrl: editJob.jobUrl ?? "",
dateApplied: editJob.appliedDate ?? undefined,
resume: editJob.Resume?.id ?? undefined,
coverLetter: editJob.CoverLetter?.id ?? undefined,
tags: editJob.tags?.map((t) => t.id) ?? [],
});
// Merge any tags from editJob into the local pool so they're selectable
if (editJob.tags && editJob.tags.length > 0) {
setAvailableTags((prev) => {
const existing = new Set(prev.map((t) => t.id));
const incoming = editJob.tags!.filter((t) => !existing.has(t.id));
return incoming.length > 0 ? [...prev, ...incoming] : prev;
});
}
autoFilledDate.current = null;
setDialogOpen(true);
}
}, [editJob, reset]);
useEffect(() => {
if (!dialogOpen) return;
loadResumes();
loadCoverLetters();
}, [dialogOpen, loadResumes, loadCoverLetters]);
const setNewResumeId = (id: string) => {
setTimeout(() => {
setValue("resume", id);
}, 500);
};
function onSubmit(data: z.infer<typeof AddJobFormSchema>) {
const selected = resumes.find((r) => r.id === data.resume);
if (selected && !hasMinResumeSections(selected._count?.ResumeSections)) {
toastError(buildIncompleteResumeHint());
return;
}
startTransition(async () => {
const result = editJob ? await updateJob(data) : await addJob(data);
toastActionResult(result, {
success: `Job has been ${editJob ? "updated" : "created"} successfully`,
onSuccess: () => {
saveToLocalStorage(
APP_CONSTANTS.LAST_JOB_LOCATION_STORAGE_KEY,
data.location,
);
saveToLocalStorage(
APP_CONSTANTS.LAST_JOB_SOURCE_STORAGE_KEY,
data.source,
);
reset();
setDialogOpen(false);
redirect(redirectPath ?? "/dashboard/myjobs");
},
});
});
}
const pageTitle = editJob ? "Edit Job" : "Add Job";
const pageDescription = editJob
? "Update the details of this job application."
: "Track a new job application.";
const addJobForm = () => {
reset(newJobDefaultValues);
autoFilledDate.current = null;
resetEditJob();
setDialogOpen(true);
};
// Mirrors jobFieldsForStage: only Applied stamps today's date.
const jobStatusChange = (statusId: string) => {
const value = jobStatuses.find((s) => s.id === statusId)?.value ?? "";
const date = form.getValues("dateApplied");
if (value === "applied" && !date) {
autoFilledDate.current = new Date();
setValue("dateApplied", autoFilledDate.current);
} else if (
!APPLIED_STATUS_VALUES.includes(value) &&
date &&
// react-hook-form stores a copy, so compare by time, not identity
date.getTime() === autoFilledDate.current?.getTime()
) {
autoFilledDate.current = null;
setValue("dateApplied", undefined);
}
};
// A date the user picks means they applied, as the old toggle did.
const dateAppliedChange = (date?: Date) => {
autoFilledDate.current = null;
const status = form.getValues("status");
if (
date &&
appliedStatusId &&
(status === draftStatusId || status === newStatusId)
) {
setValue("status", appliedStatusId);
}
};
const closeDialog = () => setDialogOpen(false);
const createResume = () => {
setResumeDialogOpen(true);
};
return (
<>
{!hideTrigger && (
<Button
size="sm"
variant="outline"
className="h-8 gap-1"
onClick={addJobForm}
data-testid="add-job-btn"
>
<PlusCircle className="h-3.5 w-3.5" />
<span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
New Job
</span>
</Button>
)}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogOverlay>
<DialogContent className="h-full xl:h-[85vh] lg:h-[95vh] lg:max-w-screen-lg lg:max-h-screen overflow-y-scroll">
<DialogHeader>
<DialogTitle data-testid="add-job-dialog-title">
{pageTitle}
</DialogTitle>
<DialogDescription>{pageDescription}</DialogDescription>
</DialogHeader>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4"
>
{/* Job Title */}
<div>
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Job Title</FormLabel>
<FormControl>
<Combobox
options={jobTitles}
field={field}
creatable
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Job URL */}
<div>
<FormField
control={form.control}
name="jobUrl"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Job URL</FormLabel>
<FormControl>
<Input
placeholder="Copy and paste job link here"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Company */}
<div>
<FormField
control={form.control}
name="company"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Company</FormLabel>
<FormControl>
<Combobox
options={companies}
field={field}
creatable
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Location */}
<div>
<FormField
control={form.control}
name="location"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Job Location</FormLabel>
<FormControl>
<Combobox
options={locations}
field={field}
creatable
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Job Type */}
<div>
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel className="mb-2">Job Type</FormLabel>
<RadioGroup
name="type"
onValueChange={field.onChange}
defaultValue={field.value}
className="flex space-y-1"
>
{Object.entries(JOB_TYPES).map(([key, value]) => (
<FormItem
key={key}
className="flex items-center space-x-3 space-y-0"
>
<FormControl>
<RadioGroupItem value={key} />
</FormControl>
<FormLabel className="font-normal">
{value}
</FormLabel>
</FormItem>
))}
</RadioGroup>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Workplace Type */}
<div>
<FormField
control={form.control}
name="workplaceType"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel className="mb-2">Workplace Type</FormLabel>
<RadioGroup
name="workplaceType"
onValueChange={field.onChange}
defaultValue={field.value}
className="flex space-y-1"
>
{Object.entries(WORKPLACE_TYPES).map(
([key, value]) => (
<FormItem
key={key}
className="flex items-center space-x-3 space-y-0"
>
<FormControl>
<RadioGroupItem value={key} />
</FormControl>
<FormLabel className="font-normal">
{value}
</FormLabel>
</FormItem>
),
)}
</RadioGroup>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Job Source */}
<div>
<FormField
control={form.control}
name="source"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Job Source</FormLabel>
<Combobox
options={jobSources}
field={field}
creatable
/>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Status */}
<div>
<FormField
control={form.control}
name="status"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Status</FormLabel>
<SelectFormCtrl
label="Job Status"
options={jobStatuses}
field={{
...field,
onChange: (id: string) => {
field.onChange(id);
jobStatusChange(id);
},
}}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Date Applied */}
<div className="flex flex-col">
<FormField
control={form.control}
name="dateApplied"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Date Applied</FormLabel>
<DatePicker
field={{
...field,
onChange: (date?: Date) => {
field.onChange(date);
dateAppliedChange(date);
},
}}
presets={false}
isEnabled={true}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Due Date */}
<div>
<FormField
control={form.control}
name="dueDate"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Due Date</FormLabel>
<DatePicker
field={field}
presets={true}
isEnabled={true}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Salary Range */}
<div>
<FormField
control={form.control}
name="salaryRange"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Salary Range</FormLabel>
<Combobox
options={SALARY_RANGES}
field={field}
creatable
freeText
label="Salary Range"
/>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Resume */}
<div className="flex items-end">
<FormField
control={form.control}
name="resume"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Resume</FormLabel>
<SelectFormCtrl
label="Resume"
options={resumes?.map((r) =>
hasMinResumeSections(r._count?.ResumeSections)
? r
: {
...r,
disabled: true,
suffix: <IncompleteResumeHint />,
},
)}
field={field}
/>
<FormMessage />
</FormItem>
)}
/>
<Button variant="link" type="button" onClick={createResume}>
Add New
</Button>
<CreateResume
resumeDialogOpen={resumeDialogOpen}
setResumeDialogOpen={setResumeDialogOpen}
reloadResumes={loadResumes}
setNewResumeId={setNewResumeId}
/>
</div>
{/* Cover Letter */}
<div className="flex items-end self-start">
<FormField
control={form.control}
name="coverLetter"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Cover Letter</FormLabel>
<SelectFormCtrl
label="Cover Letter"
options={coverLetters}
field={field}
/>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Add Skill Tags */}
<div>
<FormField
control={form.control}
name="tags"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Add Skill</FormLabel>
<FormControl>
<TagInput
availableTags={availableTags}
selectedTagIds={field.value ?? []}
onChange={(ids) => field.onChange(ids)}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{/* Job Description */}
<div className="md:col-span-2">
<FormField
control={form.control}
name="jobDescription"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel id="job-description-label">
Job Description
</FormLabel>
<FormControl>
<TiptapEditor field={field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
{editJob && <NotesCollapsibleSection jobId={editJob.id} />}
<div className="md:col-span-2">
<DialogFooter
// className="md:col-span
>
<div>
<Button
type="reset"
variant="outline"
className="mt-2 md:mt-0 w-full"
onClick={closeDialog}
>
Cancel
</Button>
</div>
<Button type="submit" data-testid="save-job-btn">
Save
{isPending && (
<Loader className="h-4 w-4 shrink-0 spinner" />
)}
</Button>
</DialogFooter>
</div>
</form>
</Form>
</DialogContent>
</DialogOverlay>
</Dialog>
</>
);
}