Skip to content

Fix the autofilling of collection camp when someone has filled it already#341

Merged
pokhiii merged 2 commits intodevelopfrom
fix-the-autofilling-of-collection-camp
Oct 8, 2024
Merged

Fix the autofilling of collection camp when someone has filled it already#341
pokhiii merged 2 commits intodevelopfrom
fix-the-autofilling-of-collection-camp

Conversation

@tarunnjoshi
Copy link
Copy Markdown
Member

@tarunnjoshi tarunnjoshi commented Oct 8, 2024

Fix the auto-filling of the collection camp when someone has filled it already

Summary by CodeRabbit

  • New Features

    • Enhanced user redirection for logged-in users to the CiviCRM dashboard.
    • Improved login failure handling with specific redirection based on login errors.
    • Added validation for empty login fields and error messages on the login form.
    • Introduced a user identification form for checking existing contacts and redirecting based on inquiry purpose.
    • New shortcodes for rendering volunteer actions and collection camp templates.
  • Bug Fixes

    • Addressed issues related to password reset redirection and login validation.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes in this pull request primarily involve modifications to the functions.php file of the Goonj CRM theme. Key updates include the addition of multiple functions for user redirection, login handling, form validation, and script/style enqueuing. New functionalities enhance user experience by managing redirection based on login status, handling login failures, and processing user identification forms. Additionally, several shortcodes for rendering templates related to volunteer actions and collection camps have been introduced.

Changes

File Path Change Summary
wp-content/themes/goonj-crm/functions.php - Added multiple functions for user redirection, login handling, form validation, and script enqueuing.
- Introduced shortcodes for rendering specific templates related to volunteer actions and collection camps.

Possibly related PRs

  • redirection to correct flow after new individual creation #299: This PR introduces the goonj_redirect_after_individual_creation function, which is related to the goonj_redirect_after_individual_creation function modified in the main PR, enhancing user redirection logic after individual creation.
  • Fix/redirection for new individual signup for pu visit #311: This PR also modifies the goonj_redirect_after_individual_creation function, focusing on redirection logic for new individual signups, which aligns with the changes made in the main PR regarding user redirection.
  • Removed email & phone #328: This PR includes modifications to the functions.php file that enhance user redirection and login handling, which are also key aspects of the main PR's changes.

Suggested labels

in review

Suggested reviewers

  • pokhiii

🎉 In the code, new functions do abound,
With redirections and scripts, they astound!
From login fails to user checks,
Each line crafted, no room for wrecks.
Goonj CRM, now more refined,
A better journey for all mankind! 🌟


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.

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

🧹 Outside diff range and nitpick comments (6)
wp-content/themes/goonj-crm/functions.php (6)

Line range hint 3-38: Refactor Enqueue Functions to Eliminate Duplicate Code

The goonj_enqueue_scripts() and goonj_enqueue_admin_scripts() functions share similar logic for enqueuing styles and scripts. This duplication violates the DRY (Don't Repeat Yourself) principle, making the code harder to maintain and update. Consider abstracting the common code into a single function to improve maintainability and readability.

Refactor the code as follows to consolidate the enqueue logic:

function goonj_enqueue_assets( $is_admin = false ) {
	$suffix = $is_admin ? '-admin' : '';
	wp_enqueue_style(
		'goonj' . $suffix . '-style',
		get_template_directory_uri() . '/style' . $suffix . '.css',
		array(),
		wp_get_theme()->get( 'Version' )
	);
	wp_enqueue_script(
		'goonj' . $suffix . '-script',
		get_template_directory_uri() . '/main' . $suffix . '.js',
		array( 'jquery' ),
		wp_get_theme()->get( 'Version' ),
		true
	);
}

add_action( 'wp_enqueue_scripts', function() {
	goonj_enqueue_assets();
});

add_action( 'admin_enqueue_scripts', function() {
	goonj_enqueue_assets( true );
});

Line range hint 49-75: Consolidate Login Failure Redirection Logic

Both goonj_custom_login_failed_redirect() and goonj_check_empty_login_fields() functions handle redirection upon login failure, duplicating the redirect logic to the home page with a query parameter. This repetition breaches the DRY principle and can lead to inconsistencies if one function is updated without the other. Consider unifying the redirection logic into a single function to enhance code maintainability.

You can refactor the code as follows:

function goonj_redirect_login_failure( $error_type = 'failed' ) {
	$redirect_url = add_query_arg( 'login', $error_type, home_url() );
	wp_redirect( $redirect_url );
	exit;
}

add_action( 'wp_login_failed', function( $username ) {
	goonj_redirect_login_failure( 'failed' );
});

add_filter( 'authenticate', function( $user, $username, $password ) {
	if ( empty( $username ) || empty( $password ) ) {
		goonj_redirect_login_failure( 'empty' );
	}
	return $user;
}, 30, 3 );

Update goonj_login_form_validation_errors() to handle different error messages based on the login query parameter.


Line range hint 131-584: Refactor Large Function to Enhance Single Responsibility

The goonj_handle_user_identification_form() function spans over 450 lines and encompasses multiple responsibilities, including form handling, contact retrieval, redirection logic, and more. This violates the Single Responsibility Principle, making the code difficult to read, debug, and maintain. Breaking down this function into smaller, focused functions will improve code clarity and facilitate future updates.

Consider the following refactoring approach:

  • Form Data Validation and Sanitization: Extract the validation logic into a separate function, e.g., validate_user_identification_form().
  • Contact Retrieval: Move the contact retrieval code into its own function, e.g., get_contact_by_email_and_phone( $email, $phone ).
  • Redirection Logic: Create dedicated functions for building redirection URLs based on the purpose, e.g., get_redirect_url_for_new_contact( $purpose, $email, $phone, $target_id ) and get_redirect_url_for_existing_contact( $purpose, $found_contacts, $email, $phone, $target_id ).
  • Volunteer Induction Check: Keep goonj_is_volunteer_inducted() as it is, but ensure it's only responsible for checking induction status.

This modular approach adheres to best practices and enhances code reusability.


Line range hint 632-683: Ensure Proper Handling of Potential Null Values

In the goonj_contribution_volunteer_signup_button() function, there are instances where variables like $contact['id'] and $contact may be null or undefined if the contact retrieval fails. This can lead to PHP notices or warnings, and potentially break the application flow. To maintain robustness, ensure that all variables are checked for validity before use.

Modify the code to include checks for null or undefined variables:

if ( empty( $contact ) ) {
	\Civi::log()->info( 'Contact not found for individual ID', [ 'individualId' => $individualId ] );
	return;
}

$contactSubTypes = $contact['contact_sub_type'] ?? [];

// Proceed with the rest of the logic

This change prevents unexpected errors and maintains the stability of the function.


Line range hint 718-775: Add Default Case and Reduce Code Duplication in Redirection Logic

The goonj_redirect_after_individual_creation() function's switch statement lacks a default case to handle unforeseen $creationFlow values, which could lead to silent failures. Additionally, the code for building the $redirectPath contains duplication, as similar patterns are used in multiple cases. Addressing these issues will improve code reliability and adherence to best practices.

  • Add a Default Case: Ensure that there's a default case in the switch statement to handle unexpected values.

    default:
    	\Civi::log()->warning( 'Unknown creation flow', [ 'creationFlow' => $creationFlow ] );
    	return;
  • Reduce Code Duplication: Refactor the redirection URL construction into a helper function.

    function build_redirect_path( $base_path, $params ) {
    	return sprintf( '%s#?%s', $base_path, http_build_query( $params ) );
    }
  • Use the Helper Function: Update the cases to use the new function.

    case 'office-visit':
    	$redirectPath = build_redirect_path(
    		'/processing-center/office-visit/details/',
    		[
    			'Office_Visit.Goonj_Processing_Center' => $sourceProcessingCenter,
    			'source_contact_id' => $individual['id'],
    		]
    	);
    	break;

This refactoring enhances code maintainability and reduces the likelihood of errors.


Line range hint 586-606: Avoid Repetition in API Calls

In goonj_is_volunteer_inducted(), the API calls to retrieve optionValue and activityResult can be optimized to reduce repetition and improve performance.

  • Cache the activity_type_id value if it's used elsewhere.
  • Combine API calls if possible, or validate whether multiple calls are necessary.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 565aa4d and c35ec25.

📒 Files selected for processing (1)
  • wp-content/themes/goonj-crm/functions.php (1 hunks)
🧰 Additional context used

@tarunnjoshi tarunnjoshi self-assigned this Oct 8, 2024
@tarunnjoshi tarunnjoshi requested a review from pokhiii October 8, 2024 10:25
@pokhiii pokhiii merged commit 5164bf0 into develop Oct 8, 2024
@pokhiii pokhiii deleted the fix-the-autofilling-of-collection-camp branch October 8, 2024 10:35
@github-actions
Copy link
Copy Markdown

github-actions bot commented Oct 8, 2024

Playwright test results

failed  4 failed
passed  1 passed

Details

stats  5 tests across 4 suites
duration  18 minutes, 43 seconds
commit  c35ec25

Failed tests

webkit › active-to-lead-volunteer.spec.js › Add a volunteer to Lead Volunteer group
webkit › volunteer-induction.spec.js › Volunteer Induction Tests › schedule induction and update induction status as completed
webkit › volunteer-induction.spec.js › Volunteer Induction Tests › update induction status as cancelled
webkit › volunteer-registration.spec.js › submit the volunteer registration form and confirm on admin

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.

2 participants