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

Feat: updated chat related functionality to work with the updated chat schema #2286

Merged
merged 30 commits into from
Oct 20, 2024

Conversation

disha1202
Copy link

@disha1202 disha1202 commented Sep 22, 2024

What kind of change does this PR introduce?

Issue Number:

Fixes #2285

Did you add tests for your changes?
Yes

Snapshots/Videos:

If relevant, did you update the documentation?

Summary

Does this PR introduce a breaking change?

Other information

Have you read the contributing guide?

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive chat functionality, allowing users to create and manage both direct and group chats.
    • Added real-time updates for messages and the ability to reply to specific messages within chats.
    • Implemented new queries and mutations for fetching chat details and sending messages.
  • Bug Fixes

    • Improved error handling during message sending to enhance reliability.
  • Style

    • Updated CSS styles for better layout, responsiveness, and user experience in chat interfaces.
  • Tests

    • Enhanced test coverage for chat functionalities, incorporating new mock data and refining test cases for various scenarios.
  • Chores

    • Removed unused code and streamlined mock data in test files for improved maintainability.

Copy link

coderabbitai bot commented Sep 22, 2024

Walkthrough

The changes in this pull request enhance the GraphQL schema and related components to support new chat functionalities. New types and inputs for chats and messages are introduced, along with mutations for creating chats and sending messages. Queries for retrieving chats by ID and user ID are added, and real-time message updates are facilitated through subscriptions. Additionally, the user interface components and tests are updated to reflect these changes, streamlining chat handling and improving user interactions.

Changes

File Change Summary
schema.graphql Added Chat, ChatMessage types; new input chatInput; mutations createChat, queries chatById, chatsByUserId, subscription messageSentToChat.
src/GraphQl/Mutations/OrganizationMutations.ts Added CREATE_CHAT, SEND_MESSAGE_TO_CHAT mutations; updated existing mutations to include replyTo; added MESSAGE_SENT_TO_CHAT subscription.
src/GraphQl/Queries/PlugInQueries.ts Added CHAT_BY_ID, CHATS_LIST queries; updated existing queries to include replyTo field.
src/components/Avatar/Avatar.module.css Modified .imageContainer width and height from 56px to fit-content.
src/components/Avatar/Avatar.tsx Added optional chaining to avatar.toString() to prevent runtime errors.
src/components/UserPortal/ChatRoom/ChatRoom.module.css Updated styles for layout and appearance; added new classes for message styling.
src/components/UserPortal/ChatRoom/ChatRoom.test.tsx Restructured tests to align with new GraphQL queries and mutations; updated mock data.
src/components/UserPortal/ChatRoom/ChatRoom.tsx Unified chat handling; updated state management and rendering logic; added reply functionality.
src/components/UserPortal/ContactCard/ContactCard.test.tsx Updated tests to include isGroup and selectedContact properties.
src/components/UserPortal/ContactCard/ContactCard.tsx Removed subtitle and type properties; added isGroup property.
src/components/UserPortal/CreateDirectChat/CreateDirectChat.test.tsx Updated mock data and queries for creating direct chats; aligned tests with new structure.
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx Renamed mutation to CREATE_CHAT; updated state management and refetch logic.
src/components/UserPortal/CreateGroupChat/CreateGroupChat.test.tsx Updated mock data and tests for group chat functionalities; refined test interactions.
src/components/UserPortal/CreateGroupChat/CreateGroupChat.tsx Refactored group chat creation logic; updated UI components to Material-UI standards.
src/screens/UserPortal/Chat/Chat.module.css Renamed .contactListContainer to .contactCardContainer; updated styles for responsiveness.
src/screens/UserPortal/Chat/Chat.test.tsx Restructured tests; updated mock data and queries for unified chat handling.
src/screens/UserPortal/Chat/Chat.tsx Consolidated queries for chats; simplified state management and rendering logic.

Assessment against linked issues

Objective Addressed Explanation
Update chat related functionalities to work with the updated chat schema (2285)

Possibly related PRs

Suggested reviewers

  • palisadoes
  • aashimawadhwa

Poem

🐇 In the chat we hop and play,
New messages sent without delay.
With groups and friends, we share our cheer,
In every chat, our voices clear!
So let’s create and send away,
In our cozy chat, we’ll always stay! 🐇


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 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

We have these basic policies to make the approval process smoother for our volunteer team.

Testing Your Code

Please make sure your code passes all tests. Our test code coverage system will fail if these conditions occur:

  1. The overall code coverage drops below the target threshold of the repository
  2. Any file in the pull request has code coverage levels below the repository threshold
  3. Merge conflicts

The process helps maintain the overall reliability of the code base and is a prerequisite for getting your PR approved. Assigned reviewers regularly review the PR queue and tend to focus on PRs that are passing.

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

codecov bot commented Sep 22, 2024

Codecov Report

Attention: Patch coverage is 87.64045% with 11 lines in your changes missing coverage. Please review.

Project coverage is 97.96%. Comparing base (025bc1d) to head (e6e5c24).
Report is 3 commits behind head on develop.

Files with missing lines Patch % Lines
src/screens/UserPortal/Chat/Chat.tsx 75.00% 4 Missing and 2 partials ⚠️
src/components/UserPortal/ChatRoom/ChatRoom.tsx 89.36% 5 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2286      +/-   ##
===========================================
+ Coverage    97.62%   97.96%   +0.34%     
===========================================
  Files          250      250              
  Lines         7188     7136      -52     
  Branches      2069     2040      -29     
===========================================
- Hits          7017     6991      -26     
+ Misses         159      135      -24     
+ Partials        12       10       -2     

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

Copy link

github-actions bot commented Oct 3, 2024

This pull request did not get any activity in the past 10 days and will be closed in 180 days if no update occurs. Please verify it has no conflicts with the develop branch and rebase if needed. Mention it now if you need help or give permission to other people to finish your work.

@github-actions github-actions bot added the no-pr-activity No pull request activity label Oct 3, 2024
Copy link

@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: 36

🧹 Outside diff range and nitpick comments (21)
src/components/Avatar/Avatar.tsx (1)

47-47: Approve the change with a minor suggestion.

The addition of optional chaining to avatar?.toString() is a good defensive programming practice. It prevents potential runtime errors if avatar is null or undefined.

However, to make the component more robust, consider handling the case where svg might be undefined:

const svg = avatar?.toString() ?? '';

This ensures that svg is always a string, which might prevent issues further down in the component's render method.

src/components/UserPortal/ContactCard/ContactCard.tsx (1)

Line range hint 32-78: LGTM! Consider minor refactor for consistency.

The changes in the contactCard function align well with the interface modifications. The removal of subtitle and type-related logic simplifies the component, which is good for maintainability.

For consistency with the interface changes, consider updating the JSX to use the new isGroup property if needed. For example:

 <div className={styles.contactNameContainer}>
   <b>{props.title}</b>
+  {props.isGroup && <span> (Group)</span>}
 </div>

This change would visually indicate whether a contact is a group or not, which might be useful depending on your UI requirements.

src/components/UserPortal/ContactCard/ContactCard.test.tsx (1)

99-99: LGTM: Testing group contact scenario

Setting isGroup to true in this test case is a good addition. It ensures that the component's behavior is tested for both individual and group contacts when selected.

Consider adding a separate test case for group contacts to isolate the testing of group-specific behavior. This would improve the test structure and make it easier to identify issues specific to group contacts in the future.

src/screens/UserPortal/Chat/Chat.module.css (1)

Line range hint 1-200: Suggestions for improving overall CSS structure.

While the current structure is functional, consider the following improvements:

  1. Avoid using !important flags where possible. Instead, use more specific selectors to override styles.
  2. Consider consolidating redundant styles. For example, the ::-webkit-scrollbar property is set to display: none in multiple places.
  3. Enhance responsive design by using more flexible units (e.g., rem, %) instead of fixed pixel values where appropriate.
  4. Consider using CSS variables for commonly used values (like colors and dimensions) to improve maintainability.

Would you like assistance in implementing any of these suggestions?

src/components/UserPortal/ChatRoom/ChatRoom.module.css (3)

87-110: LGTM: New reply styling enhances chat functionality

The addition of .replyTo and .replyToMessage classes provides clear styling for a reply feature in the chat. The use of borders and background colors effectively differentiates reply messages from regular ones.

Consider using CSS variables for colors (e.g., --reply-border-color: pink;) to improve maintainability and consistency across the stylesheet.


170-218: LGTM: New interactive elements enhance user experience

The addition of .customToggle and .closeBtn classes, along with their associated styles, introduces new interactive elements to the chat interface. The hover effects and icon styling contribute to a more engaging user experience.

Consider adding a transition property to the hover effects for a smoother user experience. For example:

.customToggle,
.closeBtn {
  transition: background-color 0.2s ease;
}

225-244: LGTM: Targeted message animation improves navigation

The addition of an animation for targeted messages is a great feature that improves user navigation within the chat. The use of scroll-margin-top ensures the targeted message is fully visible.

Consider reducing the animation duration for a snappier effect. A duration of 0.5s might provide a better balance between visibility and responsiveness:

.messageSent:target,
.messageReceived:target {
  animation-duration: 0.5s;
}
src/GraphQl/Queries/PlugInQueries.ts (1)

223-229: Add the image Field to users for Consistency

In the CHAT_BY_ID query, the users field includes user details but omits the image field. However, in the CHATS_LIST query (lines 304-309), the users field includes the image attribute.

For consistency and to provide a richer set of user data, consider including the image field in the users object within the CHAT_BY_ID query.

src/components/UserPortal/CreateGroupChat/CreateGroupChat.tsx (2)

189-189: Remove debugging console statements

The console.log(organizations); statement at line 189 appears to be used for debugging purposes. It's recommended to remove such statements from production code to maintain cleanliness and avoid unintended console output.

Apply this diff to remove the debugging statement:

-          console.log(organizations);

206-227: Clean up code by removing commented-out sections

There's a block of commented-out code between lines 206 and 227. To keep the codebase clean and maintainable, consider removing unused code instead of commenting it out.

Apply this diff to remove the commented-out code:

-                {/* <FormControl fullWidth>
-                  <InputLabel id="select-org">Select Organization</InputLabel>
-                  <Select
-                    labelId="select-org"
-                    id="select-org"
-                    data-testid="orgSelect"
-                    label="Select Organization"
-                    value={selectedOrganization}
-                    onChange={(e) => handleChange(e)}
-                  >
-                    {organizations?.length &&
-                      organizations.map((organization: InterfaceOrganization) => (
-                        <MenuItem
-                          data-testid="selectOptions"
-                          key={organization._id}
-                          value={organization._id}
-                        >
-                          {`${organization.name}(${organization.address?.city},${organization.address?.state},${organization.address?.countryCode})`}
-                        </MenuItem>
-                      ))}
-                  </Select>
-                </FormControl> */}
src/components/UserPortal/ChatRoom/ChatRoom.test.tsx (1)

Line range hint 784-1039: Refactor duplicated mock definitions to improve maintainability

There is significant duplication in the mock data definitions for CHAT_BY_ID_QUERY_MOCK, GROUP_CHAT_BY_ID_QUERY_MOCK, and CHATS_LIST_MOCK. Refactoring these into reusable functions or mock generators can reduce code redundancy and enhance maintainability.

Consider creating a helper function to generate chat mocks:

function createChatMock(id, isGroup, users, messages) {
  return {
    request: {
      query: CHAT_BY_ID,
      variables: { id },
    },
    result: {
      data: {
        chatById: {
          _id: id,
          isGroup,
          users,
          messages,
          // ...other fields
        },
      },
    },
  };
}

Use this function to generate your mocks:

const CHAT_BY_ID_QUERY_MOCK = [
  createChatMock('1', false, usersArray, messagesArray),
  // ...other mocks
];
src/components/UserPortal/CreateDirectChat/CreateDirectChat.test.tsx (2)

Line range hint 352-364: Inconsistent mock data: 'messageSentToGroupChat' should be 'messageSentToChat'

In the mocks at lines 352-364 and 378-390, the query is MESSAGE_SENT_TO_CHAT, but the result data key is messageSentToGroupChat. This inconsistency may cause the tests to fail or behave unexpectedly. Please update messageSentToGroupChat to messageSentToChat in the result data to align with the updated schema.

Apply this diff to fix the inconsistency:

# At lines 359 and 389
-            messageSentToGroupChat: {
+            messageSentToChat: {

Also applies to: 378-390


Line range hint 1444-1446: Await 'waitFor' to ensure proper async handling

At lines 1444-1446, the waitFor function is called but not awaited. Since waitFor returns a promise, it should be awaited to ensure the assertion inside is correctly handled.

Apply this diff to fix the issue:

-        waitFor(() => {
+        await waitFor(() => {
          expect(addBtn[0]).toBeInTheDocument();
        });
src/screens/UserPortal/Chat/Chat.test.tsx (3)

Line range hint 694-706: Inconsistent field name in mock response

In the MESSAGE_SENT_TO_CHAT_MOCK array, the second mock's result incorrectly uses messageSentToGroupChat instead of messageSentToChat. This inconsistency may cause tests to fail or not behave as expected.

Apply this diff to fix the inconsistency:

       result: {
         data: {
-          messageSentToGroupChat: {
+          messageSentToChat: {
             _id: '668ec1f1df364e03ac47a151',

Line range hint 720-732: Inconsistent field name in mock response

Similarly, in the third mock within MESSAGE_SENT_TO_CHAT_MOCK, the result uses messageSentToGroupChat instead of messageSentToChat. This inconsistency may lead to unexpected test behaviors.

Apply this diff to correct the field name:

       result: {
         data: {
-          messageSentToGroupChat: {
+          messageSentToChat: {
             _id: '668ec1f13603ac4697a151',

1715-1722: Simplify conditional check in the test

In the "sidebar" test, the conditional check for closeMenuBtn may be unnecessary since findByTestId will throw an exception if the element is not found.

You can simplify the code by removing the if statement:

       const closeMenuBtn = await screen.findByTestId('closeMenu');
       expect(closeMenuBtn).toBeInTheDocument();
-      if (closeMenuBtn) {
           closeMenuBtn.click();
-      } else {
-          throw new Error('Close menu button not found');
-      }
src/components/UserPortal/CreateGroupChat/CreateGroupChat.test.tsx (3)

2332-2360: Nitpick: Remove commented-out code and debugging statements

The code contains several commented-out sections and a console.log statement. Cleaning up these sections enhances code readability and maintainability.

Apply this diff to remove unnecessary code:

 const selectLabel = /select organization/i;
 const orgSelect = await screen.findByLabelText('Select Organization');
-// console.log(prettyDOM(document));

-// act(() => {
-//   fireEvent.change(orgSelect, {
-//     target: { value: '6401ff65ce8e8406b8f07af2' },
-//   });
-// })
-// fireEvent.change(orgSelect, {
-//   target: { value: '6401ff65ce8e8406b8f07af2' },
-// });

 userEvent.click(orgSelect);

 const optionsPopupEl = await screen.findByRole('listbox', {
   name: selectLabel,
 });

 userEvent.click(within(optionsPopupEl).getByText(/any organization/i));
-// });

-// await waitFor(async () => {
-//   const option = await screen.findAllByText('Any Organization');
-//   console.log("option", option);
-// });

2376-2378: Nitpick: Remove obsolete commented-out assertions

There's an unused await waitFor() block that's commented out. Removing obsolete code prevents confusion and keeps the test code clean.

Apply this diff to clean up the code:

-// await waitFor(() => {
-//   expect(createBtn).not.toBeInTheDocument();
-// });

⚠️ Deprecated message mocks still in use

Found remaining references to MESSAGE_SENT_TO_DIRECT_CHAT and MESSAGE_SENT_TO_GROUP_CHAT in the following files:

  • src/screens/UserPortal/Chat/Chat.test.tsx
  • src/GraphQl/Mutations/OrganizationMutations.ts
  • src/components/UserPortal/CreateGroupChat/CreateGroupChat.test.tsx

Please update these instances to use MESSAGE_SENT_TO_CHAT to align with the updated schema.

🔗 Analysis chain

Line range hint 1213-1275: Verify: Confirm MESSAGE_SENT_TO_CHAT aligns with updated schema

Ensure that replacing MESSAGE_SENT_TO_DIRECT_CHAT and MESSAGE_SENT_TO_GROUP_CHAT with MESSAGE_SENT_TO_CHAT correctly reflects the updated chat schema and that subscriptions or queries relying on these mocks are updated accordingly.

Run the following script to find usages of MESSAGE_SENT_TO_DIRECT_CHAT and MESSAGE_SENT_TO_GROUP_CHAT:

This script searches for any remaining references to the deprecated mocks. Ensure that all such references are updated to use MESSAGE_SENT_TO_CHAT.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find references to deprecated message mocks

# Search for deprecated mocks in the codebase
rg 'MESSAGE_SENT_TO_(DIRECT|GROUP)_CHAT'

# Verify that these are replaced with `MESSAGE_SENT_TO_CHAT`

Length of output: 510

src/screens/UserPortal/Chat/Chat.tsx (2)

204-205: Lines not covered by tests

The logic determining the chat title for direct chats (lines 204-205) is not covered by tests. This could lead to unnoticed bugs if the logic changes in the future.

Consider adding unit tests to cover these scenarios, ensuring that the correct user names are displayed for direct chats.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 204-205: src/screens/UserPortal/Chat/Chat.tsx#L204-L205
Added lines #L204 - L205 were not covered by tests


211-211: Line not covered by tests

The assignment of the image property for chats (line 211) lacks test coverage. Ensuring this line is tested can prevent potential issues with displaying user images.

Add tests to verify that the correct user images are displayed in both direct and group chats.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 211-211: src/screens/UserPortal/Chat/Chat.tsx#L211
Added line #L211 was not covered by tests

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 01ef5c6 and 9a661e5.

📒 Files selected for processing (17)
  • schema.graphql (6 hunks)
  • src/GraphQl/Mutations/OrganizationMutations.ts (3 hunks)
  • src/GraphQl/Queries/PlugInQueries.ts (4 hunks)
  • src/components/Avatar/Avatar.module.css (1 hunks)
  • src/components/Avatar/Avatar.tsx (1 hunks)
  • src/components/UserPortal/ChatRoom/ChatRoom.module.css (5 hunks)
  • src/components/UserPortal/ChatRoom/ChatRoom.test.tsx (16 hunks)
  • src/components/UserPortal/ChatRoom/ChatRoom.tsx (5 hunks)
  • src/components/UserPortal/ContactCard/ContactCard.test.tsx (2 hunks)
  • src/components/UserPortal/ContactCard/ContactCard.tsx (1 hunks)
  • src/components/UserPortal/CreateDirectChat/CreateDirectChat.test.tsx (13 hunks)
  • src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (6 hunks)
  • src/components/UserPortal/CreateGroupChat/CreateGroupChat.test.tsx (22 hunks)
  • src/components/UserPortal/CreateGroupChat/CreateGroupChat.tsx (10 hunks)
  • src/screens/UserPortal/Chat/Chat.module.css (1 hunks)
  • src/screens/UserPortal/Chat/Chat.test.tsx (18 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Avatar/Avatar.module.css
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/components/UserPortal/ChatRoom/ChatRoom.tsx

[warning] 223-223: src/components/UserPortal/ChatRoom/ChatRoom.tsx#L223
Added line #L223 was not covered by tests


[warning] 229-229: src/components/UserPortal/ChatRoom/ChatRoom.tsx#L229
Added line #L229 was not covered by tests


[warning] 255-255: src/components/UserPortal/ChatRoom/ChatRoom.tsx#L255
Added line #L255 was not covered by tests


[warning] 262-262: src/components/UserPortal/ChatRoom/ChatRoom.tsx#L262
Added line #L262 was not covered by tests

src/screens/UserPortal/Chat/Chat.tsx

[warning] 204-205: src/screens/UserPortal/Chat/Chat.tsx#L204-L205
Added lines #L204 - L205 were not covered by tests


[warning] 211-211: src/screens/UserPortal/Chat/Chat.tsx#L211
Added line #L211 was not covered by tests

🪛 Biome
src/components/UserPortal/CreateGroupChat/CreateGroupChat.tsx

[error] 238-239: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (33)
src/components/Avatar/Avatar.tsx (1)

Line range hint 1-62: Request clarification on PR objectives alignment.

While the change in this file is a good improvement for error prevention, it doesn't seem to directly address the PR's stated objective of updating chat-related functionality to work with a new chat schema.

Could you please clarify:

  1. How this change relates to the chat schema update mentioned in the PR description?
  2. Are there other files not included in this review that contain the main changes for the chat functionality update?

This will help ensure that the PR fully addresses its intended objectives.

To help verify the scope of changes related to chat functionality, you could run the following command:

This will show all TypeScript and JavaScript files that contain the word 'chat' and have been changed in this PR.

src/components/UserPortal/ContactCard/ContactCard.tsx (2)

11-11: LGTM! Verify usage in parent components.

The addition of isGroup: boolean to the InterfaceContactCardProps interface aligns with the PR objective to update chat functionality for the new schema. The removal of subtitle, type, and setSelectedChatType properties (as mentioned in the AI summary) suggests a simplification of the component's props.

To ensure these changes don't break existing functionality, please verify the usage of this component in parent components. Run the following script to check for any remaining usage of the removed properties:

#!/bin/bash
# Description: Check for usage of removed properties in parent components

# Test: Search for usage of removed properties
echo "Searching for usage of removed properties:"
rg --type typescript --type tsx 'subtitle|type|setSelectedChatType' src

Line range hint 13-29: Update component documentation and verify layout.

The component's documentation comments haven't been updated to reflect the changes in the props. This could lead to confusion for other developers working on this component.

Please update the documentation to remove references to removed props (subtitle, type, setSelectedChatType) and add information about the new isGroup prop.

Also, verify that the removal of the subtitle rendering doesn't negatively impact the component's layout or appearance. You may want to add a visual test or snapshot test to ensure the layout remains correct.

If no tests are found, consider adding appropriate tests to ensure the layout remains correct after these changes.

✅ Verification successful

Visual or snapshot tests for ContactCard are present.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing visual or snapshot tests

# Test: Search for visual or snapshot tests related to ContactCard
echo "Searching for existing visual or snapshot tests for ContactCard:"
rg --type typescript --type tsx 'test|spec|snapshot.*ContactCard' src

Length of output: 297


Script:

#!/bin/bash
# Description: Check for existing visual or snapshot tests for ContactCard

echo "Searching for existing visual or snapshot tests for ContactCard:"
rg --glob '*.test.tsx' --glob '*.spec.tsx' --glob '*snapshot*ContactCard*' 'ContactCard' src

Length of output: 979

src/components/UserPortal/ContactCard/ContactCard.test.tsx (2)

29-29: LGTM: Addition of isGroup property

The addition of the isGroup property to the props object is consistent with the PR objective to update chat-related functionality. This new property will allow for differentiation between individual and group contacts in the tests, which is crucial for ensuring the component behaves correctly in both scenarios.


Line range hint 1-120: Summary of ContactCard.test.tsx changes

The changes to this test file align well with the PR objectives to update chat-related functionality for the new schema. Key points:

  1. The addition of the isGroup property enhances test coverage by allowing differentiation between individual and group contacts.
  2. The test cases now cover both individual and group contact scenarios, which is crucial for ensuring the component behaves correctly in all cases.
  3. There's an inconsistency regarding the selectedContact property that needs clarification.

Overall, these changes improve the test suite. Once the selectedContact inconsistency is resolved, the updates will provide a more comprehensive test coverage for the ContactCard component.

To ensure all changes are properly reflected, please run the following script:

This will help us confirm all intended changes are present and correctly implemented.

src/screens/UserPortal/Chat/Chat.module.css (1)

81-85: LGTM: New .contactCardContainer class looks good.

The new .contactCardContainer class is well-structured and consistent with the AI summary's mention of renaming from .contactListContainer. The flex container setup with appropriate padding and gap is suitable for displaying contact cards.

src/components/UserPortal/ChatRoom/ChatRoom.module.css (8)

27-27: LGTM: Improved spacing in user info section

The addition of gap: 10px; to the .userInfo class enhances the spacing between child elements, improving the overall layout and readability of the user information section.


57-59: LGTM: Enhanced layout for received messages

The changes to .messageReceived improve the layout and alignment of received messages. The flex display and space-between justification allow for better control over the message content and metadata.

Please verify that setting padding-bottom: 0; doesn't negatively impact the vertical spacing between messages. If it does, consider adding a margin to the bottom instead.


72-74: LGTM: Consistent layout improvements for sent messages

The changes to .messageSent mirror those made to .messageReceived, ensuring a consistent layout for both sent and received messages. This improves the overall chat interface consistency.


76-85: LGTM: New user details styling enhances chat interface

The addition of the .userDetails class and its associated styles improves the presentation of user information in the chat interface. The consistent use of gap for spacing and the defined dimensions for the user image contribute to a more polished look.


122-122: LGTM: Improved spacing for message timestamp

The addition of margin-left: 6px; to the .messageTime class enhances the separation between the message content and the timestamp, improving overall readability.


126-130: LGTM: Enhanced message content layout

The additions to the .messageContent class improve the layout and alignment of elements within each message. The use of flexbox properties ensures proper stacking and centering of content, consistent with the overall styling approach in the file.


163-168: LGTM: New message attributes styling improves layout

The addition of the .messageAttributes class provides a structured layout for message metadata or actions. The use of flexbox properties ensures proper vertical stacking and alignment, consistent with the overall chat interface design.


Line range hint 1-249: Summary: Chat interface improvements align well with PR objectives

The changes to this CSS module file significantly enhance the chat interface's layout, interactivity, and user experience. The additions of new classes and styles for features like message replies, interactive elements, and targeted message highlighting align well with the PR objectives of updating chat-related functionality to work with the updated chat schema.

These improvements contribute to a more robust and user-friendly chat experience, which is likely to positively impact the overall application. The consistent use of flexbox for layout management and the addition of interactive elements demonstrate a thoughtful approach to updating the chat functionality.

To further improve the code:

  1. Consider using CSS variables for colors and repeated values to enhance maintainability.
  2. Ensure that all new classes are being utilized in the corresponding React components.
  3. If not already done, consider adding responsive design rules to ensure the new layout works well on various screen sizes.
src/components/UserPortal/CreateDirectChat/CreateDirectChat.tsx (4)

28-28: Consistent renaming of prop to chatsListRefetch.

The prop contactRefetch has been renamed to chatsListRefetch, which accurately reflects its purpose of refreshing the chats list. This enhances code readability and maintainability.


63-66: Function name updated for clarity.

Renaming the component function to createDirectChatModal aligns with the component's functionality of creating a direct chat modal. This improves code clarity and consistency with the file name.


78-78: Updated to use CREATE_CHAT mutation.

Switching from CREATE_DIRECT_CHAT to CREATE_CHAT ensures compatibility with the updated chat schema. This aligns the frontend mutation with the backend changes.


81-85: Correctly setting isGroup to false in mutation variables.

Including isGroup: false explicitly specifies that a direct chat is being created, which is essential for the backend to process the chat appropriately.

src/GraphQl/Queries/PlugInQueries.ts (2)

144-162: Verify Alignment with the Updated Chat Schema

The PR aims to update chat functionalities to work with the updated chat schema. It's essential to ensure that all queries reflect the latest schema changes, including field names, structures, and nested relationships.

To confirm that the queries align with the updated schema, consider the following steps:

  • Review the Updated Schema: Check the updated chat schema definitions to verify that all the fields used in the queries are correct.
  • Validate Queries Against the Schema: Use a GraphQL validation tool or linter to ensure that the queries are compatible with the schema.

If the schema is available in the codebase, you can run this script to validate the queries:

Also applies to: 188-231, 243-254, 274-312


274-312: Confirm the Necessity of the type Field in Messages

The CHATS_LIST query includes the type field within messages (line 289~), which may be crucial for distinguishing between message types (e.g., text, image, file). However, this field is not present in other queries like DIRECT_CHAT_BY_ID and GROUP_CHAT_BY_ID.

Ensure that the inclusion of the type field is intentional and consistently applied across all queries that retrieve messages. This will help prevent potential runtime errors and simplify client-side logic.

To verify where the type field is used and ensure consistency, you can run the following script:

src/GraphQl/Mutations/OrganizationMutations.ts (2)

108-143: LGTM

The SEND_MESSAGE_TO_CHAT mutation is correctly defined and structured, supporting the necessary parameters and returning the expected data.


267-296: LGTM

The MESSAGE_SENT_TO_CHAT subscription is properly implemented, allowing clients to subscribe to messages sent to any chat and receive necessary message details, including replies and sender information.

src/components/UserPortal/CreateGroupChat/CreateGroupChat.tsx (1)

33-33: Ensure all references to groupChatListRefetch are updated to chatsListRefetch

The property groupChatListRefetch has been renamed to chatsListRefetch in the InterfaceCreateGroupChatProps interface. Please ensure that all instances of groupChatListRefetch are updated throughout the codebase to maintain consistency and prevent errors.

Run the following script to find any remaining references:

src/components/UserPortal/ChatRoom/ChatRoom.tsx (1)

116-116: Ensure replyTo is correctly handled when null.

In the variables object for the sendMessageToChat mutation, you're using replyTo: replyToDirectMessage?._id. Make sure that when replyToDirectMessage is null, the replyTo variable is either omitted or explicitly set to null, as required by the GraphQL API.

Run the following script to verify if replyTo can be null in the SEND_MESSAGE_TO_CHAT mutation:

✅ Verification successful

replyTo handles null values correctly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify if the 'replyTo' variable in the SEND_MESSAGE_TO_CHAT mutation allows null values.

# Test: Search for the SEND_MESSAGE_TO_CHAT mutation definition in the codebase. Expect: 'replyTo' parameter accepts null values.

rg --type graphql 'mutation SEND_MESSAGE_TO_CHAT' -A 10

# Alternatively, if using TypeScript definitions
rg --type ts 'SEND_MESSAGE_TO_CHAT' -A 10

Length of output: 11802

schema.graphql (1)

1617-1622: Ensure name is required when isGroup is true in chatInput

In the chatInput type, the name field is optional. However, for group chats (isGroup: true), a name is likely required to identify the group chat. Consider enforcing this requirement through input validation in your resolver logic.

src/screens/UserPortal/Chat/Chat.test.tsx (4)

Line range hint 1740-1744: Ensure resizeWindow function simulates resize events correctly

The resizeWindow function manipulates window.innerWidth and dispatches a resize event. Verify that this correctly triggers any resize listeners in your component, as jsdom might not fully simulate layout changes.

Consider using window.matchMedia mocks for responsive testing if necessary.


Line range hint 809-869: Potential duplication in CHAT_BY_ID_QUERY_MOCK

The CHAT_BY_ID_QUERY_MOCK array appears to contain two mocks with the same id value of '1'. Verify if both mocks are necessary or if this is unintended duplication.

Check if both mocks serve different purposes or if one can be removed to simplify the test setup.


22-23: Verify correct import paths for mutations and queries

Ensure that the import paths for MESSAGE_SENT_TO_CHAT, CHATS_LIST, and CHAT_BY_ID are correct and reflect the updated schema structure.

Run the following script to confirm that these files exist at the specified paths:

#!/bin/bash
# Description: Verify that the import paths point to existing files.

# Check if the mutation file exists
test -f "./src/GraphQl/Mutations/OrganizationMutations.tsx" && echo "OrganizationMutations.tsx exists" || echo "OrganizationMutations.tsx not found"

# Check if the queries file exists
test -f "./src/GraphQl/Queries/PlugInQueries.tsx" && echo "PlugInQueries.tsx exists" || echo "PlugInQueries.tsx not found"

1655-1657: Possible unnecessary duplication of mocks

In the "Test create new group chat" test, consider reviewing the inclusion of MESSAGE_SENT_TO_CHAT_MOCK and UserConnectionListMock. Verify if both are required or if there is an unintended duplication.

Run the following script to list the entries in the mock array and check for duplicates:

src/components/UserPortal/CreateGroupChat/CreateGroupChat.test.tsx (2)

5-9: Approved: Added imports enhance testing capabilities

The addition of prettyDOM, within, and userEvent imports from @testing-library/react and @testing-library/user-event improves the testing capabilities by providing more utilities for DOM inspection and simulating user interactions.


40-40: Approved: userEvent import aligns with best practices

Importing userEvent enhances the simulation of user interactions in tests, providing a more accurate representation of how users interact with the application.

src/screens/UserPortal/Chat/Chat.tsx (2)

237-237: Confirm 'chatsListRefetch' prop usage in 'CreateGroupChat' and 'CreateDirectChat'

The chatsListRefetch function is passed to CreateGroupChat and CreateDirectChat components. Ensure these components accept this prop and utilize it to refresh the chat list after a new chat is created.

Use the following script to confirm that chatsListRefetch is handled in these components:

#!/bin/bash
# Description: Verify 'chatsListRefetch' prop usage

# Check in 'CreateGroupChat' component
rg 'function CreateGroupChat' -A 20 -- 'components/UserPortal/CreateGroupChat/'
rg 'props.chatsListRefetch' -A 5 -- 'components/UserPortal/CreateGroupChat/'

# Check in 'CreateDirectChat' component
rg 'function CreateDirectChat' -A 20 -- 'components/UserPortal/CreateDirectChat/'
rg 'props.chatsListRefetch' -A 5 -- 'components/UserPortal/CreateDirectChat/'

Ensure that both components include chatsListRefetch in their props and call it appropriately after creating a new chat.

Also applies to: 244-244


229-229: Ensure 'ChatRoom' functions without 'selectedChatType' prop

The ChatRoom component is now rendered without the selectedChatType prop. Verify that ChatRoom has been updated accordingly and that no references to selectedChatType remain within the component.

Run the following script to check for references to selectedChatType:

✅ Verification successful

'ChatRoom' functions correctly without the selectedChatType prop

All references to selectedChatType have been successfully removed from the ChatRoom component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for 'selectedChatType' references in 'ChatRoom' component

# Expected result: No occurrences of 'selectedChatType' in 'ChatRoom' component files
rg 'selectedChatType' -A 5 -F -- 'components/UserPortal/ChatRoom/'

Length of output: 630


Script:

#!/bin/bash
# Description: Locate ChatRoom component files and search for 'selectedChatType'

# Find all ChatRoom component files (e.g., ChatRoom.tsx, ChatRoom.jsx)
chatroom_files=$(fd 'ChatRoom\.(tsx|jsx|ts|js)$')

if [ -z "$chatroom_files" ]; then
  echo "No ChatRoom component files found."
  exit 1
fi

# Search for 'selectedChatType' in the located ChatRoom component files
rg 'selectedChatType' -A 5 -F -- $chatroom_files

Length of output: 241

Comment on lines +220 to +223
.messageSent:hover,
.messageReceived:hover {
padding: 0px 6px;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider alternative hover effect to avoid layout shifts

The current hover effect changes the padding of messages, which could cause disruptive layout shifts. Consider an alternative approach that doesn't affect the message dimensions, such as a subtle background color change or a border effect.

Here's an alternative implementation that avoids layout shifts:

.messageSent:hover,
.messageReceived:hover {
  background-color: rgba(0, 0, 0, 0.05);
  transition: background-color 0.2s ease;
}

Comment on lines +81 to +88
await createChat({
variables: {
organizationId,
userIds: [userId, id],
isGroup: false,
},
});
contactRefetch();
await chatsListRefetch();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for the createChat mutation.

Currently, errors from the createChat mutation are not being handled. This could lead to unhandled exceptions or a poor user experience if the mutation fails. Consider adding error handling to manage potential failures gracefully.

You can modify the function as follows:

const handleCreateDirectChat = async (id: string): Promise<void> => {
+  try {
    await createChat({
      variables: {
        organizationId,
        userIds: [userId, id],
        isGroup: false,
      },
    });
    await chatsListRefetch();
    toggleCreateDirectChatModal();
+  } catch (error) {
+    // Handle error, e.g., display a notification to the user
+    console.error('Error creating chat:', error);
+  }
};

Committable suggestion was skipped due to low confidence.

Comment on lines +144 to +162
replyTo {
_id
createdAt
messageContent
receiver {
_id
firstName
lastName
email
image
}
sender {
_id
firstName
lastName
email
image
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure Consistency in the replyTo Structure

In the DIRECT_CHAT_BY_ID query, the replyTo field within messages includes both receiver and sender details. However, in other queries like CHAT_BY_ID and GROUP_CHAT_BY_ID, the replyTo field only includes the sender information, and sometimes includes a type field.

For consistency and to prevent potential data handling issues, consider standardizing the replyTo structure across all chat-related queries. This will ensure that the client can handle the replyTo field uniformly regardless of the chat type.

Comment on lines +188 to +231
export const CHAT_BY_ID = gql`
query chatById($id: ID!) {
chatById(id: $id) {
_id
isGroup
name
organization {
_id
}
createdAt
messages {
_id
createdAt
messageContent
replyTo {
_id
createdAt
messageContent
type
sender {
_id
firstName
lastName
email
image
}
}
sender {
_id
firstName
lastName
email
image
}
}
users {
_id
firstName
lastName
email
}
}
}
`;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Include the type Field in replyTo Across All Queries

In the CHAT_BY_ID query, the replyTo field includes a type field (line 206~), which specifies the message type. However, this field is not included in the replyTo structures of the DIRECT_CHAT_BY_ID and GROUP_CHAT_BY_ID queries.

To maintain consistency and provide complete information about the replied message, consider adding the type field to the replyTo structure in the DIRECT_CHAT_BY_ID and GROUP_CHAT_BY_ID queries as well.

Comment on lines +243 to +254
replyTo {
_id
createdAt
messageContent
sender {
_id
firstName
lastName
email
image
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure replyTo Includes type in GROUP_CHAT_BY_ID Query

In the GROUP_CHAT_BY_ID query, the replyTo field within messages does not include the type field. Since the CHAT_BY_ID query includes type in the replyTo structure, adding it here will maintain consistency across different chat types and aid in client-side message handling.

Comment on lines +26 to +28
CREATE_CHAT,
CREATE_GROUP_CHAT,
MESSAGE_SENT_TO_CHAT,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor imports to remove deprecated CREATE_GROUP_CHAT

The CREATE_GROUP_CHAT mutation appears to be deprecated in favor of CREATE_CHAT. It's advisable to remove CREATE_GROUP_CHAT from the imports to avoid confusion and ensure that only the updated mutations are used.

Apply this diff to remove the deprecated import:

 import {
      CREATE_CHAT,
-     CREATE_GROUP_CHAT,
      MESSAGE_SENT_TO_CHAT,
      MESSAGE_SENT_TO_DIRECT_CHAT,
      MESSAGE_SENT_TO_GROUP_CHAT,
 } from 'GraphQl/Mutations/OrganizationMutations';

Committable suggestion was skipped due to low confidence.

Comment on lines +2381 to +2391
test('Test add and remove user ', async () => {
setItem('userId', '1');
const mock = [
...USER_JOINED_ORG_MOCK,
...CREATE_GROUP_CHAT_MOCK,
...GROUP_CHAT_BY_ID_QUERY_MOCK,
...DIRECT_CHAT_BY_ID_QUERY_MOCK,
...MESSAGE_SENT_TO_DIRECT_CHAT_MOCK,
...MESSAGE_SENT_TO_GROUP_CHAT_MOCK,
...MESSAGE_SENT_TO_CHAT_MOCK,
...CHAT_BY_ID_QUERY_MOCK,
...CHATS_LIST_MOCK,
...UserConnectionListMock,
...MOCKS,
...CREATE_CHAT_MUTATION,
...CHATS_LIST_MOCK,
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Duplicate Mocks Found in CreateGroupChat.test.tsx

  • ...CHATS_LIST_MOCK is included multiple times in the mock array. Please remove the duplicate to prevent unexpected test behavior.
🔗 Analysis chain

Verify: Ensure all necessary mocks are included without duplication

It's important to verify that the mock array includes all necessary mocks without duplicates to prevent unexpected test behavior.

Run the following script to check for duplicate mocks:

This script searches for mock arrays in TypeScript test files and counts the number of times each mock is included. Review the output to ensure that mocks are not duplicated.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find duplicate entries in mock arrays within test files

# Find all `const mock = [` declarations and list their contents
rg --type ts 'const mock = \[' -A 50

# Count occurrences of each mock inclusion
rg --type ts '\.\.\.[A-Z_]+,' | sort | uniq -c | sort -nr

Length of output: 39465

@@ -59,6 +55,10 @@
const { t: tCommon } = useTranslation('common');

const [hideDrawer, setHideDrawer] = useState<boolean | null>(null);
const [chats, setChats] = useState<any>([]);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid using 'any' type in useState for 'chats'

Using any in useState<any>([]) bypasses TypeScript's type checking, reducing code reliability. Consider defining a specific type for the chats state to enhance type safety and catch potential bugs at compile time.

Define an interface for the chat objects and update the state declaration:

interface Chat {
  _id: string;
  name?: string;
  isGroup: boolean;
  users: Array<{
    _id: string;
    firstName: string;
    lastName: string;
    image: string;
  }>;
  image?: string;
  // Add other relevant properties
}

const [chats, setChats] = useState<Chat[]>([]);

Comment on lines +202 to +206
title: !chat.isGroup
? chat.users[0]?._id === userId
? `${chat.users[1]?.firstName} ${chat.users[1]?.lastName}`
: `${chat.users[0]?.firstName} ${chat.users[0]?.lastName}`
: chat.name,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Refactor nested ternary operators in 'title' property for readability and safety

The nested ternary operators in the title property reduce readability and may cause errors if chat.users doesn't have the expected number of users. There's also a risk of accessing undefined properties if chat.users is empty or incomplete.

Consider simplifying the logic by identifying the other user in the chat:

let title = '';
if (!chat.isGroup) {
  const otherUser = chat.users.find((user: any) => user._id !== userId);
  if (otherUser) {
    title = `${otherUser.firstName} ${otherUser.lastName}`;
  }
} else {
  title = chat.name;
}
// Assign title to cardProps

Update the cardProps assignment:

const cardProps: InterfaceContactCardProps = {
  id: chat._id,
  title,
  image: /* similar refactoring as needed */,
  setSelectedContact,
  selectedContact,
  isGroup: chat.isGroup,
};
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 204-205: src/screens/UserPortal/Chat/Chat.tsx#L204-L205
Added lines #L204 - L205 were not covered by tests

Comment on lines +207 to +211
image: chat.isGroup
? userId
? chat.users[1]?.image
: chat.users[0]?.image
: chat.image,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct conditional logic in 'image' property

The conditional expression for the image property uses userId as a boolean, which may not work as intended. Additionally, it doesn't correctly identify the other user's image in a direct chat.

Refactor the logic to properly select the other user's image in direct chats and handle group chats appropriately:

let image = '';
if (!chat.isGroup) {
  const otherUser = chat.users.find((user: any) => user._id !== userId);
  image = otherUser?.image || '';
} else {
  image = chat.image;
}
// Assign image to cardProps

Update the cardProps assignment:

const cardProps: InterfaceContactCardProps = {
  id: chat._id,
  title: /* as refactored above */,
  image,
  setSelectedContact,
  selectedContact,
  isGroup: chat.isGroup,
};
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 211-211: src/screens/UserPortal/Chat/Chat.tsx#L211
Added line #L211 was not covered by tests

@github-actions github-actions bot removed the no-pr-activity No pull request activity label Oct 4, 2024
Copy link

This pull request did not get any activity in the past 10 days and will be closed in 180 days if no update occurs. Please verify it has no conflicts with the develop branch and rebase if needed. Mention it now if you need help or give permission to other people to finish your work.

@github-actions github-actions bot added the no-pr-activity No pull request activity label Oct 14, 2024
@palisadoes
Copy link
Contributor

@disha1202 Please fix the conflicting files.

@palisadoes palisadoes removed the no-pr-activity No pull request activity label Oct 14, 2024
Copy link

@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

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9a661e5 and e6e5c24.

📒 Files selected for processing (2)
  • schema.graphql (6 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (4 hunks)
🧰 Additional context used
🔇 Additional comments (2)
src/screens/UserPortal/Chat/Chat.tsx (2)

23-23: Addition of 'isGroup' property to interface is appropriate

Adding the isGroup property to InterfaceContactCardProps appropriately supports distinguishing between group chats and direct chats.


237-237: Verify 'chatsListRefetch' prop implementation in modal components

Please ensure that the CreateGroupChat and CreateDirectChat components accept the chatsListRefetch prop and utilize it to refresh the chat list after creating a new chat.

Run the following script to confirm the prop is used correctly:

Also applies to: 244-244

✅ Verification successful

ChatsListRefetch prop is correctly implemented and utilized in both CreateGroupChat and CreateDirectChat components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that 'chatsListRefetch' is a prop in 'CreateGroupChat' and 'CreateDirectChat' components and is used within them.

# Search for the 'CreateGroupChat' component definition and check for 'chatsListRefetch' in its props
rg --type tsx "function CreateGroupChat" -A 10 | rg "chatsListRefetch"

# Search for usage of 'chatsListRefetch' within 'CreateGroupChat'
rg --type tsx "CreateGroupChat" -A 100 | rg "chatsListRefetch"

# Repeat the process for 'CreateDirectChat'
rg --type tsx "function CreateDirectChat" -A 10 | rg "chatsListRefetch"
rg --type tsx "CreateDirectChat" -A 100 | rg "chatsListRefetch"

Length of output: 377


Script:

#!/bin/bash
# Description: Verify that 'chatsListRefetch' is a prop in 'CreateGroupChat' and 'CreateDirectChat' components and is used within them.

# Search for the 'CreateGroupChat' component definition in .tsx files
rg -g "*.tsx" "function CreateGroupChat" -A 10 | rg "chatsListRefetch"

# Search for usage of 'chatsListRefetch' within 'CreateGroupChat'
rg -g "*.tsx" "CreateGroupChat" -A 100 | rg "chatsListRefetch"

# Search for the 'CreateDirectChat' component definition in .tsx files
rg -g "*.tsx" "function CreateDirectChat" -A 10 | rg "chatsListRefetch"

# Search for usage of 'chatsListRefetch' within 'CreateDirectChat'
rg -g "*.tsx" "CreateDirectChat" -A 100 | rg "chatsListRefetch"

Length of output: 1331

import styles from './Chat.module.css';
import UserSidebar from 'components/UserPortal/UserSidebar/UserSidebar';
import { GROUP_CHAT_LIST } from 'GraphQl/Queries/PlugInQueries';
import { CHATS_LIST } from 'GraphQl/Queries/PlugInQueries';
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct the casing in the import path 'GraphQl'

The import path uses 'GraphQl', which may not match the actual directory name. Ensure that the casing of 'GraphQL' is consistent to prevent module resolution issues.

Apply this diff to fix the import statement:

-import { CHATS_LIST } from 'GraphQl/Queries/PlugInQueries';
+import { CHATS_LIST } from 'GraphQL/Queries/PlugInQueries';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { CHATS_LIST } from 'GraphQl/Queries/PlugInQueries';
import { CHATS_LIST } from 'GraphQL/Queries/PlugInQueries';

Comment on lines +108 to +112
React.useEffect(() => {
if (chatsListData) {
setChats(chatsListData.chatsByUserId);
}
}, [chatsListData]);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use 'useEffect' instead of 'React.useEffect' for consistency

Since useEffect is imported directly, use it without the React. prefix for consistency with the rest of the code.

Apply this diff to correct the usage:

-  React.useEffect(() => {
+  useEffect(() => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
React.useEffect(() => {
if (chatsListData) {
setChats(chatsListData.chatsByUserId);
}
}, [chatsListData]);
useEffect(() => {
if (chatsListData) {
setChats(chatsListData.chatsByUserId);
}
}, [chatsListData]);

Comment on lines +1628 to +1633
input chatInput {
isGroup: Boolean!
organizationId: ID
userIds: [ID!]!
name: String
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure the name field is required when isGroup is true

In the chatInput type, the name field is currently optional. However, when creating a group chat (isGroup: true), a name is essential for identification and user experience. Consider enforcing this by making the name field non-nullable or implementing validation logic to ensure a name is provided when isGroup is true.

@disha1202
Copy link
Author

Hi @palisadoes
Updated the PR, please look into it.

@DMills27 DMills27 self-requested a review October 20, 2024 16:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants