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: Add activity types tab on admin page

Khuram Niazf75fb82d91b3
diff --git a/src/actions/activity.actions.ts b/src/actions/activity.actions.ts
index 7f4033a..5803a0a 100644
--- a/src/actions/activity.actions.ts
+++ b/src/actions/activity.actions.ts
@@ -302,3 +302,91 @@ export const getCurrentActivity = async (): Promise<any | undefined> => {
return handleError(error, msg);
}
};
+
+export const getActivityTypeList = async (
+ page: number = 1,
+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const skip = (page - 1) * limit;
+ const whereClause = { createdBy: user.id };
+
+ const [total, durationSums] = await Promise.all([
+ prisma.activityType.count({ where: whereClause }),
+ prisma.activity.groupBy({
+ by: ["activityTypeId"],
+ where: { userId: user.id, endTime: { not: null } },
+ _sum: { duration: true },
+ }),
+ ]);
+
+ const durationMap = new Map(
+ durationSums.map((d) => [d.activityTypeId, d._sum.duration ?? 0]),
+ );
+
+ // Fetch all activity types with counts, then sort by total duration
+ const allTypes = await prisma.activityType.findMany({
+ where: whereClause,
+ select: {
+ id: true,
+ label: true,
+ value: true,
+ _count: { select: { Activities: true, Tasks: true } },
+ },
+ });
+
+ const sorted = allTypes
+ .map((t) => ({ ...t, totalDuration: durationMap.get(t.id) ?? 0 }))
+ .sort((a, b) => b.totalDuration - a.totalDuration);
+
+ const data = sorted.slice(skip, skip + limit);
+
+ return { data, total };
+ } catch (error) {
+ const msg = "Failed to fetch activity type list. ";
+ return handleError(error, msg);
+ }
+};
+
+export const deleteActivityTypeById = async (
+ activityTypeId: string,
+): Promise<any | undefined> => {
+ try {
+ const user = await getCurrentUser();
+ if (!user) {
+ throw new Error("Not authenticated");
+ }
+
+ const [activities, tasks] = await Promise.all([
+ prisma.activity.count({ where: { activityTypeId } }),
+ prisma.task.count({ where: { activityTypeId } }),
+ ]);
+
+ if (activities > 0 || tasks > 0) {
+ const links = [
+ activities > 0 ? `${activities} activity(ies)` : "",
+ tasks > 0 ? `${tasks} task(s)` : "",
+ ]
+ .filter(Boolean)
+ .join(" and ");
+
+ throw new Error(
+ `Activity type cannot be deleted because it is linked to ${links}.`,
+ );
+ }
+
+ const res = await prisma.activityType.delete({
+ where: { id: activityTypeId, createdBy: user.id },
+ });
+
+ return { res, success: true };
+ } catch (error) {
+ const msg = "Failed to delete activity type.";
+ return handleError(error, msg);
+ }
+};
diff --git a/src/components/admin/ActivityTypesContainer.tsx b/src/components/admin/ActivityTypesContainer.tsx
new file mode 100644
index 0000000..f7b8a47
--- /dev/null
+++ b/src/components/admin/ActivityTypesContainer.tsx
@@ -0,0 +1,102 @@
+"use client";
+import { useCallback, useEffect, useState } from "react";
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { getActivityTypeList } from "@/actions/activity.actions";
+import { APP_CONSTANTS } from "@/lib/constants";
+import Loading from "../Loading";
+import { Button } from "../ui/button";
+import { RecordsPerPageSelector } from "../RecordsPerPageSelector";
+import { RecordsCount } from "../RecordsCount";
+import ActivityTypesTable from "./ActivityTypesTable";
+import AddActivityType from "./AddActivityType";
+
+function ActivityTypesContainer() {
+ const [activityTypes, setActivityTypes] = useState<any[]>([]);
+ const [totalActivityTypes, setTotalActivityTypes] = useState<number>(0);
+ const [page, setPage] = useState<number>(1);
+ const [loading, setLoading] = useState<boolean>(false);
+ const [recordsPerPage, setRecordsPerPage] = useState<number>(
+ APP_CONSTANTS.RECORDS_PER_PAGE,
+ );
+
+ const loadActivityTypes = useCallback(
+ async (page: number) => {
+ setLoading(true);
+ try {
+ const { data, total } = await getActivityTypeList(page, recordsPerPage);
+ if (data) {
+ setActivityTypes((prev) => (page === 1 ? data : [...prev, ...data]));
+ setTotalActivityTypes(total);
+ setPage(page);
+ }
+ } finally {
+ setLoading(false);
+ }
+ },
+ [recordsPerPage],
+ );
+
+ const reloadActivityTypes = useCallback(async () => {
+ await loadActivityTypes(1);
+ }, [loadActivityTypes]);
+
+ useEffect(() => {
+ (async () => await loadActivityTypes(1))();
+ }, [loadActivityTypes, recordsPerPage]);
+
+ return (
+ <>
+ <div className="col-span-3">
+ <Card>
+ <CardHeader className="flex-row justify-between items-center">
+ <CardTitle>Activity Types / Projects</CardTitle>
+ <div className="flex items-center">
+ <div className="ml-auto flex items-center gap-2">
+ <AddActivityType reloadActivityTypes={reloadActivityTypes} />
+ </div>
+ </div>
+ </CardHeader>
+ <CardContent>
+ {loading && <Loading />}
+ {activityTypes.length > 0 && (
+ <>
+ <ActivityTypesTable
+ activityTypes={activityTypes}
+ reloadActivityTypes={reloadActivityTypes}
+ />
+ <div className="flex items-center justify-between mt-4">
+ <RecordsCount
+ count={activityTypes.length}
+ total={totalActivityTypes}
+ label="activity types"
+ />
+ {totalActivityTypes > APP_CONSTANTS.RECORDS_PER_PAGE && (
+ <RecordsPerPageSelector
+ value={recordsPerPage}
+ onChange={setRecordsPerPage}
+ />
+ )}
+ </div>
+ </>
+ )}
+ {activityTypes.length < totalActivityTypes && (
+ <div className="flex justify-center p-4">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => loadActivityTypes(page + 1)}
+ disabled={loading}
+ className="btn btn-primary"
+ >
+ {loading ? "Loading..." : "Load More"}
+ </Button>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ </>
+ );
+}
+
+export default ActivityTypesContainer;
diff --git a/src/components/admin/ActivityTypesTable.tsx b/src/components/admin/ActivityTypesTable.tsx
new file mode 100644
index 0000000..0157428
--- /dev/null
+++ b/src/components/admin/ActivityTypesTable.tsx
@@ -0,0 +1,163 @@
+"use client";
+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 { MoreHorizontal, Trash } from "lucide-react";
+import { useState } from "react";
+import { deleteActivityTypeById } from "@/actions/activity.actions";
+import { toast } from "../ui/use-toast";
+import { DeleteAlertDialog } from "../DeleteAlertDialog";
+import { AlertDialog } from "@/models/alertDialog.model";
+
+type ActivityTypeRow = {
+ id: string;
+ label: string;
+ value: string;
+ totalDuration: number;
+ _count?: { Activities?: number; Tasks?: number };
+};
+
+type ActivityTypesTableProps = {
+ activityTypes: ActivityTypeRow[];
+ reloadActivityTypes: () => void;
+};
+
+function ActivityTypesTable({
+ activityTypes,
+ reloadActivityTypes,
+}: ActivityTypesTableProps) {
+ const [alert, setAlert] = useState<AlertDialog>({
+ openState: false,
+ deleteAction: false,
+ });
+
+ const onDelete = (at: ActivityTypeRow) => {
+ const activityCount = at._count?.Activities ?? 0;
+ const taskCount = at._count?.Tasks ?? 0;
+
+ if (activityCount > 0 || taskCount > 0) {
+ const links = [
+ activityCount > 0 ? `${activityCount} activity(ies)` : "",
+ taskCount > 0 ? `${taskCount} task(s)` : "",
+ ]
+ .filter(Boolean)
+ .join(" and ");
+
+ setAlert({
+ openState: true,
+ title: "Activity type is in use!",
+ description: `This activity type is linked to ${links} and cannot be deleted.`,
+ deleteAction: false,
+ });
+ } else {
+ setAlert({
+ openState: true,
+ deleteAction: true,
+ itemId: at.id,
+ });
+ }
+ };
+
+ const deleteType = async (id: string | undefined) => {
+ if (!id) return;
+ const { success, message } = await deleteActivityTypeById(id);
+ if (success) {
+ toast({
+ variant: "success",
+ description: "Activity type has been deleted successfully",
+ });
+ reloadActivityTypes();
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Error!",
+ description: message,
+ });
+ }
+ };
+
+ const formatHours = (minutes: number) => {
+ const hours = minutes / 60;
+ return hours % 1 === 0 ? hours.toString() : hours.toFixed(1);
+ };
+
+ return (
+ <>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Label</TableHead>
+ <TableHead className="hidden sm:table-cell">Value</TableHead>
+ <TableHead># Activities</TableHead>
+ <TableHead># Tasks</TableHead>
+ <TableHead>Total Hours</TableHead>
+ <TableHead>Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {activityTypes.map((at) => (
+ <TableRow key={at.id}>
+ <TableCell className="font-medium">{at.label}</TableCell>
+ <TableCell className="font-medium hidden sm:table-cell">
+ {at.value}
+ </TableCell>
+ <TableCell className="font-medium">
+ {at._count?.Activities ?? 0}
+ </TableCell>
+ <TableCell className="font-medium">
+ {at._count?.Tasks ?? 0}
+ </TableCell>
+ <TableCell className="font-medium">
+ {formatHours(at.totalDuration)} hrs
+ </TableCell>
+ <TableCell>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button aria-haspopup="true" size="icon" variant="ghost">
+ <MoreHorizontal className="h-4 w-4" />
+ <span className="sr-only">Toggle menu</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuLabel>Actions</DropdownMenuLabel>
+ <DropdownMenuItem
+ className="text-red-600 cursor-pointer"
+ onClick={() => onDelete(at)}
+ >
+ <Trash className="mr-2 h-4 w-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ <DeleteAlertDialog
+ pageTitle="activity 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 ActivityTypesTable;
diff --git a/src/components/admin/AddActivityType.tsx b/src/components/admin/AddActivityType.tsx
new file mode 100644
index 0000000..de0762f
--- /dev/null
+++ b/src/components/admin/AddActivityType.tsx
@@ -0,0 +1,138 @@
+"use client";
+import { useTransition, useState } from "react";
+import { Button } from "../ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "../ui/dialog";
+import { Loader, PlusCircle } 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 { toast } from "../ui/use-toast";
+import { createActivityType } from "@/actions/activity.actions";
+
+const AddActivityTypeFormSchema = z.object({
+ label: z
+ .string({ error: "Activity type label is required." })
+ .min(1, { message: "Activity type label cannot be empty." })
+ .max(60, { message: "Activity type label must be 60 characters or fewer." }),
+});
+
+type AddActivityTypeProps = {
+ reloadActivityTypes: () => void;
+};
+
+function AddActivityType({ reloadActivityTypes }: AddActivityTypeProps) {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [isPending, startTransition] = useTransition();
+
+ const form = useForm<z.infer<typeof AddActivityTypeFormSchema>>({
+ resolver: zodResolver(AddActivityTypeFormSchema),
+ defaultValues: { label: "" },
+ });
+
+ const { reset } = form;
+
+ const openDialog = () => {
+ reset();
+ setDialogOpen(true);
+ };
+
+ const onSubmit = (values: z.infer<typeof AddActivityTypeFormSchema>) => {
+ startTransition(async () => {
+ try {
+ await createActivityType(values.label);
+ toast({
+ variant: "success",
+ description: "Activity type has been added successfully.",
+ });
+ setDialogOpen(false);
+ reset();
+ reloadActivityTypes();
+ } catch {
+ toast({
+ variant: "destructive",
+ title: "Error!",
+ description: "Failed to create activity type.",
+ });
+ }
+ });
+ };
+
+ return (
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-8 gap-1"
+ onClick={openDialog}
+ >
+ <PlusCircle className="h-3.5 w-3.5" />
+ <span className="sr-only sm:not-sr-only sm:whitespace-nowrap">
+ Add Activity Type
+ </span>
+ </Button>
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add Activity Type</DialogTitle>
+ <DialogDescription>
+ Add a new activity type to categorize your activities and tasks.
+ </DialogDescription>
+ </DialogHeader>
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
+ <FormField
+ control={form.control}
+ name="label"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Activity Type Name</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="e.g. Networking, Interview Prep"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setDialogOpen(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 AddActivityType;
diff --git a/src/components/admin/AdminTabsContainer.tsx b/src/components/admin/AdminTabsContainer.tsx
index 450b2df..d575073 100644
--- a/src/components/admin/AdminTabsContainer.tsx
+++ b/src/components/admin/AdminTabsContainer.tsx
@@ -1,4 +1,5 @@
"use client";
+import ActivityTypesContainer from "@/components/admin/ActivityTypesContainer";
import CompaniesContainer from "@/components/admin/CompaniesContainer";
import JobLocationsContainer from "@/components/admin/JobLocationsContainer";
import JobSourcesContainer from "@/components/admin/JobSourcesContainer";
@@ -37,6 +38,7 @@ function AdminTabsContainer() {
<TabsTrigger value="locations">Locations</TabsTrigger>
<TabsTrigger value="sources">Sources</TabsTrigger>
<TabsTrigger value="skills">Skills</TabsTrigger>
+ <TabsTrigger value="activity-types">Activity Types</TabsTrigger>
</TabsList>
<TabsContent value="companies">
<CompaniesContainer />
@@ -53,6 +55,9 @@ function AdminTabsContainer() {
<TabsContent value="skills">
<TagsContainer />
</TabsContent>
+ <TabsContent value="activity-types">
+ <ActivityTypesContainer />
+ </TabsContent>
</Tabs>
);
}