Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
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
2 changes: 1 addition & 1 deletion apps/customer-portal/webapp/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "customer-portal",
"private": true,
"version": "1.0.0-rc.2",
"version": "1.0.0-rc.3",
"type": "module",
"scripts": {
"dev": "vite",
Expand Down
18 changes: 15 additions & 3 deletions apps/customer-portal/webapp/src/api/useGetConversationStats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,29 @@ import { useLogger } from "@hooks/useLogger";
import { ApiQueryKeys } from "@constants/apiConstants";
import type { ConversationStats } from "@models/responses";

export interface UseGetConversationStatsOptions {
createdByMe?: boolean;
enabled?: boolean;
}

/**
* Custom hook to fetch conversation statistics for a project.
*
* @param {string} projectId - The ID of the project.
* @param {UseGetConversationStatsOptions} [options] - Optional query options.
* @returns {UseQueryResult<ConversationStats, Error>} The query result object.
*/
export function useGetConversationStats(
projectId: string,
options?: UseGetConversationStatsOptions,
): UseQueryResult<ConversationStats, Error> {
const logger = useLogger();
const { isSignedIn, isLoading: isAuthLoading } = useAsgardeo();
const authFetch = useAuthApiClient();
const { createdByMe, enabled = true } = options ?? {};

return useQuery<ConversationStats, Error>({
queryKey: [ApiQueryKeys.CONVERSATION_STATS, projectId],
queryKey: [ApiQueryKeys.CONVERSATION_STATS, projectId, createdByMe],
queryFn: async (): Promise<ConversationStats> => {
logger.debug(`Fetching conversation stats for project ID: ${projectId}`);

Expand All @@ -46,7 +54,11 @@ export function useGetConversationStats(
throw new Error("CUSTOMER_PORTAL_BACKEND_BASE_URL is not configured");
}

const requestUrl = `${baseUrl}/projects/${projectId}/stats/conversations`;
let requestUrl = `${baseUrl}/projects/${projectId}/stats/conversations`;

if (createdByMe) {
requestUrl += "?createdBy=me";
}

const response = await authFetch(requestUrl, {
method: "GET",
Expand Down Expand Up @@ -77,7 +89,7 @@ export function useGetConversationStats(
throw error;
}
},
enabled: !!projectId && isSignedIn && !isAuthLoading,
enabled: (enabled ?? true) && !!projectId && isSignedIn && !isAuthLoading,
staleTime: 5 * 60 * 1000, // 5 minutes
gcTime: 10 * 60 * 1000, // 10 minutes
retry: 2,
Expand Down
2 changes: 2 additions & 0 deletions apps/customer-portal/webapp/src/api/useGetProducts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useAsgardeo } from "@asgardeo/react";
import { useAuthApiClient } from "@api/useAuthApiClient";
import { useLogger } from "@hooks/useLogger";
import { ApiQueryKeys } from "@constants/apiConstants";
import { PRODUCT_CLASS } from "@constants/commonConstants";
import type { ProductsResponse } from "@models/responses";

/**
Expand Down Expand Up @@ -48,6 +49,7 @@ export function useGetProducts(params?: {
}

const searchParams = new URLSearchParams();
searchParams.set("class", PRODUCT_CLASS.PRODUCT_MODEL);
searchParams.set("offset", String(offset));
searchParams.set("limit", String(limit));
const requestUrl = `${baseUrl}/products?${searchParams.toString()}`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface UseGetProjectCasesStatsOptions {
incidentId?: string;
queryId?: string;
caseTypes?: Array<`${(typeof CaseType)[keyof typeof CaseType]}` | string>;
createdByMe?: boolean;
enabled?: boolean;
}

Expand All @@ -46,10 +47,10 @@ export function useGetProjectCasesStats(
const logger = useLogger();
const { isSignedIn, isLoading: isAuthLoading } = useAsgardeo();
const authFetch = useAuthApiClient();
const { incidentId, queryId, caseTypes, enabled = true } = options ?? {};
const { incidentId, queryId, caseTypes, createdByMe, enabled = true } = options ?? {};

return useQuery<ProjectCasesStats, Error>({
queryKey: [ApiQueryKeys.CASES_STATS, id, incidentId, queryId, caseTypes],
queryKey: [ApiQueryKeys.CASES_STATS, id, incidentId, queryId, caseTypes, createdByMe],
queryFn: async (): Promise<ProjectCasesStats> => {
logger.debug(`Fetching case stats for project ID: ${id}`);

Expand All @@ -75,6 +76,10 @@ export function useGetProjectCasesStats(
params.append("caseTypes", incidentId);
}

if (createdByMe) {
params.append("createdBy", "me");
}

const queryString = params.toString();
if (queryString) {
requestUrl += `?${queryString}`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import {
Typography,
alpha,
colors,
useTheme,
useMediaQuery,
} from "@wso2/oxygen-ui";
import {
ChevronDown,
Expand Down Expand Up @@ -59,6 +61,26 @@ const GREEN_STROKE = oxygenColors.green?.[500] ?? "#22C55E";
const CYAN_STROKE = oxygenColors.cyan?.[500] ?? "#06B6D4";
const AMBER_STROKE = oxygenColors.amber?.[500] ?? "#F59E0B";

/** Format ISO date (YYYY-MM-DD) to date format for the chart, responsive to screen size. */
function formatDateForChart(isoDate: string, isSmallScreen: boolean = false): string {
try {
const date = new Date(`${isoDate}T00:00:00Z`);
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const month = monthNames[date.getUTCMonth()];
const day = date.getUTCDate();
const year = date.getUTCFullYear();

// Small screens: show only month-day (MM-DD format)
if (isSmallScreen) {
return `${month} ${day}`;
}
// Large screens: show month-day with year on new line
return `${month} ${day}\n${year}`;
} catch {
return isoDate.slice(5); // Fallback to MM-DD
}
}
Comment thread
dileepapeiris marked this conversation as resolved.
Resolved

/** Format a raw transaction count to a human-readable label. */
function formatCount(n: number): string {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
Expand All @@ -78,6 +100,7 @@ function sumTransactions(entry: InstanceUsageEntry): number {
function buildTrendFromUsages(
usages: InstanceUsageEntry[],
countKey: string,
isSmallScreen: boolean = false,
): UsageTrendRow[] {
const periodMap = new Map<string, number>();
for (const entry of usages) {
Expand All @@ -88,7 +111,7 @@ function buildTrendFromUsages(
}
return Array.from(periodMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([period, value]) => ({ name: period.slice(5), value })); // "MM-DD" label
.map(([period, value]) => ({ name: formatDateForChart(period, isSmallScreen), value }));
}

/** Compute headline value (last point) and delta % vs previous point. */
Expand All @@ -106,7 +129,7 @@ function computeHeadlineDelta(trend: UsageTrendRow[]): {
}

/** Build a daily trend of summed cores across all instance metrics. */
function buildDailyCoreTrend(metrics: InstanceMetricEntry[]): UsageTrendRow[] {
function buildDailyCoreTrend(metrics: InstanceMetricEntry[], isSmallScreen: boolean = false): UsageTrendRow[] {
const dayMap = new Map<string, number>();

for (const m of metrics) {
Expand All @@ -123,18 +146,18 @@ function buildDailyCoreTrend(metrics: InstanceMetricEntry[]): UsageTrendRow[] {
return Array.from(dayMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([date, total]) => ({
name: date.slice(5),
name: formatDateForChart(date, isSmallScreen),
value: total,
}));
}

/** Derive the 5 aggregated metric cards from project usages and metrics. */
function deriveAggregatedMetrics(usages: InstanceUsageEntry[], metrics: InstanceMetricEntry[]): UsageAggregatedMetricDefinition[] {
const txTrend = buildTrendFromUsages(usages, "TRANSACTION_COUNT");
const apiTrend = buildTrendFromUsages(usages, "API_COUNT");
const userTrend = buildTrendFromUsages(usages, "TOTAL_USERS");
const b2bTrend = buildTrendFromUsages(usages, "TOTAL_B2B_ORGS");
const coreTrend = buildDailyCoreTrend(metrics);
function deriveAggregatedMetrics(usages: InstanceUsageEntry[], metrics: InstanceMetricEntry[], isSmallScreen: boolean = false): UsageAggregatedMetricDefinition[] {
const txTrend = buildTrendFromUsages(usages, "TRANSACTION_COUNT", isSmallScreen);
const apiTrend = buildTrendFromUsages(usages, "API_COUNT", isSmallScreen);
const userTrend = buildTrendFromUsages(usages, "TOTAL_USERS", isSmallScreen);
const b2bTrend = buildTrendFromUsages(usages, "TOTAL_B2B_ORGS", isSmallScreen);
const coreTrend = buildDailyCoreTrend(metrics, isSmallScreen);

const txHD = computeHeadlineDelta(txTrend);
const apiHD = computeHeadlineDelta(apiTrend);
Expand Down Expand Up @@ -590,6 +613,9 @@ export default function UsageOverviewPanel({
onToggleEnvironment,
timeRangeSelector,
}: UsageOverviewPanelProps): JSX.Element {
const theme = useTheme();
const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));

const metricsPayload = useMemo(
() => ({ filters: { startDate: dateRange.startDate, endDate: dateRange.endDate } }),
[dateRange],
Expand Down Expand Up @@ -678,8 +704,8 @@ export default function UsageOverviewPanel({

// ── Aggregated metric trend cards ─────────────────────────────────────────
const aggregatedMetrics = useMemo((): UsageAggregatedMetricDefinition[] => {
return deriveAggregatedMetrics(usagesData?.usages ?? [], metricsData?.metrics ?? []);
}, [usagesData, metricsData]);
return deriveAggregatedMetrics(usagesData?.usages ?? [], metricsData?.metrics ?? [], isSmallScreen);
}, [usagesData, metricsData, isSmallScreen]);

if (isError) {
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,12 @@ export default function AnnouncementDetailsPanel({
caseId={caseId}
statusLabel={data.status?.label}
assignedEngineer={data.assignedEngineer}
engineerInitials={data.assignedEngineer?.name?.split(" ")?.[0]?.[0] ?? ""}
engineerInitials={
typeof data.assignedEngineer === "object" &&
data.assignedEngineer?.name
? data.assignedEngineer.name.split(" ")[0]?.[0] ?? ""
: ""
}
closedOn={data.closedOn}
restrictToCloseOnly={true}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
} from "@utils/support";
import ChatHistorySkeleton from "@components/support/support-overview-cards/ChatHistorySkeleton";
import ErrorIndicator from "@components/common/error-indicator/ErrorIndicator";
import EmptyIcon from "@components/common/empty-state/EmptyIcon";

export interface ChatHistoryListProps {
items: ChatHistoryItem[];
Expand Down Expand Up @@ -69,9 +70,21 @@ export default function ChatHistoryList({

if (!items || items.length === 0) {
return (
<Typography variant="body2" color="text.secondary">
No chat history.
</Typography>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
py: 2,
}}
>
<EmptyIcon
style={{ width: 120, maxWidth: "100%", height: "auto", marginBottom: 12 }}
/>
<Typography variant="body2" color="text.secondary">
No chat history.
</Typography>
</Box>
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { Clock } from "@wso2/oxygen-ui-icons-react";
import type { JSX } from "react";
import type { CaseListItem } from "@models/responses";
import ErrorIndicator from "@components/common/error-indicator/ErrorIndicator";
import EmptyIcon from "@components/common/empty-state/EmptyIcon";
import OutstandingCasesSkeleton from "./OutstandingCasesSkeleton";
import { getSeverityLegendColor } from "@constants/dashboardConstants";
import {
Expand Down Expand Up @@ -71,9 +72,21 @@ export default function OutstandingCasesList({

if (cases.length === 0) {
return (
<Typography variant="body2" color="text.secondary">
No outstanding cases.
</Typography>
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
py: 2,
}}
>
<EmptyIcon
style={{ width: 120, maxWidth: "100%", height: "auto", marginBottom: 12 }}
/>
<Typography variant="body2" color="text.secondary">
No outstanding cases.
</Typography>
</Box>
);
}

Expand Down
5 changes: 5 additions & 0 deletions apps/customer-portal/webapp/src/constants/commonConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@
// under the License.

export const ROUTE_PREVIOUS_PAGE = -1;

/** Product class values. Must match backend entity:ProductClass. */
export const PRODUCT_CLASS = {
PRODUCT_MODEL: "product_model",
} as const;
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import type { UsageTimeRangePreset } from "@models/usageMetrics.types";

export const USAGE_LINE_CHART_MARGIN = {
top: 5,
right: 30,
right: 40,
left: 20,
bottom: 5,
bottom: 40,
};

export const USAGE_TIME_RANGE_LABELS: Record<UsageTimeRangePreset, string> = {
Expand Down
1 change: 1 addition & 0 deletions apps/customer-portal/webapp/src/pages/AllCasesPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ export default function AllCasesPage(): JSX.Element {
isError: isStatsError,
} = useGetProjectCasesStats(projectId || "", {
caseTypes: [CaseType.DEFAULT_CASE],
createdByMe: createdByMe || undefined,
enabled: !!projectId,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ export default function AllConversationsPage(): JSX.Element {
data: statsData,
isLoading: isStatsLoading,
isError: isStatsError,
} = useGetConversationStats(projectId || "");
} = useGetConversationStats(projectId || "", {
createdByMe: createdByMe || undefined,
});

const stats: Partial<Record<AllConversationsStatKey, number>> | undefined =
statsData
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export default function ServiceRequestsPage(): JSX.Element {
isError: isStatsError,
} = useGetProjectCasesStats(projectId || "", {
caseTypes: [CaseType.SERVICE_REQUEST],
createdByMe: createdByMe || undefined,
enabled: !!projectId,
});

Expand Down