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

chore: Add total doctors count to hospital doctor list response #2629

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

Conversation

shauryag2002
Copy link

@shauryag2002 shauryag2002 commented Dec 2, 2024

Proposed Changes

Associated Issue

total_staff_scroll.mp4

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

  • New Features
    • Introduced a new read-only field, total_doctors, displaying the total count of doctors associated with a facility.
    • Enhanced data representation with a customized output method for better clarity on doctor counts.

@shauryag2002 shauryag2002 requested a review from a team as a code owner December 2, 2024 18:45
Copy link

coderabbitai bot commented Dec 2, 2024

Warning

Rate limit exceeded

@shauryag2002 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 20 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9a20757 and 80aefde.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes involve modifications to the HospitalDoctorSerializer in care/facility/api/serializers/hospital_doctor.py. A new read-only field, total_doctors, has been added to provide the total count of doctors associated with a facility. Additionally, the to_representation method has been implemented to customize the serialization output, ensuring that the total_doctors value is included in the serialized data.

Changes

File Path Change Summary
care/facility/api/serializers/hospital_doctor.py Added total_doctors field (read-only) and implemented to_representation method in HospitalDoctorSerializer.

Assessment against linked issues

Objective Addressed Explanation
Total capacity card should display the total staff capacity across all pages. (#2628)
Auto-scroll should stop at the staff capacity section instead of the page's top. (#2628) Changes do not address auto-scroll behavior.

🎉 In the realm of code where changes flow,
A new field emerges, watch it grow!
Total doctors counted, a sight to behold,
Serialization magic, a story told.
With each line crafted, precision in mind,
In the world of serializers, new treasures we find! 🌟


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

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

🧹 Outside diff range and nitpick comments (2)
care/facility/api/viewsets/hospital_doctor.py (2)

46-51: Consider optimizing database queries

The current implementation makes two separate database queries: one for the list and another for the count. While not critical, it might be worth optimizing if this endpoint experiences high traffic.

Here's a more efficient approach:

     def list(self, request, *args, **kwargs):
-        response = super().list(request, *args, **kwargs)
-        total_doctors = self.get_queryset().aggregate(total_doctors=Sum("count"))["total_doctors"]
-        response.data["total_doctors"] = total_doctors
+        queryset = self.get_queryset()
+        page = self.paginate_queryset(queryset)
+        
+        total_doctors = queryset.aggregate(total_doctors=Sum("count"))["total_doctors"] or 0
+        
+        if page is not None:
+            serializer = self.get_serializer(page, many=True)
+            return self.get_paginated_response({
+                **serializer.data,
+                "total_doctors": total_doctors
+            })
+            
+        serializer = self.get_serializer(queryset, many=True)
+        return Response({
+            "results": serializer.data,
+            "total_doctors": total_doctors
+        })
         return response
🧰 Tools
🪛 Ruff (0.8.0)

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Use double quotes for string literals

I see you're using single quotes. While it works, the project's style guide might prefer double quotes, as suggested by the static analysis tool.

-        total_doctors = self.get_queryset().aggregate(total_doctors=Sum('count'))['total_doctors']
+        total_doctors = self.get_queryset().aggregate(total_doctors=Sum("count"))["total_doctors"]
🧰 Tools
🪛 Ruff (0.8.0)

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 907e87a and 42350b4.

📒 Files selected for processing (1)
  • care/facility/api/viewsets/hospital_doctor.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
care/facility/api/viewsets/hospital_doctor.py

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

🔇 Additional comments (2)
care/facility/api/viewsets/hospital_doctor.py (2)

5-5: LGTM! Import statement is properly placed.

The Sum import is correctly grouped with other Django imports and is effectively utilized in the new implementation.


46-51: Verify the impact on API consumers

Since this modifies the response structure, ensure that all API consumers are prepared for the new total_doctors field.

✅ Verification successful

No need to worry about API consumers, as this is a new endpoint

From the codebase analysis, I can see that this is a new endpoint being added at facility/hospital_doctor and is properly registered in the router configuration. While one might think we should be concerned about API consumers, the evidence suggests this is actually a new feature:

  1. No frontend code references were found using hospitalDoctor or related patterns
  2. The endpoint is freshly registered in config/api_router.py under the facility nested router
  3. The addition of total_doctors is part of the initial implementation

The change is safe to proceed with, as it won't break any existing consumers - though it would have been nice if there were some tests to go along with it.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API consumers that might be affected by the response structure change

# Look for frontend components that consume this endpoint
rg -l "hospitalDoctor.*list" --type js --type ts

# Look for tests that might need updating
rg -l "HospitalDoctorViewSet.*list" --type python

Length of output: 133


Script:

#!/bin/bash
# Let's try a more comprehensive search for API consumers and tests

# Search for frontend components using hospitalDoctor
rg -i "hospitaldoctor" --type js --type jsx --type ts --type tsx

# Search for related test files with proper file extensions
rg -l "HospitalDoctorViewSet" --type-add 'python:*.py' --type python

# Search for any API calls related to hospital doctors
rg -i "api.*hospital.*doctor" --type js --type jsx --type ts --type tsx

# Look for test files specifically
fd "test.*\.py$" -x rg -l "HospitalDoctorViewSet" {}

Length of output: 385


Script:

#!/bin/bash
# Let's see what's actually using this viewset and how

# Check the actual router configuration
cat config/api_router.py

# Look for any tests in the facility app
fd "test.*\.py$" care/facility -x cat {}

# Let's also check if there are any frontend files that might be using this endpoint
fd "\.(js|ts|vue|jsx|tsx)$" -x rg -l "hospital.*doctor" {}

Length of output: 93207

🧰 Tools
🪛 Ruff (0.8.0)

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

Comment on lines 46 to 51
def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
total_doctors = self.get_queryset().aggregate(total_doctors=Sum('count'))['total_doctors']
response.data["total_doctors"] = total_doctors
return response

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle potential None value from aggregation

The aggregation might return None if there are no records, which could lead to unexpected behavior in the frontend.

Here's a slightly more robust implementation:

     def list(self, request, *args, **kwargs):
         response = super().list(request, *args, **kwargs)
-        total_doctors = self.get_queryset().aggregate(total_doctors=Sum("count"))["total_doctors"]
-        response.data["total_doctors"] = total_doctors
+        total_doctors = self.get_queryset().aggregate(total_doctors=Sum("count"))["total_doctors"]
+        response.data["total_doctors"] = total_doctors or 0
         return response
📝 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
def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
total_doctors = self.get_queryset().aggregate(total_doctors=Sum('count'))['total_doctors']
response.data["total_doctors"] = total_doctors
return response
def list(self, request, *args, **kwargs):
response = super().list(request, *args, **kwargs)
total_doctors = self.get_queryset().aggregate(total_doctors=Sum("count"))["total_doctors"]
response.data["total_doctors"] = total_doctors or 0
return response
🧰 Tools
🪛 Ruff (0.8.0)

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

@shauryag2002
Copy link
Author

@coderabbitai full review

Copy link

coderabbitai bot commented Dec 2, 2024

✅ Actions performed

Full review triggered.

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

🧹 Outside diff range and nitpick comments (2)
care/facility/api/viewsets/hospital_doctor.py (2)

46-51: I suppose we could make this more efficient...

While the implementation works, we could optimize it by using annotation instead of aggregation to avoid an extra query. It's not urgent, but it would be nice to have.

Consider this slightly more efficient approach:

     def list(self, request, *args, **kwargs):
+        self.queryset = self.get_queryset().annotate(total_doctors=Sum("count"))
         response = super().list(request, *args, **kwargs)
-        total_doctors = self.get_queryset().aggregate(total_doctors=Sum('count'))['total_doctors']
-        response.data["total_doctors"] = total_doctors or 0
+        response.data["total_doctors"] = self.queryset.values("total_doctors")[0]["total_doctors"] or 0
         return response
🧰 Tools
🪛 Ruff (0.8.0)

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Those single quotes are just begging to be double quotes, aren't they?

Let's maintain consistency with the project's style guide.

-        total_doctors = self.get_queryset().aggregate(total_doctors=Sum('count'))['total_doctors']
+        total_doctors = self.get_queryset().aggregate(total_doctors=Sum("count"))["total_doctors"]
🧰 Tools
🪛 Ruff (0.8.0)

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 42350b4 and 5f85647.

📒 Files selected for processing (1)
  • care/facility/api/viewsets/hospital_doctor.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
care/facility/api/viewsets/hospital_doctor.py

48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)


48-48: Single quotes found but double quotes preferred

Replace single quotes with double quotes

(Q000)

🔇 Additional comments (1)
care/facility/api/viewsets/hospital_doctor.py (1)

5-5: Oh look, a properly placed import statement!

The Sum import is correctly placed with other Django imports. How refreshing to see proper import organization.

Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

Change in serializer instead. Changing here does not show up in the API docs.

Also I don't think this is the right solution to do this.

cc @sainak / @vigneshhari

@shauryag2002
Copy link
Author

@coderabbitai full review

Copy link

coderabbitai bot commented Dec 7, 2024

✅ Actions performed

Full review triggered.

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

🧹 Outside diff range and nitpick comments (2)
care/facility/api/serializers/hospital_doctor.py (2)

11-11: LGTM, though a docstring would be nice...

The read-only field declaration is correct. I suppose we'll just have to guess what it represents without any documentation.

-    total_doctors = serializers.IntegerField(read_only=True)
+    total_doctors = serializers.IntegerField(
+        read_only=True,
+        help_text="Total number of doctors across all specialties in the facility"
+    )

24-28: Consider caching the total doctors count

The current implementation calculates the total on every serialization, which could impact performance for facilities with many doctors. Consider implementing caching:

  1. Cache the count in the Facility model
  2. Update the cache when doctors are added/modified/deleted
  3. Use the cached value in the serializer

Would you like me to provide an example implementation with Django's caching mechanisms?

🧰 Tools
🪛 Ruff (0.8.0)

26-26: Undefined name Sum

(F821)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5f85647 and fa6f6bd.

📒 Files selected for processing (1)
  • care/facility/api/serializers/hospital_doctor.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.0)
care/facility/api/serializers/hospital_doctor.py

26-26: Undefined name Sum

(F821)

🔇 Additional comments (1)
care/facility/api/serializers/hospital_doctor.py (1)

18-18: Looks good!

Properly added to read_only_fields, maintaining consistency with the field declaration.

Comment on lines 22 to 29
def to_representation(self, instance):
representation = super().to_representation(instance)
representation["total_doctors"] = (
HospitalDoctors.objects.filter(facility=instance.facility)
.aggregate(total_doctors=Sum("count"))["total_doctors"]
or 0
)
return representation
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Several issues need attention in the to_representation method

  1. The Sum import is missing
  2. The method indentation is incorrect (currently inside Meta class)
  3. Missing error handling for database operations

Please apply these fixes:

+ from django.db.models import Sum
  from rest_framework import serializers
  
  from care.facility.api.serializers import TIMESTAMP_FIELDS
  from care.facility.models import DOCTOR_TYPES, HospitalDoctors
  from care.utils.serializers.fields import ChoiceField

  class HospitalDoctorSerializer(serializers.ModelSerializer):
      # ... other fields ...

      class Meta:
          model = HospitalDoctors
          read_only_fields = (
              "id",
              "area_text",
              "total_doctors"
          )
          exclude = (*TIMESTAMP_FIELDS, "facility", "external_id")

-         def to_representation(self, instance):
-             representation = super().to_representation(instance)
-             representation["total_doctors"] = (
-                 HospitalDoctors.objects.filter(facility=instance.facility)
-                 .aggregate(total_doctors=Sum("count"))["total_doctors"]
-                 or 0
-             )
-             return representation

+     def to_representation(self, instance):
+         representation = super().to_representation(instance)
+         try:
+             representation["total_doctors"] = (
+                 HospitalDoctors.objects.filter(facility=instance.facility)
+                 .aggregate(total_doctors=Sum("count"))["total_doctors"]
+                 or 0
+             )
+         except Exception as e:
+             representation["total_doctors"] = 0
+             # Consider logging the error here
+         return representation
📝 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
def to_representation(self, instance):
representation = super().to_representation(instance)
representation["total_doctors"] = (
HospitalDoctors.objects.filter(facility=instance.facility)
.aggregate(total_doctors=Sum("count"))["total_doctors"]
or 0
)
return representation
from django.db.models import Sum
from rest_framework import serializers
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.models import DOCTOR_TYPES, HospitalDoctors
from care.utils.serializers.fields import ChoiceField
class HospitalDoctorSerializer(serializers.ModelSerializer):
# ... other fields ...
class Meta:
model = HospitalDoctors
read_only_fields = (
"id",
"area_text",
"total_doctors"
)
exclude = (*TIMESTAMP_FIELDS, "facility", "external_id")
def to_representation(self, instance):
representation = super().to_representation(instance)
try:
representation["total_doctors"] = (
HospitalDoctors.objects.filter(facility=instance.facility)
.aggregate(total_doctors=Sum("count"))["total_doctors"]
or 0
)
except Exception as e:
representation["total_doctors"] = 0
# Consider logging the error here
return representation
🧰 Tools
🪛 Ruff (0.8.0)

26-26: Undefined name Sum

(F821)

@shauryag2002
Copy link
Author

@coderabbitai full review

Copy link

coderabbitai bot commented Dec 7, 2024

✅ Actions performed

Full review triggered.

@shauryag2002
Copy link
Author

shauryag2002 commented Dec 7, 2024

Change in serializer instead. Changing here does not show up in the API docs.

Also I don't think this is the right solution to do this.

cc @sainak / @vigneshhari

@rithviknishad , Now changes will show up in API docs and changed in serializer only now.
image

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.

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