Skip to content

Do Not Send Feedback Emails for Closed Status in Biannual Cron#399

Merged
belwalshubham merged 2 commits intodevelopfrom
feat/biannual-cron-fixes
Oct 29, 2024
Merged

Do Not Send Feedback Emails for Closed Status in Biannual Cron#399
belwalshubham merged 2 commits intodevelopfrom
feat/biannual-cron-fixes

Conversation

@belwalshubham
Copy link
Copy Markdown
Collaborator

@belwalshubham belwalshubham commented Oct 29, 2024

Description

  1. The biannual cron is responsible for sending feedback emails when a dropping center is active. Currently, it sends an email if the dropping center has been open for six months, even if the status is closed. To address this issue, the code has been updated to include a check that prevents emails from being sent to dropping centers that are closed.

  2. Send the feedback cron email only if the status is authorized

Summary by CodeRabbit

  • New Features

    • Enhanced feedback email logic to ensure emails are sent only for active dropping centers.
    • Improved clarity in comments regarding the email sending process.
    • Added selection of additional data for better feedback processing based on dropping center status.
  • Bug Fixes

    • Added conditional checks to prevent sending emails for permanently closed dropping centers.
    • Updated error logging to include more detailed information for better troubleshooting.

@belwalshubham belwalshubham self-assigned this Oct 29, 2024
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Oct 29, 2024

Walkthrough

The changes in this pull request modify the civicrm_api3_goonjcustom_biannual_dropping_center_feedback_cron function within the BiannualDroppingCenterFeedbackCron.php file. A conditional check was added to determine if feedback emails should be sent based on the status of the dropping center. If the $droppingCenterMeta array is empty, indicating the center is not "Permanently Closed," the email is sent, and the last feedback date is updated. Debug logging was also introduced for closed centers, and comments were updated for clarity. Additionally, the civicrm_api3_goonjcustom_feedback_dropping_center_cron function in FeedbackDroppingCenterCron.php was modified to include new data selection and refined logic for processing feedback based on the authorization status.

Changes

File Change Summary
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/BiannualDroppingCenterFeedbackCron.php Modified feedback email logic to include a check for dropping center status; updated comments.
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/FeedbackDroppingCenterCron.php Enhanced data selection and modified processing logic based on the authorization status; updated error logging.

Possibly related PRs

Suggested reviewers

  • tarunnjoshi
  • pokhiii

🌟 In the land of code, where logic does flow,
A check was added, to help emails know.
If closed, no feedback, just silence and peace,
Logging the status, letting confusion cease.
With comments now clear, the intent shines bright,
In the realm of Civi, all functions take 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 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
Copy Markdown

@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 (3)
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/BiannualDroppingCenterFeedbackCron.php (3)

Line range hint 25-35: Consider optimizing the dropping centers query for better performance.

The current implementation fetches all authorized centers first and then performs additional queries for each center to check their status. This could be inefficient for large datasets.

Consider combining the queries using a JOIN operation:

  $droppingCenters = EckEntity::get('Collection_Camp', TRUE)
    ->addSelect('Collection_Camp_Core_Details.Contact_Id', 'Dropping_Centre.last_feedback_sent_date')
+   ->addJoin('Dropping_Center_Meta AS dcm', 'LEFT', ['id', '=', 'dcm.Dropping_Center'])
    ->addWhere('Dropping_Centre.When_do_you_wish_to_open_center_Date_', '<=', $thresholdDate)
    ->addWhere('Collection_Camp_Core_Details.Status:name', '=', 'Authorized')
+   ->addWhere('dcm.Status.Status:name', '!=', 'Permanently_Closed')
    ->addClause('OR', ['Dropping_Centre.last_feedback_sent_date', 'IS NULL'], ['Dropping_Centre.last_feedback_sent_date', '<=', $thresholdDate])
    ->execute();

Line range hint 38-45: Remove unused status variable.

The $status variable is fetched from $droppingCenterMeta but never used in the actual processing logic.

Remove the unused code:

- $status = !empty($droppingCenterMeta) ? $droppingCenterMeta[0]['Status.Feedback_Email_Delivered'] : null;

  // Send email only if not delivered and not permanently closed

60-60: Enhance debug logging with additional context.

The current debug message could provide more useful information for troubleshooting.

Consider enhancing the log message:

- \CRM_Core_Error::debug_log_message("Feedback cron: Dropping Center ID {$droppingCenterId} is marked as 'Permanently Closed'. As a result, no email will be sent by the biannual feedback cron.");
+ \CRM_Core_Error::debug_log_message("Feedback cron: Skipping email for Dropping Center ID {$droppingCenterId} (Contact: {$initiatorId}). Reason: Center is marked as 'Permanently Closed' since " . $droppingCenterMeta[0]['Status.Feedback_Email_Delivered']);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 66ca0fb and 78a1d0e.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/BiannualDroppingCenterFeedbackCron.php (1 hunks)

Comment on lines +52 to +58
if (empty($droppingCenterMeta[0])) {
// Proceed with sending the feedback email.
DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);

// Update the last_feedback_sent_date to the current date after the email is sent.
DroppingCenterFeedbackService::updateFeedbackLastSentDate($droppingCenterId);
// Update the last_feedback_sent_date to the current date after the email is sent
DroppingCenterFeedbackService::updateFeedbackLastSentDate($droppingCenterId);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling for email processing and date updates.

The email sending and date update operations should be wrapped in proper error handling to ensure data consistency.

Consider implementing the following changes:

  if (empty($droppingCenterMeta[0])) {
+   try {
      // Proceed with sending the feedback email.
      DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);
      
      // Update the last_feedback_sent_date to the current date after the email is sent
      DroppingCenterFeedbackService::updateFeedbackLastSentDate($droppingCenterId);
+   } catch (Exception $e) {
+     \CRM_Core_Error::debug_log_message("Failed to process feedback for center {$droppingCenterId}: " . $e->getMessage());
+     continue;
+   }
  }
📝 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
if (empty($droppingCenterMeta[0])) {
// Proceed with sending the feedback email.
DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);
// Update the last_feedback_sent_date to the current date after the email is sent.
DroppingCenterFeedbackService::updateFeedbackLastSentDate($droppingCenterId);
// Update the last_feedback_sent_date to the current date after the email is sent
DroppingCenterFeedbackService::updateFeedbackLastSentDate($droppingCenterId);
}
if (empty($droppingCenterMeta[0])) {
try {
// Proceed with sending the feedback email.
DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);
// Update the last_feedback_sent_date to the current date after the email is sent
DroppingCenterFeedbackService::updateFeedbackLastSentDate($droppingCenterId);
} catch (Exception $e) {
\CRM_Core_Error::debug_log_message("Failed to process feedback for center {$droppingCenterId}: " . $e->getMessage());
continue;
}
}

// Send email only if not delivered and not permanently closed
// Send the feedback email.
DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);
if (empty($droppingCenterMeta[0])) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
if (empty($droppingCenterMeta[0])) {
if (!$droppingCenterMeta)) {

is that not work, why we are fetching the 0th index and then check it's empty or not

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I only want to check the zeroth index. If this index is not present, it indicates that there are no entries for 'Permanently Closed' centers, which means we can proceed with triggering the biannual cron. However, if an entry is present, we do not want to run this cron.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think i have added a feedback on your previous PR where we need to change this to single so that we don't need this type of problem, please check that out and try to implement that on another PR.

Copy link
Copy Markdown

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

🧹 Outside diff range and nitpick comments (1)
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/FeedbackDroppingCenterCron.php (1)

50-50: Consider documenting the complex field relationships

The query includes deeply nested field selections which could be difficult to maintain. Adding comments explaining the relationship between Dropping_Center_Meta, Collection_Camp_Core_Details, and their respective status fields would improve maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 78a1d0e and 2e1fafc.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/FeedbackDroppingCenterCron.php (2 hunks)
🔇 Additional comments (2)
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/FeedbackDroppingCenterCron.php (2)

Line range hint 50-70: Implementation looks good overall

The changes effectively implement the requirement to prevent feedback emails for closed dropping centers through a combination of query filtering and status checks. The code is well-structured and includes proper error handling.


64-66: Verify the business logic alignment

The PR's objective is to prevent feedback emails for closed centers, but this condition checks for 'authorized' status. Please verify:

  1. Are there other valid statuses besides 'authorized' that should receive feedback?
  2. Is this condition redundant with the 'Permanently_Closed' check in the query?
✅ Verification successful

Based on the search results, I can now provide a conclusive response about the status checks in the codebase:

'authorized' status check is consistent with codebase patterns

The 'authorized' status check in the code is correct and aligns with the codebase's business logic. Evidence:

  • All other cron jobs consistently check for 'authorized' status:
    • BiannualDroppingCenterFeedbackCron.php
    • VolunteerFeedbackReminderCron.php
    • CollectionCampOutcomeReminderCron.php
    • CollectionCampCron.php
    • VolunteerFeedbackCollectionCampCron.php

The 'Permanently_Closed' check in the query and the 'authorized' status check serve different purposes:

  1. The query filters dropping centers that are permanently closed
  2. The 'authorized' check verifies if the dropping center itself is in an authorized state
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for status definitions and usage
ast-grep --pattern 'Status.Status:name'
rg -A 2 'Collection_Camp_Core_Details.Status'

Length of output: 20249

}
catch (Exception $e) {
\CRM_Core_Error::debug_log_message('Error processing Dropping Center ID: ' . $meta['Dropping_Center_Meta.Dropping_Center']);
\CRM_Core_Error::debug_log_message('Error processing Dropping Center ID: ' . $droppingCenterId . ' - ' . $e->getMessage());
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using structured logging

While the error logging has been improved, consider using a more structured format for better log parsing and monitoring:

- \CRM_Core_Error::debug_log_message('Error processing Dropping Center ID: ' . $droppingCenterId . ' - ' . $e->getMessage());
+ \CRM_Core_Error::debug_log_message(sprintf(
+   'Dropping center feedback processing failed. Center ID: %d, Error: %s, Stack: %s',
+   $droppingCenterId,
+   $e->getMessage(),
+   $e->getTraceAsString()
+ ));
📝 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
\CRM_Core_Error::debug_log_message('Error processing Dropping Center ID: ' . $droppingCenterId . ' - ' . $e->getMessage());
\CRM_Core_Error::debug_log_message(sprintf(
'Dropping center feedback processing failed. Center ID: %d, Error: %s, Stack: %s',
$droppingCenterId,
$e->getMessage(),
$e->getTraceAsString()
));

Comment on lines +62 to +66
$authorizedStatus = $meta['Dropping_Center_Meta.Dropping_Center.Collection_Camp_Core_Details.Status'];
// Trigger only if the status is 'authorized'.
if ($authorizedStatus === 'authorized') {
DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract 'authorized' as a constant

The hardcoded string 'authorized' should be defined as a constant at the class/module level for better maintainability and reusability.

+ const STATUS_AUTHORIZED = 'authorized';
...
- if ($authorizedStatus === 'authorized') {
+ if ($authorizedStatus === self::STATUS_AUTHORIZED) {

Committable suggestion was skipped due to low confidence.

// Send email only if not delivered and not permanently closed
// Send the feedback email.
DroppingCenterFeedbackService::processDroppingCenterStatus($droppingCenterId, $initiatorId, $status, $from);
if (empty($droppingCenterMeta[0])) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think i have added a feedback on your previous PR where we need to change this to single so that we don't need this type of problem, please check that out and try to implement that on another PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants