Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e412456
ProjectHub: simplify fetching and handle auth
dileepapeiris Feb 4, 2026
7812454
test: enhance ProjectHub tests and mocks
dileepapeiris Feb 4, 2026
db41a87
Add ErrorIndicator handling to ProjectCardStats
dileepapeiris Feb 4, 2026
baa00c0
Show error indicator for project status
dileepapeiris Feb 4, 2026
0a834ca
Add isStatsError prop to ProjectCard
dileepapeiris Feb 4, 2026
6573947
Mock ErrorIndicator and add error-state test
dileepapeiris Feb 4, 2026
5654e9c
Mock ErrorIndicator and add error test
dileepapeiris Feb 4, 2026
5ae5e81
Add isError handling and test in ProjectCard mocks
dileepapeiris Feb 4, 2026
b5777a1
Account for auth loading and fallback in UserProfile
dileepapeiris Feb 4, 2026
c9038cf
Switch projects hook to useQuery with auth/mock
dileepapeiris Feb 4, 2026
d212839
Enable user details query only when authenticated
dileepapeiris Feb 4, 2026
a456618
Default size and scale TriangleAlert icon
dileepapeiris Feb 4, 2026
5926674
Enhance Header tests for auth & project errors
dileepapeiris Feb 4, 2026
6c4a09f
Add ProjectSwitcher error state test
dileepapeiris Feb 4, 2026
05107fe
Refactor UserProfile tests with new hook mocks
dileepapeiris Feb 4, 2026
85dbab6
Simplify projects fetch and handle auth loading
dileepapeiris Feb 4, 2026
fbd7a81
Add error state to ProjectSwitcher
dileepapeiris Feb 4, 2026
a6c783f
Remove useNavigate and disable auto-redirect
dileepapeiris Feb 4, 2026
492bdfc
Fix login alignment and slogan typography
dileepapeiris Feb 4, 2026
99bc3b5
Import ReactNode and use it for children prop
dileepapeiris Feb 4, 2026
aa581c4
Refactor UserProfile tests: add mocks & checks
dileepapeiris Feb 4, 2026
475f39e
Remove useMockConfig and isSignedIn usage
dileepapeiris Feb 4, 2026
d9e1832
Merge branch 'customer-portal-milestone-1' into feat/add-projects-sea…
Rashmika998 Feb 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 71 additions & 40 deletions apps/customer-portal/webapp/src/api/useGetProjects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@
// specific language governing permissions and limitations
// under the License.

import {
useInfiniteQuery,
type UseInfiniteQueryResult,
type InfiniteData,
} from "@tanstack/react-query";
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import { useAsgardeo } from "@asgardeo/react";
import { useMockConfig } from "@/providers/MockConfigProvider";
import { useLogger } from "@/hooks/useLogger";
import { mockProjects } from "@/models/mockData";
import { ApiQueryKeys, API_MOCK_DELAY } from "@/constants/apiConstants";
Expand All @@ -27,62 +25,95 @@ import type { SearchProjectsResponse } from "@/models/responses";

/**
* Custom hook to search projects.
* This hook uses an infinite query to fetch projects in pages.
* This hook uses a standard query to fetch projects.
*
* @param {SearchProjectsRequest} searchData - The search and pagination parameters.
* @param {boolean} fetchAll - If true, treats this as a shared "all projects" query.
* @returns {UseInfiniteQueryResult<InfiniteData<SearchProjectsResponse>, Error>} The infinite query result object.
* @returns {UseQueryResult<SearchProjectsResponse, Error>} The query result object.
*/
export default function useGetProjects(
searchData?: SearchProjectsRequest,
fetchAll: boolean = false,
): UseInfiniteQueryResult<InfiniteData<SearchProjectsResponse>, Error> {
): UseQueryResult<SearchProjectsResponse, Error> {
const logger = useLogger();
const { getIdToken, isSignedIn, isLoading: isAuthLoading } = useAsgardeo();
const { isMockEnabled } = useMockConfig();
const limit = fetchAll ? 100 : searchData?.pagination?.limit || 10;
const offset = searchData?.pagination?.offset || 0;

// A stable key for the "all projects" query ensures cache sharing
const queryKey = fetchAll
? [ApiQueryKeys.PROJECTS, "all"]
: [ApiQueryKeys.PROJECTS, searchData ?? "default"];
? [ApiQueryKeys.PROJECTS, "all", isMockEnabled]
: [ApiQueryKeys.PROJECTS, searchData ?? "default", isMockEnabled];

return useInfiniteQuery<SearchProjectsResponse, Error>({
getPreviousPageParam: (firstPage) => {
const prevOffset = firstPage.offset - limit;
return prevOffset >= 0 ? prevOffset : undefined;
},
getNextPageParam: (lastPage) => {
const nextOffset = lastPage.offset + limit;
return nextOffset < lastPage.totalRecords ? nextOffset : undefined;
},
initialPageParam: 0,
queryFn: async ({ pageParam = 0 }): Promise<SearchProjectsResponse> => {
return useQuery<SearchProjectsResponse, Error>({
queryKey,
queryFn: async (): Promise<SearchProjectsResponse> => {
logger.debug(
`Fetching projects... offset: ${pageParam}, limit: ${limit}, fetchAll: ${fetchAll}`,
`Fetching projects... offset: ${offset}, limit: ${limit}, fetchAll: ${fetchAll}, mock: ${isMockEnabled}`,
);

// Mock behavior: simulate network latency for the in-memory `mockProjects` data.
await new Promise((resolve) => setTimeout(resolve, API_MOCK_DELAY));
if (isMockEnabled) {
// Mock behavior: simulate network latency for the in-memory `mockProjects` data.
await new Promise((resolve) => setTimeout(resolve, API_MOCK_DELAY));

const results: SearchProjectsResponse = {
limit,
offset,
projects: mockProjects
.slice(offset, offset + limit)
.map((project) => ({
createdOn: project.createdOn,
description: project.description,
id: project.id,
key: project.key,
name: project.name,
})),
totalRecords: mockProjects.length,
};

logger.debug("Projects fetched successfully (mock)", results);

const offset = typeof pageParam === "number" ? pageParam : 0;
return results;
}

const results: SearchProjectsResponse = {
limit,
offset,
projects: mockProjects.slice(offset, offset + limit).map((project) => ({
createdOn: project.createdOn,
description: project.description,
id: project.id,
key: project.key,
name: project.name,
})),
totalRecords: mockProjects.length,
};
try {
const idToken = await getIdToken();
const baseUrl = import.meta.env.CUSTOMER_PORTAL_BACKEND_BASE_URL;

logger.debug("Projects fetched successfully", results);
if (!baseUrl) {
throw new Error("CUSTOMER_PORTAL_BACKEND_BASE_URL is not configured");
}

return results;
const requestUrl = `${baseUrl}/projects/search`;
const body = {};
Comment thread
dileepapeiris marked this conversation as resolved.
Resolved

const response = await fetch(requestUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${idToken}`,
"x-user-id-token": idToken,
},
body: JSON.stringify(body),
});
Comment thread
dileepapeiris marked this conversation as resolved.
Resolved

logger.debug(`[useGetProjects] Response status: ${response.status}`);

if (!response.ok) {
throw new Error(`Error fetching projects: ${response.statusText}`);
}

const data: SearchProjectsResponse = await response.json();
logger.debug("[useGetProjects] Data received:", data);
return data;
} catch (error) {
logger.error("[useGetProjects] Error:", error);
throw error;
}
},
queryKey,
staleTime: Infinity,
enabled: isMockEnabled || (isSignedIn && !isAuthLoading),
});
}
4 changes: 2 additions & 2 deletions apps/customer-portal/webapp/src/api/useGetUserDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { useLogger } from "@/hooks/useLogger";
* @returns {UseQueryResult<UserDetails, Error>} The user details.
*/
const useGetUserDetails = (): UseQueryResult<UserDetails, Error> => {
const { getIdToken } = useAsgardeo();
const { getIdToken, isSignedIn, isLoading: isAuthLoading } = useAsgardeo();
const { isMockEnabled } = useMockConfig();
const logger = useLogger();

Expand Down Expand Up @@ -77,7 +77,7 @@ const useGetUserDetails = (): UseQueryResult<UserDetails, Error> => {
throw error;
}
},
enabled: true,
enabled: isMockEnabled || (isSignedIn && !isAuthLoading),
});
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@ interface ErrorIndicatorProps {
*/
export default function ErrorIndicator({
entityName,
size,
size = "small",
}: ErrorIndicatorProps): JSX.Element {
const iconSize = size === "small" ? 16 : size === "medium" ? 24 : 32;

return (
<Tooltip title={`Failed to fetch ${entityName} data`}>
<IconButton size={size || "small"} color="error">
<TriangleAlert />
<IconButton size={size} color="error">
<TriangleAlert size={iconSize} />
</IconButton>
</Tooltip>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import Brand from "@/components/common/header/Brand";
import Actions from "@/components/common/header/Actions";
import SearchBar from "@/components/common/header/SearchBar";
import ProjectSwitcher from "@/components/common/header/ProjectSwitcher";
import { useAsgardeo } from "@asgardeo/react";

interface HeaderProps {
onToggleSidebar: () => void;
Expand All @@ -43,26 +44,18 @@ export default function Header({ onToggleSidebar }: HeaderProps): JSX.Element {
const { projectId } = useParams<{
projectId?: string;
}>();
const { isLoading: isAuthLoading } = useAsgardeo();

const isProjectHub = location.pathname === "/";
const {
data: projectsResponse,
fetchNextPage,
hasNextPage,
isLoading,
isFetchingNextPage,
isError,
} = useGetProjects({}, true);

useEffect(() => {
if (hasNextPage && !isFetchingNextPage && !isError) {
fetchNextPage();
}
}, [hasNextPage, isFetchingNextPage, isError, fetchNextPage]);

const projects = useMemo(
() => projectsResponse?.pages.flatMap((page) => page.projects) || [],
[projectsResponse?.pages],
() => projectsResponse?.projects || [],
[projectsResponse?.projects],
);

const projectFromUrl = projects.find((project) => project.id === projectId);
Expand Down Expand Up @@ -137,7 +130,8 @@ export default function Header({ onToggleSidebar }: HeaderProps): JSX.Element {
projects={projects}
selectedProject={selectedProject}
onProjectChange={handleProjectChange}
isLoading={isLoading}
isLoading={isLoading || isAuthLoading}
isError={isError}
/>
{/* header search bar */}
<SearchBar />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ import {
import { FolderOpen } from "@wso2/oxygen-ui-icons-react";
import type { JSX } from "react";
import type { ProjectListItem } from "@/models/responses";
import ErrorIndicator from "@/components/common/errorIndicator/ErrorIndicator";

// Props for the ProjectSwitcher component.
interface ProjectSwitcherProps {
projects: ProjectListItem[];
selectedProject?: ProjectListItem;
onProjectChange: (projectId: string) => void;
isLoading?: boolean;
isError?: boolean;
}

/**
Expand All @@ -43,6 +45,7 @@ export default function ProjectSwitcher({
selectedProject,
onProjectChange,
isLoading,
isError,
}: ProjectSwitcherProps): JSX.Element {
if (isLoading) {
return (
Expand All @@ -66,6 +69,30 @@ export default function ProjectSwitcher({
);
}

if (isError) {
return (
<HeaderUI.Switchers showDivider={false}>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: 1,
height: 40,
width: 200,
px: 1.5,
border: "1px solid",
borderColor: "error.main",
borderRadius: "4px",
color: "error.main",
}}
>
<ErrorIndicator entityName="Projects" />
</Box>
</HeaderUI.Switchers>
);
}

return (
<HeaderUI.Switchers showDivider={false}>
{/* project switcher select */}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,9 @@ import ErrorIndicator from "@/components/common/errorIndicator/ErrorIndicator";
* @returns {JSX.Element} The User profile component.
*/
export default function UserProfile(): JSX.Element {
// Navigation hook.
const navigate = useNavigate();
const { signOut } = useAsgardeo();
const { signOut, isLoading: isAuthLoading } = useAsgardeo();
const { data: userDetails, isLoading, isError } = useGetUserDetails();

// Logger hook.
const logger = useLogger();

const user = userDetails
Expand Down Expand Up @@ -68,7 +65,12 @@ export default function UserProfile(): JSX.Element {
avatar: <User />,
};

const userToRender = isLoading ? loadingUser : isError ? errorUser : user;
const userToRender =
isLoading || isAuthLoading
? loadingUser
: isError
? errorUser
: user || errorUser;

return (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,27 @@ vi.mock("../SearchBar", () => ({
default: () => <div data-testid="search-bar" />,
}));

// Mock useAsgardeo
const mockUseAsgardeo = vi.fn(() => ({
isLoading: false,
}));
vi.mock("@asgardeo/react", () => ({
useAsgardeo: () => mockUseAsgardeo(),
}));

vi.mock("../ProjectSwitcher", () => ({
default: ({ projects, selectedProject, onProjectChange, isLoading }: any) => (
default: ({
projects,
selectedProject,
onProjectChange,
isLoading,
isError,
}: any) => (
<div
data-testid="project-switcher"
data-selected-id={selectedProject?.id || ""}
data-loading={isLoading ? "true" : "false"}
data-error={isError ? "true" : "false"}
>
<select
data-testid="project-select"
Expand Down Expand Up @@ -320,4 +335,30 @@ describe("Header", () => {
const switcher = screen.getByTestId("project-switcher");
expect(switcher).toHaveAttribute("data-loading", "true");
});

it("should pass isAuthLoading as isLoading into ProjectSwitcher", () => {
mockLocation.pathname = "/project-1/dashboard";
mockParams.projectId = "project-1";
mockUseAsgardeo.mockReturnValue({ isLoading: true });

render(<Header onToggleSidebar={mockOnToggleSidebar} />);

const switcher = screen.getByTestId("project-switcher");
expect(switcher).toHaveAttribute("data-loading", "true");
});

it("should pass isError to ProjectSwitcher", () => {
mockLocation.pathname = "/project-1/dashboard";
mockParams.projectId = "project-1";
mockUseSearchProjects.mockReturnValue({
data: null,
isLoading: false,
isError: true,
});

render(<Header onToggleSidebar={mockOnToggleSidebar} />);

const switcher = screen.getByTestId("project-switcher");
expect(switcher).toHaveAttribute("data-error", "true");
});
});
Loading