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

Add pagination and search to OrganizationUsers #9967

Conversation

Jacobjeevan
Copy link
Contributor

@Jacobjeevan Jacobjeevan commented Jan 14, 2025

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Added search functionality to filter users by username
    • Enhanced user management interface with dynamic search input
  • Improvements

    • Updated query parameter handling for more flexible user filtering
    • Refined loading state and rendering logic for better user experience
    • Improved layout structure by repositioning pagination component for clarity
    • Removed redundant components to enhance maintainability
    • Adjusted results per page from 14 to 15 in the patient management interface

@Jacobjeevan Jacobjeevan requested a review from a team as a code owner January 14, 2025 15:35
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

The pull request modifies the OrganizationUsers component to introduce search and pagination functionality for organization users. The changes replace the existing useQueryParams hook with a custom useFilters hook, enabling dynamic user filtering through a search input. The query for fetching users now incorporates search parameters, and the component's rendering logic has been updated to support these new filtering capabilities while maintaining the existing component structure.

Changes

File Change Summary
src/pages/Organization/OrganizationUsers.tsx - Replaced useQueryParams with useFilters hook
- Added search input for filtering users
- Updated query to include qParams.search and qParams.page
- Adjusted loading state handling and rendering logic
src/pages/Organization/OrganizationPatients.tsx - Updated useFilters hook's limit parameter from 14 to 15

Assessment against linked issues

Objective Addressed Explanation
Add pagination and search functionality in user tab
Implement search input for filtering users

Possibly related PRs

Suggested labels

needs review

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

🐰 Hop, hop, through users we'll scan,
Search magic now in our new plan!
Filters dancing, pagination's grace,
Organization's users find their place!
Code hops lightly, search so bright! 🔍


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

netlify bot commented Jan 14, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit fc4b75a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6787ad34ecb3460008bb42aa
😎 Deploy Preview https://deploy-preview-9967--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@nihal467
Copy link
Member

nihal467 commented Jan 14, 2025

the pagination is not working, even though query params are being modified, the things are not changing

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

🧹 Nitpick comments (3)
src/pages/Organization/OrganizationUsers.tsx (3)

76-87: Remove unnecessary type casting

The type casting of e.target.value to string is redundant as it's already a string.

-               search: e.target.value as string,
+               search: e.target.value,

90-102: Align skeleton loader count with page size

The skeleton loader shows 3 items while the page size is set to 18. This creates an inconsistent loading experience.

-         Array.from({ length: 3 }).map((_, i) => (
+         Array.from({ length: qParams.limit }).map((_, i) => (

181-181: Add loading state for pagination

The Pagination component should show a loading state during page transitions to provide better user feedback.

-         <Pagination totalCount={users?.count || 0} />
+         <Pagination totalCount={users?.count || 0} loading={isLoadingUsers} />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 27fef8d and 795b425.

📒 Files selected for processing (1)
  • src/pages/Organization/OrganizationUsers.tsx (3 hunks)

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/pages/Organization/OrganizationUsers.tsx (3)

78-89: Consider enhancing the search input with loading state and clear button.

The search implementation could benefit from additional UX improvements:

  • Show loading indicator during search
  • Add a clear button when search has value
  • Add debouncing to prevent excessive API calls
 <Input
   type="text"
   placeholder="Search users..."
   value={qParams.search || ""}
   onChange={(e) =>
     updateQuery({
       search: e.target.value as string,
     })
   }
-  className="max-w-sm"
+  className="max-w-sm relative"
+  disabled={isLoadingUsers}
+  rightIcon={
+    qParams.search && (
+      <Button
+        variant="ghost"
+        size="sm"
+        className="absolute right-2 top-1/2 -translate-y-1/2"
+        onClick={() => updateQuery({ search: "" })}
+      >
+        <CareIcon icon="l-times" className="h-4 w-4" />
+      </Button>
+    )
+  }
   data-cy="search-user"
 />

92-104: Optimize skeleton loading performance.

Consider memoizing the skeleton loader array to prevent unnecessary re-renders:

+const SKELETON_CARDS = Array.from({ length: 3 }).map((_, i) => (
+  <Card key={i}>
+    <CardContent className="p-6">
+      <div className="flex items-center space-x-4">
+        <div className="h-12 w-12 rounded-full bg-gray-200 animate-pulse" />
+        <div className="space-y-2 flex-1">
+          <div className="h-4 bg-gray-200 rounded animate-pulse w-1/4" />
+          <div className="h-4 bg-gray-200 rounded animate-pulse w-1/3" />
+        </div>
+      </div>
+    </CardContent>
+  </Card>
+));

-Array.from({ length: 3 }).map((_, i) => (
-  <Card key={i}>
-    // ... skeleton content
-  </Card>
-))
+{SKELETON_CARDS}

114-179: Enhance accessibility of user cards.

Consider adding ARIA labels and roles to improve accessibility:

-<Card key={userRole.id} className="h-full">
+<Card 
+  key={userRole.id} 
+  className="h-full"
+  role="article"
+  aria-label={`User card for ${userRole.user.first_name} ${userRole.user.last_name}`}
+>
   <CardContent className="p-4 sm:p-6">
     // ... card content
   </CardContent>
 </Card>

Also consider adding keyboard navigation support for the "More Details" button:

 <Button
   variant="secondary"
   size="sm"
   className="w-full gap-2"
+  aria-label={`View more details for ${userRole.user.first_name} ${userRole.user.last_name}`}
 >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 795b425 and f6481b6.

📒 Files selected for processing (1)
  • src/pages/Organization/OrganizationUsers.tsx (3 hunks)
🔇 Additional comments (1)
src/pages/Organization/OrganizationUsers.tsx (1)

183-183: Verify pagination behavior with large datasets.

The pagination implementation looks correct. However, given the reported issue about pagination not working correctly, please verify:

  1. The page size matches the API's expectations
  2. The total count is accurately reflected in the UI
  3. Navigation between pages works as expected with large datasets
✅ Verification successful

Pagination implementation is correctly implemented and standardized across the application.

The verification shows that:

  • Page size is consistently set to 14 items
  • Offset calculation is correct: (page - 1) * resultsPerPage
  • Total count is properly handled and reflected in the UI
  • Implementation is standardized across all list views
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check pagination implementation across the codebase

# Check for pagination limit constants or configurations
rg -l "resultsPerPage|pageSize|itemsPerPage" --type ts

# Check other components using the same pagination pattern
ast-grep --pattern 'const { Pagination, resultsPerPage } = useFilters'

Length of output: 411


Script:

#!/bin/bash
# Check useFilters implementation and Pagination component usage

# Examine useFilters hook implementation
echo "=== useFilters.tsx content ==="
cat src/hooks/useFilters.tsx

# Look for Pagination component definition
echo -e "\n=== Pagination component usage patterns ==="
ast-grep --pattern 'const Pagination = ({ totalCount }: { totalCount: number }) => {'

# Check how resultsPerPage is used in components
echo -e "\n=== resultsPerPage usage in components ==="
rg "resultsPerPage" -B 2 -A 2 --type ts

Length of output: 14562

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/pages/Organization/OrganizationUsers.tsx (2)

85-87: Remove unnecessary type cast.

The type cast to string is redundant as e.target.value is already of type string.

-                search: e.target.value as string,
+                search: e.target.value,

93-106: Add ARIA attributes for better accessibility.

The skeleton loader should indicate its loading state to screen readers.

-          Array.from({ length: 3 }).map((_, i) => (
+          Array.from({ length: 3 }).map((_, i) => (
-            <Card key={i}>
+            <Card key={i} aria-busy="true" aria-label="Loading user card">
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f6481b6 and d26d016.

📒 Files selected for processing (1)
  • src/pages/Organization/OrganizationUsers.tsx (3 hunks)
🔇 Additional comments (4)
src/pages/Organization/OrganizationUsers.tsx (4)

29-45: LGTM! Pagination and search parameters are properly implemented.

The implementation correctly:

  • Includes pagination parameters in the query
  • Calculates proper offset based on page number
  • Uses debounced query for search
  • Blacklists search from cache persistence

63-74: LGTM! Sheet state management through URL parameters.

Good use of URL parameters for managing sheet visibility, enabling shareable URLs and browser navigation.


185-185: LGTM! Pagination implementation is complete.

The pagination component correctly uses the total count from the API response with proper fallback for undefined state.


38-45: Verify that pagination is now working as expected.

The previous issue where "pagination itself is not functioning correctly" should be resolved as the implementation now includes all necessary parameters. Please verify that:

  1. The page changes when using pagination controls
  2. The correct items are displayed for each page
  3. The search functionality works in combination with pagination

@nihal467
Copy link
Member

LGTM

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/pages/Organization/OrganizationUsers.tsx (2)

80-92: Remove unnecessary type assertion.

The type assertion as string is redundant since the event target value is already a string.

-                search: e.target.value as string,
+                search: e.target.value,

109-184: Consider restructuring nested conditionals for better readability.

The current implementation uses nested ternary operators which can be hard to maintain. Consider extracting the user list rendering into a separate component or using early returns.

Example restructure:

const UserList = ({ users }) => {
  if (users?.results?.length === 0) {
    return (
      <Card className="col-span-full">
        <CardContent className="p-6 text-center text-gray-500">
          {t("no_users_found")}
        </CardContent>
      </Card>
    );
  }

  return users?.results?.map((userRole) => (
    // ... existing user card implementation
  ));
};

// In the main render
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
  <UserList users={users} />
</div>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d26d016 and fc4b75a.

📒 Files selected for processing (2)
  • src/pages/Organization/OrganizationPatients.tsx (1 hunks)
  • src/pages/Organization/OrganizationUsers.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: cypress-run (1)
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (5)
src/pages/Organization/OrganizationPatients.tsx (1)

32-32: LGTM! Consistent pagination limit across components.

The change aligns the pagination limit with OrganizationUsers component, maintaining consistency in the UI.

src/pages/Organization/OrganizationUsers.tsx (4)

29-32: LGTM! Proper hook configuration for search and pagination.

The useFilters hook is correctly configured with appropriate limit and cache blacklist for search parameter.


94-107: LGTM! Clean loading state implementation.

The loading skeleton provides good visual feedback with appropriate animations and placeholder content.


39-46: LGTM! Pagination implementation complete and functional.

The pagination is properly implemented with:

  • Correct query parameters (limit, offset)
  • Query key includes pagination state
  • Pagination component receives accurate total count

Also applies to: 186-186


29-46: Verify the completeness of pagination and search implementation.

Let's verify that all necessary changes for pagination and search are in place.

✅ Verification successful

Pagination and search implementation verified successfully

The implementation correctly handles pagination and search functionality with proper API integration, debouncing, and cache invalidation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify pagination and search implementation

# Check if pagination and search parameters are consistently handled
echo "Checking pagination and search parameter handling..."
rg -l "useFilters|qParams.search|qParams.page" src/pages/Organization/

# Verify if there are any remaining useQueryParams instances that should be migrated
echo "Checking for remaining useQueryParams instances..."
rg "useQueryParams" src/pages/Organization/

# Check for proper query parameter usage in API calls
echo "Checking API query parameter usage..."
rg "queryParams.*username|queryParams.*limit|queryParams.*offset" src/pages/Organization/

Length of output: 775


Script:

#!/bin/bash
# Check pagination and search implementation details

# Check pagination implementation consistency
echo "Checking pagination implementation..."
ast-grep --pattern 'useFilters({$$$})' 

# Check API integration for pagination and search
echo "Checking API integration..."
ast-grep --pattern 'queryFn: $$$({
  $$$
  queryParams: {
    $$$
  }
})'

# Check search handling
echo "Checking search implementation..."
rg -A 5 "qParams.search" src/pages/Organization/

Length of output: 3754

@Jacobjeevan Jacobjeevan merged commit 2a21d25 into ohcnetwork:develop Jan 15, 2025
19 checks passed
@Jacobjeevan Jacobjeevan deleted the issues/9961-organizationusers-pagination branch January 15, 2025 13:41
Copy link

@Jacobjeevan Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
P1 breaking issue or vital feature tested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Pagination and user Search Functionality in user section organization tab page
3 participants