Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Chat Route in App.tsx to make Chat feature accessible #3255

Merged

Conversation

Aad1tya27
Copy link
Contributor

@Aad1tya27 Aad1tya27 commented Jan 11, 2025

What kind of change does this PR introduce?
Added Chat route to make the Chat feature accessible

Issue Number:

Fixes #2875

Snapshots/Videos:
image

If relevant, did you update the documentation?
No

Does this PR introduce a breaking change?
Yes

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Other information

Have you read the contributing guide?
Yes

Summary by CodeRabbit

  • New Features

    • Added a dedicated chat route in the user portal.
    • Enhanced chat component with improved data handling and responsiveness.
  • Bug Fixes

    • Improved chat data fetching and state management to enhance reliability and prevent potential issues.

The changes introduce a new chat functionality accessible via /user/chat/:orgId, providing users with a streamlined chat experience within the application.

Copy link
Contributor

coderabbitai bot commented Jan 11, 2025

Walkthrough

The pull request introduces a new route for the chat functionality in the user portal, specifically adding /user/chat/:orgId to the application's routing structure. The changes involve modifying the src/App.tsx to include the new route and updating the Chat.tsx component with an asynchronous implementation for fetching chat data. This enhances the reliability of the chat feature and ensures that the component reacts appropriately to data changes.

Changes

File Change Summary
src/App.tsx Added new route /user/chat/:orgId for chat functionality
src/screens/UserPortal/Chat/Chat.tsx Replaced synchronous useEffect with an asynchronous implementation for fetching chat data; added new useEffect for setting chats state
src/screens/UserPortal/Chat/Chat.spec.tsx Updated mock data structure and test cases for chat filters; added new mock requests for UNREAD_CHAT_LIST and GROUP_CHAT_LIST

Assessment against linked issues

Objective Addressed Explanation
Establish websocket connection on /user/chat Unable to confirm full websocket connection establishment from routing changes alone

Possibly related PRs

Suggested reviewers

  • palisadoes
  • rishav-jha-mech

Poem

🐰 A route appears, chat's new domain
Where websockets dance, no more in vain
Hooks twirl and spin with graceful might
Connecting users, pure delight!
Code rabbit hops, the path is clear 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🔭 Outside diff range comments (1)
src/screens/UserPortal/Chat/Chat.tsx (1)

Remove redundant useEffect hook

The useEffect with [chatsListData] dependency is redundant as its functionality is already covered by the filterType useEffect. This duplication could lead to race conditions when switching filters.

🔗 Analysis chain

Line range hint 183-186: Verify the necessity of this useEffect.

This useEffect seems redundant with the 'all' filter case in the previous useEffect. Consider consolidating the logic to avoid potential conflicts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for other uses of chatsListData in the codebase
rg "chatsListData" -A 5 -B 5

Length of output: 2476

🧰 Tools
🪛 Biome (1.9.4)

[error] 167-167: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 172-172: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 177-177: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 184-184: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🧹 Nitpick comments (1)
src/App.tsx (1)

194-195: Remove commented out route.

The old route /user/chat is commented out but should be removed for cleaner code maintenance. There's also another commented route at the bottom of the file that should be removed.

-          {/* <Route path="/user/chat" element={<Chat />} /> */}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3a2bdf and 38a2379.

📒 Files selected for processing (2)
  • src/App.tsx (2 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/screens/UserPortal/Chat/Chat.tsx

[error] 167-167: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 172-172: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 177-177: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (1)
src/App.tsx (1)

194-194: LGTM! Route is properly secured.

The new chat route is correctly placed under SecuredRouteForUser, ensuring that only authenticated users can access it. The :orgId parameter follows the same pattern as other organization-scoped routes.

src/screens/UserPortal/Chat/Chat.tsx Outdated Show resolved Hide resolved
src/screens/UserPortal/Chat/Chat.tsx Outdated Show resolved Hide resolved
Copy link

codecov bot commented Jan 11, 2025

Codecov Report

Attention: Patch coverage is 78.57143% with 3 lines in your changes missing coverage. Please review.

Project coverage is 90.24%. Comparing base (e3a2bdf) to head (2d9e5a9).
Report is 6 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/screens/UserPortal/Chat/Chat.tsx 78.57% 0 Missing and 3 partials ⚠️
Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #3255       +/-   ##
=====================================================
+ Coverage              8.51%   90.24%   +81.73%     
=====================================================
  Files                   309      330       +21     
  Lines                  7811     8492      +681     
  Branches               1730     1934      +204     
=====================================================
+ Hits                    665     7664     +6999     
+ Misses                 7072      598     -6474     
- Partials                 74      230      +156     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@palisadoes palisadoes added the ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files label Jan 11, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 12, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/screens/UserPortal/Chat/Chat.tsx (2)

164-184: LGTM! Race conditions are properly handled.

The async/await implementation properly prevents race conditions by awaiting each refetch operation before updating the state.

Add error handling for refetch operations.

Consider adding try-catch blocks to handle potential refetch failures gracefully.

   async function getChats(): Promise<void> {
+    try {
       if (filterType === 'all') {
         await chatsListRefetch();
         if (chatsListData?.chatsByUserId) {
           setChats(chatsListData.chatsByUserId);
         }
       } else if (filterType === 'unread') {
         await unreadChatListRefetch();
         if (unreadChatListData?.getUnreadChatsByUserId) {
           setChats(unreadChatListData.getUnreadChatsByUserId);
         }
       } else if (filterType === 'group') {
         await groupChatListRefetch();
         if (groupChatListData?.getGroupChatsByUserId) {
           setChats(groupChatListData.getGroupChatsByUserId);
         }
       }
+    } catch (error) {
+      console.error('Failed to fetch chats:', error);
+      // Consider showing a user-friendly error message
+    }
   }

Use optional chaining for safer property access.

Replace the conditional checks with optional chaining for more concise and safer code.

-      if (chatsListData && chatsListData.chatsByUserId) {
+      if (chatsListData?.chatsByUserId) {
         setChats(chatsListData.chatsByUserId);
       }

-      if (unreadChatListData && unreadChatListData.getUnreadChatsByUserId) {
+      if (unreadChatListData?.getUnreadChatsByUserId) {
         setChats(unreadChatListData.getUnreadChatsByUserId);
       }

-      if (groupChatListData && groupChatListData.getGroupChatsByUserId) {
+      if (groupChatListData?.getGroupChatsByUserId) {
         setChats(groupChatListData.getGroupChatsByUserId);
       }
🧰 Tools
🪛 Biome (1.9.4)

[error] 168-168: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 173-173: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 178-178: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


Line range hint 186-190: Simplify the condition using optional chaining.

The condition can be more concise while maintaining the same functionality.

-    if (chatsListData && chatsListData?.chatsByUserId.length) {
+    if (chatsListData?.chatsByUserId?.length) {
       setChats(chatsListData.chatsByUserId);
     }
🧰 Tools
🪛 Biome (1.9.4)

[error] 168-168: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 173-173: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 178-178: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 187-187: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e25c29 and 44fc7d5.

📒 Files selected for processing (1)
  • src/screens/UserPortal/Chat/Chat.tsx (1 hunks)
🧰 Additional context used
📓 Learnings (1)
src/screens/UserPortal/Chat/Chat.tsx (2)
Learnt from: Aad1tya27
PR: PalisadoesFoundation/talawa-admin#3255
File: src/screens/UserPortal/Chat/Chat.tsx:0-0
Timestamp: 2025-01-12T16:25:38.818Z
Learning: In the Chat component of talawa-admin, the `chats` state is initialized with an empty array by default using `useState<Chat[]>([])`, making explicit empty array assignments in else conditions unnecessary.
Learnt from: Aad1tya27
PR: PalisadoesFoundation/talawa-admin#3255
File: src/screens/UserPortal/Chat/Chat.tsx:0-0
Timestamp: 2025-01-12T16:24:16.293Z
Learning: In React components where a useEffect triggers data fetching operations and a separate useEffect handles the state updates based on that data (e.g., watching query results), it's not necessary to include the data variables in the first useEffect's dependency array. This pattern helps prevent unnecessary re-runs while maintaining proper data flow.
🪛 Biome (1.9.4)
src/screens/UserPortal/Chat/Chat.tsx

[error] 168-168: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 173-173: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


[error] 178-178: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Application

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 12, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/screens/UserPortal/Chat/Chat.spec.tsx (3)

4341-4369: Consider adding test cases for non-empty responses.

While the empty response mocks are good for basic testing, consider adding test cases that verify the component's behavior with:

  • Multiple unread chats
  • Multiple group chats
  • Error states
      {
        request: {
          query: UNREAD_CHAT_LIST,
        },
        result: {
          data: {
-           getUnreadChatsByUserId: [],
+           getUnreadChatsByUserId: [
+             {
+               _id: '1',
+               messages: [{
+                 messageContent: 'Unread message',
+                 sender: { _id: '2', firstName: 'Test' }
+               }],
+               unseenMessagesByUsers: JSON.stringify({ '1': 1 })
+             }
+           ],
          },
        },
      }

Line range hint 4371-4440: Enhance test coverage with additional assertions.

The test successfully verifies basic filter functionality, but consider adding:

  1. Assertions for loading states
  2. Verification of error handling
  3. Checks for correct filter button states (active/inactive)
    await act(async () => {
      fireEvent.click(unreadChatButton);
    });
+   expect(unreadChatButton).toHaveClass('active');
+   expect(allChatButton).not.toHaveClass('active');
+   expect(groupChatButton).not.toHaveClass('active');

    await act(async () => {
      fireEvent.click(groupChatButton);
    });
+   expect(groupChatButton).toHaveClass('active');
+   expect(unreadChatButton).not.toHaveClass('active');
+   expect(allChatButton).not.toHaveClass('active');

Line range hint 1-4568: Use obviously fake data in test mocks.

The test data contains realistic-looking emails and IDs. Consider:

  1. Using clearly fake domains (e.g., @example.test)
  2. Using consistent and obviously fake ID patterns
  3. Avoiding patterns that might match production data

This prevents accidental leaks and makes it clear the data is for testing.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44fc7d5 and 2d9e5a9.

📒 Files selected for processing (1)
  • src/screens/UserPortal/Chat/Chat.spec.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (1)
src/screens/UserPortal/Chat/Chat.spec.tsx (1)

4293-4313: Mock data structure looks good but consider adding validation tests.

The mock data structure correctly includes all required fields for users and creator objects. However, consider adding test cases to verify the handling of null/empty values for optional fields like image.

✅ Verification successful

Mock data structure is appropriate for testing chat creation

The null values in the mock data are suitable for testing chat creation functionality, as the Chat component primarily handles data management rather than direct image rendering. The image field's presence in the mock data correctly validates the expected data structure, while actual image rendering and null-handling are managed by child components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any null checks for image field in the component
ast-grep --pattern 'image && $$$' || ast-grep --pattern 'image ? $$$'

Length of output: 134


Script:

#!/bin/bash
# Check Chat component for image handling
ast-grep --pattern 'const Chat = $$$' -f src/screens/UserPortal/Chat/Chat.tsx

# Look for image props or references in Chat
rg "image[\"']?:" src/screens/UserPortal/Chat/Chat.tsx -A 2

# Check for different null check patterns
rg "(\?\?|!=\s*null|!==\s*null|===\s*null|==\s*null).*image" src/screens/UserPortal/Chat/Chat.tsx

Length of output: 891


Script:

#!/bin/bash
# Look for Avatar or Image component imports and usage
rg "import.*Avatar|import.*Image" src/screens/UserPortal/Chat/Chat.tsx

# Look for JSX elements using image prop
ast-grep --pattern '<$_$_ image={$_}'

# Look for avatar usage in Chat.tsx
rg "<Avatar|<Image" src/screens/UserPortal/Chat/Chat.tsx -A 2

Length of output: 176

@Aad1tya27
Copy link
Contributor Author

@palisadoes I've fixed the issue and 1 faulty test. The /chat/:orgId was missing and 1 test had less than expected Mock Responses.

@palisadoes palisadoes merged commit 0af5a6f into PalisadoesFoundation:develop-postgres Jan 12, 2025
19 checks passed
@disha1202
Copy link
Contributor

disha1202 commented Jan 13, 2025

@Aad1tya27
image
The side navigation and page title are not visible for chat.

The Chat route that you added should be nested under the <Route element={<UserScreen />}> route.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants