Skip to content

[Customer Portal][FE][Web] Implement get chat history API with test cases for both mock and real environments - #100

Merged
Rashmika998 merged 7 commits into
wso2-open-operations:customer-portal-milestone-1from
dileepapeiris:feat/add-support-outstanding-cases-chat-history
Feb 9, 2026
Merged

Rashmika998 merged 7 commits into
wso2-open-operations:customer-portal-milestone-1from
dileepapeiris:feat/add-support-outstanding-cases-chat-history

Conversation

@dileepapeiris

@dileepapeiris dileepapeiris commented Feb 8, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR implements the frontend infrastructure for fetching and managing chat history within the Customer Portal. It introduces a custom React Query hook, useGetChatHistory, which is designed to handle dual-mode execution: fetching from a live backend API (with authentication) or utilizing mock data for local development and testing environments.

Key Features

  • Flexible Data Fetching: Implements useGetChatHistory using @tanstack/react-query, allowing for seamless caching, loading states, and error handling.
  • Mock Mode Support: Integrated logic to toggle between real API calls and local mock data, facilitating frontend development even when the backend is unavailable.
  • Authentication Integration: Real-mode execution automatically retrieves and attaches the ID token from the Auth Service to the request headers.
  • Type Safety: Defined robust TypeScript interfaces for ChatHistoryItem and ChatHistoryResponse to ensure data consistency across the application.
  • Guard Logic: Includes a safety check for projectId to prevent unnecessary or invalid API calls.

Technical Changes

API & Hooks

  • useGetChatHistory.ts: The core hook implementation. Handles the conditional logic between mock and real environments.
  • apiConstants.ts: Added CHAT_HISTORY query key for consistent React Query cache management.

Models & Data

  • responses.ts: Defined the structure for chat history entries (IDs, timestamps, messages, etc.).
  • mockData.ts & mockFunctions.ts: Created a realistic dataset and helper functions to simulate backend responses.

Testing

  • useGetChatHistory.test.tsx: Added 6 comprehensive test cases using Vitest/React Testing Library:
    1. Loading State: Verifies the hook correctly reports the loading status.
    2. Mock Data Return: Ensures mock data is returned when mock mode is enabled.
    3. Real Fetch: Validates the API call structure and header attachment in real mode.
    4. Error Handling: Tests how the hook reacts to backend failures.
    5. Query Options: Ensures custom React Query configurations are respected.
    6. Guard Scenario: Confirms the hook does not execute if projectId is missing.

Sequence Diagram

sequenceDiagram
    actor User
    participant Hook as useGetChatHistory Hook
    participant MockMode as Mock Mode Logic
    participant Auth as Auth Service
    participant Backend as Backend API
    participant ReactQuery as React Query
    
    User->>Hook: Call with projectId
    Hook->>ReactQuery: Initialize query
    activate ReactQuery
    
    alt Mock Mode Enabled
        Hook->>MockMode: Fetch mock data
        MockMode-->>Hook: Return mockChatHistory
        Hook->>ReactQuery: Return cached data
    else Real Backend Mode
        Hook->>Auth: Retrieve ID Token
        Auth-->>Hook: Return token
        Hook->>Backend: GET /chat-history (with auth header)
        alt Success
            Backend-->>Hook: Return ChatHistoryResponse
            Hook->>ReactQuery: Return data
        else Error
            Backend-->>Hook: Error response
            Hook->>ReactQuery: Return error
        end
    end
    
    ReactQuery-->>User: Expose query result
    deactivate ReactQuery
Loading

Adds a new test suite for the useGetChatHistory React Query hook. Tests cover initial loading state, behavior when mocks are enabled, query options (staleTime), real API fetching with auth token, API error handling, and behavior when projectId is missing. Mocks are provided for logger, Asgardeo auth, mock config, API delay constant, and global fetch; tests run within a QueryClientProvider.
Introduce useGetChatHistory hook to fetch project chat history via react-query. Supports mock mode (uses getMockChatHistory with API_MOCK_DELAY) and real API calls (gets idToken from Asgardeo, builds request to CUSTOMER_PORTAL_BACKEND_BASE_URL, and adds headers via addApiHeaders). Includes logging, error handling, query key scoping, enabled gating based on auth/mock state, and 5 minute staleTime.
Introduce a new CHAT_HISTORY entry in ApiQueryKeys (apps/customer-portal/webapp/src/constants/apiConstants.ts) with value 'chat-history' to support caching/identification of chat history API/query operations.
Introduce getMockChatHistory() returning a ChatHistoryResponse with sample chat entries (chatId, title, startedTime, messages, kbArticles, status) for the customer portal webapp. Also update imports to include ChatHistoryResponse. This provides mock data for UI development and testing of chat/history components.
Introduce ChatHistoryItem and ChatHistoryResponse interfaces to represent support chat session summaries and project chat history lists. ChatHistoryItem includes chatId, title, startedTime, messages, kbArticles, and status to support chat listing APIs.
Move hardcoded chat history out of mockFunctions and into a reusable mockChatHistory export in mockData.ts. Update imports and have getMockChatHistory return the shared mockChatHistory to centralize mock data and avoid duplication.
@dileepapeiris dileepapeiris self-assigned this Feb 8, 2026
@dileepapeiris
dileepapeiris requested a review from Copilot February 8, 2026 16:19
@coderabbitai

coderabbitai Bot commented Feb 8, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces a new chat history fetching feature for the customer portal. It adds a useGetChatHistory React Query hook supporting both mock and real backend modes, along with data models, mock data, API constants, and comprehensive test coverage across six files totaling 377 lines.

Changes

Cohort / File(s) Summary
API Models & Types
apps/customer-portal/webapp/src/models/responses.ts, apps/customer-portal/webapp/src/constants/apiConstants.ts
Adds ChatHistoryItem and ChatHistoryResponse interfaces defining the chat history data structure, and introduces CHAT_HISTORY query key constant for React Query identification.
Mock Data & Functions
apps/customer-portal/webapp/src/models/mockData.ts, apps/customer-portal/webapp/src/models/mockFunctions.ts
Provides mockChatHistory data with sample chat entries and a getMockChatHistory() function to support mock mode testing and development.
Hook Implementation & Tests
apps/customer-portal/webapp/src/api/useGetChatHistory.ts, apps/customer-portal/webapp/src/api/__tests__/useGetChatHistory.test.tsx
Implements the useGetChatHistory hook with mock/real backend mode support, authentication, error handling, and 6 comprehensive test cases covering loading, data return, query options, real fetch, error handling, and missing projectId guard scenarios.

Sequence Diagram

sequenceDiagram
    actor User
    participant Hook as useGetChatHistory<br/>Hook
    participant MockMode as Mock Mode<br/>Logic
    participant Auth as Auth Service
    participant Backend as Backend API
    participant ReactQuery as React Query
    
    User->>Hook: Call with projectId
    Hook->>ReactQuery: Initialize query
    activate ReactQuery
    
    alt Mock Mode Enabled
        Hook->>MockMode: Fetch mock data
        MockMode-->>Hook: Return mockChatHistory
        Hook->>ReactQuery: Return cached data
    else Real Backend Mode
        Hook->>Auth: Retrieve ID Token
        Auth-->>Hook: Return token
        Hook->>Backend: GET /chat-history<br/>(with auth header)
        alt Success
            Backend-->>Hook: Return ChatHistoryResponse
            Hook->>ReactQuery: Return data
        else Error
            Backend-->>Hook: Error response
            Hook->>ReactQuery: Return error
        end
    end
    
    ReactQuery-->>User: Expose query result
    deactivate ReactQuery
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hop-hop, a new feature hops in place,
Chat history now tracked with grace,
Mock or real, the choice is clear,
React Query makes data near,
Tests ensure each path runs right,
A fluffy bundle of delight! 🐇

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description covers implementation details and technical changes but omits most required template sections including Purpose, Goals, Documentation, Release notes, and security checks. Complete the PR description template by adding: Purpose/Goals/Approach sections with issue links, Release notes, Documentation impact assessment, Security checks confirmation (secure coding, FindSecurityBugs, no secrets), and other relevant sections from the template.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: implementing a get chat history API hook with comprehensive test coverage for both mock and real environments.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new React Query hook for retrieving project chat history, including mock-data support and Vitest coverage for both mock and real API execution paths in the Customer Portal webapp.

Changes:

  • Introduces useGetChatHistory hook to fetch chat history from the backend (or mock data when mocks are enabled).
  • Adds new response models and mock data for chat history.
  • Adds query key constant and unit tests for the new hook.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
apps/customer-portal/webapp/src/models/responses.ts Adds ChatHistoryItem and ChatHistoryResponse response types.
apps/customer-portal/webapp/src/models/mockFunctions.ts Exposes getMockChatHistory() for mock-enabled API flows.
apps/customer-portal/webapp/src/models/mockData.ts Adds mockChatHistory dataset used by the new hook.
apps/customer-portal/webapp/src/constants/apiConstants.ts Adds CHAT_HISTORY query key constant.
apps/customer-portal/webapp/src/api/useGetChatHistory.ts Implements the chat history data-fetching hook (mock + real API).
apps/customer-portal/webapp/src/api/tests/useGetChatHistory.test.tsx Adds tests for loading, mock mode, real mode, error handling, and query options.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread apps/customer-portal/webapp/src/api/useGetChatHistory.ts

@Rashmika998 Rashmika998 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Rashmika998
Rashmika998 merged commit 7e129c1 into wso2-open-operations:customer-portal-milestone-1 Feb 9, 2026
1 check passed
@dileepapeiris dileepapeiris moved this from Done to Staging Deployed in Customer Portal Development Feb 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

App/Customer Portal Area/Frontend Platform/Web Type/New Feature Represents a request or task for a new feature Type/Task General task that does not fit into other categories

Projects

Status: Staging Deployed

Development

Successfully merging this pull request may close these issues.

3 participants