Skip to content

Refactor: Institution Relationship#602

Merged
belwalshubham merged 2 commits intodevelopfrom
feat/resolve-feedbacks
Dec 11, 2024
Merged

Refactor: Institution Relationship#602
belwalshubham merged 2 commits intodevelopfrom
feat/resolve-feedbacks

Conversation

@belwalshubham
Copy link
Copy Markdown
Collaborator

@belwalshubham belwalshubham commented Dec 11, 2024

Description

  1. Refactor Institution Relationship
  2. Code cleanups

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request involve modifications to the InstitutionCollectionCampService, InstitutionService, and related classes, focusing on updating relationship type mappings and control flow adjustments. The assignCoordinatorByRelationshipType method now uses more general terms for mapping registration categories. The getRelationshipTypeName method in InstitutionService has reorganized its relationship type mappings, while error handling has been improved in the getChapterGroupForState method. Additionally, a cron job's data source for footfall calculations has been corrected.

Changes

File Path Change Summary
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php Updated assignCoordinatorByRelationshipType method to simplify mapping of registration categories.
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php Altered getRelationshipTypeName method mappings; modified assignChapterGroupToIndividual to return immediately; enhanced error logging in getChapterGroupForState.
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/InstitutionDroppingCenterOutcomeCron.php Corrected data source for $totalFootfall calculation in civicrm_api3_goonjcustom_institution_dropping_center_outcome_cron.
wp-content/civi-extensions/goonjcustom/Civi/InstitutionDroppingCenterService.php Modified mailNotificationToMmt method to update variable assignments and improve email content accuracy.

Possibly related PRs

  • Assign Coordinating POC Based on Type of institution and state #519: The assignCoordinatorByRelationshipType method in the main PR directly relates to the changes in the InstitutionCollectionCampService class, which includes new methods for assigning coordinators based on relationship types and state office IDs.
  • Generate Institution collection camp title #475: The changes in the getStateIdForSubtype method in the main PR are relevant as they enhance the logic for determining state IDs based on camp titles, which is also a focus in the InstitutionCollectionCampService modifications.
  • Send Institution Dropping Center Dispatch and Ack. Email #557: The mailNotificationToMmt method in the main PR is related to the changes in the InstitutionDroppingCenterService, which include enhancements to email notifications for the Material Management Team.
  • Add Institution Dropping Center Outcome #590: The cron job functionality introduced in the main PR for updating metrics is related to the new cron job for the institution dropping center outcomes, indicating a broader context of automated updates in both PRs.

Suggested labels

status : ready for review

Suggested reviewers

  • tarunnjoshi
  • pokhiii

🎉 In the realm of code, changes unfold,
Mappings refined, new stories told.
Coordinators assigned with a simpler name,
Footfalls counted, accuracy the aim.
With logs that guide, and flows that shine,
This PR brings order, oh so divine! 🌟


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
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

298-300: Consider using constants for relationship type names.

The relationship type mappings use string literals which could lead to maintenance issues if these values need to be changed across the codebase.

Consider defining these as class constants:

+ const RELATIONSHIP_TYPE_FOUNDATION = 'Foundation Coordinator of';
+ const RELATIONSHIP_TYPE_EDUCATION = 'Education Institute Coordinator of';
+ const RELATIONSHIP_TYPE_ASSOCIATIONS = 'Associations Coordinator of';

  private static function getRelationshipTypeName($contactId) {
    // ...
    $typeToRelationshipMap = [
-     'Foundation'   => 'Foundation Coordinator of',
-     'Education'    => 'Education Institute Coordinator of',
-     'Associations' => 'Associations Coordinator of',
+     'Foundation'   => self::RELATIONSHIP_TYPE_FOUNDATION,
+     'Education'    => self::RELATIONSHIP_TYPE_EDUCATION,
+     'Associations' => self::RELATIONSHIP_TYPE_ASSOCIATIONS,
      // ...
    ];
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (1)

Line range hint 556-577: Refactor method to improve separation of concerns.

The assignCoordinatorByRelationshipType method has multiple responsibilities: mapping types, finding coordinators, and updating entities. This makes it harder to maintain and test.

Consider breaking it down into smaller, focused methods:

private function getRelationshipTypeForRegistration($registrationType) {
    $registrationCategory = trim($registrationType['Institution_Collection_Camp_Intent.You_wish_to_register_as:name']);
    return $this->relationshipTypeMap[$registrationCategory] ?? 'Other Entities Coordinator of';
}

private function updateCollectionCampCoordinator($collectionCampId, $coordinatorId) {
    return EckEntity::update('Collection_Camp', FALSE)
        ->addValue('Institution_collection_camp_Review.Coordinating_POC', $coordinatorId)
        ->addWhere('id', '=', $collectionCampId)
        ->execute();
}

public function assignCoordinatorByRelationshipType($stateOfficeId, $registrationType, $collectionCampId) {
    $relationshipTypeName = $this->getRelationshipTypeForRegistration($registrationType);
    
    $coordinator = $this->getCoordinator($stateOfficeId, $relationshipTypeName);
    if (!$coordinator) {
        \CRM_Core_Error::debug_log_message(
            sprintf('No coordinator available for relationship type %s and office %d', 
                $relationshipTypeName, 
                $stateOfficeId
            )
        );
        return FALSE;
    }
    
    return $this->updateCollectionCampCoordinator($collectionCampId, $coordinator['contact_id_a']);
}
wp-content/civi-extensions/goonjcustom/api/v3/Goonjcustom/InstitutionDroppingCenterOutcomeCron.php (3)

Line range hint 14-77: Consider refactoring for better maintainability and readability.

The main function is handling multiple responsibilities and could benefit from being split into smaller, focused functions. Consider these improvements:

  1. Extract data collection logic into separate methods:
+ private function collectCashContributions() {
+   $cashContributionById = [];
+   $droppingCenterMetas = EckEntity::get('Dropping_Center_Meta', TRUE)
+     ->addSelect('Donation.Cash_Contribution', 'Dropping_Center_Meta.Institution_Dropping_Center')
+     ->addClause('OR', ['Donation.Cash_Contribution', 'IS NOT EMPTY'])
+     ->execute();
+   foreach ($droppingCenterMetas as $center) {
+     $id = $center['Dropping_Center_Meta.Institution_Dropping_Center'];
+     $cashContributionById[$id] = ($cashContributionById[$id] ?? 0) + (float) ($center['Donation.Cash_Contribution'] ?? 0);
+   }
+   return $cashContributionById;
+ }
  1. Define constants for frequently used column names:
+ private const COLUMN_INSTITUTION_DROPPING_CENTER = 'Material_Contribution.Institution_Dropping_Center';
+ private const COLUMN_CASH_CONTRIBUTION = 'Donation.Cash_Contribution';
  1. Add error handling for database operations:
+ try {
+   $activities = Activity::get(TRUE)
+     ->addSelect(self::COLUMN_INSTITUTION_DROPPING_CENTER)
+     ->addWhere('activity_type_id:name', '=', 'Material Contribution')
+     ->addWhere(self::COLUMN_INSTITUTION_DROPPING_CENTER, 'IS NOT NULL')
+     ->execute();
+ } catch (Exception $e) {
+   \Civi::log()->error('Failed to fetch activities: ' . $e->getMessage());
+   return civicrm_api3_create_error('Failed to process dropping center outcomes');
+ }

Line range hint 1-13: Improve documentation for better maintainability.

The file lacks comprehensive documentation about its purpose and behavior.

Add PHPDoc blocks explaining:

 /**
  * @file
+ * Provides cron functionality for updating dropping center metrics.
  */

 use Civi\Api4\Activity;
 use Civi\Api4\EckEntity;

 /**
  * Cron job to update Dropping Center outcomes.
+ * 
+ * @param array $params Parameters passed to the API
+ * @return array API result array
+ * 
+ * This cron job aggregates various metrics for dropping centers including:
+ * - Cash contributions
+ * - Product sales
+ * - Vehicle dispatch counts
+ * - Center footfall
+ * - Bags received
  */

Line range hint 58-68: Add return type hints and parameter documentation.

The helper function lacks proper type hints and parameter documentation.

   /**
-   *
+   * Updates a specific metric for institution dropping centers.
+   *
+   * @param string $metricName The name of the metric to update
+   * @param array<int,float|int> $data Array of values indexed by dropping center ID
+   * @return void
    */
-  function updateInstitutionDroppingCenterMetric($metricName, $data) {
+  function updateInstitutionDroppingCenterMetric(string $metricName, array $data): void {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d9d03ad and 1272c2e.

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

47-47: Verify the column name change impact.

The change from using Dropping_Center to Institution_Dropping_Center for footfall calculation appears correct, but let's verify this doesn't miss any existing data.

✅ Verification successful

The column name change is consistent with the codebase structure

The codebase shows a clear distinction between regular dropping centers (Dropping_Center) and institution dropping centers (Institution_Dropping_Center). The change from Material_Contribution.Dropping_Center to Material_Contribution.Institution_Dropping_Center in the footfall calculation is correct because:

  • The file InstitutionDroppingCenterOutcomeCron.php specifically handles institution dropping centers, as evidenced by:
    • All other queries in the file use Institution_Dropping_Center
    • The entity subtype is explicitly checked as Institution_Dropping_Center
    • The corresponding service class InstitutionDroppingCenterService.php uses the same naming
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of old column name
rg -i "dropping_center[^_]" --type php

# Search for the new column name pattern to confirm consistency
rg -i "institution_dropping_center" --type php

Length of output: 22050

Comment on lines +556 to +560
'Corporate' => 'Corporate Coordinator of',
'School' => 'School Coordinator of',
'College' => 'College Coordinator of',
'Associations' => 'Associations Coordinator of',
'Others' => 'Others Coordinator of',
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

Eliminate duplicate relationship type mappings.

The relationship type mappings are duplicated between InstitutionService and InstitutionCollectionCampService. This violates the DRY principle and could lead to inconsistencies if one mapping is updated but not the other.

Consider extracting these mappings to a shared configuration class:

class RelationshipTypeConfig {
    const COORDINATOR_TYPES = [
        'Corporate' => 'Corporate Coordinator of',
        'School' => 'School Coordinator of',
        'College' => 'College Coordinator of',
        'Associations' => 'Associations Coordinator of',
        'Others' => 'Others Coordinator of',
    ];
}

Then use this shared configuration in both services:

- $relationshipTypeMap = [
-   'Corporate' => 'Corporate Coordinator of',
-   'School' => 'School Coordinator of',
-   'College' => 'College Coordinator of',
-   'Associations' => 'Associations Coordinator of',
-   'Others' => 'Others Coordinator of',
- ];
+ $relationshipTypeMap = RelationshipTypeConfig::COORDINATOR_TYPES;

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Line range hint 302-344: Consider refactoring for better maintainability

The mailNotificationToMmt method could benefit from:

  1. Separation of concerns (data fetching, email composition, sending)
  2. Improved error handling for database operations
  3. Early returns to reduce nesting

Consider splitting the method into smaller, focused methods:

private function fetchInstitutionData($institutionDroppingCenterId) {
    return EckEntity::get('Collection_Camp', FALSE)
        ->addSelect('Institution_Dropping_Center_Intent.Dropping_Center_Address', 'title')
        ->addWhere('id', '=', $institutionDroppingCenterId)
        ->execute()
        ->single();
}

private function fetchMmtCoordinator($goonjFieldId) {
    $coordinators = Relationship::get(FALSE)
        ->addWhere('contact_id_b', '=', $goonjFieldId)
        ->addWhere('relationship_type_id:name', '=', self::MATERIAL_RELATIONSHIP_TYPE_NAME)
        ->addWhere('is_current', '=', TRUE)
        ->execute()
        ->first();
    
    return $coordinators['contact_id_a'] ?? null;
}

private function sendMmtNotification($mmtId, $institutionData, $vehicleDispatchId) {
    // Email composition and sending logic
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1272c2e and a17ee1d.

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

341-341: ⚠️ Potential issue

Fix undefined variable usage

The $fromEmail variable used in the replyTo field is undefined, which could cause runtime errors.

-      'replyTo' => $fromEmail['label'],
+      'replyTo' => $from,

Likely invalid or redundant comment.


302-302: Verify field name change consistency

The field name has been changed from 'Collection_Camp' to 'Institution_Dropping_Center'. Let's verify this change is consistent across the codebase.

->execute()->single();

$institutionDroppingCenter = $institutionDroppingCenter['title'];
$InstitutionDroppingCenterCode = $institutionDroppingCenter['title'];
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

Follow PHP variable naming conventions

The variable name InstitutionDroppingCenterCode uses PascalCase, which violates PHP naming conventions. Variables should use camelCase.

-    $InstitutionDroppingCenterCode = $institutionDroppingCenter['title'];
+    $institutionDroppingCenterCode = $institutionDroppingCenter['title'];
📝 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
$InstitutionDroppingCenterCode = $institutionDroppingCenter['title'];
$institutionDroppingCenterCode = $institutionDroppingCenter['title'];

@belwalshubham belwalshubham changed the title Resolve Feedbacks Refactor: Institution Relationship Dec 11, 2024
@belwalshubham belwalshubham self-assigned this Dec 11, 2024
@belwalshubham belwalshubham merged commit 5065218 into develop Dec 11, 2024
@belwalshubham belwalshubham deleted the feat/resolve-feedbacks branch December 11, 2024 10:14
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