Skip to content

Show contribution count on Outcome form#496

Merged
tarunnjoshi merged 2 commits intodevelopfrom
show-contribution-on-outcome
Nov 26, 2024
Merged

Show contribution count on Outcome form#496
tarunnjoshi merged 2 commits intodevelopfrom
show-contribution-on-outcome

Conversation

@tarunnjoshi
Copy link
Copy Markdown
Member

@tarunnjoshi tarunnjoshi commented Nov 25, 2024

Show contribution count on Outcome form
image

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Introduced a method to update and track contribution counts for collection camps.
  • Bug Fixes
    • Updated the method for contribution count tracking to ensure accurate data handling in camp status updates.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 25, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce a new method, updateContributionCount, to the CollectionCampService class, which calculates and updates the total contributions for a specific collection camp. Additionally, the existing method updateCampStatusAfterAuth is modified to update the camp status to 'planned' when the new status is 'authorized'. The CollectionCampCron API function is updated to call the new contribution counting method, reflecting a shift in how contributions are managed.

Changes

File Path Change Summary
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php - Added method public static function updateContributionCount($collectionCamp).
- Modified updateCampStatusAfterAuth to update status to 'planned' when new status is 'authorized'.
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/CollectionCampCron.php - Updated method call from updateContributorCount to updateContributionCount in civicrm_api3_goonjcustom_collection_camp_cron.

Possibly related PRs

Suggested reviewers

  • pokhiii

🎉 In the land of code where changes flow,
Contributions counted, watch them grow!
Camp statuses shift with a planned embrace,
In the realm of Civi, we quicken the pace.
With methods anew, our functions align,
Here's to the updates, oh how they shine! ✨


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 (2)
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/CollectionCampCron.php (1)

Line range hint 77-83: Enhance error logging for better debugging

While the error handling captures basic information, it could be more helpful for debugging production issues.

Consider enhancing the error logging like this:

-      \Civi::log()->info('Error processing camp', [
-        'id' => $camp['id'],
-        'error' => $e->getMessage(),
-      ]);
+      \Civi::log()->error('Error processing collection camp', [
+        'camp_id' => $camp['id'],
+        'camp_title' => $camp['title'],
+        'error_message' => $e->getMessage(),
+        'error_trace' => $e->getTraceAsString(),
+        'operation' => 'cron_processing',
+      ]);
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (1)

Line range hint 27-1456: Consider refactoring the service class to improve maintainability

The CollectionCampService class has grown too large and handles multiple responsibilities, including:

  • Collection camp management
  • Email notifications
  • QR code generation
  • Activity tracking
  • Contribution management
  • Form handling

This violates the Single Responsibility Principle and makes the code harder to maintain and test.

Consider breaking down this class into smaller, focused services:

  1. CollectionCampManager - Core camp management
  2. CollectionCampNotificationService - Email notifications
  3. CollectionCampQRCodeService - QR code generation
  4. CollectionCampActivityTracker - Activity tracking
  5. CollectionCampContributionService - Contribution management
  6. CollectionCampFormHandler - Form handling

Example refactoring for the contribution-related functionality:

class CollectionCampContributionService {
    private $logger;
    private $entityManager;
    
    public function __construct(LoggerInterface $logger, EntityManagerInterface $entityManager) {
        $this->logger = $logger;
        $this->entityManager = $entityManager;
    }
    
    public function updateContributionCount(CollectionCamp $collectionCamp): void {
        // Implementation moved from static method
    }
    
    public function updateContributorCount(CollectionCamp $collectionCamp): void {
        // Implementation moved from static method
    }
}

This refactoring would:

  1. Improve testability by allowing dependency injection
  2. Make the code more maintainable by separating concerns
  3. Make it easier to modify or extend individual components
  4. Reduce the risk of breaking unrelated functionality
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8248a5e and c8de629.

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

CollectionCampService::sendLogisticsEmail($camp);
CollectionCampService::updateContributorCount($camp);

CollectionCampService::updateContributionCount($camp);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codebase verification

The two count methods serve distinct purposes - no duplication concern

Looking at the implementations, these methods track different metrics:

  • updateContributorCount: Counts unique contributors (activities) for a collection camp
  • updateContributionCount: Calculates the total monetary amount of contributions

The sequential calls are justified as they update different business metrics. However, there are a few suggestions for improvement:

  • The updateContributionCount method has is_test = TRUE condition which seems suspicious - this might be filtering out real contributions
  • Consider adding PHPDoc comments to document the distinct purpose of each method
  • Consider combining these updates in a transaction if your database supports it
🔗 Analysis chain

Clarify the distinction between contributor and contribution counts

The code now calls both updateContributorCount and updateContributionCount sequentially. This raises several concerns:

  1. Are these counts measuring different things? If so, the distinction should be documented.
  2. If they're related, could they be combined into a single update operation?
  3. Multiple database updates in sequence might impact performance.

Let's check the implementation of both methods to understand their differences:

Consider the following improvements:

  1. If these are truly separate counts, add documentation explaining their purposes
  2. If they're related, consider combining them into a single update operation
  3. Consider wrapping related updates in a transaction for better data consistency

The previous ast-grep command had issues with some files, so let's try using ripgrep instead to find these method implementations. This will help us understand if they serve different purposes or if there's potential duplication.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for both count update methods to compare their implementations
ast-grep --pattern 'function updateContributorCount($_) {
  $$$
}'

ast-grep --pattern 'function updateContributionCount($_) {
  $$$
}'

Length of output: 18682


Script:

#!/bin/bash
# Let's try a different approach using ripgrep to find these methods
rg -U "function updateContributor(Count|Count)" --type php -A 10
rg -U "function updateContribution(Count|Count)" --type php -A 10

# Also search for the class definition to understand the context
rg "class CollectionCampService" --type php -A 5

Length of output: 3199

Comment on lines +1262 to +1281
public static function updateContributionCount($collectionCamp) {
$contributions = Contribution::get(FALSE)
->addSelect('total_amount')
->addWhere('Contribution_Details.Source', '=', $collectionCamp['id'])
->addWhere('is_test', '=', TRUE)
->execute();

// Initialize sum variable.
$totalSum = 0;

// Iterate through the results and sum the total_amount.
foreach ($contributions as $contribution) {
$totalSum += $contribution['total_amount'];
}

EckEntity::update('Collection_Camp', FALSE)
->addValue('Camp_Outcome.Monitory_Contribution', $totalSum)
->addWhere('id', '=', $collectionCamp['id'])
->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.

⚠️ Potential issue

Critical: Fix contribution query filter and add error handling

The implementation has several issues that need to be addressed:

  1. The query filter is_test = TRUE will only return test contributions, which is likely incorrect. Production contributions will be excluded.
  2. Missing error handling for database operations.
  3. No validation of the input parameter.
  4. Direct floating-point arithmetic on monetary values could lead to precision issues.

Apply this diff to fix the issues:

  public static function updateContributionCount($collectionCamp) {
+   if (empty($collectionCamp['id'])) {
+     \Civi::log()->error('updateContributionCount: Invalid collection camp');
+     return;
+   }
+   
+   try {
      $contributions = Contribution::get(FALSE)
        ->addSelect('total_amount')
        ->addWhere('Contribution_Details.Source', '=', $collectionCamp['id'])
-       ->addWhere('is_test', '=', TRUE)
+       ->addWhere('is_test', '=', FALSE)
        ->execute();

      // Initialize sum variable using BCMath for precision
-     $totalSum = 0;
+     $totalSum = '0.00';

      // Iterate through the results and sum the total_amount
      foreach ($contributions as $contribution) {
-       $totalSum += $contribution['total_amount'];
+       $totalSum = bcadd($totalSum, $contribution['total_amount'], 2);
      }

      EckEntity::update('Collection_Camp', FALSE)
        ->addValue('Camp_Outcome.Monitory_Contribution', $totalSum)
        ->addWhere('id', '=', $collectionCamp['id'])
        ->execute();
+   } catch (\Exception $e) {
+     \Civi::log()->error('Error updating contribution count: ' . $e->getMessage());
+   }
  }
📝 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
public static function updateContributionCount($collectionCamp) {
$contributions = Contribution::get(FALSE)
->addSelect('total_amount')
->addWhere('Contribution_Details.Source', '=', $collectionCamp['id'])
->addWhere('is_test', '=', TRUE)
->execute();
// Initialize sum variable.
$totalSum = 0;
// Iterate through the results and sum the total_amount.
foreach ($contributions as $contribution) {
$totalSum += $contribution['total_amount'];
}
EckEntity::update('Collection_Camp', FALSE)
->addValue('Camp_Outcome.Monitory_Contribution', $totalSum)
->addWhere('id', '=', $collectionCamp['id'])
->execute();
}
public static function updateContributionCount($collectionCamp) {
if (empty($collectionCamp['id'])) {
\Civi::log()->error('updateContributionCount: Invalid collection camp');
return;
}
try {
$contributions = Contribution::get(FALSE)
->addSelect('total_amount')
->addWhere('Contribution_Details.Source', '=', $collectionCamp['id'])
->addWhere('is_test', '=', FALSE)
->execute();
// Initialize sum variable using BCMath for precision
$totalSum = '0.00';
// Iterate through the results and sum the total_amount
foreach ($contributions as $contribution) {
$totalSum = bcadd($totalSum, $contribution['total_amount'], 2);
}
EckEntity::update('Collection_Camp', FALSE)
->addValue('Camp_Outcome.Monitory_Contribution', $totalSum)
->addWhere('id', '=', $collectionCamp['id'])
->execute();
} catch (\Exception $e) {
\Civi::log()->error('Error updating contribution count: ' . $e->getMessage());
}
}

$contributions = Contribution::get(FALSE)
->addSelect('total_amount')
->addWhere('Contribution_Details.Source', '=', $collectionCamp['id'])
->addWhere('is_test', '=', TRUE)
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 don't think this is right.

We should do both IN , [TRUE, FALSE]

Copy link
Copy Markdown
Member Author

@tarunnjoshi tarunnjoshi Nov 26, 2024

Choose a reason for hiding this comment

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

For both ->addWhere('is_test', 'IS NOT NULL') this one gave all the results contains yes and no both,but when i trying to do ->addWhere('is_test', 'IN', ['true,false']) then it gave me only TRUE results.

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