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

Feat/assign to chapter group #617

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

Conversation

belwalshubham
Copy link
Collaborator

@belwalshubham belwalshubham commented Dec 13, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced functionality for assigning chapter groups to individuals, accommodating multiple institution types.
    • Introduced a new method for linking collection camps to contacts, including activity creation upon status changes.
  • Bug Fixes

    • Improved error handling and logging for missing IDs in group assignments.

Copy link

coderabbitai bot commented Dec 13, 2024

Walkthrough

The pull request introduces modifications to the InstitutionService and InstitutionCollectionCampService classes within the Civi namespace. Key changes in InstitutionService include an updated method signature for assignChapterGroupToIndividual, the addition of an assignments array for improved logic handling, and enhanced error logging. In InstitutionCollectionCampService, a new method linkInstitutionCollectionCampToContact is added, along with two private methods to create activities. These changes enhance functionality and improve error handling across the services.

Changes

File Path Change Summary
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php - Added imports for Civi\Api4\Group and Civi\Api4\GroupContact.
- Updated method signature of assignChapterGroupToIndividual to accept a variable type for $objectId.
- Expanded logic to include an assignments array for field mapping and improved validation.
- Updated logging for missing IDs and changed return value to TRUE.
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php - Added method linkInstitutionCollectionCampToContact for linking collection camps to contacts.
- Introduced private methods createCollectionCampOrganizeActivity and createActivity for activity creation.
- Updated getSubscribedEvents to include the new method.

Possibly related PRs

Suggested labels

status : ready for review

Suggested reviewers

  • tarunnjoshi

🎉 In the realm of code, a change has begun,
assignChapterGroupToIndividual shines like the sun.
With logic refined and errors now logged,
The path is clearer, no longer a fog.
So raise up your glasses, let’s cheer and rejoice,
For clean code and structure, let's all raise our voice! 🎊


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. (Experiment)
  • @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: 1

🧹 Outside diff range and nitpick comments (3)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php (3)

94-105: Replace magic strings with constants in the $assignments array

Using hardcoded strings for assignment keys and field names can lead to errors and makes the code harder to maintain. Consider defining constants for the keys like 'Institution Collection Camp' and field names within the class or in a configuration file. This will enhance readability and make future modifications easier.


130-135: Eliminate code duplication when adding contacts to the group

To adhere to the DRY (Don't Repeat Yourself) principle, consider collecting the contact IDs into an array and iterating over them. This reduces code duplication and simplifies the addition of more contacts in the future.

Apply this diff to refactor the code:

 if ($groupId) {
-    self::addContactToGroup($contactId, $groupId);
-    if ($organizationId) {
-        self::addContactToGroup($organizationId, $groupId);
-    }
+    $contactIds = [$contactId];
+    if ($organizationId) {
+        $contactIds[] = $organizationId;
+    }
+    foreach ($contactIds as $id) {
+        self::addContactToGroup($id, $groupId);
+    }
 }

92-137: Refactor assignChapterGroupToIndividual to follow the Single Responsibility Principle

The assignChapterGroupToIndividual method handles multiple responsibilities, including validation, data retrieval, error logging, and group assignment. Breaking this method into smaller, focused functions will enhance readability, promote reusability, and adhere to the Single Responsibility Principle.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d1c89f and ef03d00.

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

return;
if ($objectName !== 'Eck_Collection_Camp' || empty($objectRef['title']) || $objectRef['title'] !== 'Institution Collection Camp') {
return FALSE;
public static function assignChapterGroupToIndividual(string $op, string $objectName, $objectId, &$objectRef) {
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ensure consistent parameter type for $objectId

The type hint for $objectId has been changed from int to untyped. This could lead to type safety issues or unexpected behavior if non-integer values are passed. Consider specifying the expected type(s) for $objectId or using appropriate type declarations to maintain type safety.

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

🧹 Outside diff range and nitpick comments (2)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (2)

53-78: Define status constants for better maintainability

Magic strings for status values make the code harder to maintain and more prone to errors.

+    private const STATUS_AUTHORIZED = 'authorized';
+
     public static function linkCollectionCampToContact(string $op, string $objectName, $objectId, &$objectRef) {
         // ...
-        if ($currentStatus !== $newStatus && $newStatus === 'authorized') {
+        if ($currentStatus !== $newStatus && $newStatus === self::STATUS_AUTHORIZED) {

81-103: Enhance error handling in createCollectionCampOrganizeActivity

The catch block only logs the error. Consider:

  1. Using more specific exception types
  2. Providing more context in the error message
  3. Potentially rethrowing critical errors
-    } catch (\CiviCRM_API4_Exception $ex) {
-        \Civi::log()->debug("Exception while creating Organize Collection Camp activity: " . $ex->getMessage());
+    } catch (\CiviCRM_API4_Exception $ex) {
+        $context = [
+            'collection_camp_id' => $collectionCampId,
+            'poc_id' => $PocId,
+            'organization_id' => $organizationId
+        ];
+        \Civi::log()->error(
+            "Failed to create Collection Camp activity: " . $ex->getMessage(),
+            ['context' => $context]
+        );
+        // Optionally rethrow if this is a critical error
+        throw $ex;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ef03d00 and 937ce81.

📒 Files selected for processing (2)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (2 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php (3 hunks)
🔇 Additional comments (3)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php (2)

9-10: LGTM: Clean import additions

The new imports for Group and GroupContact APIs are properly organized and follow the existing pattern.


92-92: Verify impact of parameter type change

The type hint for $objectId has been removed. This could impact type safety if non-integer values are passed.

Let's verify all callers of this method:

#!/bin/bash
# Search for all calls to assignChapterGroupToIndividual
rg -l "assignChapterGroupToIndividual" | while read -r file; do
    echo "=== $file ==="
    rg -A 2 "assignChapterGroupToIndividual" "$file"
done
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (1)

38-38: LGTM: Event subscription addition is well-placed

The new event handler is correctly added to the existing pre-hook subscriptions.

@@ -26,7 +28,7 @@ public static function getSubscribedEvents() {
'&hook_civicrm_post' => [
['organizationCreated'],
['setOfficeDetails'],
['assignChapterGroupToIndividual'],
// ['assignChapterGroupToIndividual'],
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid commenting out event subscriptions without proper cleanup

The commented-out event subscription could lead to:

  1. Dead code if not properly cleaned up
  2. Breaking changes if other parts of the system depend on this hook
  3. Confusion about the intended state of the feature

Either remove the line completely or document why it's temporarily disabled.

Comment on lines +92 to +137
// public static function assignChapterGroupToIndividual(string $op, string $objectName, $objectId, &$objectRef) {
// // Define the assignments array
// $assignments = [
// 'Institution Collection Camp' => [
// 'stateField' => 'Institution_Collection_Camp_Intent.State',
// 'contactField' => 'Institution_Collection_Camp_Intent.Institution_POC',
// 'organizationField' => 'Institution_Collection_Camp_Intent.Organization_Name'
// ],
// 'Institution Dropping Center' => [
// 'stateField' => 'Institution_Dropping_Center_Intent.State',
// 'contactField' => 'Institution_Dropping_Center_Intent.Institution_POC',
// 'organizationField' => 'Institution_Dropping_Center_Intent.Organization_Name'
// ]
// ];



// // Validate objectName and objectRef
// if ($objectName !== 'Eck_Collection_Camp' || empty($objectRef['title']) || !isset($assignments[$objectRef['title']])) {
// return FALSE;
// }

// $assignment = $assignments[$objectRef['title']];

// // Access fields using array syntax
// $stateId = $objectRef[$assignment['stateField']] ?? NULL;
// $contactId = $objectRef[$assignment['contactField']] ?? NULL;
// $organizationId = $objectRef[$assignment['organizationField']] ?? NULL;

// if (!$stateId || !$contactId) {
// \Civi::log()->info("Missing Contact ID or State ID for " . $objectRef['title']);
// return FALSE;
// }

// // Get the group and add contacts
// $groupId = self::getChapterGroupForState($stateId);

// if ($groupId) {
// self::addContactToGroup($contactId, $groupId);
// if ($organizationId) {
// self::addContactToGroup($organizationId, $groupId);
// }
// }

// return TRUE;
// }
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor commented implementation for better maintainability

The commented-out implementation has several areas for improvement:

  1. Move the assignments array to a configuration file or class constant to improve maintainability
  2. Break down the method into smaller, focused methods following Single Responsibility Principle
  3. Consider using enums or constants for the title strings to prevent typos

Here's a suggested refactor:

private const INSTITUTION_ASSIGNMENTS = [
    self::INSTITUTION_COLLECTION_CAMP => [
        'stateField' => 'Institution_Collection_Camp_Intent.State',
        'contactField' => 'Institution_Collection_Camp_Intent.Institution_POC',
        'organizationField' => 'Institution_Collection_Camp_Intent.Organization_Name'
    ],
    self::INSTITUTION_DROPPING_CENTER => [
        'stateField' => 'Institution_Dropping_Center_Intent.State',
        'contactField' => 'Institution_Dropping_Center_Intent.Institution_POC',
        'organizationField' => 'Institution_Dropping_Center_Intent.Organization_Name'
    ]
];

public static function assignChapterGroupToIndividual(string $op, string $objectName, $objectId, &$objectRef) {
    if (!self::isValidAssignment($objectName, $objectRef)) {
        return FALSE;
    }

    $assignment = self::INSTITUTION_ASSIGNMENTS[$objectRef['title']];
    $ids = self::extractAssignmentIds($objectRef, $assignment);
    
    if (!self::areIdsValid($ids)) {
        return FALSE;
    }

    return self::processGroupAssignment($ids);
}

private static function isValidAssignment(string $objectName, array $objectRef): bool {
    return $objectName === 'Eck_Collection_Camp' 
        && !empty($objectRef['title']) 
        && isset(self::INSTITUTION_ASSIGNMENTS[$objectRef['title']]);
}

private static function extractAssignmentIds(array $objectRef, array $assignment): array {
    return [
        'stateId' => $objectRef[$assignment['stateField']] ?? NULL,
        'contactId' => $objectRef[$assignment['contactField']] ?? NULL,
        'organizationId' => $objectRef[$assignment['organizationField']] ?? NULL,
    ];
}

private static function areIdsValid(array $ids): bool {
    if (!$ids['stateId'] || !$ids['contactId']) {
        \Civi::log()->info("Missing Contact ID or State ID");
        return FALSE;
    }
    return TRUE;
}

private static function processGroupAssignment(array $ids): bool {
    $groupId = self::getChapterGroupForState($ids['stateId']);
    if (!$groupId) {
        return FALSE;
    }

    self::addContactToGroup($ids['contactId'], $groupId);
    if ($ids['organizationId']) {
        self::addContactToGroup($ids['organizationId'], $groupId);
    }

    return TRUE;
}

Comment on lines 105 to 111
private static function createActivity($contactId, $activityData) {
Activity::create(FALSE)
->addValue('source_contact_id', $contactId)
->addValue('target_contact_id', $contactId)
->addValues($activityData)
->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

Add error handling to createActivity method

The method should handle potential API exceptions to prevent silent failures.

 private static function createActivity($contactId, $activityData) {
+    try {
         Activity::create(FALSE)
             ->addValue('source_contact_id', $contactId)
             ->addValue('target_contact_id', $contactId)
             ->addValues($activityData)
             ->execute();
+    } catch (\CiviCRM_API4_Exception $ex) {
+        \Civi::log()->error(
+            "Failed to create activity for contact {$contactId}: " . $ex->getMessage(),
+            ['activity_data' => $activityData]
+        );
+        throw $ex;
+    }
 }
📝 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
private static function createActivity($contactId, $activityData) {
Activity::create(FALSE)
->addValue('source_contact_id', $contactId)
->addValue('target_contact_id', $contactId)
->addValues($activityData)
->execute();
}
private static function createActivity($contactId, $activityData) {
try {
Activity::create(FALSE)
->addValue('source_contact_id', $contactId)
->addValue('target_contact_id', $contactId)
->addValues($activityData)
->execute();
} catch (\CiviCRM_API4_Exception $ex) {
\Civi::log()->error(
"Failed to create activity for contact {$contactId}: " . $ex->getMessage(),
['activity_data' => $activityData]
);
throw $ex;
}
}

Comment on lines 48 to 79
public static function linkCollectionCampToContact(string $op, string $objectName, $objectId, &$objectRef) {
if ($objectName !== 'Eck_Collection_Camp' || !$objectId) {
return;
}

$newStatus = $objectRef['Collection_Camp_Core_Details.Status'] ?? '';
if (!$newStatus) {
return;
}

$collectionCamps = EckEntity::get('Collection_Camp', FALSE)
->addSelect('Collection_Camp_Core_Details.Status', 'Institution_Collection_Camp_Intent.Organization_Name', 'title', 'Institution_Collection_Camp_Intent.Institution_POC')
->addWhere('id', '=', $objectId)
->execute();

$currentCollectionCamp = $collectionCamps->first();
$currentStatus = $currentCollectionCamp['Collection_Camp_Core_Details.Status'];
$PocId = $currentCollectionCamp['Institution_Collection_Camp_Intent.Institution_POC'];
$organizationId = $currentCollectionCamp['Institution_Collection_Camp_Intent.Organization_Name'];

if (!$PocId && !$organizationId) {
return;
}

$collectionCampTitle = $currentCollectionCamp['title'];
$collectionCampId = $currentCollectionCamp['id'];

// Check for status change and handle activity creation
if ($currentStatus !== $newStatus && $newStatus === 'authorized') {
self::createCollectionCampOrganizeActivity($PocId, $organizationId, $collectionCampTitle, $collectionCampId);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring to improve separation of concerns

The linkCollectionCampToContact method handles multiple responsibilities. Consider splitting it into smaller, focused methods:

  • Status validation
  • Collection camp data retrieval
  • Activity creation orchestration
-public static function linkCollectionCampToContact(string $op, string $objectName, $objectId, &$objectRef) {
+private static function validateCollectionCampStatus(string $objectName, $objectId, $newStatus): bool {
+    return $objectName === 'Eck_Collection_Camp' && $objectId && $newStatus;
+}
+
+private static function getCollectionCampData($objectId) {
+    return EckEntity::get('Collection_Camp', FALSE)
+        ->addSelect(
+            'Collection_Camp_Core_Details.Status',
+            'Institution_Collection_Camp_Intent.Organization_Name',
+            'title',
+            'Institution_Collection_Camp_Intent.Institution_POC'
+        )
+        ->addWhere('id', '=', $objectId)
+        ->execute()
+        ->first();
+}
+
+public static function linkCollectionCampToContact(string $op, string $objectName, $objectId, &$objectRef) {
+    $newStatus = $objectRef['Collection_Camp_Core_Details.Status'] ?? '';
+    if (!self::validateCollectionCampStatus($objectName, $objectId, $newStatus)) {
+        return;
+    }
+
+    $currentCollectionCamp = self::getCollectionCampData($objectId);

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

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

🧹 Outside diff range and nitpick comments (2)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (2)

51-81: Consider breaking down the method for better maintainability

The method handles multiple responsibilities:

  1. Validation
  2. Data retrieval
  3. Status comparison
  4. Activity creation

Consider extracting these into separate private methods for better maintainability and testability.

-public static function linkInstitutionCollectionCampToContact(string $op, string $objectName, $objectId, &$objectRef) {
+private static function validateCollectionCampInput(string $objectName, $objectId, $newStatus): bool {
+  return $objectName === 'Eck_Collection_Camp' && $objectId && $newStatus;
+}
+
+private static function getCollectionCampDetails($objectId) {
+  return EckEntity::get('Collection_Camp', FALSE)
+    ->addSelect(
+      'Collection_Camp_Core_Details.Status',
+      'Institution_Collection_Camp_Intent.Organization_Name',
+      'title',
+      'Institution_Collection_Camp_Intent.Institution_POC'
+    )
+    ->addWhere('id', '=', $objectId)
+    ->execute()
+    ->first();
+}
+
+public static function linkInstitutionCollectionCampToContact(string $op, string $objectName, $objectId, &$objectRef) {
+  $newStatus = $objectRef['Collection_Camp_Core_Details.Status'] ?? '';
+  if (!self::validateCollectionCampInput($objectName, $objectId, $newStatus)) {
+    return;
+  }
+
+  $currentCollectionCamp = self::getCollectionCampDetails($objectId);

Line range hint 1-1000: Consider splitting the class into smaller services

The InstitutionCollectionCampService class has grown to handle multiple concerns:

  • Collection camp management
  • Email notifications
  • Activity creation
  • Coordinator assignment
  • Office management

Consider splitting these into separate services:

  • CollectionCampActivityService
  • CollectionCampNotificationService
  • CollectionCampCoordinatorService

This would improve maintainability and adhere better to the Single Responsibility Principle.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 937ce81 and 5d0c1b1.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (2 hunks)
🔇 Additional comments (2)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (2)

106-118: ⚠️ Potential issue

Add error handling to createActivity method

The method should handle potential API exceptions to prevent silent failures.

 private static function createActivity($contactId, $collectionCampTitle, $collectionCampId) {
+  try {
     Activity::create(FALSE)
       ->addValue('subject', $collectionCampTitle)
       ->addValue('activity_type_id:name', 'Organize Collection Camp')
       ->addValue('status_id:name', 'Authorized')
       ->addValue('activity_date_time', date('Y-m-d H:i:s'))
       ->addValue('source_contact_id', $contactId)
       ->addValue('target_contact_id', $contactId)
       ->addValue('Collection_Camp_Data.Collection_Camp_ID', $collectionCampId)
       ->execute();
 
     \Civi::log()->info("Activity created for contact {$contactId} for Institution Collection Camp {$collectionCampTitle}");
+  } catch (\CiviCRM_API4_Exception $ex) {
+    \Civi::log()->error(
+      "Failed to create activity for contact {$contactId}: " . $ex->getMessage(),
+      ['collection_camp' => $collectionCampTitle]
+    );
+    throw $ex;
+  }
 }

Likely invalid or redundant comment.


38-38: Verify hook implementation order

The new hook implementation is added to the hook_civicrm_pre event. Ensure that the order of execution doesn't affect other hooks in the chain.

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