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

Updated the User Management Design #9954

Merged
merged 30 commits into from
Jan 16, 2025

Conversation

AdityaJ2305
Copy link
Contributor

@AdityaJ2305 AdityaJ2305 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 pluralization support for user count display.
    • Introduced search functionality for users.
    • Added toggle between card and list views for user display.
  • Bug Fixes

    • Improved handling of missing user data by providing default values.
    • Enhanced type safety for active tab selection.
  • Refactor

    • Streamlined user list component logic.
    • Updated query parameters and data fetching mechanism for users.
    • Enhanced loading state management for user lists.
    • Simplified props and rendering logic in user card component.

Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Walkthrough

This pull request introduces updates to the user management interface across multiple files. The changes enhance localization by adding new keys, refactor the FacilityUsers and UserListAndCard components, and improve overall user interaction and design. Modifications include updating the search functionality, introducing tab views, and adjusting the rendering of user information, while ensuring better type safety and loading state management.

Changes

File Change Summary
public/locale/en.json Added new localization keys: "user_count_one": "{{count}} user" and "user_count_other": "{{count}} users"
src/components/Facility/FacilityUsers.tsx - Updated import statements
- Modified state and query handling
- Refactored loading state
- Added search input and tabs
- Updated page layout and title
src/components/Users/UserListAndCard.tsx - Updated component imports
- Simplified UserCard structure
- Removed unnecessary props and functions
- Changed activeTab type from number to `"card"

Assessment against linked issues

Objective Addressed Explanation
Update User Management Design [#9953]
Resolve Page Crashes on Small Screens [#9955] Small screen responsiveness not explicitly demonstrated.
Fix User Search Functionality [#9741] Search functionality has been updated, but further verification is needed for user visibility in results.

Possibly related PRs

  • New Patient Search and Register UI #9400: The changes in public/locale/en.json related to user management and patient assignment enhance localization, which aligns with the new key-value pairs added in the main PR for user count display.
  • Added no user assingned message #9666: The addition of the key "no_user_assigned" in public/locale/en.json directly relates to the changes made in the main PR, which also enhances user management functionalities.
  • Add pagination and search to OrganizationUsers #9967: The implementation of pagination and search in OrganizationUsers complements the user management enhancements in the main PR, as both focus on improving user interaction and data display.

Suggested labels

changes required

Suggested reviewers

  • Jacobjeevan
  • rithviknishad

Poem

🐰 A Rabbit's Ode to User Management 🔍
Tabs and search, a new design unfurls,
Users dancing in card and list swirls,
Localization keys bloom with grace,
A management page with a brighter face!
Hop, hop, improvements take their flight! 🚀


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 c79b915
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67889208df592c0008885f55
😎 Deploy Preview https://deploy-preview-9954--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.

@Jacobjeevan
Copy link
Contributor

User search is already assigned to a different contributor, kindly refrain from taking up other issues without getting them assigned first 😅

@AdityaJ2305
Copy link
Contributor Author

User search is already assigned to a different contributor, kindly refrain from taking up other issues without getting them assigned first 😅

@Jacobjeevan Actually the User Search issue needs to be fix to test the design

@AdityaJ2305 AdityaJ2305 marked this pull request as ready for review January 14, 2025 12:32
@AdityaJ2305 AdityaJ2305 requested a review from a team as a code owner January 14, 2025 12:32
@AdityaJ2305
Copy link
Contributor Author

@rithviknishad @Jacobjeevan Ready for Review

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 (5)
src/components/Facility/FacilityUsers.tsx (2)

Line range hint 47-76: Consider extracting the skeleton loader component.

The skeleton loader implementation is well-structured but could be moved to a separate component for reusability across the application.

+// src/components/Common/UserSkeleton.tsx
+export const UserSkeleton = () => (
+  <Card>
+    <CardContent className="p-6">
+      <div className="flex items-start">
+        <Skeleton className="h-16 w-16 rounded-lg mr-4" />
+        <div className="flex-1">
+          <div className="flex justify-between items-start">
+            <div>
+              <Skeleton className="h-6 w-24 mb-1" />
+              <Skeleton className="h-4 w-12" />
+            </div>
+            <Skeleton className="h-6 w-16" />
+          </div>
+          <div className="mt-2">
+            <Skeleton className="h-4 w-20 mb-1" />
+            <Skeleton className="h-4 w-12" />
+          </div>
+        </div>
+      </div>
+    </CardContent>
+  </Card>
+);

// In FacilityUsers.tsx
-// Current skeleton implementation
+import { UserSkeleton } from "@/components/Common/UserSkeleton";
+usersList = (
+  <div>
+    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-4">
+      {Array.from({ length: 6 }).map((_, i) => (
+        <UserSkeleton key={i} />
+      ))}
+    </div>
+  </div>
+);

89-126: Enhance accessibility for search and navigation.

While the UI components are well-structured, consider these accessibility improvements:

 <Input
   id="search-by-username"
   name="username"
+  aria-label={t("search_by_username")}
   onChange={(e) => updateQuery({ username: e.target.value })}
   value={qParams.username}
   placeholder={t("search_by_username")}
   className="w-full max-w-sm"
 />
 <Tabs
   value={activeTab}
   onValueChange={(value) => setActiveTab(value as "card" | "list")}
+  aria-label={t("view_options")}
   className="ml-auto"
 >
-  <TabsList className="flex">
+  <TabsList className="flex" aria-label={t("select_view_type")}>
src/components/Users/UserListAndCard.tsx (3)

135-143: Improve type safety for user properties.

While the null checks are good, consider using TypeScript's non-null assertion operator or optional chaining for better type safety:

-{user.user_type ? user.user_type : "-"}
+{user.user_type ?? "-"}

-{user.phone_number
-  ? formatPhoneNumber(user.phone_number)
-  : "-"}
+{user.phone_number ? formatPhoneNumber(user.phone_number) : "-"}

246-256: Use literal types for better type safety.

Consider using a literal type for the activeTab prop to prevent potential runtime errors:

 interface UserListViewProps {
   users: UserBase[];
-  activeTab: string;
+  activeTab: "card" | "list";
 }

Line range hint 249-267: Consider memoizing components for better performance.

To prevent unnecessary re-renders, consider memoizing the UserGrid and UserList components:

+import { memo } from "react";

-export const UserGrid = ({ users }: { users?: UserBase[] }) => (
+export const UserGrid = memo(({ users }: { users?: UserBase[] }) => (
   <div className="grid grid-cols-1 gap-4 @xl:grid-cols-3 @4xl:grid-cols-4 @6xl:grid-cols-5 lg:grid-cols-2">
     {users?.map((user) => <UserCard key={user.id} user={user} />)}
   </div>
-);
+));

-export const UserList = ({ users }: { users?: UserBase[] }) => {
+export const UserList = memo(({ users }: { users?: UserBase[] }) => {
   // ... existing code
-};
+});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1021155 and b789369.

📒 Files selected for processing (3)
  • public/locale/en.json (1 hunks)
  • src/components/Facility/FacilityUsers.tsx (2 hunks)
  • src/components/Users/UserListAndCard.tsx (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • public/locale/en.json
🔇 Additional comments (2)
src/components/Facility/FacilityUsers.tsx (2)

5-11: LGTM! Good use of standardized UI components.

The changes show improved organization by:

  • Using standardized UI components from a shared library
  • Moving away from hardcoded values to constants

Also applies to: 18-18


29-42: Great improvements to query handling and type safety!

Notable improvements:

  • Added debouncing for search queries
  • Explicit typing for tab state
  • Well-structured pagination parameters

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/components/Facility/FacilityUsers.tsx (2)

Line range hint 47-85: Consider extracting the loading skeleton to a separate component.

The loading state implementation is good, but extracting the skeleton to a separate component would improve maintainability and reusability.

+const UserCardSkeleton = () => (
+  <Card>
+    <CardContent className="p-6">
+      <div className="flex items-start">
+        <Skeleton className="h-16 w-16 rounded-lg mr-4" />
+        <div className="flex-1">
+          <div className="flex justify-between items-start">
+            <div>
+              <Skeleton className="h-6 w-24 mb-1" />
+              <Skeleton className="h-4 w-12" />
+            </div>
+            <Skeleton className="h-6 w-16" />
+          </div>
+          <div className="mt-2">
+            <Skeleton className="h-4 w-20 mb-1" />
+            <Skeleton className="h-4 w-12" />
+          </div>
+        </div>
+      </div>
+    </CardContent>
+  </Card>
+)

 if (userListLoading || !userListData) {
   usersList = (
     <div>
       <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-4">
-        {Array.from({ length: 6 }).map((_, i) => (
-          <Card key={i}>
-            <CardContent className="p-6">
-              <div className="flex items-start">
-                <Skeleton className="h-16 w-16 rounded-lg mr-4" />
-                <div className="flex-1">
-                  <div className="flex justify-between items-start">
-                    <div>
-                      <Skeleton className="h-6 w-24 mb-1" />
-                      <Skeleton className="h-4 w-12" />
-                    </div>
-                    <Skeleton className="h-6 w-16" />
-                  </div>
-                  <div className="mt-2">
-                    <Skeleton className="h-4 w-20 mb-1" />
-                    <Skeleton className="h-4 w-12" />
-                  </div>
-                </div>
-              </div>
-            </CardContent>
-          </Card>
-        ))}
+        {Array.from({ length: 6 }).map((_, i) => (
+          <UserCardSkeleton key={i} />
+        ))}
       </div>
     </div>
   );

98-105: Consider debouncing the search input to optimize performance.

While the query is debounced, debouncing the search input itself would prevent unnecessary state updates and re-renders.

+import { useDebouncedCallback } from 'use-debounce';

+const debouncedUpdateQuery = useDebouncedCallback(
+  (value: string) => updateQuery({ username: value }),
+  300
+);

 <Input
   id="search-by-username"
   name="username"
-  onChange={(e) => updateQuery({ username: e.target.value })}
+  onChange={(e) => debouncedUpdateQuery(e.target.value)}
   value={qParams.username}
   placeholder={t("search_by_username")}
   className="w-full max-w-sm"
 />
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b789369 and 04d7899.

📒 Files selected for processing (3)
  • public/locale/en.json (1 hunks)
  • src/components/Facility/FacilityUsers.tsx (2 hunks)
  • src/components/Users/UserListAndCard.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
🔇 Additional comments (5)
src/components/Facility/FacilityUsers.tsx (2)

5-11: LGTM! Good improvements to the imports organization.

The switch to shadcn/ui components and the use of the RESULTS_PER_PAGE_LIMIT constant improves maintainability and consistency.

Also applies to: 18-18


26-26: Well-implemented query optimization and type safety!

Good improvements:

  • Using debounced query to prevent excessive API calls
  • Adding type safety for activeTab
  • Proper pagination implementation with offset calculation

Also applies to: 29-29, 35-42

src/components/Users/UserListAndCard.tsx (3)

135-143: Good improvement in handling missing user data!

The addition of fallback values for missing user_type and phone_number improves the robustness of the component.


246-246: Good improvement in type safety!

The change from numeric to string literal union type for activeTab makes the code more type-safe and self-documenting.


249-256: Well-structured component with clear conditional rendering!

The simplified logic with string literal comparison makes the code more readable and maintainable.

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 (4)
src/components/Users/UserListAndCard.tsx (1)

115-116: Use formatPhoneNumber for consistent phone number display

The phone number should be formatted using the existing formatPhoneNumber utility (which is already imported and used in UserListRow) for consistency.

-              <div className="font-medium truncate">{user.phone_number}</div>
+              <div className="font-medium truncate">{formatPhoneNumber(user.phone_number)}</div>
src/components/Facility/FacilityUsers.tsx (3)

58-58: Consider using a constant for skeleton item counts

The magic numbers 7 and 6 for skeleton items should be replaced with a named constant for better maintainability.

+const SKELETON_ITEMS = {
+  LIST: 7,
+  CARD: 6,
+};

-          {Array.from({ length: 7 }).map((_, i) => (
+          {Array.from({ length: SKELETON_ITEMS.LIST }).map((_, i) => (

-        {Array.from({ length: 6 }).map((_, i) => (
+        {Array.from({ length: SKELETON_ITEMS.CARD }).map((_, i) => (

Also applies to: 91-91


167-174: Enhance search input accessibility

Add aria-label and role attributes to improve accessibility for screen readers.

 <Input
   id="search-by-username"
   name="username"
+  role="searchbox"
+  aria-label={t("search_by_username")}
   onChange={(e) => updateQuery({ username: e.target.value })}
   value={qParams.username}
   placeholder={t("search_by_username")}
   className="w-full max-w-sm"
 />

159-164: Improve user count loading state

The current implementation shows an empty string while loading, which could cause layout shift. Consider showing a skeleton or placeholder.

       <Badge
         className="bg-purple-50 text-purple-700 ml-2 text-sm font-medium rounded-xl px-3 m-3"
         variant="outline"
       >
-        {`${userListData ? userListData.count : ""} ${t("users")}`}
+        {userListData ? `${userListData.count} ${t("users")}` : <Skeleton className="h-4 w-16 bg-purple-100" />}
       </Badge>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 04d7899 and d801e1c.

📒 Files selected for processing (2)
  • src/components/Facility/FacilityUsers.tsx (1 hunks)
  • src/components/Users/UserListAndCard.tsx (4 hunks)
🔇 Additional comments (2)
src/components/Users/UserListAndCard.tsx (1)

213-214: LGTM! Good architectural improvement

The simplified interface and strongly typed activeTab improve the component's API design and type safety.

Also applies to: 217-217

src/components/Facility/FacilityUsers.tsx (1)

133-137: Add validation for pagination parameters

The offset calculation assumes qParams.page is positive. Consider adding validation to ensure page numbers are positive to prevent potential issues with negative offsets.

@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

♻️ Duplicate comments (1)
src/components/Facility/FacilityUsers.tsx (1)

165-165: 🛠️ Refactor suggestion

Use correct pluralization key format.

The translation key should follow i18next's pluralization convention.

Update the translation files to use the correct key format:

{
  "user_count_one": "{{count}} user",
  "user_count_other": "{{count}} users"
}
🧹 Nitpick comments (1)
src/components/Facility/FacilityUsers.tsx (1)

21-116: Extract skeleton components into separate files.

While the skeleton components are properly defined outside the main component (good!), they should be moved to separate files under a common directory for better maintainability and reusability.

Consider creating a new directory structure:

src/
  components/
    Skeletons/
      UserCardSkeleton.tsx
      UserListSkeleton.tsx
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d7f6d9 and c79b915.

📒 Files selected for processing (2)
  • public/locale/en.json (2 hunks)
  • src/components/Facility/FacilityUsers.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: OSSAR-Scan
  • GitHub Check: cypress-run (1)
🔇 Additional comments (2)
src/components/Facility/FacilityUsers.tsx (2)

120-122: 🛠️ Refactor suggestion

Adjust limit to match grid layout.

The limit of 15 doesn't align with the 3-column grid layout in card view. For even rows, the limit should be a multiple of 3.

  const { qParams, updateQuery, Pagination } = useFilters({
-   limit: 15,
+   limit: 18,
    cacheBlacklist: ["username"],
  });

Likely invalid or redundant comment.


129-141: ⚠️ Potential issue

Add error handling for the query.

The query implementation should handle error states to provide feedback to users when API calls fail.

- const { data: userListData, isLoading: userListLoading } = useQuery({
+ const { data: userListData, isLoading: userListLoading, error } = useQuery({
    queryKey: ["facilityUsers", facilityId, qParams],
    queryFn: query.debounced(routes.facility.getUsers, {
      pathParams: { facility_id: facilityId },
      queryParams: {
        username: qParams.username,
        limit: qParams.limit,
        offset: (qParams.page - 1) * qParams.limit,
      },
    }),
    enabled: !!facilityId,
  });

And update the rendering logic:

- if (userListLoading || !userListData) {
+ if (error) {
+   usersList = (
+     <div className="text-red-600 p-4 text-center">
+       {t("error_loading_users")}
+     </div>
+   );
+ } else if (userListLoading || !userListData) {

Likely invalid or redundant comment.

@rithviknishad rithviknishad merged commit d9a5101 into ohcnetwork:develop Jan 16, 2025
16 of 17 checks passed
Copy link

@AdityaJ2305 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
Projects
Status: Done
4 participants