Skip to content

Fetch contacts details based on contact id#472

Closed
belwalshubham wants to merge 2 commits intodevelopfrom
feat/fetch-contacts
Closed

Fetch contacts details based on contact id#472
belwalshubham wants to merge 2 commits intodevelopfrom
feat/fetch-contacts

Conversation

@belwalshubham
Copy link
Copy Markdown
Collaborator

@belwalshubham belwalshubham commented Nov 18, 2024

  • checks if the subtype 'Institute' exists within the contact_sub_type array using in_array(). This ensures that the code further run only when the contact has the 'Institute' subtype.

Summary by CodeRabbit

  • New Features
    • Enhanced office details management, allowing for streamlined operations related to address creation.
    • Improved logic for handling contact IDs, ensuring more accurate data retrieval and error logging.
  • Bug Fixes
    • Resolved issues with coordinator retrieval and selection, ensuring fallback options are available when necessary.
  • Refactor
    • Simplified method logic for better clarity and functionality, including adjustments to query behavior.

@belwalshubham belwalshubham self-assigned this Nov 18, 2024
@belwalshubham belwalshubham requested review from nishant22029 and tarunnjoshi and removed request for tarunnjoshi November 18, 2024 16:26
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Nov 18, 2024

Walkthrough

The pull request introduces significant changes to the setOfficeDetails method within the InstitutionService class. The method's parameter list has been modified, and the internal logic has been streamlined to enhance clarity. Notably, the handling of contact IDs and state IDs has been simplified, and the method now includes checks for specific conditions related to the operation type and contact sub-type. Additionally, the getRelationshipTypeName method has been adjusted to alter the organization retrieval behavior.

Changes

File Path Change Summary
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php - Updated setOfficeDetails method signature, changing $objectId to $contactId.
- Streamlined logic for operation checks and contact ID retrieval.
- Simplified state ID handling and error logging.
- Modified coordinator retrieval logic.
- Updated getRelationshipTypeName to change organization query behavior.

Possibly related PRs

Suggested labels

status : ready for review

Suggested reviewers

  • tarunnjoshi

Poem

In the land of code where functions play,
A method transformed, brightening the way.
Parameters shifted, logic refined,
With clearer paths, new treasures to find.
So here's to the changes, let’s raise a cheer,
For cleaner code brings us all near! 🎉


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.

Comment on lines +48 to +51
$contacts = Contact::get(FALSE)
->addSelect('contact_sub_type')
->addWhere('id', '=', $contactId)
->execute()->single();
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

$contactDetails = Contact::get(FALSE)
      ->addSelect('contact_sub_type')
      ->addWhere('id', '=', $contactId)
      ->execute();
$contactDetail = $contactDetails->first();

if( empty($contactDetail)){
      return;
} 

Comment on lines +177 to 180
$organization = Organization::get(FALSE)
->addSelect('Institute_Registration.Type_of_Institution:label')
->addWhere('id', '=', $contactId)
->execute()->single();
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

If contact not exist then this query will give error do you have tested that case?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

It never breaks because I've added a check before this condition to return if no contact ID is found:

if (!$contactId) 
{
 \CRM_Core_Error::debug_log_message('Contact ID not found'); 
 return; }

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 (3)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php (3)

Line range hint 59-66: Eliminate duplicate checks for $stateId

The condition if (!$stateId) is checked twice consecutively, which is redundant. Consolidate these checks to improve code clarity and maintainability.

Apply this diff to remove the duplicate condition:

-        if (!$stateId) {
-          return;
-        }

-        if (!$stateId) {
-          \CRM_Core_Error::debug_log_message('Cannot assign Goonj Office to institution id: ' . $contactId);
-          return;
-        }
+        if (!$stateId) {
+          \CRM_Core_Error::debug_log_message('Cannot assign Goonj Office to institution id: ' . $contactId);
+          return;
+        }

Line range hint 40-100: Refactor setOfficeDetails for single responsibility

The setOfficeDetails method handles multiple concerns, including:

  • Validating operation type and object name.
  • Retrieving contact and state information.
  • Assigning offices and coordinators.

To adhere to the Single Responsibility Principle and enhance readability, consider splitting this method into smaller, focused methods.


Line range hint 177-190: Improve robustness of getRelationshipTypeName mapping

The getRelationshipTypeName method relies on extracting the first word of $typeOfInstitution to determine the relationship type. This may not account for institution types with multiple words or unexpected formats. To ensure accurate mappings:

  • Use the full $typeOfInstitution as a key in the $typeToRelationshipMap.
  • Validate that all possible institution types are covered in the mapping.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f9399bc and e8a44c8.

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

* The parameters that were sent into the calling function.
*/
public static function setOfficeDetails(string $op, string $objectName, int $objectId, &$objectRef) {
public static function setOfficeDetails(string $op, string $objectName, int $contactId, &$objectRef) {
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

Avoid overwriting the $contactId parameter

The $contactId parameter is being overwritten inside the setOfficeDetails method with $objectRef->contact_id. This can lead to confusion and potential bugs. Consider either:

  • Removing $contactId from the parameter list and relying solely on $objectRef->contact_id.
  • Using the passed $contactId without overwriting it.

Apply this diff to avoid overwriting the parameter:

-        $contactId = $objectRef->contact_id;

Also applies to: 46-46

public static function setOfficeDetails(string $op, string $objectName, int $contactId, &$objectRef) {

if ($objectName !== 'AfformSubmission') {
if ($op !== 'create' || $objectName !== 'Address') {
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.

can we add one more check here to check the form or something unique because I expect the other things won't work if we merge it like this?
Use case: Please check the monitory contribution case here, and check if the new individual came there then it goes to their correct group.

NOTE: Please don't merge this PR before resolving these things and please test all the cases on staging after taking latest staging pull

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 (3)
wp-content/civi-extensions/goonjcustom/Civi/InstitutionService.php (3)

48-49: Enhance error logging with more context

The error message could be more informative by including the state ID that was missing.

-      \CRM_Core_Error::debug_log_message('Cannot assign Goonj Office to institution id: ' . $contactId);
+      \CRM_Core_Error::debug_log_message(sprintf(
+        'Cannot assign Goonj Office to institution (ID: %d) - missing state_province_id',
+        $contactId
+      ));

55-56: Improve error message with operation context

The error message should include more context about the operation being performed.

-      \CRM_Core_Error::debug_log_message('Contact id not found');
+      \CRM_Core_Error::debug_log_message(sprintf(
+        'Contact ID not found while setting office details for address creation (Reference ID: %s)',
+        $objectRef->id ?? 'unknown'
+      ));

Line range hint 40-195: Consider extracting common patterns into helper methods

There are several opportunities to improve code organization:

  1. Create a centralized error logging helper
  2. Extract coordinator selection logic into a separate method

Here's a suggested approach:

private static function logError($message, $context = []) {
  $contextStr = !empty($context) ? ' Context: ' . json_encode($context) : '';
  \CRM_Core_Error::debug_log_message($message . $contextStr);
}

private static function selectRandomCoordinator($coordinators) {
  if ($coordinators->count() === 0) {
    return null;
  }
  $randomIndex = rand(0, $coordinators->count() - 1);
  return $coordinators->itemAt($randomIndex);
}

This would allow for consistent error logging and remove duplicate coordinator selection logic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e8a44c8 and a9b1db6.

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

40-42: Verify test coverage for all use cases

As mentioned in previous reviews, please ensure test coverage for:

  1. Monitory contribution cases
  2. New individual scenarios
  3. Edge cases like missing contacts, invalid state IDs, etc.

Comment on lines +178 to 181
$organization = Organization::get(FALSE)
->addSelect('Institute_Registration.Type_of_Institution:label')
->addWhere('id', '=', $contactId)
->execute()->single();
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

Add error handling for organization retrieval

Similar to the contact retrieval, the single() method needs error handling to prevent exceptions.

-    $organization = Organization::get(FALSE)
-      ->addSelect('Institute_Registration.Type_of_Institution:label')
-      ->addWhere('id', '=', $contactId)
-      ->execute()->single();
+    try {
+      $organization = Organization::get(FALSE)
+        ->addSelect('Institute_Registration.Type_of_Institution:label')
+        ->addWhere('id', '=', $contactId)
+        ->execute()->first();
+
+      if (!$organization) {
+        \CRM_Core_Error::debug_log_message(sprintf(
+          'Organization not found for contact ID: %d while getting relationship type',
+          $contactId
+        ));
+        return 'Default Coordinator of';
+      }
+    } catch (\Exception $e) {
+      \CRM_Core_Error::debug_log_message(sprintf(
+        'Error retrieving organization (Contact ID: %d): %s',
+        $contactId,
+        $e->getMessage()
+      ));
+      return 'Default Coordinator of';
+    }
📝 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
$organization = Organization::get(FALSE)
->addSelect('Institute_Registration.Type_of_Institution:label')
->addWhere('id', '=', $contactId)
->execute()->single();
try {
$organization = Organization::get(FALSE)
->addSelect('Institute_Registration.Type_of_Institution:label')
->addWhere('id', '=', $contactId)
->execute()->first();
if (!$organization) {
\CRM_Core_Error::debug_log_message(sprintf(
'Organization not found for contact ID: %d while getting relationship type',
$contactId
));
return 'Default Coordinator of';
}
} catch (\Exception $e) {
\CRM_Core_Error::debug_log_message(sprintf(
'Error retrieving organization (Contact ID: %d): %s',
$contactId,
$e->getMessage()
));
return 'Default Coordinator of';
}

Comment on lines +60 to +63
$contacts = Contact::get(FALSE)
->addSelect('contact_sub_type')
->addWhere('id', '=', $contactId)
->execute()->single();
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

Add error handling for contact retrieval

The single() method will throw an exception if no contact is found. Consider using first() with proper error handling.

-    $contacts = Contact::get(FALSE)
-      ->addSelect('contact_sub_type')
-      ->addWhere('id', '=', $contactId)
-      ->execute()->single();
+    try {
+      $contact = Contact::get(FALSE)
+        ->addSelect('contact_sub_type')
+        ->addWhere('id', '=', $contactId)
+        ->execute()->first();
+      
+      if (!$contact) {
+        \CRM_Core_Error::debug_log_message(sprintf(
+          'Contact not found for ID: %d while checking contact subtype',
+          $contactId
+        ));
+        return;
+      }
+    } catch (\Exception $e) {
+      \CRM_Core_Error::debug_log_message(sprintf(
+        'Error retrieving contact (ID: %d): %s',
+        $contactId,
+        $e->getMessage()
+      ));
+      return;
+    }
📝 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
$contacts = Contact::get(FALSE)
->addSelect('contact_sub_type')
->addWhere('id', '=', $contactId)
->execute()->single();
try {
$contact = Contact::get(FALSE)
->addSelect('contact_sub_type')
->addWhere('id', '=', $contactId)
->execute()->first();
if (!$contact) {
\CRM_Core_Error::debug_log_message(sprintf(
'Contact not found for ID: %d while checking contact subtype',
$contactId
));
return;
}
} catch (\Exception $e) {
\CRM_Core_Error::debug_log_message(sprintf(
'Error retrieving contact (ID: %d): %s',
$contactId,
$e->getMessage()
));
return;
}

@belwalshubham
Copy link
Copy Markdown
Collaborator Author

Closing, This approach no longer needed.

@pokhiii pokhiii deleted the feat/fetch-contacts branch April 19, 2025 11:29
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.

3 participants