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

Remove event handlers #2593

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open

Conversation

sainak
Copy link
Member

@sainak sainak commented Nov 10, 2024

Proposed Changes

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

Release Notes

  • Bug Fixes

    • Streamlined the creation and update processes for daily rounds and encounter symptoms by removing unnecessary event creation logic.
    • Ensured validation logic remains intact while simplifying methods for better performance.
  • New Features

    • Enhanced the PatientConsultationSerializer and PatientNotesViewSet by removing redundant event handling, allowing for more efficient patient note creation and updates.
  • Chores

    • Removed outdated event handling functions and management commands to improve code maintainability and clarity.

Copy link

coderabbitai bot commented Nov 10, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request involve significant modifications across multiple serializer and viewset classes in the healthcare application. The primary focus has been on simplifying the control flow by removing the create_consultation_events function calls from various methods, including create and update. This has led to the deletion of the handler.py file, which previously managed consultation event creation. Additionally, the load_event_types.py file has been removed, along with several utility functions in event_utils.py, further streamlining the codebase.

Changes

File Path Change Summary
care/facility/api/serializers/daily_round.py Removed create_consultation_events calls from create and update methods in DailyRoundSerializer.
care/facility/api/serializers/encounter_symptom.py Removed create_consultation_events calls from create and update methods in EncounterSymptomSerializer.
care/facility/api/serializers/patient_consultation.py Removed copy import and create_consultation_events logic from create and update methods in PatientConsultationSerializer and PatientConsultationDischargeSerializer.
care/facility/api/viewsets/consultation_diagnosis.py Removed event creation logic from perform_create and deleted the perform_update and update methods.
care/facility/api/viewsets/patient.py Removed create_consultation_events call from perform_create method in PatientNotesViewSet.
care/facility/events/handler.py Deleted file containing functions for managing consultation event entries.
care/facility/management/commands/load_event_types.py Deleted file containing a management command for loading event types into the database.
care/utils/event_utils.py Removed utility functions for model field handling, including is_null, get_changed_fields, serialize_field, and model_diff.

Poem

In the code where events once thrived,
A simpler path has now arrived.
Functions gone, the flow is clear,
Less cluttered code, oh what a cheer!
With every change, we take a stride,
In the world of code, let’s enjoy the ride! 🚀


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

codecov bot commented Nov 10, 2024

Codecov Report

Attention: Patch coverage is 83.33333% with 1 line in your changes missing coverage. Please review.

Project coverage is 69.39%. Comparing base (d6d069e) to head (fa14346).

Files with missing lines Patch % Lines
care/facility/api/serializers/daily_round.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2593      +/-   ##
===========================================
+ Coverage    69.20%   69.39%   +0.18%     
===========================================
  Files          211      209       -2     
  Lines        11944    11807     -137     
  Branches      1208     1190      -18     
===========================================
- Hits          8266     8193      -73     
+ Misses        3302     3241      -61     
+ Partials       376      373       -3     

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

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 (4)
care/facility/api/serializers/daily_round.py (1)

169-169: Oh, I see we're keeping the notification logic while removing event handlers... interesting choice.

While removing the event handlers is a step in the right direction, it seems we're still mixing multiple responsibilities in this method. Perhaps we could also consider:

  1. Extracting notification logic to a dedicated service
  2. Separating validation logic from data updates
  3. Breaking down the rather lengthy update method into smaller, focused methods

I mean, if we're cleaning up the code, we might as well do it properly, right? 😊

Here's a potential refactor to consider:

class DailyRoundService:
    def handle_notifications(self, daily_round, user):
        NotificationGenerator(
            event=Notification.Event.PATIENT_CONSULTATION_UPDATE_UPDATED,
            caused_by=user,
            caused_object=daily_round,
            facility=daily_round.consultation.patient.facility,
        ).generate()

    def handle_consultation_update(self, daily_round, is_telemedicine):
        daily_round.consultation.last_updated_by_telemedicine = is_telemedicine
        daily_round.consultation.save(update_fields=["last_updated_by_telemedicine"])

class DailyRoundSerializer(serializers.ModelSerializer):
    def update(self, instance, validated_data):
        self._validate_discharge_status(instance)
        self._handle_patient_actions(instance, validated_data)
        
        service = DailyRoundService()
        is_telemedicine = self._is_telemedicine_update(instance)
        service.handle_consultation_update(instance, is_telemedicine)
        
        updated_instance = super().update(instance, validated_data)
        service.handle_notifications(updated_instance, self.context["request"].user)
        
        return updated_instance
care/facility/api/serializers/patient_consultation.py (3)

Line range hint 407-414: Inconsistent variable naming: use 'create_diagnoses' for clarity

To maintain consistency and improve readability, consider renaming the variable create_diagnosis to create_diagnoses to match the key used in validated_data.


Line range hint 420-429: Wrap generator expression in a list for 'bulk_create'

The bulk_create method expects a list of model instances, but a generator expression is provided. Wrapping the generator in a list ensures proper execution.

Apply this diff to fix the issue:

                 EncounterSymptom.objects.bulk_create(
+                    [
                     EncounterSymptom(
                         consultation=consultation,
                         symptom=obj.get("symptom"),
                         onset_date=obj.get("onset_date"),
                         cure_date=obj.get("cure_date"),
                         clinical_impression_status=obj.get("clinical_impression_status"),
                         other_symptom=obj.get("other_symptom") or "",
                         created_by=user,
                     )
                     for obj in create_symptoms
-                )
+                    ]
+                )

Line range hint 459-459: Typo in error message: 'Atleast' should be 'At least'

There's a minor typo in the validation error message that could be corrected for clarity.

Apply this diff:

-            msg = "Atleast one diagnosis is required"
+            msg = "At least one diagnosis is required"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d6d069e and fa14346.

📒 Files selected for processing (8)
  • care/facility/api/serializers/daily_round.py (1 hunks)
  • care/facility/api/serializers/encounter_symptom.py (1 hunks)
  • care/facility/api/serializers/patient_consultation.py (2 hunks)
  • care/facility/api/viewsets/consultation_diagnosis.py (1 hunks)
  • care/facility/api/viewsets/patient.py (0 hunks)
  • care/facility/events/handler.py (0 hunks)
  • care/facility/management/commands/load_event_types.py (0 hunks)
  • care/utils/event_utils.py (0 hunks)
💤 Files with no reviewable changes (4)
  • care/facility/api/viewsets/patient.py
  • care/facility/events/handler.py
  • care/facility/management/commands/load_event_types.py
  • care/utils/event_utils.py
🔇 Additional comments (5)
care/facility/api/viewsets/consultation_diagnosis.py (2)

55-55: LGTM, but let's verify the event logging impact.

The simplified version looks much cleaner, I must say. Though, I can't help but wonder if we're absolutely certain that removing the event logging won't impact any audit requirements or downstream systems that might have depended on these events.

Let's check if there are any remaining references to consultation events that might expect this logging:


Line range hint 29-42: Architectural consideration regarding removed update methods.

I notice we're silently falling back to the default update behavior after removing perform_update and update. While this certainly makes the code more... streamlined 🙂, we should probably document that we've intentionally removed the old instance copying functionality, just so future maintainers don't think it was an oversight.

Let's check if there are any other places in the codebase that might have expected this copying behavior:

care/facility/api/serializers/encounter_symptom.py (2)

94-94: At least we're consistently removing transactions everywhere.

The update method follows the same pattern as create(). While I appreciate the consistency, I'm slightly concerned about potential race conditions or partial updates. But I suppose that's a problem for future us?

Let's check if there are any concurrent update scenarios we should worry about:

#!/bin/bash
# Look for potential concurrent access patterns
rg "EncounterSymptom.*update" -A 5

Consider adding a comment explaining why transaction management was deemed unnecessary, just so future developers don't waste time wondering about it. Not that I'm wondering or anything...


89-89: Oh, I see we're living dangerously without transaction management now.

While removing the event handlers aligns with the PR objectives, I couldn't help but notice we've also dropped the transaction.atomic() wrapper. I'm sure you have your reasons, but perhaps we should discuss the implications?

Let's check if other serializers still use transactions:

Consider keeping the transaction management to ensure data consistency, even if we're removing the event handlers. It's just a thought... 🤷

care/facility/api/serializers/daily_round.py (1)

Line range hint 1-400: Just making sure we didn't forget any event handler references...

Let's verify that all event handler related code has been properly cleaned up from this file.

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.

Remove the existing event handlers
1 participant