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.

Add search feature to activities page

Khuram Niaz009837574672
diff --git a/__tests__/ActivitiesContainer.spec.tsx b/__tests__/ActivitiesContainer.spec.tsx
new file mode 100644
index 0000000..84a9f7a
--- /dev/null
+++ b/__tests__/ActivitiesContainer.spec.tsx
@@ -0,0 +1,490 @@
+import ActivitiesContainer from "@/components/activities/ActivitiesContainer";
+import "@testing-library/jest-dom";
+import { screen, render, waitFor, act } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import {
+ getActivitiesList,
+ getCurrentActivity,
+ startActivityById,
+ stopActivityById,
+} from "@/actions/activity.actions";
+
+jest.mock("next-auth", () => {
+ const mockAuth = jest.fn();
+ const mockSignIn = jest.fn();
+ const mockSignOut = jest.fn();
+ const mockHandlers = { GET: jest.fn(), POST: jest.fn() };
+
+ return {
+ __esModule: true,
+ default: jest.fn(() => ({
+ auth: mockAuth,
+ handlers: mockHandlers,
+ signIn: mockSignIn,
+ signOut: mockSignOut,
+ })),
+ auth: mockAuth,
+ signIn: mockSignIn,
+ signOut: mockSignOut,
+ handlers: mockHandlers,
+ };
+});
+
+jest.mock("next-auth/providers/credentials", () => ({
+ __esModule: true,
+ default: jest.fn(() => ({
+ id: "credentials",
+ name: "Credentials",
+ type: "credentials",
+ })),
+}));
+
+jest.mock("@/actions/activity.actions", () => ({
+ getActivitiesList: jest.fn(),
+ getCurrentActivity: jest.fn(),
+ startActivityById: jest.fn(),
+ stopActivityById: jest.fn(),
+ getAllActivityTypes: jest.fn(),
+ createActivityType: jest.fn(),
+ createActivity: jest.fn(),
+ deleteActivityById: jest.fn(),
+}));
+
+global.ResizeObserver = jest.fn().mockImplementation(() => ({
+ observe: jest.fn(),
+ unobserve: jest.fn(),
+ disconnect: jest.fn(),
+}));
+
+document.createRange = () => {
+ const range = new Range();
+
+ range.getBoundingClientRect = jest.fn().mockReturnValue({
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 0,
+ top: 0,
+ width: 0,
+ });
+
+ range.getClientRects = () => {
+ return {
+ item: () => null,
+ length: 0,
+ [Symbol.iterator]: jest.fn(),
+ };
+ };
+
+ return range;
+};
+
+describe("ActivitiesContainer Search Functionality", () => {
+ const mockActivities = [
+ {
+ id: "1",
+ activityName: "TypeScript Learning",
+ startTime: new Date("2024-06-19T09:00:00"),
+ endTime: new Date("2024-06-19T10:00:00"),
+ duration: 60,
+ description: "Learning TypeScript advanced concepts",
+ createdAt: new Date("2024-06-19"),
+ activityType: { id: "1", label: "Learning", value: "learning" },
+ },
+ {
+ id: "2",
+ activityName: "Build Portfolio",
+ startTime: new Date("2024-06-19T11:00:00"),
+ endTime: new Date("2024-06-19T12:30:00"),
+ duration: 90,
+ description: "Working on portfolio website",
+ createdAt: new Date("2024-06-19"),
+ activityType: { id: "2", label: "Side Project", value: "side-project" },
+ },
+ {
+ id: "3",
+ activityName: "Job Search",
+ startTime: new Date("2024-06-20T14:00:00"),
+ endTime: new Date("2024-06-20T15:00:00"),
+ duration: 60,
+ description: "Applying to developer positions",
+ createdAt: new Date("2024-06-20"),
+ activityType: { id: "3", label: "Job Search", value: "job-search" },
+ },
+ ];
+
+ const user = userEvent.setup({ delay: null });
+ window.HTMLElement.prototype.scrollIntoView = jest.fn();
+ window.HTMLElement.prototype.hasPointerCapture = jest.fn();
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ (getCurrentActivity as jest.Mock).mockResolvedValue({ success: false });
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ const renderComponent = () => {
+ return render(<ActivitiesContainer />);
+ };
+
+ describe("Search Input", () => {
+ it("should render search input with placeholder", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText("Search activities...")
+ ).toBeInTheDocument();
+ });
+ });
+
+ it("should update search input value when typing", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText("Search activities...")
+ ).toBeInTheDocument();
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+
+ await act(async () => {
+ await user.type(searchInput, "TypeScript");
+ });
+
+ expect(searchInput).toHaveValue("TypeScript");
+ });
+
+ it("should debounce search input for 300ms", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledTimes(1);
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+
+ await act(async () => {
+ await user.type(searchInput, "T");
+ });
+
+ // Should not have called getActivitiesList yet (debounce not elapsed)
+ expect(getActivitiesList).toHaveBeenCalledTimes(1);
+
+ // Advance timer by 300ms to trigger debounce
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ // Now search should have been triggered
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ it("should call getActivitiesList with search term after debounce", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledTimes(1);
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+
+ await act(async () => {
+ await user.type(searchInput, "Learning");
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledWith(1, 25, "Learning");
+ });
+ });
+
+ it("should not trigger search on initial mount with empty search", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledTimes(1);
+ });
+
+ // Initial call should not have search parameter
+ expect(getActivitiesList).toHaveBeenCalledWith(1, 25, undefined);
+ });
+
+ it("should trigger search when clearing search term after searching", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledTimes(1);
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+
+ // Type to trigger search
+ await act(async () => {
+ await user.type(searchInput, "Test");
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledWith(1, 25, "Test");
+ });
+
+ // Clear the search input
+ await act(async () => {
+ await user.clear(searchInput);
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ // Should call with undefined when cleared after having searched
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledWith(1, 25, undefined);
+ });
+ });
+ });
+
+ describe("Search Results Display", () => {
+ it("should display filtered activities after search", async () => {
+ const learningActivity = [mockActivities[0]];
+
+ (getActivitiesList as jest.Mock)
+ .mockResolvedValueOnce({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ })
+ .mockResolvedValueOnce({
+ success: true,
+ data: learningActivity,
+ total: 1,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(screen.getByText("TypeScript Learning")).toBeInTheDocument();
+ expect(screen.getByText("Build Portfolio")).toBeInTheDocument();
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+ await act(async () => {
+ await user.type(searchInput, "TypeScript");
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("TypeScript Learning")).toBeInTheDocument();
+ });
+ });
+
+ it("should show loading state during search", async () => {
+ let resolvePromise: (value: any) => void;
+ const searchPromise = new Promise((resolve) => {
+ resolvePromise = resolve;
+ });
+
+ (getActivitiesList as jest.Mock)
+ .mockResolvedValueOnce({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ })
+ .mockReturnValueOnce(searchPromise);
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(screen.getByText("TypeScript Learning")).toBeInTheDocument();
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+ await act(async () => {
+ await user.type(searchInput, "test");
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ // Should show loading indicator
+ await waitFor(() => {
+ expect(screen.getByTestId("loader")).toBeInTheDocument();
+ });
+
+ // Resolve the search
+ await act(async () => {
+ resolvePromise!({
+ success: true,
+ data: [],
+ total: 0,
+ });
+ });
+ });
+ });
+
+ describe("Load More with Search", () => {
+ it("should preserve search term when loading more", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 50,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(screen.getByText("Load More")).toBeInTheDocument();
+ });
+
+ // Type search
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+ await act(async () => {
+ await user.type(searchInput, "Learning");
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledWith(1, 25, "Learning");
+ });
+
+ // Click load more
+ const loadMoreButton = screen.getByText("Load More");
+ await act(async () => {
+ await user.click(loadMoreButton);
+ });
+
+ // Should include search term in load more call
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledWith(2, 25, "Learning");
+ });
+ });
+ });
+
+ describe("Error Handling", () => {
+ it("should handle search error gracefully", async () => {
+ (getActivitiesList as jest.Mock)
+ .mockResolvedValueOnce({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ })
+ .mockResolvedValueOnce({
+ success: false,
+ message: "Search failed",
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(screen.getByText("TypeScript Learning")).toBeInTheDocument();
+ });
+
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+ await act(async () => {
+ await user.type(searchInput, "test");
+ });
+
+ await act(async () => {
+ jest.advanceTimersByTime(300);
+ });
+
+ await waitFor(() => {
+ expect(getActivitiesList).toHaveBeenCalledWith(1, 25, "test");
+ });
+ });
+ });
+
+ describe("Search UI Elements", () => {
+ it("should render search icon", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ expect(
+ screen.getByPlaceholderText("Search activities...")
+ ).toBeInTheDocument();
+ });
+
+ // Search input should have the correct container structure
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+ expect(searchInput).toHaveClass("pl-8");
+ });
+
+ it("should have correct input type", async () => {
+ (getActivitiesList as jest.Mock).mockResolvedValue({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+
+ renderComponent();
+
+ await waitFor(() => {
+ const searchInput = screen.getByPlaceholderText("Search activities...");
+ expect(searchInput).toHaveAttribute("type", "search");
+ });
+ });
+ });
+});
diff --git a/__tests__/activity.actions.spec.ts b/__tests__/activity.actions.spec.ts
new file mode 100644
index 0000000..343582a
--- /dev/null
+++ b/__tests__/activity.actions.spec.ts
@@ -0,0 +1,265 @@
+import { getActivitiesList } from "@/actions/activity.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { PrismaClient } from "@prisma/client";
+
+const prisma = new PrismaClient();
+
+jest.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ activity: {
+ findMany: jest.fn(),
+ count: jest.fn(),
+ },
+ activityType: {
+ findMany: jest.fn(),
+ },
+ };
+ return { PrismaClient: jest.fn(() => mPrismaClient) };
+});
+
+jest.mock("@/utils/user.utils", () => ({
+ getCurrentUser: jest.fn(),
+}));
+
+describe("activity.actions", () => {
+ const mockUser = { id: "user-id" };
+
+ const mockActivities = [
+ {
+ id: "1",
+ activityName: "TypeScript Learning",
+ startTime: new Date("2024-06-19T09:00:00"),
+ endTime: new Date("2024-06-19T10:00:00"),
+ duration: 60,
+ description: "Learning TypeScript advanced concepts",
+ createdAt: new Date("2024-06-19"),
+ activityType: { id: "1", label: "Learning", value: "learning" },
+ },
+ {
+ id: "2",
+ activityName: "Build Portfolio",
+ startTime: new Date("2024-06-19T11:00:00"),
+ endTime: new Date("2024-06-19T12:30:00"),
+ duration: 90,
+ description: "Working on portfolio website",
+ createdAt: new Date("2024-06-19"),
+ activityType: { id: "2", label: "Side Project", value: "side-project" },
+ },
+ {
+ id: "3",
+ activityName: "Job Search",
+ startTime: new Date("2024-06-20T14:00:00"),
+ endTime: new Date("2024-06-20T15:00:00"),
+ duration: 60,
+ description: "Applying to developer positions",
+ createdAt: new Date("2024-06-20"),
+ activityType: { id: "3", label: "Job Search", value: "job-search" },
+ },
+ ];
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe("getActivitiesList", () => {
+ it("should retrieve activities with default parameters", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue(mockActivities);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(3);
+
+ const result = await getActivitiesList();
+
+ expect(result).toEqual({
+ success: true,
+ data: mockActivities,
+ total: 3,
+ });
+ expect(prisma.activity.findMany).toHaveBeenCalledTimes(1);
+ expect(prisma.activity.count).toHaveBeenCalledTimes(1);
+ });
+
+ it("should return error when user is not authenticated", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(null);
+
+ const result = await getActivitiesList();
+
+ expect(result).toEqual({
+ success: false,
+ message: "Not authenticated",
+ });
+ });
+
+ it("should return error when fetching data fails", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockRejectedValue(
+ new Error("Database error")
+ );
+
+ const result = await getActivitiesList();
+
+ expect(result).toEqual({
+ success: false,
+ message: "Database error",
+ });
+ });
+
+ describe("search functionality", () => {
+ it("should build OR clause when search parameter is provided", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "TypeScript");
+
+ expect(prisma.activity.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({
+ userId: mockUser.id,
+ endTime: { not: null },
+ OR: [
+ { activityName: { contains: "TypeScript" } },
+ { description: { contains: "TypeScript" } },
+ { activityType: { label: { contains: "TypeScript" } } },
+ ],
+ }),
+ })
+ );
+ expect(prisma.activity.count).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({
+ OR: [
+ { activityName: { contains: "TypeScript" } },
+ { description: { contains: "TypeScript" } },
+ { activityType: { label: { contains: "TypeScript" } } },
+ ],
+ }),
+ })
+ );
+ });
+
+ it("should search across activity name", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "Portfolio");
+
+ const findManyCall = (prisma.activity.findMany as jest.Mock).mock
+ .calls[0][0];
+ expect(findManyCall.where.OR).toContainEqual({
+ activityName: { contains: "Portfolio" },
+ });
+ });
+
+ it("should search across description", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "developer");
+
+ const findManyCall = (prisma.activity.findMany as jest.Mock).mock
+ .calls[0][0];
+ expect(findManyCall.where.OR).toContainEqual({
+ description: { contains: "developer" },
+ });
+ });
+
+ it("should search across activity type label", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "Learning");
+
+ const findManyCall = (prisma.activity.findMany as jest.Mock).mock
+ .calls[0][0];
+ expect(findManyCall.where.OR).toContainEqual({
+ activityType: { label: { contains: "Learning" } },
+ });
+ });
+
+ it("should not include OR clause when search is undefined", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, undefined);
+
+ const findManyCall = (prisma.activity.findMany as jest.Mock).mock
+ .calls[0][0];
+ expect(findManyCall.where.OR).toBeUndefined();
+ });
+
+ it("should not include OR clause when search is empty string", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "");
+
+ const findManyCall = (prisma.activity.findMany as jest.Mock).mock
+ .calls[0][0];
+ expect(findManyCall.where.OR).toBeUndefined();
+ });
+
+ it("should return filtered results with correct pagination", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ const mockFilteredData = [mockActivities[0]];
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue(
+ mockFilteredData
+ );
+ (prisma.activity.count as jest.Mock).mockResolvedValue(1);
+
+ const result = await getActivitiesList(1, 25, "TypeScript");
+
+ expect(result).toEqual({
+ success: true,
+ data: mockFilteredData,
+ total: 1,
+ });
+ });
+
+ it("should apply pagination with skip and take", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(2, 10, "test");
+
+ expect(prisma.activity.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ skip: 10,
+ take: 10,
+ })
+ );
+ });
+
+ it("should order results by createdAt descending", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "test");
+
+ expect(prisma.activity.findMany).toHaveBeenCalledWith(
+ expect.objectContaining({
+ orderBy: { createdAt: "desc" },
+ })
+ );
+ });
+
+ it("should only return completed activities (with endTime)", async () => {
+ (getCurrentUser as jest.Mock).mockResolvedValue(mockUser);
+ (prisma.activity.findMany as jest.Mock).mockResolvedValue([]);
+ (prisma.activity.count as jest.Mock).mockResolvedValue(0);
+
+ await getActivitiesList(1, 25, "test");
+
+ const findManyCall = (prisma.activity.findMany as jest.Mock).mock
+ .calls[0][0];
+ expect(findManyCall.where.endTime).toEqual({ not: null });
+ });
+ });
+ });
+});
diff --git a/package.json b/package.json
index 7e4dfcb..b23a0db 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "jobsync",
- "version": "0.2.1",
+ "version": "0.2.2",
"private": true,
"scripts": {
"dev": "next dev -p 3000",
diff --git a/src/actions/activity.actions.ts b/src/actions/activity.actions.ts
index 1511d79..56355d1 100644
--- a/src/actions/activity.actions.ts
+++ b/src/actions/activity.actions.ts
@@ -55,7 +55,8 @@ export const createActivityType = async (
export const getActivitiesList = async (
page: number = 1,
- limit: number = APP_CONSTANTS.RECORDS_PER_PAGE
+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,
+ search?: string
): Promise<any | undefined> => {
try {
const user = await getCurrentUser();
@@ -66,14 +67,24 @@ export const getActivitiesList = async (
const offset = (page - 1) * limit;
+ const whereClause: any = {
+ userId: user.id,
+ endTime: {
+ not: null,
+ },
+ };
+
+ if (search) {
+ whereClause.OR = [
+ { activityName: { contains: search } },
+ { description: { contains: search } },
+ { activityType: { label: { contains: search } } },
+ ];
+ }
+
const [data, total] = await Promise.all([
prisma.activity.findMany({
- where: {
- userId: user.id,
- endTime: {
- not: null,
- },
- },
+ where: whereClause,
select: {
id: true,
activityName: true,
@@ -91,12 +102,7 @@ export const getActivitiesList = async (
take: limit,
}),
prisma.activity.count({
- where: {
- userId: user.id,
- endTime: {
- not: null,
- },
- },
+ where: whereClause,
}),
]);
diff --git a/src/components/activities/ActivitiesContainer.tsx b/src/components/activities/ActivitiesContainer.tsx
index b30494c..728dfa3 100644
--- a/src/components/activities/ActivitiesContainer.tsx
+++ b/src/components/activities/ActivitiesContainer.tsx
@@ -2,7 +2,8 @@
import ActivitiesTable from "./ActivitiesTable";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Button } from "../ui/button";
-import { PlusCircle } from "lucide-react";
+import { Input } from "../ui/input";
+import { PlusCircle, Search } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Dialog,
@@ -39,6 +40,8 @@ function ActivitiesContainer() {
const [recordsPerPage, setRecordsPerPage] = useState<number>(
APP_CONSTANTS.RECORDS_PER_PAGE,
);
+ const [searchTerm, setSearchTerm] = useState("");
+ const hasSearched = useRef(false);
const closeActivityForm = () => setActivityFormOpen(false);
@@ -51,35 +54,42 @@ function ActivitiesContainer() {
setTimeElapsed(0);
}, []);
- const loadActivities = useCallback(async (page: number, limit: number) => {
- setLoading(true);
- try {
- const { data, success, message, total } = await getActivitiesList(page, limit);
- if (success) {
- setActivitiesList((prev) => (page === 1 ? data : [...prev, ...data]));
- setTotalActivities(total);
- setPage(page);
- } else {
+ const loadActivities = useCallback(
+ async (page: number, limit: number, search?: string) => {
+ setLoading(true);
+ try {
+ const { data, success, message, total } = await getActivitiesList(
+ page,
+ limit,
+ search
+ );
+ if (success) {
+ setActivitiesList((prev) => (page === 1 ? data : [...prev, ...data]));
+ setTotalActivities(total);
+ setPage(page);
+ } else {
+ toast({
+ variant: "destructive",
+ title: "Error!",
+ description: message,
+ });
+ }
+ } catch (error) {
toast({
variant: "destructive",
title: "Error!",
- description: message,
+ description: "Failed to load activities. Please try again.",
});
+ } finally {
+ setLoading(false);
}
- } catch (error) {
- toast({
- variant: "destructive",
- title: "Error!",
- description: "Failed to load activities. Please try again.",
- });
- } finally {
- setLoading(false);
- }
- }, []);
+ },
+ []
+ );
const reloadActivities = useCallback(async () => {
- await loadActivities(1, recordsPerPage);
- }, [loadActivities, recordsPerPage]);
+ await loadActivities(1, recordsPerPage, searchTerm || undefined);
+ }, [loadActivities, recordsPerPage, searchTerm]);
const stopActivity = useCallback(
async (autoStop: boolean = false) => {
@@ -194,11 +204,36 @@ function ActivitiesContainer() {
}
}, [currentActivity, startTimer]);
+ // Debounced search effect
+ useEffect(() => {
+ if (searchTerm !== "") {
+ hasSearched.current = true;
+ }
+ if (searchTerm === "" && !hasSearched.current) return;
+
+ const timer = setTimeout(() => {
+ loadActivities(1, recordsPerPage, searchTerm || undefined);
+ }, 300);
+ return () => clearTimeout(timer);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [searchTerm]);
+
return (
<Card>
<CardHeader className="flex-row justify-between items-center">
<CardTitle>Activities</CardTitle>
- <Dialog open={activityFormOpen} onOpenChange={setActivityFormOpen}>
+ <div className="flex items-center gap-2">
+ <div className="relative">
+ <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
+ <Input
+ type="search"
+ placeholder="Search activities..."
+ className="pl-8 h-8 w-[150px] lg:w-[200px]"
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ />
+ </div>
+ <Dialog open={activityFormOpen} onOpenChange={setActivityFormOpen}>
<DialogTrigger asChild>
<Button
size="sm"
@@ -223,7 +258,8 @@ function ActivitiesContainer() {
/>
</div>
</DialogContent>
- </Dialog>
+ </Dialog>
+ </div>
</CardHeader>
<CardContent>
{loading && <Loading />}
@@ -264,7 +300,7 @@ function ActivitiesContainer() {
<Button
size="sm"
variant="outline"
- onClick={() => loadActivities(page + 1, recordsPerPage)}
+ onClick={() => loadActivities(page + 1, recordsPerPage, searchTerm || undefined)}
disabled={loading}
className="btn btn-primary"
>