Skip to content

Add setIndianStateOptions Hook for Dynamic State Options in CollectionBaseService#533

Merged
pokhiii merged 1 commit intodevelopfrom
refactor/set-indian-states-in-dropdown
Dec 4, 2024
Merged

Add setIndianStateOptions Hook for Dynamic State Options in CollectionBaseService#533
pokhiii merged 1 commit intodevelopfrom
refactor/set-indian-states-in-dropdown

Conversation

@pokhiii
Copy link
Copy Markdown
Member

@pokhiii pokhiii commented Dec 4, 2024

This pull request introduces a new hook_civicrm_fieldOptions in the CollectionBaseService class to dynamically populate Indian state options for specific fields. The refactoring adds extensibility and scalability to the handling of state-related options, making future development more modular and maintainable.

Why Refactored?

  • Centralized and dynamic handling of state options removes hardcoded values, improving maintainability.
  • The hook-based implementation allows for easy integration with existing and future features without invasive changes to the core logic.
  • Adopting the StateProvince API ensures consistent and reliable data fetching while adhering to best practices in CiviCRM.

How to Extend in the Future

  • Add Support for Other Countries: Modify the setIndianStateOptions method to include additional country filters or add a method for other entities.
  • Extend Field Handling: Expand the getStateFieldNames() utility to include more fields requiring dynamic options.
  • Additional Data Options: Leverage the hook for other data sources like city or district fields by introducing similar methods.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a method to provide options for Indian states specifically for the Eck_Collection_Camp entity.
  • Bug Fixes

    • Enhanced error handling and logging in the office assignment process.
    • Improved checks and logging for email notifications.
  • Refactor

    • Cleaned up the fetchTypeOfInduction method for better readability.
  • Chores

    • Removed outdated methods related to Indian state options across multiple services, streamlining functionality.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Dec 4, 2024

Walkthrough

The pull request introduces significant changes across multiple classes in the Civi namespace. The primary modification is the addition of the setIndianStateOptions method in the CollectionBaseService, which integrates a new dependency on the StateProvince API to provide Indian state options for the Eck_Collection_Camp entity. Concurrently, the setIndianStateOptions method is removed from several other classes, including CollectionCampService, DroppingCenterService, GoonjActivitiesService, InstitutionCollectionCampService, and InstitutionDroppingCenterService. These changes streamline state management functionalities while enhancing error handling in related methods.

Changes

File Path Change Summary
wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php Added methods: setIndianStateOptions, getStateFieldNames; registered hook &hook_civicrm_fieldOptions.
wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php Removed method: setIndianStateOptions; enhanced error handling in setOfficeDetails and mailNotificationToMmt.
wp-content/civi-extensions/goonjcustom/Civi/DroppingCenterService.php Removed method: setIndianStateOptions; updated getSubscribedEvents to remove associated hook.
wp-content/civi-extensions/goonjcustom/Civi/GoonjActivitiesService.php Removed method: setIndianStateOptions; removed hook subscription from getSubscribedEvents.
wp-content/civi-extensions/goonjcustom/Civi/InductionService.php Updated method: fetchTypeOfInduction for cleaner API call and improved readability.
wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php Removed method: setIndianStateOptions; updated getSubscribedEvents to remove associated hook.
wp-content/civi-extensions/goonjcustom/Civi/InstitutionDroppingCenterService.php Removed method: setIndianStateOptions; removed hook from getSubscribedEvents.

Possibly related PRs

Suggested labels

status : ready for review

Suggested reviewers

  • belwalshubham

🎉 In the land of code where functions play,
setIndianStateOptions found its way.
With hooks and states, it danced anew,
While others let go, their purpose withdrew.
Error handling shines, like stars in the night,
Together we code, making everything right! 🌟


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.

@pokhiii pokhiii changed the title refactor: how we use setIndianStateOptions Add setIndianStateOptions Hook for Dynamic State Options in CollectionBaseService Dec 4, 2024
@pokhiii pokhiii self-assigned this Dec 4, 2024
@pokhiii pokhiii marked this pull request as ready for review December 4, 2024 07:19
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 (6)
wp-content/civi-extensions/goonjcustom/Civi/InductionService.php (4)

Line range hint 826-840: Add error handling for database operations

The Contact API query could fail, but there's no try-catch block to handle potential exceptions. This could lead to unhandled errors in production.

Consider wrapping the database operation in a try-catch block:

+   try {
      $officeContact = Contact::get(FALSE)
        ->addWhere('contact_sub_type', 'CONTAINS', 'Goonj_Office')
        ->addClause('OR', 
          ['Goonj_Office_Details.Other_Induction_Cities', 'CONTAINS', $contactCityFormatted],
          ['address_primary.city', 'CONTAINS', $contactCityFormatted]
        )
        ->execute();
+   } catch (\Exception $e) {
+     \Civi::log()->error('Failed to fetch office contact', [
+       'error' => $e->getMessage(),
+       'city' => $contactCityFormatted
+     ]);
+     return 'Online';
+   }

Line range hint 841-845: Remove redundant else block

The else block is unnecessary as it returns the same value that would be returned if the if-condition is false. This makes the code harder to read without adding any value.

Simplify the logic by removing the else block:

    if (!empty($officeDetails)) {
      return $inductionType;
    }
-   else {
-     $inductionType = 'Online';
-     return $inductionType;
-   }
+   $inductionType = 'Online';
+   return $inductionType;

Line range hint 826-840: Consider case-insensitive city comparison

The current implementation uses case-sensitive CONTAINS for city matching, which might miss valid matches if the case doesn't match exactly.

Consider using a case-insensitive comparison or normalizing the city names before comparison:

    $officeContact = Contact::get(FALSE)
      ->addWhere('contact_sub_type', 'CONTAINS', 'Goonj_Office')
      ->addClause('OR', 
-       ['Goonj_Office_Details.Other_Induction_Cities', 'CONTAINS', $contactCityFormatted],
-       ['address_primary.city', 'CONTAINS', $contactCityFormatted]
+       ['LOWER(Goonj_Office_Details.Other_Induction_Cities)', 'CONTAINS', strtolower($contactCityFormatted)],
+       ['LOWER(address_primary.city)', 'CONTAINS', strtolower($contactCityFormatted)]
      )

Line range hint 826-845: Refactor method for better maintainability

The fetchTypeOfInduction method is quite long and handles multiple responsibilities. Consider breaking it down into smaller, more focused methods.

Consider extracting the office lookup logic into a separate method:

private static function findGoonjOfficeForCity($cityName) {
    try {
        return Contact::get(FALSE)
            ->addWhere('contact_sub_type', 'CONTAINS', 'Goonj_Office')
            ->addClause('OR', 
                ['LOWER(Goonj_Office_Details.Other_Induction_Cities)', 'CONTAINS', strtolower($cityName)],
                ['LOWER(address_primary.city)', 'CONTAINS', strtolower($cityName)]
            )
            ->execute();
    } catch (\Exception $e) {
        \Civi::log()->error('Failed to fetch office contact', [
            'error' => $e->getMessage(),
            'city' => $cityName
        ]);
        return NULL;
    }
}

This would make the main method cleaner and more maintainable.

wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php (2)

521-533: Improve documentation and readability of getStateFieldNames

The method would benefit from:

  1. PHPDoc explaining the purpose of the state group mapping
  2. More readable array transformation

Here's a suggested improvement:

   /**
+   * Returns an array of field names for state fields across different entity types.
+   * 
+   * Maps entity types to their corresponding custom group names and constructs
+   * the full field path in the format: {CustomGroupName}.State
+   * 
+   * @return array Array of field names for state fields
    */
   public static function getStateFieldNames() {
     $stateGroupNameMapper = [
       'Collection_Camp' => 'Collection_Camp_Intent_Details',
       'Dropping_Center' => 'Dropping_Centre',
       'Institution_Collection_Camp' => 'Institution_Collection_Camp_Intent',
       'Goonj_Activities' => 'Goonj_Activities',
       'Institution_Dropping_Center' => 'Institution_Dropping_Center_Intent',
     ];
 
-    $statefieldNames = array_map(fn ($field) => "{$field}.State", $stateGroupNameMapper);
+    $stateFieldNames = array_map(
+      function ($customGroupName) {
+        return "{$customGroupName}.State";
+      },
+      $stateGroupNameMapper
+    );
 
-    return $statefieldNames;
+    return $stateFieldNames;
   }

488-533: Consider future extensibility for location-based options

The current implementation successfully centralizes state options management, but consider:

  1. Creating a more generic location options service that could handle:
    • Different countries
    • Cities and districts
    • Custom geographical hierarchies
  2. Implementing a caching mechanism for frequently accessed location data
  3. Adding support for location validation rules

This would make the system more maintainable and scalable for future requirements.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4324e66 and ee72a34.

📒 Files selected for processing (7)
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php (3 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php (0 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/DroppingCenterService.php (0 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/GoonjActivitiesService.php (0 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/InductionService.php (2 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php (0 hunks)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionDroppingCenterService.php (0 hunks)
💤 Files with no reviewable changes (5)
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionCollectionCampService.php
  • wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php
  • wp-content/civi-extensions/goonjcustom/Civi/DroppingCenterService.php
  • wp-content/civi-extensions/goonjcustom/Civi/GoonjActivitiesService.php
  • wp-content/civi-extensions/goonjcustom/Civi/InstitutionDroppingCenterService.php
🔇 Additional comments (2)
wp-content/civi-extensions/goonjcustom/Civi/CollectionBaseService.php (2)

16-16: LGTM: StateProvince API import follows existing patterns

The import is correctly placed with other API imports and follows the established naming conventions.


47-47: LGTM: Hook registration is properly implemented

The hook registration follows the established pattern in getSubscribedEvents.

Comment on lines +491 to +516
public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) {
if ($entity !== 'Eck_Collection_Camp') {
return;
}

$stateFieldNames = self::getStateFieldNames();

if (!in_array($field, $stateFieldNames)) {
return;
}

$indianStates = StateProvince::get(FALSE)
->addWhere('country_id.iso_code', '=', 'IN')
->addOrderBy('name', 'ASC')
->execute();

$stateOptions = [];
foreach ($indianStates as $state) {
if ($state['is_active']) {
$stateOptions[$state['id']] = $state['name'];
}
}

$options = $stateOptions;

}
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 error handling and reduce nesting in setIndianStateOptions

Consider the following improvements:

  1. Use early returns to reduce nesting
  2. Add error handling for the StateProvince API call
  3. Consider making the country code configurable for better reusability

Here's a suggested refactor:

 public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) {
-    if ($entity !== 'Eck_Collection_Camp') {
-      return;
-    }
+    if ($entity !== 'Eck_Collection_Camp' || !in_array($field, self::getStateFieldNames())) {
+      return;
+    }
 
-    $stateFieldNames = self::getStateFieldNames();
+    try {
+      $indianStates = StateProvince::get(FALSE)
+        ->addWhere('country_id.iso_code', '=', 'IN')
+        ->addOrderBy('name', 'ASC')
+        ->execute();
 
-    if (!in_array($field, $stateFieldNames)) {
-      return;
-    }
- 
-    $indianStates = StateProvince::get(FALSE)
-      ->addWhere('country_id.iso_code', '=', 'IN')
-      ->addOrderBy('name', 'ASC')
-      ->execute();
- 
-    $stateOptions = [];
-    foreach ($indianStates as $state) {
-      if ($state['is_active']) {
-        $stateOptions[$state['id']] = $state['name'];
-      }
-    }
+      $options = array_reduce($indianStates, function ($carry, $state) {
+        if ($state['is_active']) {
+          $carry[$state['id']] = $state['name'];
+        }
+        return $carry;
+      }, []);
-    $options = $stateOptions;
+    } catch (\Exception $e) {
+      \Civi::log()->error('Failed to fetch state options', [
+        'error' => $e->getMessage(),
+        'entity' => $entity,
+        'field' => $field
+      ]);
+      $options = [];
+    }
   }
📝 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 setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) {
if ($entity !== 'Eck_Collection_Camp') {
return;
}
$stateFieldNames = self::getStateFieldNames();
if (!in_array($field, $stateFieldNames)) {
return;
}
$indianStates = StateProvince::get(FALSE)
->addWhere('country_id.iso_code', '=', 'IN')
->addOrderBy('name', 'ASC')
->execute();
$stateOptions = [];
foreach ($indianStates as $state) {
if ($state['is_active']) {
$stateOptions[$state['id']] = $state['name'];
}
}
$options = $stateOptions;
}
public static function setIndianStateOptions(string $entity, string $field, ?array &$options, array $params) {
if ($entity !== 'Eck_Collection_Camp' || !in_array($field, self::getStateFieldNames())) {
return;
}
try {
$indianStates = StateProvince::get(FALSE)
->addWhere('country_id.iso_code', '=', 'IN')
->addOrderBy('name', 'ASC')
->execute();
$options = array_reduce($indianStates, function ($carry, $state) {
if ($state['is_active']) {
$carry[$state['id']] = $state['name'];
}
return $carry;
}, []);
} catch (\Exception $e) {
\Civi::log()->error('Failed to fetch state options', [
'error' => $e->getMessage(),
'entity' => $entity,
'field' => $field
]);
$options = [];
}
}

@pokhiii pokhiii merged commit f692c14 into develop Dec 4, 2024
@pokhiii pokhiii deleted the refactor/set-indian-states-in-dropdown branch December 4, 2024 07:24
@coderabbitai coderabbitai bot mentioned this pull request Dec 12, 2024
@coderabbitai coderabbitai bot mentioned this pull request Dec 8, 2025
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