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
add activity form
Khuram Niaz210221554d63
diff --git a/prisma/migrations/20241210004820_add_activity_and_activty_type_table/migration.sql b/prisma/migrations/20241210004820_add_activity_and_activty_type_table/migration.sqlnew file mode 100644index 0000000..00d8f45--- /dev/null+++ b/prisma/migrations/20241210004820_add_activity_and_activty_type_table/migration.sql@@ -0,0 +1,30 @@+-- CreateTable+CREATE TABLE "ActivityType" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "label" TEXT NOT NULL,+ "value" TEXT NOT NULL,+ "description" TEXT,+ "createdBy" TEXT NOT NULL,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ CONSTRAINT "ActivityType_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++-- CreateTable+CREATE TABLE "Activity" (+ "id" TEXT NOT NULL PRIMARY KEY,+ "userId" TEXT NOT NULL,+ "activityName" TEXT NOT NULL,+ "startTime" DATETIME NOT NULL,+ "endTime" DATETIME,+ "duration" INTEGER,+ "description" TEXT,+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" DATETIME NOT NULL,+ "activityTypeId" TEXT NOT NULL,+ CONSTRAINT "Activity_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,+ CONSTRAINT "Activity_activityTypeId_fkey" FOREIGN KEY ("activityTypeId") REFERENCES "ActivityType" ("id") ON DELETE RESTRICT ON UPDATE CASCADE+);++-- CreateIndex+CREATE UNIQUE INDEX "ActivityType_value_key" ON "ActivityType"("value");diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 26a2b78..8c9cc54 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -13,17 +13,19 @@ datasource db {}model User {- id String @id @default(uuid())- name String- email String @unique- password String- createdAt DateTime @default(now())- jobsApplied Job[]- JobTitle JobTitle[]- Location Location[]- Company Company[]- Contact Contact[]- Profile Profile[]+ id String @id @default(uuid())+ name String+ email String @unique+ password String+ createdAt DateTime @default(now())+ jobsApplied Job[]+ JobTitle JobTitle[]+ Location Location[]+ Company Company[]+ Contact Contact[]+ Profile Profile[]+ Activity Activity[]+ ActivityType ActivityType[]}model Profile {@@ -239,3 +241,32 @@ model Job {Resume Resume? @relation(fields: [resumeId], references: [id])resumeId String?}++model ActivityType {+ id String @id @default(uuid())+ label String+ value String @unique+ description String?+ createdBy String // userId+ user User @relation(fields: [createdBy], references: [id])+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ Activities Activity[]+}++model Activity {+ id String @id @default(uuid())+ userId String+ User User @relation(fields: [userId], references: [id])+ activityName String+ startTime DateTime+ endTime DateTime?+ duration Int?+ description String?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ activityType ActivityType @relation(fields: [activityTypeId], references: [id])+ activityTypeId String+}diff --git a/src/actions/activity.actions.ts b/src/actions/activity.actions.tsnew file mode 100644index 0000000..0e2f16a--- /dev/null+++ b/src/actions/activity.actions.ts@@ -0,0 +1,50 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { getCurrentUser } from "@/utils/user.utils";++export const getAllActivityTypes = async (): Promise<any | undefined> => {+ try {+ const user = await getCurrentUser();++ if (!user) {+ throw new Error("Not authenticated");+ }++ const activityTypes = await prisma.activityType.findMany({+ where: {+ createdBy: user.id,+ },+ });+ return activityTypes;+ } catch (error) {+ const msg = "Failed to fetch all activity types. ";+ return handleError(error, msg);+ }+};++export const createActivityType = async (+ label: string+): Promise<any | undefined> => {+ try {+ const user = await getCurrentUser();++ if (!user) {+ throw new Error("Not authenticated");+ }++ const value = label.trim().toLowerCase();++ const upsertedActivityType = await prisma.activityType.upsert({+ where: { value, createdBy: user.id },+ update: { label },+ create: { label, value, createdBy: user.id },+ });++ return upsertedActivityType;+ } catch (error) {+ const msg = "Failed to create activity type. ";+ console.error(msg, error);+ throw new Error(msg);+ }+};diff --git a/src/actions/job.actions.ts b/src/actions/job.actions.tsindex a681fd7..0e11fe1 100644--- a/src/actions/job.actions.ts+++ b/src/actions/job.actions.ts@@ -2,7 +2,7 @@import prisma from "@/lib/db";import { handleError } from "@/lib/utils";import { AddJobFormSchema } from "@/models/addJobForm.schema";-import { JobStatus } from "@/models/job.model";+import { JOB_TYPES, JobStatus } from "@/models/job.model";import { getCurrentUser } from "@/utils/user.utils";import { revalidatePath } from "next/cache";import { z } from "zod";@@ -41,11 +41,15 @@ export const getJobsList = async (const skip = (page - 1) * limit;const filterBy = filter- ? {- Status: {- value: filter,- },- }+ ? filter === Object.keys(JOB_TYPES)[1]+ ? {+ jobType: filter,+ }+ : {+ Status: {+ value: filter,+ },+ }: {};const [data, total] = await Promise.all([prisma.job.findMany({@@ -59,6 +63,7 @@ export const getJobsList = async (id: true,JobSource: true,JobTitle: true,+ jobType: true,Company: true,Status: true,Location: true,diff --git a/src/components/ComboBox.tsx b/src/components/ComboBox.tsxindex 5d37c2f..6797aeb 100644--- a/src/components/ComboBox.tsx+++ b/src/components/ComboBox.tsx@@ -27,6 +27,7 @@ import { JobForm } from "@/models/job.model";import { addCompany } from "@/actions/company.actions";import { createJobTitle } from "@/actions/jobtitle.actions";import { toast } from "./ui/use-toast";+import { createActivityType } from "@/actions/activity.actions";interface ComboboxProps {options: any[];@@ -63,6 +64,9 @@ export function Combobox({ options, field, creatable }: ComboboxProps) {}response = data;break;+ case "activityType":+ response = await createActivityType(label);+ break;default:break;}diff --git a/src/components/activities/ActivitiesContainer.tsx b/src/components/activities/ActivitiesContainer.tsxindex 789510e..19fb560 100644--- a/src/components/activities/ActivitiesContainer.tsx+++ b/src/components/activities/ActivitiesContainer.tsx@@ -1,11 +1,45 @@+"use client";import ActivitiesTable from "./ActivitiesTable";import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";+import { Button } from "../ui/button";+import { PlusCircle } from "lucide-react";+import { useState } from "react";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "../ui/dialog";+import { ActivityForm } from "./ActivityForm";function ActivitiesContainer() {+ const [activityFormOpen, setActivityFormOpen] = useState<boolean>(false);return (<Card>- <CardHeader>+ <CardHeader className="flex-row justify-between items-center"><CardTitle>Activities</CardTitle>+ <Dialog open={activityFormOpen} onOpenChange={setActivityFormOpen}>+ <DialogTrigger asChild>+ <Button+ size="sm"+ variant="outline"+ className="h-8 gap-1"+ data-testid="add-job-btn"+ >+ <PlusCircle className="h-3.5 w-3.5" />+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">+ Add Activity+ </span>+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-[625px]">+ <DialogHeader>+ <DialogTitle>Add New Activity</DialogTitle>+ </DialogHeader>+ <ActivityForm onClose={() => setActivityFormOpen(false)} />+ </DialogContent>+ </Dialog></CardHeader><CardContent><ActivitiesTable />diff --git a/src/components/activities/ActivityForm.tsx b/src/components/activities/ActivityForm.tsxnew file mode 100644index 0000000..4e9b158--- /dev/null+++ b/src/components/activities/ActivityForm.tsx@@ -0,0 +1,229 @@+"use client";++import { useForm } from "react-hook-form";+import { Button } from "../ui/button";+import { DialogFooter } from "../ui/dialog";+import { AddActivityFormSchema } from "@/models/addActivityForm.schema";+import { zodResolver } from "@hookform/resolvers/zod";+import { z } from "zod";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "../ui/form";+import { Input } from "../ui/input";+import { format } from "date-fns";+import { DatePicker } from "../DatePicker";+import TiptapEditor from "../TiptapEditor";+import { Combobox } from "../ComboBox";+import { useEffect, useState } from "react";+import { ActivityType } from "@/models/activity.model";+import { getAllActivityTypes } from "@/actions/activity.actions";++interface ActivityFormProps {+ onClose: () => void;+}++export function ActivityForm({ onClose }: ActivityFormProps) {+ const [activityTypes, setActivityTypes] = useState<ActivityType[]>([]);+ const now = new Date();+ const currentDate = now;+ const currentTime = format(now, "hh:mm a");+ const form = useForm<z.infer<typeof AddActivityFormSchema>>({+ resolver: zodResolver(AddActivityFormSchema),+ defaultValues: {+ activityName: "",+ activityType: "",+ startDate: currentDate,+ startTime: currentTime,+ endDate: currentDate,+ endTime: "",+ },+ });++ const {+ reset,+ formState: { errors, isValid },+ } = form;++ const loadActivityTypes = async () => {+ try {+ const activityTypes = await getAllActivityTypes();+ setActivityTypes(activityTypes);+ } catch (error) {+ console.error("Error loading activity types");+ }+ };++ useEffect(() => {+ loadActivityTypes();+ }, []);++ const onSubmit = (data: z.infer<typeof AddActivityFormSchema>) => {};+ return (+ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4"+ >+ {/* ACTIVITY NAME */}+ <div>+ <FormField+ control={form.control}+ name="activityName"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Activity Name</FormLabel>+ <FormControl>+ <Input+ {...field}+ placeholder="Ex: Job Search, Learning skill, etc"+ />+ </FormControl>+ <FormMessage>+ {errors.activityName && (+ <span className="text-red-500">+ {errors.activityName?.message}+ </span>+ )}+ </FormMessage>+ </FormItem>+ )}+ />+ </div>++ {/* ACTIVITY TYPE */}+ <div>+ <FormField+ control={form.control}+ name="activityType"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Activity Type</FormLabel>+ <FormControl>+ <Combobox options={activityTypes} field={field} creatable />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Start Date */}+ <div>+ <FormField+ control={form.control}+ name="startDate"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Start Date</FormLabel>+ <DatePicker field={field} presets={false} isEnabled={true} />+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* Start Time */}+ <div>+ <FormField+ control={form.control}+ name="startTime"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Start Time</FormLabel>+ <FormControl>+ <Input {...field} placeholder="hh:mm AM/PM" />+ </FormControl>+ <FormMessage>+ {errors.startTime && (+ <span className="text-red-500">+ {errors.startTime?.message}+ </span>+ )}+ </FormMessage>+ </FormItem>+ )}+ />+ </div>++ {/* End Date */}+ <div>+ <FormField+ control={form.control}+ name="endDate"+ render={({ field }) => (+ <FormItem>+ <FormLabel>End Date</FormLabel>+ <DatePicker field={field} presets={false} isEnabled={true} />+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ {/* End Time */}+ <div>+ <FormField+ control={form.control}+ name="endTime"+ render={({ field }) => (+ <FormItem>+ <FormLabel>End Time</FormLabel>+ <FormControl>+ <Input {...field} placeholder="hh:mm AM/PM" />+ </FormControl>+ <FormMessage>+ {errors.endTime && (+ <span className="text-red-500">+ {errors.endTime?.message}+ </span>+ )}+ </FormMessage>+ </FormItem>+ )}+ />+ </div>++ {/* Description */}+ <div className="md:col-span-2">+ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem className="flex flex-col">+ <FormLabel id="job-description-label">Description</FormLabel>+ <FormControl>+ <TiptapEditor field={field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ <div className="md:col-span-2 mt-4">+ <DialogFooter>+ <div>+ <Button+ type="reset"+ variant="outline"+ className="mt-2 md:mt-0 w-full"+ onClick={() => onClose()}+ >+ Cancel+ </Button>+ </div>+ <Button type="submit" data-testid="save-activity-btn">+ Save+ {/* {isPending && <Loader className="h-4 w-4 shrink-0 spinner" />} */}+ </Button>+ </DialogFooter>+ </div>+ </form>+ </Form>+ );+}diff --git a/src/components/myjobs/JobsContainer.tsx b/src/components/myjobs/JobsContainer.tsxindex 57cd377..11179e9 100644--- a/src/components/myjobs/JobsContainer.tsx+++ b/src/components/myjobs/JobsContainer.tsx@@ -195,6 +195,7 @@ function JobsContainer({<SelectItem value="interview">Interview</SelectItem><SelectItem value="draft">Draft</SelectItem><SelectItem value="rejected">Rejected</SelectItem>+ <SelectItem value="PT">Part-time</SelectItem></SelectGroup></SelectContent></Select>diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 4ebb7be..60a3693 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -8,6 +8,7 @@ import {export enum APP_CONSTANTS {RECORDS_PER_PAGE = 10,+ ACTIVITY_MAX_DURATION_MINUTES = 8 * 60, // 8 Hours}export const SIDEBAR_LINKS = [diff --git a/src/lib/utils.ts b/src/lib/utils.tsindex aa00986..b262a0c 100644--- a/src/lib/utils.ts+++ b/src/lib/utils.ts@@ -1,4 +1,5 @@import { type ClassValue, clsx } from "clsx";+import { parse } from "date-fns";import { NextApiRequest } from "next";import { twMerge } from "tailwind-merge";@@ -57,3 +58,17 @@ export function getTimestampedFileName(originalName: string): string {return `${baseName}_${timestamp}.${extension}`;}++export const combineDateAndTime = (date: Date, time: string): Date => {+ // Parse the time string into a `Date` object using a reference date+ const parsedTime = parse(time, "hh:mm a", new Date());+ // if (isNaN(parsedTime.getTime())) throw new Error("Invalid time format");++ return new Date(+ date.getFullYear(),+ date.getMonth(),+ date.getDate(),+ parsedTime.getHours(),+ parsedTime.getMinutes()+ );+};diff --git a/src/models/activity.model.ts b/src/models/activity.model.tsnew file mode 100644index 0000000..505b98a--- /dev/null+++ b/src/models/activity.model.ts@@ -0,0 +1,8 @@+export interface ActivityType {+ id: string;+ label: string;+ value: string;+ description?: string;+ createdAt: Date;+ updatedAt: Date;+}diff --git a/src/models/addActivityForm.schema.ts b/src/models/addActivityForm.schema.tsnew file mode 100644index 0000000..b89a139--- /dev/null+++ b/src/models/addActivityForm.schema.ts@@ -0,0 +1,88 @@+import { APP_CONSTANTS } from "@/lib/constants";+import { combineDateAndTime } from "@/lib/utils";+import { differenceInMinutes } from "date-fns";+import { z } from "zod";++export const AddActivityFormSchema = z+ .object({+ id: z.string().optional(),+ userId: z.string().optional(),+ activityName: z+ .string({+ required_error: "Activity name is required.",+ })+ .min(2, {+ message: "Activity name must be at least 2 characters.",+ }),+ activityType: z.string().min(1),+ startDate: z.date(),+ startTime: z+ .string()+ .regex(+ /^(0[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/,+ "Start time must be in hh:mm AM/PM format"+ ),+ endDate: z.date().optional(),+ endTime: z+ .string()+ .regex(+ /^(0[1-9]|1[0-2]):[0-5][0-9] (AM|PM)$/,+ "End time must be in hh:mm AM/PM format"+ )+ .optional(),+ duration: z+ .number()+ .min(0, "Duration must be a positive number")+ .optional(),+ description: z+ .string()+ .max(1000, {+ message: "Description cannot be more than 1000 characters.",+ })+ .optional(),+ })+ .refine(+ (data) => {+ if (!data.endDate) return true; // Skip if no endDate+ return data.endDate >= data.startDate;+ },+ {+ message: "End date must be the same as or after the start date",+ path: ["endDate"], // Target the error message to `endDate`+ }+ )+ // Check if `endTime` is earlier than `startTime` when the `endDate` equals `startDate`+ .refine(+ (data) => {+ if (!data.endDate || !data.endTime) return true; // Skip if no endDate or endTime+ if (data.endDate > data.startDate) return true; // Valid if endDate is after startDate++ // Combine date and time to compare+ const startDateTime = combineDateAndTime(data.startDate, data.startTime);+ const endDateTime = combineDateAndTime(data.endDate, data.endTime);++ return endDateTime > startDateTime; // Valid only if endDateTime is after startDateTime+ },+ {+ message:+ "End time must be after the start time when the end date is the same",+ path: ["endTime"],+ }+ )+ .refine(+ (data) => {+ if (!data.endDate || !data.endTime) return true; // Skip if no endDate or endTime++ const startDateTime = combineDateAndTime(data.startDate, data.startTime);+ const endDateTime = combineDateAndTime(data.endDate, data.endTime);++ const durationInMinutes = differenceInMinutes(endDateTime, startDateTime);+ return durationInMinutes <= APP_CONSTANTS.ACTIVITY_MAX_DURATION_MINUTES; // Ensure duration is within max duration allowed+ },+ {+ message: `The duration between start and end date/time cannot exceed ${+ APP_CONSTANTS.ACTIVITY_MAX_DURATION_MINUTES / 60+ } hours`,+ path: ["endTime"],+ }+ );