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

SSEMR-471 Match the total TX Curr on graph, card and regimens #54

Merged
merged 3 commits into from
Feb 14, 2025

Conversation

Michaelndula
Copy link
Collaborator

@Michaelndula Michaelndula commented Feb 12, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced cumulative summary reports now ensure the final month’s patient count aligns with the overall total, improving report consistency and accuracy.
    • Introduced a utility method for handling date ranges, facilitating improved filtering of patient regimen data.
  • Style

    • Adjusted formatting in patient data retrieval processes for improved clarity.
  • Refactor

    • Updated summary generation across components to incorporate the overall patient count for uniform reporting.

Copy link

coderabbitai bot commented Feb 12, 2025

Walkthrough

This pull request updates the patient summary generation functionality. The method in the summary generator now accepts an additional parameter to enforce that the last month's patient count matches the provided total. Corresponding method calls in the TxCurrController are updated to include this parameter, and the comments within the generator are renumbered accordingly. Additionally, the SSEMRWebServicesController has been modified to adjust the endDate parameter by adding 23 hours for consistency in patient regimen treatment retrieval.

Changes

File(s) Change Summary
omod/.../GenerateCumulativeSummary.java
omod/.../TxCurrController.java
Updated method signatures to include an extra parameter (totalPatients/totalCount) and corresponding logic to enforce the patient count in the cumulative summary. Also, comment steps have been renumbered.
omod/.../SSEMRWebServicesController.java Adjusted the endDate parameter in methods to add 23 hours for consistency in patient regimen treatment retrieval without altering existing logic.
omod/.../GetPatientRegimens.java Introduced a new method getStartAndEndDate for handling date ranges based on provided string parameters.

Sequence Diagram(s)

sequenceDiagram
    participant TxCurr as TxCurrController
    participant Generator as GenerateCumulativeSummary
    participant Logger as System Logger

    TxCurr->>Generator: generateCumulativeSummary(dates, startDate, endDate, totalPatients)
    Generator->>Generator: Compute monthly summary
    Generator->>Generator: Validate last month count equals totalPatients
    alt Count mismatch detected
        Generator->>Logger: Log warning about count adjustment
    end
    Generator-->>TxCurr: Return summary map
Loading

Possibly related PRs

Suggested reviewers

  • nelsonkimaiga

Poem

I’m a bunny on a code parade,
Hopping through changes that have been made,
With counters strict and sums in tune,
My little paws tap out a happy tune,
Leaping high with lines so neat—code carrots can’t be beat!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

@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)
omod/src/main/java/org/openmrs/module/ssemrws/web/constants/GenerateCumulativeSummary.java (2)

40-47: Consider adding validation for the totalPatients parameter.

While the logic to enforce the total patients count is correct, consider adding validation to ensure totalPatients is non-negative and at least equal to the count from the previous month to maintain data consistency.

 // Step 3: Ensure total patients count is correct in the last month
 Calendar endCal = Calendar.getInstance();
 endCal.setTime(endDate);
 String lastMonth = months[endCal.get(Calendar.MONTH)];
 
+// Validate totalPatients parameter
+if (totalPatients < 0) {
+    throw new IllegalArgumentException("Total patients count cannot be negative");
+}
+
+String previousMonth = months[(endCal.get(Calendar.MONTH) + 11) % 12];
+if (cumulativeSummary.containsKey(previousMonth) && 
+    totalPatients < cumulativeSummary.get(previousMonth)) {
+    throw new IllegalArgumentException("Total patients count cannot be less than previous month's count");
+}
+
 // Force last month count to be exactly totalPatients
 cumulativeSummary.put(lastMonth, totalPatients);

63-67: Consider using a logging framework instead of System.err.

While the warning message is helpful, using a proper logging framework would be more appropriate for production code. This would provide better control over log levels and output destinations.

-System.err.println("Warning: Adjusting final month count to match total patients.");
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+private static final Log log = LogFactory.getLog(GenerateCumulativeSummary.class);
+log.warn("Adjusting final month count to match total patients.");
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35078fa and e1c7947.

📒 Files selected for processing (3)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/constants/GenerateCumulativeSummary.java (3 hunks)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/controller/SSEMRWebServicesController.java (2 hunks)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/controller/TxCurrController.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/controller/SSEMRWebServicesController.java
🔇 Additional comments (4)
omod/src/main/java/org/openmrs/module/ssemrws/web/constants/GenerateCumulativeSummary.java (3)

8-9: LGTM! Method signature updated to support total patient count validation.

The addition of the totalPatients parameter aligns with the PR objective to match totals across different views.


48-51: LGTM! Step renumbering improves code organization.

The filtering logic is well-placed and properly documented.


68-68: LGTM! Clear documentation of final step.

The comment clearly indicates the purpose of the final map creation.

omod/src/main/java/org/openmrs/module/ssemrws/web/controller/TxCurrController.java (1)

71-72: LGTM! Improved formatting and consistency.

The changes improve code readability and ensure consistency in patient counts by passing the totalCount parameter to GenerateCumulativeSummary.generateCumulativeSummary.

Please verify that:

  1. The totalCount matches the actual number of patients in the list
  2. The GenerateCumulativeSummary.generateCumulativeSummary method properly handles the new parameter
❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Search for the implementation of generateCumulativeSummary to verify parameter handling
ast-grep --pattern 'class GenerateCumulativeSummary {
  $$$
  generateCumulativeSummary($$$) {
    $$$
  }
  $$$
}'

Length of output: 117


Action Required: Manual Verification Needed for GenerateCumulativeSummary Parameter Handling

The automated search didn't yield evidence of the updated implementation of the generateCumulativeSummary method. Please manually verify the following:

  • That the totalCount parameter correctly reflects the actual number of patients in the list.
  • That the GenerateCumulativeSummary.generateCumulativeSummary method is updated to properly accept and use the new totalCount parameter.

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

🧹 Nitpick comments (1)
omod/src/main/java/org/openmrs/module/ssemrws/web/constants/GetPatientRegimens.java (1)

110-128: Consider thread safety and modern date-time API improvements.

The implementation has several areas for improvement:

  1. SimpleDateFormat is not thread-safe, which could cause issues in a multi-threaded environment.
  2. The legacy Date and Calendar APIs are used instead of the more robust modern java.time API.
  3. No input validation for malformed date strings.

Consider refactoring to use the modern java.time API:

-public static Date[] getStartAndEndDate(String qStartDate, String qEndDate, SimpleDateFormat dateTimeFormatter)
-        throws ParseException {
-    Date endDate = (qEndDate != null) ? dateTimeFormatter.parse(qEndDate) : new Date();
-    
-    // Extend endDate to 23:59:59
-    Calendar calendar = Calendar.getInstance();
-    calendar.setTime(endDate);
-    calendar.set(Calendar.HOUR_OF_DAY, 23);
-    calendar.set(Calendar.MINUTE, 59);
-    calendar.set(Calendar.SECOND, 59);
-    calendar.set(Calendar.MILLISECOND, 999);
-    endDate = calendar.getTime();
-    
-    // Set startDate correctly
-    calendar.set(Calendar.DAY_OF_MONTH, 1);
-    Date startDate = (qStartDate != null) ? dateTimeFormatter.parse(qStartDate) : calendar.getTime();
-    
-    return new Date[] { startDate, endDate };
+public static Date[] getStartAndEndDate(String qStartDate, String qEndDate, DateTimeFormatter formatter) {
+    LocalDate endLocalDate = qEndDate != null ? 
+        LocalDate.parse(qEndDate, formatter) : 
+        LocalDate.now();
+    
+    // Convert to Date with end of day time
+    Date endDate = Date.from(endLocalDate
+        .atTime(23, 59, 59, 999_000_000)
+        .atZone(ZoneId.systemDefault())
+        .toInstant());
+    
+    // Set startDate to first of month if not provided
+    LocalDate startLocalDate = qStartDate != null ?
+        LocalDate.parse(qStartDate, formatter) :
+        endLocalDate.withDayOfMonth(1);
+    
+    Date startDate = Date.from(startLocalDate
+        .atStartOfDay()
+        .atZone(ZoneId.systemDefault())
+        .toInstant());
+    
+    return new Date[] { startDate, endDate };
+}

Also add input validation:

if (qStartDate != null && !qStartDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
    throw new IllegalArgumentException("Invalid start date format. Expected: yyyy-MM-dd");
}
if (qEndDate != null && !qEndDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
    throw new IllegalArgumentException("Invalid end date format. Expected: yyyy-MM-dd");
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e1c7947 and 19dcc16.

📒 Files selected for processing (2)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/constants/GetPatientRegimens.java (1 hunks)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/controller/SSEMRWebServicesController.java (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • omod/src/main/java/org/openmrs/module/ssemrws/web/controller/SSEMRWebServicesController.java
🔇 Additional comments (1)
omod/src/main/java/org/openmrs/module/ssemrws/web/constants/GetPatientRegimens.java (1)

22-23: LGTM! Good integration of date handling.

The new method is well integrated into the existing code and provides consistent date range handling across the application.

@Michaelndula Michaelndula merged commit 711ef98 into IntelliSOFT-Consulting:main Feb 14, 2025
1 check passed
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.

1 participant