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

Fix Auto-Scroll Issue and Total Count Card in facility details page #9275

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

shauryag2002
Copy link
Contributor

@shauryag2002 shauryag2002 commented Dec 2, 2024

Proposed Changes

total_staff_scroll.mp4

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs/tests for bug fixes or features.
  • Update [product documentation](https://docs.ohc.network).
  • Ensure UI text is in I18n files.
  • Attach screenshots or demo videos for changelog.
  • Request peer reviews.
  • Complete QA testing.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new property total_doctors in the paginated response, providing additional information on the total number of doctors.
    • Added an optional scrollToTop property to the pagination component, allowing users to control scrolling behavior when navigating pages.
    • Enhanced pagination functionality with a new handlePageChange method for improved user experience.
  • Bug Fixes

    • Streamlined logic for calculating the total number of doctors, improving performance and accuracy.

@shauryag2002 shauryag2002 requested a review from a team as a code owner December 2, 2024 17:11
Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The changes in this pull request introduce enhancements to the pagination and data handling in the application. A new interface DoctorPaginatedResponse<T> is added, which extends the existing PaginatedResponse<TItem> interface to include a total_doctors property. Additionally, the PaginationProps interface now includes an optional scrollToTop property for conditional scrolling behavior. The FacilityStaffList component has been updated to simplify the total doctor count calculation and improve pagination handling through a new handlePageChange function.

Changes

File Change Summary
src/Utils/request/types.ts Added interface DoctorPaginatedResponse<T> extending PaginatedResponse<T> with total_doctors: number.
src/components/Common/Pagination.tsx Added optional property scrollToTop?: boolean to PaginationProps; updated goToPage function to conditionally scroll based on scrollToTop.
src/components/Facility/FacilityStaffList.tsx Simplified total doctor count calculation using data.results[0]?.total_doctors; added handlePageChange(page: number) method for pagination handling.
src/Utils/request/api.tsx Updated listDoctor endpoint to use DoctorPaginatedResponse<DoctorModal> instead of PaginatedResponse<DoctorModal>.
src/components/Facility/models.tsx Added optional property total_doctors?: number to DoctorModal interface.

Assessment against linked issues

Objective Addressed Explanation
Auto-scrolling should stop at the beginning of the staff capacity section (#[9122])
The total capacity card should display the total staff capacity for the entire section (#[9122])

Possibly related PRs

Suggested labels

needs review, tested, P1

Suggested reviewers

  • rithviknishad
  • shivankacker
  • Jacobjeevan

🐰 In a field where doctors roam,
A new count helps us call them home.
With pagination's gentle sway,
We scroll to staff without delay.
Total doctors now in sight,
Hopping forward, all feels right! 🌼


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.

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 Dec 2, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 48b365c
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67545d8fac9a3d0008729577
😎 Deploy Preview https://deploy-preview-9275--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.

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

🧹 Outside diff range and nitpick comments (3)
src/components/Common/Pagination.tsx (1)

86-92: Improve scroll behavior implementation

The current implementation has a few concerns:

  1. It depends on a specific element with ID "pages" which might not exist
  2. The scroll behavior could be more flexible

Consider these improvements:

- const pageContainer = window.document.getElementById("pages");
- if (ScrollToTop) {
-   pageContainer?.scroll({
-     top: 0,
-     left: 0,
-     behavior: "smooth",
-   });
- }
+ if (scrollToTop) {
+   window.scrollTo({
+     top: 0,
+     behavior: "smooth"
+   });
+ }
src/components/Facility/FacilityStaffList.tsx (2)

36-36: Add error handling for missing total_doctors

Consider adding error handling for cases where total_doctors is undefined:

- setTotalDoctors(data?.total_doctors ?? 0);
+ const total = data?.total_doctors;
+ if (typeof total !== 'number') {
+   console.warn('Expected total_doctors to be a number');
+ }
+ setTotalDoctors(total ?? 0);

94-97: Consider using data-testid for testing

Instead of using id for testing, consider using data-testid attribute which is more maintainable:

  <div
    className="mt-5 rounded bg-white p-3 shadow-sm md:p-6"
-   id="staff_capacity"
+   id="staff_capacity"
+   data-testid="staff-capacity-section"
  >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2d9669e and 2812e9c.

📒 Files selected for processing (3)
  • src/Utils/request/types.ts (1 hunks)
  • src/components/Common/Pagination.tsx (2 hunks)
  • src/components/Facility/FacilityStaffList.tsx (3 hunks)

@@ -41,4 +41,5 @@ export interface PaginatedResponse<TItem> {
next: string | null;
previous: string | null;
results: TItem[];
total_doctors: number;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider moving domain-specific field to a separate interface

Adding total_doctors to the generic PaginatedResponse interface violates the Interface Segregation Principle, as not all paginated responses will need this field. Consider creating a specific interface for doctor-related responses:

interface DoctorPaginatedResponse<T> extends PaginatedResponse<T> {
  total_doctors: number;
}

@@ -12,13 +12,15 @@ interface PaginationProps {
defaultPerPage: number;
cPage: number;
className?: string;
ScrollToTop?: boolean;
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Follow TypeScript naming conventions

The prop name ScrollToTop should follow camelCase convention as per TypeScript standards.

- ScrollToTop?: boolean;
+ scrollToTop?: boolean;
📝 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
ScrollToTop?: boolean;
scrollToTop?: boolean;

Comment on lines 136 to 137
ScrollToTop={false}
onChange={(page: number) => handlePageChange(page)}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Maintain consistent prop naming

The ScrollToTop prop should match the casing used in the Pagination component:

- ScrollToTop={false}
+ scrollToTop={false}
📝 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
ScrollToTop={false}
onChange={(page: number) => handlePageChange(page)}
scrollToTop={false}
onChange={(page: number) => handlePageChange(page)}

Comment on lines 41 to 47
const handlePageChange = (page: number) => {
updatePage(page);
const staffCapacityElement = document.getElementById("staff_capacity");
if (staffCapacityElement) {
staffCapacityElement.scrollIntoView({ behavior: "smooth" });
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add null check before scrollIntoView

The current implementation might throw an error if the element is not found. Consider adding a null check:

  const handlePageChange = (page: number) => {
    updatePage(page);
    const staffCapacityElement = document.getElementById("staff_capacity");
-   if (staffCapacityElement) {
-     staffCapacityElement.scrollIntoView({ behavior: "smooth" });
-   }
+   staffCapacityElement?.scrollIntoView({ behavior: "smooth" });
  };
📝 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
const handlePageChange = (page: number) => {
updatePage(page);
const staffCapacityElement = document.getElementById("staff_capacity");
if (staffCapacityElement) {
staffCapacityElement.scrollIntoView({ behavior: "smooth" });
}
};
const handlePageChange = (page: number) => {
updatePage(page);
const staffCapacityElement = document.getElementById("staff_capacity");
staffCapacityElement?.scrollIntoView({ behavior: "smooth" });
};

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

🧹 Outside diff range and nitpick comments (1)
src/components/Facility/FacilityStaffList.tsx (1)

41-45: Consider separating scroll behavior from page update logic

While the implementation is correct and fixes the auto-scroll issue, consider separating the scroll behavior into its own function for better maintainability:

+ const scrollToStaffCapacity = () => {
+   const staffCapacityElement = document.getElementById("staff_capacity");
+   staffCapacityElement?.scrollIntoView({ behavior: "smooth" });
+ };

  const handlePageChange = (page: number) => {
    updatePage(page);
-   const staffCapacityElement = document.getElementById("staff_capacity");
-   staffCapacityElement?.scrollIntoView({ behavior: "smooth" });
+   scrollToStaffCapacity();
  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2812e9c and 4d0a553.

📒 Files selected for processing (4)
  • src/Utils/request/api.tsx (2 hunks)
  • src/Utils/request/types.ts (1 hunks)
  • src/components/Common/Pagination.tsx (2 hunks)
  • src/components/Facility/FacilityStaffList.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Common/Pagination.tsx
  • src/Utils/request/types.ts
🔇 Additional comments (6)
src/Utils/request/api.tsx (2)

92-95: LGTM: Clean import organization

The addition of DoctorPaginatedResponse alongside PaginatedResponse is well-organized and maintains clean import structure.


677-677: LGTM: Type enhancement improves API response handling

The change from PaginatedResponse<DoctorModal> to DoctorPaginatedResponse<DoctorModal> aligns with the PR objective to utilize total_doctors for displaying overall staff capacity, which should help eliminate unnecessary API calls.

Let's verify the interface implementation:

✅ Verification successful

LGTM: Type enhancement correctly implements total_doctors field

The verification confirms that DoctorPaginatedResponse is properly defined in src/Utils/request/types.ts as an interface that extends PaginatedResponse<T> with the additional total_doctors field. The implementation aligns with the PR's objective to utilize total_doctors for staff capacity display.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify DoctorPaginatedResponse interface implementation
# Expected: Should find the interface definition with total_doctors property

# Search for DoctorPaginatedResponse interface definition
ast-grep --pattern 'interface DoctorPaginatedResponse<$_> {
  $$$
  total_doctors: number;
  $$$
}'

Length of output: 101


Script:

#!/bin/bash
# Let's try different approaches to find the DoctorPaginatedResponse type/interface

# Search for any file containing DoctorPaginatedResponse
rg "DoctorPaginatedResponse" -A 5

# Also search for type definition as it might be a type alias
ast-grep --pattern 'type DoctorPaginatedResponse<$_> = $_'

# Search for PaginatedResponse as it might be related
rg "PaginatedResponse" -A 5

Length of output: 28835

src/components/Facility/FacilityStaffList.tsx (4)

36-36: LGTM: Improved total doctors calculation

The change simplifies the logic by directly using total_doctors from the API response, eliminating unnecessary iteration and fixing the total count display issue.


92-95: LGTM: Added necessary id for scroll functionality

The added id attribute enables the smooth scroll functionality and follows the existing naming convention.


134-135: LGTM: Pagination configuration properly handles scroll behavior

The changes correctly configure the Pagination component to prevent automatic scrolling to top and use the new page change handler.


36-36: Verify the fixes for all pagination scenarios

The implementation addresses both the auto-scroll and total count issues. Please verify:

  1. Scrolling behavior works correctly when navigating between all pages (not just page 1 to 2)
  2. Total doctor count remains accurate after pagination

Also applies to: 41-45, 134-135

✅ Verification successful

Verification completed for pagination and scroll behavior

The implementation has been properly handled:

  1. The component uses smooth scrolling to the staff capacity section when changing pages: scrollIntoView({ behavior: "smooth" })
  2. The total doctors count is correctly updated from the API response: setTotalDoctors(data?.total_doctors ?? 0)
  3. Pagination is implemented with scrollToTop={false} to prevent unwanted page jumps
  4. The component is properly integrated in FacilityHome.tsx
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other scroll-related code that might interfere
rg -i 'scroll(to|into)' --type ts --type tsx

# Check for other usages of total_doctors to ensure consistency
ast-grep --pattern 'total_doctors'

Length of output: 109


Script:

#!/bin/bash
# Search for scroll-related code with proper file extensions
rg -i 'scroll(to|into)' -t ts -t tsx -t jsx -t js

# Check for total_doctors usage in TypeScript/JavaScript files
rg "total_doctors" -t ts -t tsx -t jsx -t js

# Find all TypeScript/JavaScript files in the Facility component directory
fd -e ts -e tsx -e js -e jsx . src/components/Facility

Length of output: 5873


Script:

#!/bin/bash
# Try with different ripgrep options for scroll-related code
rg -i 'scroll' --type=typescript --type=javascript

# Search for total_doctors in FacilityStaffList.tsx specifically
rg "total_doctors" src/components/Facility/FacilityStaffList.tsx

# Look for pagination-related code in FacilityStaffList.tsx
rg "pagination|setPage|currentPage" src/components/Facility/FacilityStaffList.tsx

Length of output: 285


Script:

#!/bin/bash
# Search with basic file extensions
rg -i 'scroll' -g '*.ts' -g '*.tsx' -g '*.js' -g '*.jsx'

# Look for pagination and page-related state in FacilityStaffList.tsx
cat src/components/Facility/FacilityStaffList.tsx

# Search for any references to FacilityStaffList component
rg "FacilityStaffList" -g '*.ts' -g '*.tsx' -g '*.js' -g '*.jsx'

Length of output: 23303

@shauryag2002
Copy link
Contributor Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

✅ Actions performed

Full review triggered.

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

🧹 Outside diff range and nitpick comments (3)
src/components/Facility/FacilityStaffList.tsx (1)

92-95: Consider adding aria-label for accessibility

While the id is correctly added for scroll functionality, consider enhancing accessibility.

 <div
   className="mt-5 rounded bg-white p-3 shadow-sm md:p-6"
   id="staff_capacity"
+  aria-label="Staff Capacity Section"
 >
src/components/Common/Pagination.tsx (1)

86-92: Consider using a more specific element selector

While the scroll functionality works, using ID 'pages' might be too generic. Consider using a more specific ID or data attribute.

-const pageContainer = window.document.getElementById("pages");
+const pageContainer = window.document.getElementById("pagination-container");
src/Utils/request/api.tsx (1)

92-95: Clean implementation for staff capacity improvements.

The changes are minimal, focused, and well-structured:

  1. New type import for specialized doctor pagination
  2. Updated return type for the listDoctor endpoint
    These changes effectively support the PR objective of fixing the total count card in the facility details page.

Consider documenting the DoctorPaginatedResponse type usage in the API documentation to help other developers understand when to use this specialized pagination type versus the generic one.

Also applies to: 677-677

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2d9669e and 4d0a553.

📒 Files selected for processing (4)
  • src/Utils/request/api.tsx (2 hunks)
  • src/Utils/request/types.ts (1 hunks)
  • src/components/Common/Pagination.tsx (2 hunks)
  • src/components/Facility/FacilityStaffList.tsx (3 hunks)
🔇 Additional comments (7)
src/Utils/request/types.ts (1)

46-48: LGTM! Well-structured interface extension

The new DoctorPaginatedResponse interface properly extends PaginatedResponse to include the domain-specific total_doctors field, following the Interface Segregation Principle.

src/components/Facility/FacilityStaffList.tsx (3)

36-36: LGTM! Simplified total doctors calculation

Using total_doctors from the API response is more efficient than calculating it client-side. The nullish coalescing operator provides a safe fallback.


41-45: LGTM! Well-implemented scroll behavior

The handlePageChange function properly implements the PR objective of controlling scroll behavior. The use of optional chaining (?.) provides null safety.


134-135: LGTM! Proper pagination configuration

The pagination is correctly configured with scrollToTop={false} and the new handlePageChange function, implementing the PR objective of controlling scroll behavior.

src/components/Common/Pagination.tsx (1)

15-15: LGTM! Well-typed optional prop

The scrollToTop prop is properly typed as an optional boolean, following TypeScript conventions.

src/Utils/request/api.tsx (2)

92-95: LGTM! Clean import addition.

The new import follows the existing pattern and is properly grouped with related pagination types.


677-677: Verify DoctorPaginatedResponse implementation.

The type change aligns with the PR objectives to utilize total_doctors for staff capacity display. However, let's verify the implementation.

✅ Verification successful

Type implementation verified successfully

The DoctorPaginatedResponse type is correctly implemented in src/Utils/request/types.ts, extending PaginatedResponse and adding the total_doctors field. The type change in the listDoctor endpoint is appropriate and consistent with the codebase's type system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify DoctorPaginatedResponse type implementation
# Expected: DoctorPaginatedResponse should extend PaginatedResponse and add total_doctors

# Search for the type definition
ast-grep --pattern 'interface DoctorPaginatedResponse<$_> extends PaginatedResponse<$_> {
  $$$
}'

# Verify usage in components
rg -t tsx -t ts "DoctorPaginatedResponse"

Length of output: 362


Script:

#!/bin/bash
# Let's try a different approach to verify the implementation and usage

# Search for DoctorPaginatedResponse definition and usage with ripgrep
rg "DoctorPaginatedResponse" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' -t tsx -t ts

# Also verify PaginatedResponse to ensure it's properly defined
rg "PaginatedResponse" --type-add 'tsx:*.tsx' --type-add 'ts:*.ts' -t tsx -t ts

Length of output: 7388

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

🧹 Outside diff range and nitpick comments (1)
src/components/Facility/models.tsx (1)

130-130: LGTM! Consider adding JSDoc comments.

The addition of the optional total_doctors field aligns with the PR objective to utilize it for displaying the overall staff capacity. This change will help eliminate unnecessary API calls.

Consider adding JSDoc comments to document the purpose of each field in the DoctorModal interface:

 export interface DoctorModal {
+  /** Unique identifier for the doctor record */
   id?: number;
+  /** Area or department where the doctor works */
   area?: number;
+  /** Number of doctors in the current page */
   count?: number;
+  /** Total number of doctors across all pages */
   total_doctors?: number;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4d0a553 and 4fb718c.

📒 Files selected for processing (2)
  • src/components/Facility/FacilityStaffList.tsx (3 hunks)
  • src/components/Facility/models.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Facility/FacilityStaffList.tsx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required invalid This doesn't seem right
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Fix Auto-Scroll Issue and Total Count Card for Staff Capacity Pagination in facility details page
2 participants