Skip to content

Add the Update Scheduled Time Job#320

Merged
tarunnjoshi merged 13 commits intodevelopfrom
update-the-scheduled-time-for-logistics-and-feedback-cron
Oct 4, 2024
Merged

Add the Update Scheduled Time Job#320
tarunnjoshi merged 13 commits intodevelopfrom
update-the-scheduled-time-for-logistics-and-feedback-cron

Conversation

@tarunnjoshi
Copy link
Copy Markdown
Member

@tarunnjoshi tarunnjoshi commented Oct 3, 2024

Add the update schd time job

Summary by CodeRabbit

  • New Features
    • Introduced a new API for managing scheduled cron jobs within the Goonjcustom extension.
  • Bug Fixes
    • Implemented error handling for cron job execution, ensuring better stability and logging of issues.
  • Improvements
    • Enhanced scheduling logic to automatically update the run date for cron jobs based on current execution time.
  • Changes
    • Commented out configuration for the 'activities' tab in the CollectionCampService, preserving other tab configurations.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Oct 3, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce the file UpdateScheduledTimeCron.php, which includes three functions for managing scheduled cron jobs in the Goonjcustom API. The first function, _civicrm_api3_goonjcustom_update_scheduled_time_cron_spec, defines the API specification with no parameters required. The second function, civicrm_api3_goonjcustom_update_scheduled_time_cron, processes the cron job logic, managing exceptions and updating scheduled run dates as necessary. A helper function, updateJobScheduledTime, encapsulates the logic for updating job schedules. Additionally, a configuration block for the 'activities' tab has been commented out in the CollectionCampService.php file.

Changes

File Path Change Summary
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/UpdateScheduledTimeCron.php Added functions: _civicrm_api3_goonjcustom_update_scheduled_time_cron_spec (defines API spec), civicrm_api3_goonjcustom_update_scheduled_time_cron (executes cron job logic), and updateJobScheduledTime (updates job scheduled time).
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php Commented out configuration block for the 'activities' tab in the collectionCampTabset method, preserving other tab configurations.

Possibly related PRs

  • Seperate the cron for feedback and logistics #309: The changes in this PR involve separating the cron jobs for feedback and logistics, which is directly related to the management of scheduled cron jobs as introduced in the main PR.
  • Send an email on the start date of the camp #318: This PR modifies the cron job logic to send emails based on the start date of the camp, which relates to the scheduling and timing aspects of cron jobs discussed in the main PR.
  • Change the type of custom field #319: This PR updates the URL construction for the camp vehicle dispatch form, which is relevant to the changes made in the main PR regarding the management of scheduled jobs and their associated parameters.

Suggested reviewers

  • pokhiii

Poem

In the fields where the cron jobs play,
A new script hops in, brightening the day.
With tasks to manage, it leaps with glee,
Handling errors, as smooth as can be!
So here's to the code, fresh and spry,
A rabbit's cheer, as time ticks by! 🐇✨


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

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

1-5: Improve file-level documentation

The file-level documentation block is currently empty. Consider adding a brief description of the file's purpose and its role within the Goonjcustom extension. This will help other developers understand the file's contents and functionality at a glance.

Example improvement:

<?php

/**
 * @file
 * Implements the UpdateScheduledTimeCron API for the Goonjcustom extension.
 * This file contains functions to define and execute a scheduled cron job.
 */

7-18: Update function documentation for accuracy

The function documentation has some inconsistencies:

  1. The function name in the comment is incorrect. It mentions "CollectionCampCron" instead of "UpdateScheduledTimeCron".
  2. The @return annotation doesn't match the actual function behavior (void vs. no return statement).

Please update the documentation to accurately reflect the function:

/**
 * Goonjcustom.UpdateScheduledTimeCron API specification (optional)
 * This is used for documentation and validation.
 *
 * @param array $spec description of fields supported by this API call
 *
 * @return void
 */
function _civicrm_api3_goonjcustom_update_scheduled_cron_spec(&$spec) {
  // There are no parameters for the Goonjcustom cron.
}

37-39: Improve error logging

The current error logging can be improved for better readability and consistency with CiviCRM best practices.

Consider updating the error logging as follows:

catch (Exception $e) {
  \Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
    'error' => $e->getMessage(),
    'exception' => $e,
  ]);
}

This approach uses placeholders and provides more context about where the error occurred.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6ecfc91 and 1232053.

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

Comment on lines +32 to +35
function civicrm_api3_goonjcustom_update_scheduled_cron($params) {
$returnValues = [];
try {

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

Implement the missing cron job logic

The try block is currently empty, which means the cron job is not performing any actions. Implement the necessary logic for updating the scheduled time as per the requirements of your project.

Would you like assistance in outlining the steps for implementing the cron job logic?

Comment on lines +41 to +87
return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_cron');
}
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

Reconsider the unconditional success response

The function currently returns a success response regardless of whether any work was done or if an exception was caught. This may lead to misleading results if the cron job fails.

Consider the following improvements:

  1. Return an error response if an exception is caught.
  2. Only return a success response if the cron job actually performed some work.

Example:

function civicrm_api3_goonjcustom_update_scheduled_cron($params) {
  try {
    $returnValues = []; // Initialize with default value
    
    // Implement cron job logic here
    // If work is done, populate $returnValues with relevant data
    
    if (empty($returnValues)) {
      return civicrm_api3_create_success([], $params, 'Goonjcustom', 'update_scheduled_cron', ['message' => 'No updates were necessary.']);
    }
    
    return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_cron');
  }
  catch (Exception $e) {
    \Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
      'error' => $e->getMessage(),
      'exception' => $e,
    ]);
    return civicrm_api3_create_error('Failed to update scheduled time. Check logs for details.');
  }
}

This approach provides more accurate feedback about the cron job's execution.

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

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

1-74: Summary of review and offer of assistance

The implementation of the scheduled time update cron job is mostly correct, but there are several areas that need improvement:

  1. Clarify the mismatch between the function name and the job being updated.
  2. Improve logging and return values when no update is needed.
  3. Enhance error handling and logging.
  4. Refine the return value to accurately reflect the function's outcome.

These improvements will make the cron job more robust and easier to maintain.

Would you like assistance in implementing these improvements or clarifying any of the suggested changes?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1232053 and 713343e.

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

18-20: LGTM: Spec function is correctly implemented

The specification function follows CiviCRM API conventions and correctly indicates that no parameters are required for this cron job.


57-66: LGTM: Update logic is correctly implemented

The logic for updating the scheduled run date when the current date is past it is implemented correctly. It sets the next scheduled date to 10:00 AM of the next day and updates the job record in the database.


73-73: ⚠️ Potential issue

Improve the return value to reflect the function's outcome

The current implementation always returns a success response, which doesn't accurately reflect the function's outcome. This issue was pointed out in a previous review. To address this:

  1. Return an error response if an exception is caught (as suggested in the error handling comment).
  2. Return a success response with appropriate messages based on the action taken:
    • No update needed
    • Update performed successfully

Example:

if ($updated) {
  return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'Scheduled time updated successfully.']);
} else {
  return civicrm_api3_create_success([], $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'No update was necessary.']);
}

Comment on lines +42 to +51
$jobs = Job::get(TRUE)
->addSelect('scheduled_run_date')
->addWhere('api_action', '=', 'collection_camp_cron')
->execute()->single();
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

Clarify the mismatch between function name and queried job

The function name suggests it's updating the scheduled time, but the query is filtering for a job with api_action = 'collection_camp_cron'. This mismatch could lead to confusion. Consider either:

  1. Renaming the function to match the job it's updating, or
  2. Updating the query to match the intended job for this function.

Please clarify which job this function is intended to update.

Comment on lines +52 to +55
if ($todayDate == $scheduledDate) {
error_log("Hello");
return;
}
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 logging and return value when dates match

When today's date matches the scheduled date, the function logs "Hello" and returns early. Consider the following improvements:

  1. Use a more descriptive log message.
  2. Return a success response indicating no action was needed.

Example:

if ($todayDate == $scheduledDate) {
  \Civi::log()->info("Scheduled date matches current date. No update needed.");
  return civicrm_api3_create_success([], $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'No update needed.']);
}

Comment on lines +69 to +84
catch (Exception $e) {
\Civi::log()->info("Error is there: " . $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.

⚠️ Potential issue

Improve error handling and logging

The current error handling can be improved:

  1. Use \Civi::log()->error() instead of info() for logging exceptions.
  2. Include more details in the log message, such as the exception trace.
  3. Reflect the error in the function's return value.

Example:

catch (Exception $e) {
  \Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
    'error' => $e->getMessage(),
    'trace' => $e->getTraceAsString(),
  ]);
  return civicrm_api3_create_error('Failed to update scheduled time. Check logs for details.');
}

@tarunnjoshi tarunnjoshi requested a review from pokhiii October 3, 2024 11:24
@tarunnjoshi tarunnjoshi self-assigned this Oct 3, 2024
@tarunnjoshi tarunnjoshi changed the title Add the update schd time job Add the Update Scheduled Time Job Oct 3, 2024
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: 4

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

34-36: Consider improving return value initialization

The $returnValues array is initialized but never populated. Consider removing it if it's not needed, or populate it with relevant data about the updates performed.


1-87: Overall assessment: Good foundation with room for improvement

The UpdateScheduledTimeCron.php file provides a good foundation for updating scheduled cron job times in CiviCRM. It follows the API3 conventions and implements the basic functionality correctly. However, there are several areas where the code can be improved:

  1. Error handling and logging can be enhanced to provide better feedback and traceability.
  2. Code duplication in job update logic can be reduced through refactoring.
  3. The return value can be improved to provide more meaningful information about the cron job execution.
  4. Input validation and edge case handling could be added for more robustness.

Implementing the suggested improvements will result in a more maintainable, robust, and informative cron job implementation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 500084a and f0677a9.

📒 Files selected for processing (2)
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (1 hunks)
  • wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/UpdateScheduledTimeCron.php (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php
🔇 Additional comments (2)
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/UpdateScheduledTimeCron.php (2)

18-20: LGTM: API specification function is correctly implemented

The _civicrm_api3_goonjcustom_update_scheduled_time_cron_spec function follows the CiviCRM API3 naming convention and correctly indicates that there are no parameters for this API call. The documentation block is present and follows the standard format.


37-45: LGTM: Date and time setup is well-implemented

The code correctly sets up two different times (10:00 AM and 2:00 PM) for the two jobs. Using clone to create a separate date object is a good practice to avoid unintended modifications.

Comment on lines +48 to +68
$logisticJob = Job::get(TRUE)
->addSelect('scheduled_run_date')
->addWhere('api_action', '=', 'collection_camp_cron')
->execute()->single();

$logisticScheduledRunDate = $logisticJob['scheduled_run_date'];

$feedbackJob = Job::get(TRUE)
->addSelect('scheduled_run_date')
->addWhere('api_action', '=', 'volunteer_feedback_collection_camp_cron')
->execute()->single();

$volunteerScheduledRunDate = $feedbackJob['scheduled_run_date'];

// Update the scheduled run time for logistics mail.
if ($logisticScheduledRunDate != $todayDateTimeForLogistics) {
$results = Job::update(TRUE)
->addValue('scheduled_run_date', $todayDateTimeForLogistics)
->addWhere('api_action', '=', 'collection_camp_cron')
->execute();
}
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

Improve error handling and logging for job updates

While the code correctly fetches and updates the logistics job, consider the following improvements:

  1. Add a check to ensure the job exists before attempting to update it.
  2. Log the results of the update operation for better traceability.
  3. Update the $returnValues array with information about the changes made.

Example:

if (empty($logisticJob)) {
  \Civi::log()->error('Logistics job not found');
  return civicrm_api3_create_error('Logistics job not found');
}

if ($logisticScheduledRunDate != $todayDateTimeForLogistics) {
  $results = Job::update(TRUE)
    ->addValue('scheduled_run_date', $todayDateTimeForLogistics)
    ->addWhere('api_action', '=', 'collection_camp_cron')
    ->execute();
  
  \Civi::log()->info('Updated logistics job scheduled time', ['results' => $results]);
  $returnValues['logistics_job_updated'] = TRUE;
}

This will provide better error handling and logging, making it easier to track the changes made by this cron job.

Comment on lines +55 to +76
$feedbackJob = Job::get(TRUE)
->addSelect('scheduled_run_date')
->addWhere('api_action', '=', 'volunteer_feedback_collection_camp_cron')
->execute()->single();

$volunteerScheduledRunDate = $feedbackJob['scheduled_run_date'];

// Update the scheduled run time for logistics mail.
if ($logisticScheduledRunDate != $todayDateTimeForLogistics) {
$results = Job::update(TRUE)
->addValue('scheduled_run_date', $todayDateTimeForLogistics)
->addWhere('api_action', '=', 'collection_camp_cron')
->execute();
}

// Update the scheduled run time for volunteer feedback mail.
if ($volunteerScheduledRunDate != $todayDateTimeForFeedback) {
$results = Job::update(TRUE)
->addValue('scheduled_run_date', $todayDateTimeForFeedback)
->addWhere('api_action', '=', 'volunteer_feedback_collection_camp_cron')
->execute();
}
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

Refactor job update logic to reduce duplication

The code for updating the volunteer feedback job is very similar to the logistics job update. Consider refactoring this logic into a separate function to reduce duplication and improve maintainability.

Example:

function updateJobSchedule($jobAction, $scheduledTime, &$returnValues) {
  $job = Job::get(TRUE)
    ->addSelect('scheduled_run_date')
    ->addWhere('api_action', '=', $jobAction)
    ->execute()->first();

  if (empty($job)) {
    \Civi::log()->error("Job not found: {$jobAction}");
    return FALSE;
  }

  if ($job['scheduled_run_date'] != $scheduledTime) {
    $results = Job::update(TRUE)
      ->addValue('scheduled_run_date', $scheduledTime)
      ->addWhere('api_action', '=', $jobAction)
      ->execute();
    
    \Civi::log()->info("Updated job scheduled time: {$jobAction}", ['results' => $results]);
    $returnValues["{$jobAction}_updated"] = TRUE;
    return TRUE;
  }

  return FALSE;
}

// Usage:
updateJobSchedule('collection_camp_cron', $todayDateTimeForLogistics, $returnValues);
updateJobSchedule('volunteer_feedback_collection_camp_cron', $todayDateTimeForFeedback, $returnValues);

This refactoring will make the code more maintainable and easier to extend in the future.

Comment on lines +79 to +84
catch (Exception $e) {
\Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
}
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 to return appropriate response

While the error logging is well-implemented, the function currently returns a success response even if an exception occurs. Consider returning an error response when an exception is caught:

catch (Exception $e) {
  \Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
    'error' => $e->getMessage(),
    'trace' => $e->getTraceAsString(),
  ]);
  return civicrm_api3_create_error('Failed to update scheduled time. Check logs for details.');
}

This will ensure that the API caller is aware of any errors that occurred during the execution of the cron job.

]);
}

return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_time_cron');
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 return value to provide meaningful feedback

The current implementation always returns a success response without providing any information about the actions performed. Consider the following improvements:

  1. Populate the $returnValues array with information about the updates made.
  2. Return a success response only if updates were made or a specific condition was met.
  3. Include a message in the response to provide more context.

Example:

if (empty($returnValues)) {
  return civicrm_api3_create_success([], $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'No updates were necessary.']);
}

return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'Scheduled times updated successfully.']);

This will provide more meaningful feedback about the execution of the cron job.

@tarunnjoshi tarunnjoshi force-pushed the update-the-scheduled-time-for-logistics-and-feedback-cron branch from f0677a9 to 0dc7f35 Compare October 4, 2024 04:56
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0dc7f35 and 783b399.

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

18-20: LGTM: API specification function is correct and well-documented.

The specification function correctly indicates that there are no parameters for this API call. The documentation comments follow CiviCRM conventions.

Comment on lines +34 to +59
function civicrm_api3_goonjcustom_update_scheduled_time_cron($params) {
$returnValues = [];
try {
$currentDate = new DateTime();
// Set time to 10:00 AM.
$currentDate->setTime(10, 0, 0);
$todayDateTimeForLogistics = $currentDate->format('Y-m-d H:i:s');

$twoPmDateTime = clone $currentDate;
// Set time to 2:00 PM.
$twoPmDateTime->setTime(14, 0, 0);
$todayDateTimeForFeedback = $twoPmDateTime->format('Y-m-d H:i:s');

// Update scheduled run time for logistics and volunteer feedback.
updateJobScheduledTime('collection_camp_cron', $todayDateTimeForLogistics);
updateJobScheduledTime('volunteer_feedback_collection_camp_cron', $todayDateTimeForFeedback);

} catch (Exception $e) {
\Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
}

return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_time_cron');
}
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

Improve return value and exception handling

While the overall structure of the function has improved, there are two areas that could be enhanced:

  1. The return value doesn't provide meaningful feedback about the actions performed. Consider populating the $returnValues array with information about the updates made and returning a more informative response.

  2. The exception handling could be improved to return an error response when an exception occurs, rather than a success response.

Here's a suggested improvement:

function civicrm_api3_goonjcustom_update_scheduled_time_cron($params) {
  $returnValues = [];
  try {
    // ... (existing code) ...

    $returnValues['logistics_updated'] = updateJobScheduledTime('collection_camp_cron', $todayDateTimeForLogistics);
    $returnValues['feedback_updated'] = updateJobScheduledTime('volunteer_feedback_collection_camp_cron', $todayDateTimeForFeedback);

    if (empty(array_filter($returnValues))) {
      return civicrm_api3_create_success([], $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'No updates were necessary.']);
    }

    return civicrm_api3_create_success($returnValues, $params, 'Goonjcustom', 'update_scheduled_time_cron', ['message' => 'Scheduled times updated successfully.']);
  } catch (Exception $e) {
    \Civi::log()->error('Error in Goonjcustom.UpdateScheduledTimeCron job: {error}', [
      'error' => $e->getMessage(),
      'trace' => $e->getTraceAsString(),
    ]);
    return civicrm_api3_create_error('Failed to update scheduled time. Check logs for details.');
  }
}

This modification provides more meaningful feedback about the execution of the cron job and ensures that API callers are aware of any errors that occurred during execution.

Comment on lines +61 to +77
function updateJobScheduledTime($apiAction, $scheduledRunDate) {
// Fetch the scheduled run date.
$job = Job::get(TRUE)
->addSelect('scheduled_run_date')
->addWhere('api_action', '=', $apiAction)
->execute()->single();

$scheduledRunDateFromDb = $job['scheduled_run_date'];

// Update the scheduled run time if it differs from the current value.
if ($scheduledRunDateFromDb != $scheduledRunDate) {
Job::update(TRUE)
->addValue('scheduled_run_date', $scheduledRunDate)
->addWhere('api_action', '=', $apiAction)
->execute();
}
}
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

Enhance helper function with return value and error handling

The updateJobScheduledTime function effectively reduces code duplication, but it could be improved in the following ways:

  1. Return a boolean value to indicate whether an update was performed.
  2. Add error handling and logging within the function.
  3. Use a more descriptive variable name for the job data.

Here's a suggested improvement:

function updateJobScheduledTime($apiAction, $scheduledRunDate) {
  try {
    // Fetch the scheduled run date.
    $jobData = Job::get(TRUE)
      ->addSelect('scheduled_run_date')
      ->addWhere('api_action', '=', $apiAction)
      ->execute()->single();

    $scheduledRunDateFromDb = $jobData['scheduled_run_date'];

    // Update the scheduled run time if it differs from the current value.
    if ($scheduledRunDateFromDb != $scheduledRunDate) {
      Job::update(TRUE)
        ->addValue('scheduled_run_date', $scheduledRunDate)
        ->addWhere('api_action', '=', $apiAction)
        ->execute();
      \Civi::log()->info("Updated scheduled time for job: {$apiAction}", ['old' => $scheduledRunDateFromDb, 'new' => $scheduledRunDate]);
      return true;
    }
    return false;
  } catch (Exception $e) {
    \Civi::log()->error("Error updating scheduled time for job: {$apiAction}", [
      'error' => $e->getMessage(),
      'trace' => $e->getTraceAsString(),
    ]);
    throw $e; // Re-throw the exception to be caught by the main function
  }
}

These changes will make the helper function more robust and informative, allowing the main function to better track which updates were performed and handle any errors that occur during the update process.

$scheduledRunDateFromDb = $job['scheduled_run_date'];

// Update the scheduled run time if it differs from the current value.
if ($scheduledRunDateFromDb != $scheduledRunDate) {
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 ($scheduledRunDateFromDb != $scheduledRunDate) {
if ($scheduledRunDateFromDb !== $scheduledRunDate) {

@tarunnjoshi tarunnjoshi merged commit 6d3e076 into develop Oct 4, 2024
@tarunnjoshi tarunnjoshi deleted the update-the-scheduled-time-for-logistics-and-feedback-cron branch October 4, 2024 11:08
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.

2 participants