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

Add Activity In Institution related to institution Campaign #633

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

belwalshubham
Copy link
Collaborator

@belwalshubham belwalshubham commented Dec 17, 2024

Add functionality to log an "Institution Campaign" activity in CiviCRM when a campaign is linked to an institution.

Summary by CodeRabbit

  • New Features

    • Introduced functionality to link campaigns to institutions within the CiviCRM system.
    • Added automated logging of activities related to campaigns.
  • Bug Fixes

    • Implemented error handling for activity creation to ensure robust API interactions.

Copy link

coderabbitai bot commented Dec 17, 2024

Warning

Rate limit exceeded

@belwalshubham has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 27 minutes and 6 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c16074d and 2e94b40.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionCampaignService.php (1 hunks)

Walkthrough

The pull request introduces a new InstitutionCampaignService class in the CiviCRM extensions directory. This service is designed to handle campaign-related events, specifically linking campaigns to institutions by creating an activity when a campaign is created or modified. The class uses CiviCRM's event hook system to automatically process campaign information and log relevant organizational activities.

Changes

File Change Summary
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCampaignService.php - Added new service class InstitutionCampaignService
- Implemented event subscription method getSubscribedEvents()
- Created linkCollectionCampToContact() event handler
- Added createCollectionCampOrganizeActivity() for logging campaign-related activities

Sequence Diagram

sequenceDiagram
    participant CiviCRM
    participant InstitutionCampaignService
    participant ActivityLog

    CiviCRM->>InstitutionCampaignService: Campaign Post Event
    InstitutionCampaignService->>InstitutionCampaignService: Validate Campaign
    InstitutionCampaignService->>ActivityLog: Create Campaign Organization Activity
    Note over InstitutionCampaignService: Log activity with campaign details
Loading

Poem

🏛️ In realms of data, campaigns take flight
A service that links with algorithmic might
Institutions dance, activities bloom
Code weaves magic, dispelling the gloom
CiviCRM's symphony, precisely composed! 🎉


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

🧹 Nitpick comments (10)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCampaignService.php (10)

9-11: Provide Class-Level Documentation for InstitutionCampaignService

The class InstitutionCampaignService lacks a descriptive docblock. Adding a meaningful class-level comment will improve code readability and maintainability by explaining the purpose and responsibilities of this class.


14-16: Add Docblock to getSubscribedEvents Method

The method getSubscribedEvents is missing a docblock. Including a brief description of the method's functionality will enhance understanding for other developers.


25-27: Document linkCollectionCampToContact Method

The linkCollectionCampToContact method lacks a docblock detailing its purpose and parameters. Providing this information will aid in code comprehension and maintenance.


28-28: Ensure Consistent Parameter Type Hinting

The parameters of linkCollectionCampToContact are type-hinted, which is good. However, for consistency, consider adding type hints to all methods in the class.


45-47: Remove Redundant Check for $currentInstitutionId

After verifying that $currentInstitutionId is not empty and returning early if it is, the subsequent check before calling createCollectionCampOrganizeActivity is redundant.

Apply this diff to remove the redundant condition:

 if (!$currentInstitutionId) {
   return;
 }
 $campaignTitle = $currentInstitutionCampaign['title'];
 $campaignId = $currentInstitutionCampaign['id'];

-// Check for status change.
-if ($currentInstitutionId) {
   self::createCollectionCampOrganizeActivity($currentInstitutionId, $campaignTitle, $campaignId);
-}

Also applies to: 52-54


57-59: Provide Documentation for createCollectionCampOrganizeActivity Method

The method createCollectionCampOrganizeActivity lacks a docblock. Adding a description of its purpose, along with parameter explanations, will improve code clarity.


60-60: Add Type Hints to createCollectionCampOrganizeActivity Parameters

The method createCollectionCampOrganizeActivity does not have type hints for its parameters. Consistently using type hints enhances code reliability and readability.

Apply this diff to add type hints:

-private static function createCollectionCampOrganizeActivity($currentInstitutionId, $campaignTitle, $campaignId) {
+private static function createCollectionCampOrganizeActivity(int $currentInstitutionId, string $campaignTitle, int $campaignId) {

72-73: Use Appropriate Logging Level for Exceptions

Currently, exceptions are logged using debug, which may not be sufficient for error tracking. Using error level logging will ensure that these exceptions are more visible and can be addressed promptly.

Apply this diff to change the logging level:

-\Civi::log()->debug("Exception while creating Organize Collection Camp activity: " . $ex->getMessage());
+\Civi::log()->error("Exception while creating Organize Collection Camp activity: " . $ex->getMessage());

1-77: Ensure Single Responsibility Principle Is Followed

The InstitutionCampaignService class is handling event subscription, campaign data retrieval, and activity creation. This could be a violation of the Single Responsibility Principle. Consider splitting the code into separate classes or services for handling these distinct responsibilities.


34-41: Avoid Duplicate Code by Creating a Reusable Method for API Calls

The code for making API calls using Campaign::get() and Activity::create() could be refactored into reusable methods or a helper class to reduce duplication and improve maintainability.

Also applies to: 62-69

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3c46818 and c16074d.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionCampaignService.php (1 hunks)

Comment on lines +34 to +41
$institutionCampaign = Campaign::get(TRUE)
->addSelect(
'id',
'Additional_Details.Institution',
'title'
)
->addWhere('id', '=', $objectId)
->execute();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle Potential Empty Result from Campaign::get()

There is no check to ensure that $institutionCampaign contains results before calling $institutionCampaign->first(). If the campaign with the given $objectId does not exist, calling first() may result in an error.

Apply this diff to add a check for empty results:

 $institutionCampaign = Campaign::get(TRUE)
   ->addSelect(
       'id',
       'Additional_Details.Institution',
       'title'
   )
   ->addWhere('id', '=', $objectId)
   ->execute();

+$currentInstitutionCampaign = $institutionCampaign->first();
+if (!$currentInstitutionCampaign) {
+  // Handle the case where the campaign is not found.
+  return;
+}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 61 to 74
try {
$results = Activity::create(FALSE)
->addValue('subject', $campaignTitle)
->addValue('activity_type_id:name', 'Institution Campaign')
->addValue('status_id:name', 'Completed')
->addValue('activity_date_time', date('Y-m-d H:i:s'))
->addValue('source_contact_id', $currentInstitutionId)
->addValue('target_contact_id', $currentInstitutionId)
->execute();

}
catch (\CiviCRM_API4_Exception $ex) {
\Civi::log()->debug("Exception while creating Organize Collection Camp activity: " . $ex->getMessage());
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Catch General Exceptions in Addition to API Exceptions

Only catching \CiviCRM_API4_Exception may cause other exceptions to go unhandled. It's advisable to catch general exceptions to prevent the application from crashing due to unexpected errors.

Apply this diff to catch general exceptions:

 try {
   $results = Activity::create(FALSE)
     ->addValue('subject', $campaignTitle)
     ->addValue('activity_type_id:name', 'Institution Campaign')
     ->addValue('status_id:name', 'Completed')
     ->addValue('activity_date_time', date('Y-m-d H:i:s'))
     ->addValue('source_contact_id', $currentInstitutionId)
     ->addValue('target_contact_id', $currentInstitutionId)
     ->execute();

-}
-catch (\CiviCRM_API4_Exception $ex) {
-  \Civi::log()->error("Exception while creating Organize Collection Camp activity: " . $ex->getMessage());
+} catch (\Exception $ex) {
+  \Civi::log()->error("An error occurred while creating the activity: " . $ex->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
try {
$results = Activity::create(FALSE)
->addValue('subject', $campaignTitle)
->addValue('activity_type_id:name', 'Institution Campaign')
->addValue('status_id:name', 'Completed')
->addValue('activity_date_time', date('Y-m-d H:i:s'))
->addValue('source_contact_id', $currentInstitutionId)
->addValue('target_contact_id', $currentInstitutionId)
->execute();
}
catch (\CiviCRM_API4_Exception $ex) {
\Civi::log()->debug("Exception while creating Organize Collection Camp activity: " . $ex->getMessage());
}
try {
$results = Activity::create(FALSE)
->addValue('subject', $campaignTitle)
->addValue('activity_type_id:name', 'Institution Campaign')
->addValue('status_id:name', 'Completed')
->addValue('activity_date_time', date('Y-m-d H:i:s'))
->addValue('source_contact_id', $currentInstitutionId)
->addValue('target_contact_id', $currentInstitutionId)
->execute();
} catch (\Exception $ex) {
\Civi::log()->error("An error occurred while creating the activity: " . $ex->getMessage());
}

Comment on lines +44 to +47
$currentInstitutionId = $currentInstitutionCampaign['Additional_Details.Institution'];
if (!$currentInstitutionId) {
return;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check for Undefined Index in Data Retrieval

When accessing $currentInstitutionCampaign['Additional_Details.Institution'], there's a risk of an undefined index if the 'Additional_Details.Institution' key is missing. This could lead to a PHP notice or error.

Apply this diff to ensure the index exists before accessing it:

 $currentInstitutionId = $currentInstitutionCampaign['Additional_Details.Institution'];
+if (!isset($currentInstitutionCampaign['Additional_Details.Institution'])) {
+  return;
+}

Committable suggestion skipped: line range outside the PR's diff.

@belwalshubham belwalshubham self-assigned this Dec 17, 2024
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