diff --git a/apps/customer-portal/webapp/src/api/useSearchProjectTimeCards.ts b/apps/customer-portal/webapp/src/api/useSearchProjectTimeCards.ts index 83a3c658ac..40c29f1102 100644 --- a/apps/customer-portal/webapp/src/api/useSearchProjectTimeCards.ts +++ b/apps/customer-portal/webapp/src/api/useSearchProjectTimeCards.ts @@ -14,7 +14,11 @@ // specific language governing permissions and limitations // under the License. -import { useQuery, type UseQueryResult } from "@tanstack/react-query"; +import { + useInfiniteQuery, + type UseInfiniteQueryResult, + type InfiniteData, +} from "@tanstack/react-query"; import { useAsgardeo } from "@asgardeo/react"; import { useLogger } from "@hooks/useLogger"; import { ApiQueryKeys } from "@constants/apiConstants"; @@ -26,42 +30,39 @@ export interface UseSearchProjectTimeCardsParams { projectId: string; startDate?: string; endDate?: string; - limit?: number; - offset?: number; + states?: string[]; } /** - * Custom hook to search project time cards with date range filters. + * Custom hook to search project time cards with date range filters using infinite query. * * @param {UseSearchProjectTimeCardsParams} params - Project ID and filters. - * @returns {UseQueryResult} The query result object. + * @returns {UseInfiniteQueryResult, Error>} The infinite query result object. */ export default function useSearchProjectTimeCards({ projectId, startDate, endDate, - limit = 10, - offset = 0, -}: UseSearchProjectTimeCardsParams): UseQueryResult< - TimeCardSearchResponse, + states, +}: UseSearchProjectTimeCardsParams): UseInfiniteQueryResult< + InfiniteData, Error > { const logger = useLogger(); const { isSignedIn, isLoading: isAuthLoading } = useAsgardeo(); const fetchFn = useAuthApiClient(); - return useQuery({ + return useInfiniteQuery({ queryKey: [ ApiQueryKeys.TIME_CARDS_SEARCH, projectId, startDate, endDate, - limit, - offset, + states, ], - queryFn: async (): Promise => { + queryFn: async ({ pageParam = 0, signal }): Promise => { logger.debug( - `Searching time cards for project ID: ${projectId}, start: ${startDate}, end: ${endDate}`, + `Searching time cards for project ID: ${projectId}, start: ${startDate}, end: ${endDate}, offset: ${pageParam}`, ); try { @@ -76,14 +77,16 @@ export default function useSearchProjectTimeCards({ filters: { startDate, endDate, + ...(states && states.length > 0 && { states }), }, - pagination: { limit, offset }, + pagination: { limit: 10, offset: pageParam as number }, }; const response = await fetchFn(requestUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), + signal, }); logger.debug( @@ -104,6 +107,11 @@ export default function useSearchProjectTimeCards({ throw error; } }, + initialPageParam: 0, + getNextPageParam: (lastPage) => { + const nextOffset = lastPage.offset + lastPage.limit; + return nextOffset < lastPage.totalRecords ? nextOffset : undefined; + }, enabled: !!projectId && !!startDate && !!endDate && isSignedIn && !isAuthLoading, staleTime: 5 * 60 * 1000, diff --git a/apps/customer-portal/webapp/src/components/project-details/time-tracking/ProjectTimeTracking.tsx b/apps/customer-portal/webapp/src/components/project-details/time-tracking/ProjectTimeTracking.tsx index b9b452234c..4e227ade70 100644 --- a/apps/customer-portal/webapp/src/components/project-details/time-tracking/ProjectTimeTracking.tsx +++ b/apps/customer-portal/webapp/src/components/project-details/time-tracking/ProjectTimeTracking.tsx @@ -15,9 +15,10 @@ // under the License. import { Box, Grid } from "@wso2/oxygen-ui"; -import { useState, useMemo, type JSX } from "react"; +import { useState, useMemo, useEffect, useRef, type JSX } from "react"; import useSearchProjectTimeCards from "@api/useSearchProjectTimeCards"; import useGetTimeCardsStats from "@api/useGetTimeCardsStats"; +import useGetProjectFilters from "@api/useGetProjectFilters"; import TimeTrackingStatCards from "@time-tracking/TimeTrackingStatCards"; import TimeCardsDateFilter from "@time-tracking/TimeCardsDateFilter"; import TimeTrackingCard from "@time-tracking/TimeTrackingCard"; @@ -55,11 +56,15 @@ export default function ProjectTimeTracking({ projectId, }: ProjectTimeTrackingProps): JSX.Element { const { startDate: defaultStart, endDate: defaultEnd } = useMemo( - getDefaultDateRange, + () => getDefaultDateRange(), [], ); const [startDate, setStartDate] = useState(defaultStart); const [endDate, setEndDate] = useState(defaultEnd); + const [state, setState] = useState(""); const [showLoadMore, setShowLoadMore] = useState(false); const autoFetchCountRef = useRef(0); + const maxAutoFetches = 3; + + const { data: filters } = useGetProjectFilters(projectId); const { data: stats, @@ -72,19 +77,53 @@ export default function ProjectTimeTracking({ }); const { - data: timeCardsData, + data, isLoading: isTimeCardsLoading, isError: isTimeCardsError, + hasNextPage, + fetchNextPage, } = useSearchProjectTimeCards({ projectId, startDate, endDate, - limit: 50, - offset: 0, + states: state ? [state] : undefined, }); - const timeCards = timeCardsData?.timeCards ?? []; - const totalRecords = timeCardsData?.totalRecords ?? 0; + // Auto-fetch pages with limit to prevent request bursts + useEffect(() => { + if (!data || !hasNextPage) return; + if (autoFetchCountRef.current >= maxAutoFetches) { + // Don't auto-fetch, let user click Load More + return; + } + autoFetchCountRef.current += 1; + void fetchNextPage(); + }, [data, hasNextPage, fetchNextPage]); + + useEffect(() => { + if (data && hasNextPage && autoFetchCountRef.current >= maxAutoFetches) { + setShowLoadMore(true); + } else { + setShowLoadMore(false); + } + }, [data, hasNextPage]); + + // Reset auto-fetch counter when filters change + useEffect(() => { + autoFetchCountRef.current = 0; + }, [projectId, startDate, endDate, state]); + + const handleLoadMore = () => { + setShowLoadMore(false); + autoFetchCountRef.current = 0; + void fetchNextPage(); + }; + + // Flatten all pages into a single array + const timeCards = useMemo( + () => data?.pages.flatMap((page) => page.timeCards) ?? [], + [data] + ); return ( @@ -100,34 +139,59 @@ export default function ProjectTimeTracking({ endDate={endDate} onStartDateChange={setStartDate} onEndDateChange={setEndDate} - shownCount={timeCards.length} - totalCount={totalRecords} - isLoading={isTimeCardsLoading} + state={state} + onStateChange={setState} + timeCardStates={filters?.timeCardStates} /> {isTimeCardsError ? ( ) : ( - - {isTimeCardsLoading ? ( - Array.from({ length: 7 }).map((_, index) => ( - - - - )) - ) : timeCards.length === 0 ? ( - - - - ) : ( - timeCards.map((card) => ( - - + <> + + {isTimeCardsLoading ? ( + Array.from({ length: 7 }).map((_, index) => ( + + + + )) + ) : timeCards.length === 0 ? ( + + - )) + ) : ( + timeCards.map((card) => ( + + + + )) + )} + + {showLoadMore && ( + + + Load More Time Cards + + )} - + )} ); diff --git a/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeCardsDateFilter.tsx b/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeCardsDateFilter.tsx index c662d9c12f..b15da843c7 100644 --- a/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeCardsDateFilter.tsx +++ b/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeCardsDateFilter.tsx @@ -20,24 +20,28 @@ import { Typography, TextField, InputAdornment, + FormControl, + Select, + MenuItem, } from "@wso2/oxygen-ui"; import { Calendar } from "@wso2/oxygen-ui-icons-react"; import { type JSX } from "react"; +import type { MetadataItem } from "@models/responses"; export interface TimeCardsDateFilterProps { startDate: string; endDate: string; onStartDateChange: (value: string) => void; onEndDateChange: (value: string) => void; - shownCount: number; - totalCount: number; - isLoading?: boolean; + state: string; + onStateChange: (value: string) => void; + timeCardStates?: MetadataItem[]; } /** - * TimeCardsDateFilter provides date range filters for time cards and shows count summary. + * TimeCardsDateFilter provides date range and state filters for time cards. * - * @param {TimeCardsDateFilterProps} props - Date values, handlers, and counts. + * @param {TimeCardsDateFilterProps} props - Date values (startDate, endDate), change handlers (onStartDateChange, onEndDateChange, onStateChange), current state value, and available timeCardStates. * @returns {JSX.Element} The rendered filter card. */ export default function TimeCardsDateFilter({ @@ -45,9 +49,9 @@ export default function TimeCardsDateFilter({ endDate, onStartDateChange, onEndDateChange, - shownCount, - totalCount, - isLoading = false, + state, + onStateChange, + timeCardStates = [], }: TimeCardsDateFilterProps): JSX.Element { return ( - - - + + {/* Date Range Filter */} + Filter by Date Range: - - + + + {/* State Filter */} + - {isLoading - ? "Loading..." - : `Showing ${shownCount} of ${totalCount} time logs`} + Filter by State: + + + diff --git a/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeTrackingCard.tsx b/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeTrackingCard.tsx index 198adb8d56..2d7ce20efa 100644 --- a/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeTrackingCard.tsx +++ b/apps/customer-portal/webapp/src/components/project-details/time-tracking/TimeTrackingCard.tsx @@ -82,7 +82,7 @@ export default function TimeTrackingCard({ sx={getPlainChipSx()} /> ({ default: ({ isLoading, isError }: { isLoading?: boolean; isError?: boolean }) => ( @@ -33,7 +35,24 @@ vi.mock("@time-tracking/TimeTrackingStatCards", () => ({ })); vi.mock("@time-tracking/TimeCardsDateFilter", () => ({ - default: () =>
Date Filter
, + default: ({ state, onStateChange, startDate, endDate }: { + state: string; + onStateChange: (value: string) => void; + startDate: string; + endDate: string; + }) => ( +
+ {state || "no-state"} + {startDate} + {endDate} + +
+ ), })); vi.mock("@time-tracking/TimeTrackingCard", () => ({ @@ -63,6 +82,19 @@ describe("ProjectTimeTracking", () => { beforeEach(() => { vi.clearAllMocks(); + + // Mock project filters with timeCardStates + vi.mocked(useGetProjectFilters).mockReturnValue({ + data: { + timeCardStates: [ + { id: "Pending", label: "Pending" }, + { id: "Submitted", label: "Submitted" }, + { id: "Approved", label: "Approved" }, + ], + }, + isLoading: false, + isError: false, + } as any); }); it("should render 7 skeletons when time cards are loading", () => { @@ -76,6 +108,8 @@ describe("ProjectTimeTracking", () => { data: undefined, isLoading: true, isError: false, + hasNextPage: false, + fetchNextPage: vi.fn(), } as any); render(); @@ -94,6 +128,8 @@ describe("ProjectTimeTracking", () => { data: undefined, isLoading: false, isError: true, + hasNextPage: false, + fetchNextPage: vi.fn(), } as any); render(); @@ -103,31 +139,35 @@ describe("ProjectTimeTracking", () => { it("should render time cards when data is loaded", () => { const mockData = { - timeCards: [ - { - id: "1", - case: { label: "Log 1", number: "CS001", id: "c1" }, - totalTime: 60, - state: "Approved", - hasBillable: false, - approvedBy: null, - project: { id: "p1", label: "Project 1" }, - createdOn: "2025-12-10", - }, + pages: [ { - id: "2", - case: { label: "Log 2", number: "CS002", id: "c2" }, - totalTime: 30, - state: "Submitted", - hasBillable: true, - approvedBy: null, - project: { id: "p1", label: "Project 1" }, - createdOn: "2025-12-11", + timeCards: [ + { + id: "1", + case: { label: "Log 1", number: "CS001", id: "c1" }, + totalTime: 60, + state: { id: "approved", label: "Approved" }, + hasBillable: false, + approvedBy: null, + project: { id: "p1", label: "Project 1" }, + createdOn: "2025-12-10", + }, + { + id: "2", + case: { label: "Log 2", number: "CS002", id: "c2" }, + totalTime: 30, + state: { id: "submitted", label: "Submitted" }, + hasBillable: true, + approvedBy: null, + project: { id: "p1", label: "Project 1" }, + createdOn: "2025-12-11", + }, + ], + totalRecords: 2, + offset: 0, + limit: 10, }, ], - totalRecords: 2, - offset: 0, - limit: 10, }; vi.mocked(useGetTimeCardsStats).mockReturnValue({ @@ -140,6 +180,8 @@ describe("ProjectTimeTracking", () => { data: mockData, isLoading: false, isError: false, + hasNextPage: false, + fetchNextPage: vi.fn(), } as any); render(); @@ -160,6 +202,8 @@ describe("ProjectTimeTracking", () => { data: undefined, isLoading: true, isError: false, + hasNextPage: false, + fetchNextPage: vi.fn(), } as any); render(); @@ -175,9 +219,11 @@ describe("ProjectTimeTracking", () => { } as any); vi.mocked(useSearchProjectTimeCards).mockReturnValue({ - data: { timeCards: [], totalRecords: 0, offset: 0, limit: 10 }, + data: { pages: [{ timeCards: [], totalRecords: 0, offset: 0, limit: 10 }] }, isLoading: false, isError: false, + hasNextPage: false, + fetchNextPage: vi.fn(), } as any); render(); @@ -193,9 +239,11 @@ describe("ProjectTimeTracking", () => { } as any); vi.mocked(useSearchProjectTimeCards).mockReturnValue({ - data: { timeCards: [], totalRecords: 0, offset: 0, limit: 10 }, + data: { pages: [{ timeCards: [], totalRecords: 0, offset: 0, limit: 10 }] }, isLoading: false, isError: false, + hasNextPage: false, + fetchNextPage: vi.fn(), } as any); render(); diff --git a/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeCardsDateFilter.test.tsx b/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeCardsDateFilter.test.tsx index 797d5dbf95..c0ac5f1d37 100644 --- a/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeCardsDateFilter.test.tsx +++ b/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeCardsDateFilter.test.tsx @@ -14,11 +14,17 @@ // specific language governing permissions and limitations // under the License. -import { render, screen } from "@testing-library/react"; -import { describe, it, expect } from "vitest"; +import { render, screen, fireEvent, waitFor } from "@testing-library/react"; +import { describe, it, expect, vi } from "vitest"; import TimeCardsDateFilter from "@time-tracking/TimeCardsDateFilter"; describe("TimeCardsDateFilter", () => { + const mockTimeCardStates = [ + { id: "Pending", label: "Pending" }, + { id: "Submitted", label: "Submitted" }, + { id: "Approved", label: "Approved" }, + ]; + it("should render filter by date range label and date inputs", () => { render( { endDate="2025-12-31" onStartDateChange={() => {}} onEndDateChange={() => {}} - shownCount={5} - totalCount={5} + state="" + onStateChange={() => {}} + timeCardStates={mockTimeCardStates} />, ); @@ -35,23 +42,47 @@ describe("TimeCardsDateFilter", () => { screen.getByText("Filter by Date Range:"), ).toBeInTheDocument(); expect( - screen.getByText("Showing 5 of 5 time logs"), + screen.getByText("Filter by State:"), ).toBeInTheDocument(); }); - it("should show Loading when isLoading is true", () => { + it("should show state dropdown with all options and allow selection", async () => { + const onStateChange = vi.fn(); + render( {}} onEndDateChange={() => {}} - shownCount={0} - totalCount={0} - isLoading + state="" + onStateChange={onStateChange} + timeCardStates={mockTimeCardStates} />, ); - expect(screen.getByText("Loading...")).toBeInTheDocument(); + expect(screen.getByText("Filter by State:")).toBeInTheDocument(); + + // Find the Select component + const stateSelect = screen.getByRole("combobox", { name: /filter by state/i }); + expect(stateSelect).toBeInTheDocument(); + + // Open the dropdown by clicking the select + fireEvent.mouseDown(stateSelect); + + // Wait for options to appear and check that all state options are present + await waitFor(() => { + expect(screen.getByRole("option", { name: "All States" })).toBeInTheDocument(); + }); + + expect(screen.getByRole("option", { name: "Pending" })).toBeInTheDocument(); + expect(screen.getByRole("option", { name: "Submitted" })).toBeInTheDocument(); + expect(screen.getByRole("option", { name: "Approved" })).toBeInTheDocument(); + + // Select a state by clicking the option + const pendingOption = screen.getByRole("option", { name: "Pending" }); + fireEvent.click(pendingOption); + + expect(onStateChange).toHaveBeenCalledWith("Pending"); }); }); diff --git a/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeTrackingCard.test.tsx b/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeTrackingCard.test.tsx index ed136fa812..dc54ad46c9 100644 --- a/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeTrackingCard.test.tsx +++ b/apps/customer-portal/webapp/src/components/project-details/time-tracking/__tests__/TimeTrackingCard.test.tsx @@ -25,7 +25,7 @@ describe("TimeTrackingCard", () => { totalTime: 60, createdOn: "2025-12-10 03:47:10", hasBillable: true, - state: "Approved", + state: { id: "approved", label: "Approved" }, approvedBy: { id: "a1", label: "Dileepa Peiris (Intern)" }, project: { id: "p1", label: "Customer 3 Project 1" }, case: { @@ -51,7 +51,7 @@ describe("TimeTrackingCard", () => { it("should show fallback '--' for missing values", () => { const incompleteCard: TimeCard = { ...mockCard, - state: "", + state: null, approvedBy: null, case: { number: "", id: "c1", label: "" }, totalTime: 0, @@ -60,6 +60,7 @@ describe("TimeTrackingCard", () => { render(); expect(screen.getByText(/Approved by: --/)).toBeInTheDocument(); + expect(screen.getByText(/State:\s*--/)).toBeInTheDocument(); }); it("should not render Billable chip when hasBillable is false", () => { diff --git a/apps/customer-portal/webapp/src/constants/projectDetailsConstants.ts b/apps/customer-portal/webapp/src/constants/projectDetailsConstants.ts index 45d3a76ca5..f3fec9701b 100644 --- a/apps/customer-portal/webapp/src/constants/projectDetailsConstants.ts +++ b/apps/customer-portal/webapp/src/constants/projectDetailsConstants.ts @@ -236,6 +236,18 @@ export const TIME_TRACKING_BADGE_TYPES = { export type TimeTrackingBadgeType = (typeof TIME_TRACKING_BADGE_TYPES)[keyof typeof TIME_TRACKING_BADGE_TYPES]; +export const TIME_CARD_STATE = { + PENDING: "Pending", + SUBMITTED: "Submitted", + APPROVED: "Approved", + REJECTED: "Rejected", + PROCESSED: "Processed", + RECALLED: "Recalled", +} as const; + +export type TimeCardState = + (typeof TIME_CARD_STATE)[keyof typeof TIME_CARD_STATE]; + export const DEPLOYMENT_STATUS = { HEALTHY: "Healthy", WARNING: "Warning", diff --git a/apps/customer-portal/webapp/src/models/requests.ts b/apps/customer-portal/webapp/src/models/requests.ts index ea6d1d4a3c..47995c5bf4 100644 --- a/apps/customer-portal/webapp/src/models/requests.ts +++ b/apps/customer-portal/webapp/src/models/requests.ts @@ -208,6 +208,7 @@ export interface TimeCardSearchRequest { filters?: { startDate?: string; endDate?: string; + states?: string[]; }; pagination?: { limit?: number; diff --git a/apps/customer-portal/webapp/src/models/responses.ts b/apps/customer-portal/webapp/src/models/responses.ts index ec056a336a..f01b3232e6 100644 --- a/apps/customer-portal/webapp/src/models/responses.ts +++ b/apps/customer-portal/webapp/src/models/responses.ts @@ -611,7 +611,7 @@ export interface TimeCard { totalTime: number; createdOn: string; hasBillable: boolean; - state: string; + state: { id: string; label: string } | null; approvedBy: { id: string; label: string } | null; project: { id: string; label: string }; case: { diff --git a/apps/customer-portal/webapp/src/utils/projectDetails.ts b/apps/customer-portal/webapp/src/utils/projectDetails.ts index 7c3d387fbf..b58c5c30c2 100644 --- a/apps/customer-portal/webapp/src/utils/projectDetails.ts +++ b/apps/customer-portal/webapp/src/utils/projectDetails.ts @@ -23,6 +23,7 @@ import { PROJECT_USER_STATUSES, TIME_TRACKING_BADGE_TYPES, type TimeTrackingBadgeType, + TIME_CARD_STATE, DEPLOYMENT_STATUS, PRODUCT_SUPPORT_STATUS, type ProjectStatusChipColor, @@ -32,18 +33,33 @@ import { * Get the theme color path for a time card state chip (e.g. Approved, Submitted). * Use with resolveColorFromTheme for SupportOverviewCard-style chips. * - * @param {string} state - The time card state. + * @param {Object | null | undefined} state - The time card state object with id and label. * @returns {string} Theme palette path (e.g. "success.main", "info.main"). */ export const getTimeCardStateColorPath = ( - state: string | null | undefined, + state: { id: string; label: string } | null | undefined, ): string => { - const normalized = state?.toLowerCase(); - if (normalized === "approved") return "success.main"; - if (normalized === "submitted") return "info.main"; - if (normalized === "rejected" || normalized === "draft") - return "warning.main"; - return "text.secondary"; + if (!state?.id) return "text.secondary"; + + // Normalize state ID to match TIME_CARD_STATE constants (title case) + const normalizedId = state.id.charAt(0).toUpperCase() + state.id.slice(1).toLowerCase(); + + switch (normalizedId) { + case TIME_CARD_STATE.APPROVED: + return "success.main"; + case TIME_CARD_STATE.SUBMITTED: + return "info.main"; + case TIME_CARD_STATE.REJECTED: + return "error.main"; + case TIME_CARD_STATE.RECALLED: + return "warning.main"; + case TIME_CARD_STATE.PENDING: + return "info.main"; + case TIME_CARD_STATE.PROCESSED: + return "success.main"; + default: + return "text.secondary"; + } }; /** @@ -157,6 +173,7 @@ export const formatProjectDateTime = (dateString: string): string => { }); return `${dateStr} at ${timeStr}`; } catch (error) { + console.error(`Error formatting date string: ${dateString}`, error); return ""; } };