Skip to content

Usage tracking v2#2049

Merged
Crabcyborg merged 31 commits into
masterfrom
usage-tracking-v2
Nov 12, 2024
Merged

Usage tracking v2#2049
Crabcyborg merged 31 commits into
masterfrom
usage-tracking-v2

Conversation

@truongwp
Copy link
Copy Markdown
Contributor

@truongwp truongwp commented Oct 14, 2024

This PR:

  • Changes usage endpoint to https://usage2.formidableforms.com/snapshot.
  • Adds more usage data and improves some old ones.
  • Adds code to track form templates and edit form clicked links.
  • Logs the usage request in case it's failed. I did this when debugging. I'm not sure we should keep this.

@truongwp truongwp added the deploy Deploy website on push label Oct 14, 2024
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 14, 2024

Warning

Rate limit exceeded

@truongwp has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 635477a and d0dfd16.

Walkthrough

The pull request introduces several enhancements to the usage tracking functionality within the application. Key updates include the addition of new methods in the FrmUsageController for loading scripts and handling AJAX requests, as well as improvements to the FrmUsage class for managing snapshots and flow data. A new FrmLog class is introduced for error logging, and modifications are made to the FrmHooksController and FrmAppController to integrate these features into the existing workflow.

Changes

File Change Summary
classes/controllers/FrmUsageController.php - Added constant FLOWS_ACTION_NAME.
- Added methods: load_scripts(), ajax_track_flows(), update_flows_data($key, $value), get_flows_data(), and is_forms_list_page().
classes/models/FrmUsage.php - Modified send_snapshot to include a new endpoint and timeout.
- Added methods: onboarding_wizard() and payments($table = 'frm_payments').
js/admin/usage-tracking.js - Added function sendData(key, value) for event tracking via AJAX.
stubs.php - Added class FrmLog with method add($values).
classes/controllers/FrmHooksController.php - Added action hook in load_ajax_hooks for frm_track_flows.
classes/controllers/FrmAppController.php - Updated admin_enqueue_scripts to call FrmUsageController::load_scripts().

Possibly related PRs

  • Collect feedback deactivation #1919: This PR adds an AJAX action hook for tracking flows usage data, which directly relates to the ajax_track_flows() method introduced in the main PR.
  • Move AJAX hooks into load_ajax_hooks function #2091: This PR modifies the FrmHooksController to include AJAX hooks, which may overlap with the AJAX functionality being enhanced in the main PR, particularly regarding the organization of AJAX-related methods.

Suggested reviewers

  • Crabcyborg

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
Contributor

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

🧹 Outside diff range and nitpick comments (6)
js/admin/usage-tracking.js (4)

1-3: Remove redundant 'use strict' directive

The 'use strict' directive on line 2 is redundant in modern JavaScript modules, as they are automatically in strict mode. Consider removing this line to clean up the code.

Apply this diff to remove the redundant directive:

 ( function() {
-	'use strict';
🧰 Tools
🪛 Biome

[error] 2-2: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-10: Approved with a minor suggestion for readability

The event listener for tracking edit form clicked links is well-implemented. It uses event delegation efficiently and captures relevant data.

For improved readability, consider extracting the long selector into a named constant.

Here's a suggested improvement:

const EDIT_FORM_LINK_SELECTOR = '.toplevel_page_formidable #the-list .column-primary .row-actions a';

frmDom.util.documentOn('click', EDIT_FORM_LINK_SELECTOR, function(event) {
    // ... rest of the code
});

12-18: Approved with a suggestion for error handling

The event listener for tracking form templates is well-implemented and consistent with the previous listener. It effectively captures the template slug for tracking.

Consider adding error handling in case the closest 'li' element or its dataset.slug is not found.

Here's a suggested improvement:

frmDom.util.documentOn('click', '.frm-form-templates-use-template-button', function(event) {
    const listItem = event.target.closest('li');
    if (listItem && listItem.dataset.slug) {
        sendData({
            key: 'form_templates',
            value: listItem.dataset.slug
        });
    } else {
        console.warn('Unable to find template slug for tracking');
    }
});

20-26: Approved with suggestions for robustness

The sendData function is well-implemented, efficiently converting the input object to FormData and using the custom AJAX method to send the data.

To improve robustness, consider adding error handling and type checking:

  1. Add a try-catch block to handle potential errors during the AJAX call.
  2. Implement type checking for the input data parameter.

Here's a suggested improvement:

const sendData = (data) => {
    if (typeof data !== 'object' || data === null) {
        console.error('Invalid data type passed to sendData');
        return;
    }

    const formData = new FormData();
    Object.keys(data).forEach(key => {
        formData.append(key, data[key]);
    });

    try {
        frmDom.ajax.doJsonPost('track_flows', formData)
            .catch(error => {
                console.error('Error sending tracking data:', error);
            });
    } catch (error) {
        console.error('Error in sendData function:', error);
    }
};

This implementation adds type checking for the input data and error handling for both the AJAX call and any potential errors in the function itself.

classes/controllers/FrmHooksController.php (1)

98-99: LGTM! Consider grouping related hooks for better organization.

The new action hooks for usage tracking are correctly implemented and placed appropriately within the load_hooks method. They align well with the PR objectives of enhancing usage tracking functionality.

For improved code organization, consider grouping related hooks together. You could move the existing usage-related hook at line 97 (add_action( 'formidable_send_usage', 'FrmUsageController::send_snapshot' );) to be adjacent to these new hooks, creating a clear section for usage tracking functionality.

classes/models/FrmUsage.php (1)

34-34: Consider reducing the request timeout duration

The timeout is set to 45 seconds, which might be longer than necessary for most HTTP requests. A shorter timeout can enhance user experience by reducing delay in case of network issues. Evaluate if a lower timeout value would be sufficient.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d6bbba9 and a68e5a3.

📒 Files selected for processing (5)
  • classes/controllers/FrmHooksController.php (1 hunks)
  • classes/controllers/FrmUsageController.php (2 hunks)
  • classes/models/FrmUsage.php (5 hunks)
  • formidable.php (1 hunks)
  • js/admin/usage-tracking.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • formidable.php
🧰 Additional context used
🪛 GitHub Check: Psalm
classes/models/FrmUsage.php

[failure] 39-39: UndefinedClass
classes/models/FrmUsage.php:39:15: UndefinedClass: Class, interface or enum named FrmLog does not exist (see https://psalm.dev/019)

🪛 Biome
js/admin/usage-tracking.js

[error] 2-2: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (4)
js/admin/usage-tracking.js (1)

1-27: Overall assessment: Well-implemented with minor improvement suggestions

The usage tracking implementation in this file is generally well-structured and effective. It uses event delegation for efficiency, captures relevant data, and sends it using a custom AJAX method. The suggestions provided in the review comments aim to improve:

  1. Code readability (extracting long selectors)
  2. Error handling (for both event listeners and the sendData function)
  3. Type checking (in the sendData function)
  4. Removal of redundant 'use strict' directive

Implementing these suggestions will further enhance the robustness and maintainability of the code without requiring significant changes to the overall structure or functionality.

🧰 Tools
🪛 Biome

[error] 2-2: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

classes/controllers/FrmHooksController.php (1)

Line range hint 1-379: Summary: New usage tracking hooks added successfully.

The changes to FrmHooksController.php are minimal and focused, adding two new action hooks for usage tracking. These additions are consistent with the existing code structure and naming conventions. They enhance the plugin's ability to track usage without modifying core functionality.

Key points:

  1. New hooks are correctly implemented and placed appropriately.
  2. The changes align with the PR objectives of enhancing usage tracking.
  3. The additions don't appear to interfere with existing functionality.

Ensure that the suggested performance and privacy checks are conducted to maintain the plugin's quality and user trust.

classes/controllers/FrmUsageController.php (1)

82-101: ⚠️ Potential issue

Ensure capability checks are in place for ajax_track_flows

While check_ajax_referer helps prevent CSRF attacks, it's important to ensure that only authorized users can access this AJAX endpoint. Please verify that appropriate capability checks are implemented to prevent unauthorized access.

To verify the access control for this AJAX action, you can run the following script:

classes/models/FrmUsage.php (1)

102-104: Ensure compliance with data privacy regulations

The addition of flows, payments, and subscriptions to the snapshot may involve sensitive user data. Please review and ensure that collecting and transmitting this data complies with relevant privacy laws and your company's privacy policy.

Comment thread classes/controllers/FrmHooksController.php Outdated
Comment thread classes/controllers/FrmUsageController.php
Comment thread classes/controllers/FrmUsageController.php Outdated
Comment thread classes/controllers/FrmUsageController.php
Comment thread classes/models/FrmUsage.php Outdated
Comment thread classes/models/FrmUsage.php Outdated
Copy link
Copy Markdown
Contributor

@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: 3

🧹 Outside diff range and nitpick comments (1)
classes/models/FrmUsage.php (1)

Line range hint 286-309: LGTM: Improved custom style handling with minor optimization opportunity

The changes to the custom style handling are good improvements:

  1. Creating the FrmStyle object outside the loop is more efficient.
  2. Retrieving the style name instead of using the ID directly provides more meaningful data for tracking.
  3. The approach is more flexible and robust.

A minor optimization could be made by moving the style retrieval inside the condition:

Consider applying this diff for a small optimization:

 		$style = new FrmStyle();
 		foreach ( $saved_forms as $form ) {
 			$new_form = array(
 				'form_id'           => $form->id,
 				'description'       => $form->description,
 				'logged_in'         => $form->logged_in,
 				'editable'          => $form->editable,
 				'is_template'       => $form->is_template,
 				'entry_count'       => FrmEntry::getRecordCount( $form->id ),
 				'field_count'       => $this->form_field_count( $form->id ),
 				'form_action_count' => $this->form_action_count( $form->id ),
 			);

 			foreach ( $settings as $setting ) {
 				if ( isset( $form->options[ $setting ] ) ) {
 					if ( 'custom_style' === $setting ) {
 						$style->id = $form->options[ $setting ];
-						$style_post = $style->get_one();
-						$style_name = $style_post ? $style_post->post_name : 'formidable-style';
-
-						$new_form[ $setting ] = $style_name;
+						$new_form[ $setting ] = $style->get_one()->post_name ?? 'formidable-style';
 					} else {
 						$new_form[ $setting ] = $this->maybe_json( $form->options[ $setting ] );
 					}
 				}
 			}

This change reduces the number of variables and simplifies the code while maintaining the same functionality.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a68e5a3 and f400c8b.

📒 Files selected for processing (1)
  • classes/models/FrmUsage.php (5 hunks)
🧰 Additional context used
🪛 GitHub Check: Psalm
classes/models/FrmUsage.php

[failure] 39-39: UndefinedClass
classes/models/FrmUsage.php:39:15: UndefinedClass: Class, interface or enum named FrmLog does not exist (see https://psalm.dev/019)

🔇 Additional comments (2)
classes/models/FrmUsage.php (2)

34-34: LGTM: Timeout added to prevent request failures

Adding a timeout of 45 seconds to the wp_remote_request options is a good practice. It helps prevent long-running requests from blocking the application and mitigates 'http_request_failed' errors in the Debug Log.


102-104: LGTM: Enhanced usage tracking with flows and payments data

The addition of 'flows' and 'payments' data to the snapshot array enhances the usage tracking capabilities. The reuse of the payments method for both payments and subscriptions demonstrates good code reuse and flexibility.

Comment thread classes/models/FrmUsage.php Outdated
Copy link
Copy Markdown
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f400c8b and 8df9c02.

📒 Files selected for processing (1)
  • classes/models/FrmUsage.php (5 hunks)
🧰 Additional context used
🪛 GitHub Check: Psalm
classes/models/FrmUsage.php

[failure] 39-39: UndefinedClass
classes/models/FrmUsage.php:39:15: UndefinedClass: Class, interface or enum named FrmLog does not exist (see https://psalm.dev/019)

🔇 Additional comments (3)
classes/models/FrmUsage.php (3)

34-34: Timeout addition improves request reliability

Adding a timeout to the request options is a good practice. It helps prevent long-running requests and addresses potential http_request_failed errors. The comment explaining the reason for this addition is helpful for future maintenance.


102-104: Enhanced data collection for usage tracking

The addition of 'flows' and payment data to the snapshot array is a good improvement. It will provide more comprehensive insights for usage tracking. The reuse of the payments method for both regular payments and subscriptions is an efficient approach.


Line range hint 286-313: Improved handling of custom styles

The updates to the custom style handling are well-implemented. The new code:

  1. Creates a new FrmStyle object to work with styles.
  2. Handles both the default style (ID 1) and custom styles appropriately.
  3. Retrieves the style name instead of just the ID, providing more meaningful information.

This change will provide more detailed and useful information about form styles in the usage data. The code is well-structured and easy to understand.

Comment thread classes/models/FrmUsage.php
Copy link
Copy Markdown
Contributor

@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 (1)
classes/models/FrmUsage.php (1)

102-104: LGTM: Enhanced data collection for usage tracking

The addition of flows and payments data to the snapshot is a good improvement. It will provide more comprehensive insights into the usage patterns.

Consider optimizing the payments method calls:

-			'payments'          => $this->payments(),
-			'subscriptions'     => $this->payments( 'frm_subscriptions' ),
+			'payments'          => $this->payments( 'frm_payments', 'payments' ),
+			'subscriptions'     => $this->payments( 'frm_subscriptions', 'subscriptions' ),

Then update the payments method signature to:

private function payments( $table, $key )

This change would allow you to reuse the same method for both payments and subscriptions while clearly distinguishing between the two in the returned data.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8df9c02 and a26bf3d.

📒 Files selected for processing (1)
  • classes/models/FrmUsage.php (5 hunks)
🧰 Additional context used
🪛 GitHub Check: Psalm
classes/models/FrmUsage.php

[failure] 39-39: UndefinedClass
classes/models/FrmUsage.php:39:15: UndefinedClass: Class, interface or enum named FrmLog does not exist (see https://psalm.dev/019)

🔇 Additional comments (2)
classes/models/FrmUsage.php (2)

34-34: LGTM: Timeout added to prevent request failures

Adding a timeout to the request is a good practice. It helps prevent long-running requests and mitigates potential http_request_failed errors. The comment explaining the purpose is helpful for future maintenance.


21-22: ⚠️ Potential issue

Remove commented-out testing code

The commented-out line for testing purposes should be removed from the production code. Keeping testing code in production files can lead to confusion and potential security risks if accidentally uncommented.

Apply this diff to remove the commented-out testing code:

 		$ep = 'aHR0cHM6Ly91c2FnZTIuZm9ybWlkYWJsZWZvcm1zLmNvbS9zbmFwc2hvdA==';
-		// $ep = base64_encode( 'http://localhost:8080/snapshot' ); // Uncomment for testing

Likely invalid or redundant comment.

Comment thread classes/models/FrmUsage.php
Comment thread classes/models/FrmUsage.php Outdated
Copy link
Copy Markdown
Contributor

@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 (2)
classes/controllers/FrmUsageController.php (1)

69-78: Consider adding a nonce for the tracking script.

The script loading implementation looks good, but since it's handling usage tracking data, consider localizing the script with a nonce to secure the AJAX requests.

 public static function load_scripts() {
 	if ( self::is_forms_list_page() || FrmAppHelper::is_admin_page( 'formidable-form-templates' ) ) {
 		wp_enqueue_script( 'frm-usage-tracking', FrmAppHelper::plugin_url() . '/js/admin/usage-tracking.js', array( 'formidable_dom' ), FrmAppHelper::$plug_version, true );
+		wp_localize_script(
+			'frm-usage-tracking',
+			'frmUsageTracking',
+			array(
+				'nonce' => wp_create_nonce( 'frm_usage_tracking' )
+			)
+		);
 	}
 }
stubs.php (1)

382-390: Add class-level documentation.

The implementation looks good with proper method documentation. Consider adding class-level PHPDoc to document the purpose of this logging class.

Add this documentation above the class:

+/**
+ * Logging functionality for tracking usage and issues.
+ *
+ * @since 2049
+ */
 class FrmLog {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a26bf3d and 114fd2f.

📒 Files selected for processing (3)
  • classes/controllers/FrmUsageController.php (2 hunks)
  • classes/models/FrmUsage.php (5 hunks)
  • stubs.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • classes/models/FrmUsage.php
🧰 Additional context used
🔇 Additional comments (3)
classes/controllers/FrmUsageController.php (3)

12-19: LGTM! Well-documented constant following WordPress conventions.

The constant name and value are appropriately chosen for storing flows data in the options table.


80-100: LGTM! Well-structured page detection logic.

The method effectively handles various edge cases and follows good practices with early returns.


128-137: LGTM! Clean and straightforward implementation.

The method follows WordPress conventions and safely handles the default case.

Comment thread classes/controllers/FrmUsageController.php
@truongwp truongwp requested a review from Crabcyborg October 24, 2024 02:53
Comment thread classes/models/FrmUsage.php Outdated
Copy link
Copy Markdown
Contributor

@Crabcyborg Crabcyborg left a comment

Choose a reason for hiding this comment

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

@truongwp I heard Dalton mentioning the other day in a meeting how we want to track to know if people are using AI features.

Do we have anything like that in place yet?

We'd like to know probably how many AI fields are being used? And how often they're building an AI-generated form.

Can we track those things as well?

Thank you!

@truongwp
Copy link
Copy Markdown
Contributor Author

truongwp commented Oct 29, 2024

@Crabcyborg This PR doesn't track the AI-generated form. It will be in the AI addon.

There are 2 ways to track it:

Which way do you prefer?

I won't create a new database table for this. I will merge AI-generated form data into the form templates, and AI-generated forms will have the ai template. What do you think about this?

Copy link
Copy Markdown
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 114fd2f and c84e329.

📒 Files selected for processing (1)
  • classes/models/FrmUsage.php (5 hunks)
🔇 Additional comments (2)
classes/models/FrmUsage.php (2)

34-34: LGTM: Good addition of timeout parameter.

The addition of a 45-second timeout parameter is a good improvement to prevent request failures and Debug Log errors.


117-132: LGTM: Good implementation of data filtering.

The method effectively filters out sensitive and unnecessary data keys, maintaining anonymity in usage tracking. This aligns well with the privacy-focused approach mentioned in the PR comments.

Copy link
Copy Markdown
Contributor

@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)
js/admin/usage-tracking.js (2)

1-3: Remove redundant 'use strict' directive

The 'use strict' directive is unnecessary as JavaScript modules are automatically in strict mode.

( function() {
-	'use strict';
-
🧰 Tools
🪛 Biome

[error] 2-2: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-7: Consider using data attributes for action tracking

While the current implementation works, relying on className for tracking actions can be fragile if CSS classes change. Consider using dedicated data attributes for tracking purposes.

-		sendData( 'edit_form_clicked_link', event.target.parentNode.className );
+		sendData( 'edit_form_clicked_link', event.target.parentNode.dataset.action || event.target.parentNode.className );

Also add the data attribute to your action links:

<a href="#" data-action="edit">Edit</a>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0ad800f and 3530ac0.

📒 Files selected for processing (1)
  • js/admin/usage-tracking.js (1 hunks)
🧰 Additional context used
🪛 Biome
js/admin/usage-tracking.js

[error] 2-2: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

🔇 Additional comments (2)
js/admin/usage-tracking.js (2)

9-12: LGTM! Well-structured template tracking implementation.

Good use of data attributes for template identification and event delegation for performance.


14-19: LGTM! Well-structured data transmission.

The implementation using separate 'key' and 'value' fields in FormData provides clear structure for server-side processing. This approach makes it easier to track and process different types of events consistently.

Let's verify the server-side handling of these tracking events:

✅ Verification successful

Server-side implementation properly handles the tracking data

The server-side implementation in FrmUsageController properly validates and processes the tracking data:

  • Performs permission checks and nonce verification for security
  • Sanitizes both key and value parameters
  • Validates non-empty values before storage
  • Maintains structured data organization through the update_flows_data method

The client-side implementation using separate 'key' and 'value' fields aligns well with the server-side handling, making this a robust tracking solution.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the AJAX handler that processes these tracking events
ast-grep --pattern 'function ajax_track_flows($$$)'

Length of output: 53


Script:

#!/bin/bash
# Search for track_flows in PHP files using ripgrep
rg -t php "track_flows" -A 5

# Also search for any AJAX action registration related to track_flows
rg -t php "add_action.*track_flows"

Length of output: 1126


Script:

#!/bin/bash
# Let's see the complete implementation of the ajax_track_flows method
rg -t php -B 2 -A 10 "ajax_track_flows"

Length of output: 2000


Script:

#!/bin/bash
# Let's check the update_flows_data method implementation
rg -t php -B 2 -A 10 "update_flows_data"

Length of output: 1662

Comment thread classes/models/FrmUsage.php
Comment thread classes/controllers/FrmHooksController.php Outdated
Copy link
Copy Markdown
Contributor

@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 (3)
classes/models/FrmUsage.php (3)

21-22: Remove or secure the commented testing endpoint

The commented-out testing endpoint should be removed from production code to prevent accidental exposure of internal endpoints.

 		$ep = 'aHR0cHM6Ly91c2FnZTIuZm9ybWlkYWJsZWZvcm1zLmNvbS9zbmFwc2hvdA==';
-		// $ep = base64_encode( 'http://localhost:4567/snapshot' ); // Uncomment for testing

122-137: Optimize data filtering using array_diff_key

The current implementation using foreach to unset keys can be simplified.

 	private function onboarding_wizard() {
 		$data         = FrmOnboardingWizardController::get_usage_data();
 		$skipped_keys = array(
 			'default_email',
 			'is_subscribed',
 			'allows_tracking',
 			'summary_emails',
 			'installed_addons',
 		);
-
-		foreach ( $skipped_keys as $skipped_key ) {
-			unset( $data[ $skipped_key ] );
-		}
-
-		return $data;
+		return array_diff_key( $data, array_flip( $skipped_keys ) );
 	}

344-357: Simplify style name determination logic

Consider extracting the style name logic to a dedicated method in the FrmStyle class.

 						if ( 'custom_style' === $setting ) {
 							$style->id = $form->options[ $setting ];
-
-							if ( ! $style->id ) {
-								$style_name = 0;
-							} elseif ( 1 === intval( $style->id ) ) {
-								$style_name = 'formidable-style';
-							} else {
-								$style_post = $style->get_one();
-								$style_name = $style_post ? $style_post->post_name : 'formidable-style';
-							}
-
-							$new_form[ $setting ] = $style_name;
+							$new_form[ $setting ] = $style->get_style_name();

Add this method to the FrmStyle class:

public function get_style_name() {
    if ( ! $this->id ) {
        return 0;
    }
    if ( 1 === intval( $this->id ) ) {
        return 'formidable-style';
    }
    $style_post = $this->get_one();
    return $style_post ? $style_post->post_name : 'formidable-style';
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2061e6c and e3e66e8.

📒 Files selected for processing (1)
  • classes/models/FrmUsage.php (5 hunks)
🔇 Additional comments (4)
classes/models/FrmUsage.php (4)

37-41: LGTM: Time limit removal for large datasets

Good addition to prevent timeout issues when processing large amounts of data.


42-51: Verify FrmLog class availability

The error logging implementation looks good, but ensure the FrmLog class is properly defined to prevent runtime errors.

✅ Verification successful

Let me check the implementation of FrmLog class to ensure it has the required methods.


FrmLog class implementation is properly defined

The FrmLog class is defined in stubs.php with the required add() method that accepts an array parameter, which matches the usage in FrmUsage.php. The implementation is correct and safe to use.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for the FrmLog class definition
rg --type php 'class FrmLog'

# If not found directly, check for any FrmLog references or potential includes
rg --type php 'FrmLog'

Length of output: 439


Script:

#!/bin/bash
# Check the content of stubs.php for FrmLog implementation
cat stubs.php

Length of output: 10411


147-166: ⚠️ Potential issue

Secure database query using $wpdb->prepare

While the table whitelist is good, it's safer to use $wpdb->prepare() for query construction.

 	private function payments( $table = 'frm_payments' ) {
 		$allowed_tables = array( 'frm_payments', 'frm_subscriptions' );
 		if ( ! in_array( $table, $allowed_tables, true ) ) {
 			return array();
 		}
 
 		global $wpdb;
-		$rows     = $wpdb->get_results( "SELECT amount, status, paysys, created_at FROM {$wpdb->prefix}{$table}" );
+		$query    = $wpdb->prepare( "SELECT amount, status, paysys, created_at FROM {$wpdb->prefix}%s", $table );
+		$rows     = $wpdb->get_results( $query );
 		$payments = array();

Likely invalid or redundant comment.


344-357: Verify handling of disabled styling

The style name determination logic should account for cases where styling is disabled.

✅ Verification successful

Let me gather more information about the style handling logic to understand how disabled styling is managed.


Based on the search results, I can now provide a final response about the handling of disabled styling:

Style handling is properly implemented for disabled cases

The code correctly handles disabled styling through multiple checks:

  • When $style->id is falsy (0 or empty), it sets $style_name = 0 which indicates disabled styling
  • This aligns with the global settings where load_style = 'none' disables styles globally
  • The style handling is also validated through FrmFormsHelper::get_form_style() which properly processes both per-form and global style settings
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for style disable functionality
rg --type php 'disable.*style|style.*disable'

Length of output: 3154


Script:

#!/bin/bash
# Check style handling in FrmUsage class and related files
rg --type php -A 5 'custom_style'

Length of output: 29901

Copy link
Copy Markdown
Contributor

@Crabcyborg Crabcyborg left a comment

Choose a reason for hiding this comment

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

Thanks @truongwp!

I think this is good to go for next release. I'll go ahead and merge this.

🚀

@Crabcyborg
Copy link
Copy Markdown
Contributor

@truongwp Before I merge this, can you help with the PHPCS errors?

Screen Shot 2024-11-07 at 2 11 59 PM

Thank you!

Copy link
Copy Markdown
Contributor

@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)
classes/models/FrmUsage.php (1)

21-21: LGTM! Consider monitoring the timeout value.

The implementation includes good practices:

  • Error logging with proper class existence check
  • Base64 encoded endpoint URL
  • Removal of execution time limit for long-running requests

The 45-second timeout should be sufficient but consider monitoring if requests consistently take this long.

Also applies to: 34-52

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5c67a7b and 91a3ea8.

📒 Files selected for processing (1)
  • classes/models/FrmUsage.php (5 hunks)
🔇 Additional comments (2)
classes/models/FrmUsage.php (2)

116-138: LGTM! Good data privacy practices.

The method effectively filters out sensitive and unnecessary data before sending it for tracking.


351-364: LGTM! Comprehensive style handling.

The implementation correctly handles all style cases:

  • Disabled styling (id = 0)
  • Default style (id = 1)
  • Custom styles
  • Fallback to default style name

Comment thread classes/models/FrmUsage.php
@truongwp
Copy link
Copy Markdown
Contributor Author

truongwp commented Nov 9, 2024

@Crabcyborg I fixed those errors.

This PR logs the failed usage requests. Do you think we should keep it?

@Crabcyborg
Copy link
Copy Markdown
Contributor

This PR logs the failed usage requests. Do you think we should keep it?

@truongwp I'm not sure. If there are issues, it would help make them more visible. But it also isn't something that our customers shouldn't need to worry about.

I think we're fine to just remove it.

Comment thread classes/models/FrmUsage.php Outdated
@truongwp
Copy link
Copy Markdown
Contributor Author

This PR logs the failed usage requests. Do you think we should keep it?

@truongwp I'm not sure. If there are issues, it would help make them more visible. But it also isn't something that our customers shouldn't need to worry about.

I think we're fine to just remove it.

I removed the code to log the failed requests. Thank you.

Copy link
Copy Markdown
Contributor

@Crabcyborg Crabcyborg left a comment

Choose a reason for hiding this comment

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

Thanks @truongwp!

🚀

@Crabcyborg Crabcyborg merged commit bb6b754 into master Nov 12, 2024
@Crabcyborg Crabcyborg deleted the usage-tracking-v2 branch November 12, 2024 17:11
@coderabbitai coderabbitai Bot mentioned this pull request Nov 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants