Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Rollback product statuses on dokan pro deactivation (integration) #2476

Open
wants to merge 14 commits into
base: develop
Choose a base branch
from

Conversation

mralaminahamed
Copy link
Member

@mralaminahamed mralaminahamed commented Dec 11, 2024

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

- **feat:** Rollback product statues on dokan pro activation and deactivation (integration)

Detailed Description of the pull request. What was previous behaviour
and what will be changed in this PR.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

  • New Features

    • Added a new service for managing product status rollback operations.
    • Implemented batch processing for rolling back product statuses from "reject" to "draft".
  • Improvements

    • Enhanced error handling and logging for product status management.
    • Introduced a structured approach to handling product status changes.

@mralaminahamed mralaminahamed added Needs: Testing This requires further testing Needs: Dev Review It requires a developer review and approval labels Dec 11, 2024
@mralaminahamed mralaminahamed self-assigned this Dec 11, 2024
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

This pull request introduces a new ProductStatusRollback service in the Dokan plugin, designed to manage the rollback of product statuses from "reject" to "draft" in batches. The service is registered in the CommonServiceProvider and implemented in a new ProductStatusRollback class. The implementation includes batch processing of rejected products, with built-in error handling and logging mechanisms to ensure smooth status transitions.

Changes

File Change Summary
includes/DependencyManagement/Providers/CommonServiceProvider.php Added registration for \WeDevs\Dokan\ProductStatusRollback service
includes/ProductStatusRollback.php New class implementing product status rollback functionality with batch processing

Possibly related PRs

Suggested labels

:+1: Dev Review Done, Upcoming Release, QA In Progress

Suggested reviewers

  • mrabbani

Poem

🐰 Hop, hop, through product lanes we go,
Rejected statuses, now draft's soft glow
Batch by batch, with coding might
Turning wrongs to workflows bright
A rabbit's touch, status reset complete! 🔄


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8ab1b11 and 29e907c.

📒 Files selected for processing (1)
  • includes/DependencyManagement/Providers/CommonServiceProvider.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • includes/DependencyManagement/Providers/CommonServiceProvider.php
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: e2e_api tests

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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 (3)
includes/ProductStatusRollback.php (2)

86-86: Enhance exception message with product ID for better debugging

Including the product ID in the exception message can aid in debugging by specifying which product caused the error.

Apply this diff to improve the exception message:

-throw new Exception( 'Invalid product' );
+throw new Exception( 'Invalid product with ID ' . $product_id );

28-28: Clarify the @since annotations in the documentation

The @since DOKAN_PRO_SINCE annotations use a placeholder constant DOKAN_PRO_SINCE, which may not be resolved properly in generated documentation. Consider replacing DOKAN_PRO_SINCE with the actual version number or ensure that it will be correctly processed during documentation generation.

Also applies to: 37-37, 48-48, 92-92, 102-102, 119-119

includes/DependencyManagement/Providers/CommonServiceProvider.php (1)

70-71: Adjust indentation to match the existing code style

The indentation of the method chaining in lines 70-71 is misaligned by one space compared to the existing code. Consistent indentation enhances readability and maintainability.

Apply this diff to fix the alignment:

-    $this->getContainer()
-         ->addShared( \WeDevs\Dokan\ProductStatusRollback::class, \WeDevs\Dokan\ProductStatusRollback::class )
-         ->addTag( self::TAG );
+        $this->getContainer()
+            ->addShared( \WeDevs\Dokan\ProductStatusRollback::class, \WeDevs\Dokan\ProductStatusRollback::class )
+            ->addTag( self::TAG );
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 70-70:
Found precision alignment of 1 spaces.


[warning] 71-71:
Found precision alignment of 1 spaces.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a0d9e64 and c9c3b6f.

📒 Files selected for processing (2)
  • includes/DependencyManagement/Providers/CommonServiceProvider.php (1 hunks)
  • includes/ProductStatusRollback.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
includes/DependencyManagement/Providers/CommonServiceProvider.php

[warning] 70-70:
Found precision alignment of 1 spaces.


[warning] 71-71:
Found precision alignment of 1 spaces.

includes/ProductStatusRollback.php

[failure] 126-126:
Expected no spaces between the increment operator and $processed; 1 found

includes/ProductStatusRollback.php Outdated Show resolved Hide resolved
Copy link
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 (4)
includes/ProductStatusRollback.php (4)

16-32: Consider making BATCH_SIZE configurable

While 20 items per batch is a reasonable default, consider making this configurable through filters to allow adjustment based on server capacity and load conditions.

-    private const BATCH_SIZE = 20;
+    /**
+     * Get batch size for processing
+     *
+     * @since DOKAN_PRO_SINCE
+     *
+     * @return int
+     */
+    private function get_batch_size(): int {
+        return (int) apply_filters( 'dokan_product_status_rollback_batch_size', 20 );
+    }

41-43: Document the hook priority

Consider adding a comment explaining why the default priority (10) was chosen for this hook, especially since it's part of a batch processing system.


65-76: Optimize database query performance

Consider adding an index hint to optimize the query performance, especially since this is running in batches.

     $products = $wpdb->get_col(
         $wpdb->prepare(
-            "SELECT ID FROM $wpdb->posts
+            "SELECT /*+ INDEX(wp_posts post_type_status_date) */ ID FROM $wpdb->posts
             WHERE post_type = 'product'
             AND post_status = %s
             ORDER BY ID

55-169: Consider breaking down the large method into smaller, focused methods

The process_batch_reject_operation method is quite long and handles multiple responsibilities. Consider extracting some logic into separate methods:

  1. Product retrieval logic
  2. Individual product processing logic
  3. Batch scheduling logic

This would improve readability and testability.

Example refactor:

private function get_batch_products(int $batch): array {
    // Extract product retrieval logic
}

private function process_single_product(WC_Product $product): void {
    // Extract single product processing logic
}

private function schedule_next_batch(WC_Queue_Interface $queue, int $batch, int $total_batches): void {
    // Extract scheduling logic
}
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[failure] 126-126:
Expected no spaces between the increment operator and $processed; 1 found

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c9c3b6f and 3407307.

📒 Files selected for processing (1)
  • includes/ProductStatusRollback.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
includes/ProductStatusRollback.php

[failure] 126-126:
Expected no spaces between the increment operator and $processed; 1 found

🔇 Additional comments (3)
includes/ProductStatusRollback.php (3)

1-10: LGTM! Well-organized namespace and imports.

The namespace declaration and class imports follow PSR standards and best practices.


126-126: Fix coding standard violation: remove space between increment operator and variable

The increment operator should not have a space between it and the variable.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[failure] 126-126:
Expected no spaces between the increment operator and $processed; 1 found


97-98: Verify status transition handling across the system

Let's verify that other parts of the system properly handle the status transition from 'reject' to 'draft'.

✅ Verification successful

Based on the search results, I can now generate the final response:

Status transition from 'reject' to 'draft' is properly handled

The codebase shows comprehensive handling of product status transitions:

  • The dokan_product_rollback_status filter is used consistently for status transitions
  • Product listing and dashboard components properly handle 'draft' status
  • Status transitions are properly tracked and logged
  • The system maintains proper status labels and UI elements for draft products
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other handlers of product status transitions
rg -A 5 "post_status.*reject|draft" --type php

# Search for status-related filters
ast-grep --pattern 'add_filter($_, "dokan_product_.*status.*")'

Length of output: 25775

Copy link
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 (3)
includes/ProductStatusRollback.php (3)

1-24: LGTM! Consider enhancing constant documentation.

The class structure, namespace, and imports are well-organized. The constants are appropriately defined with private scope.

Consider adding more detailed documentation for the constants, especially explaining why BATCH_SIZE is set to 20:

     /**
      * Batch size for processing
+     * 
+     * Maximum number of products to process in a single batch.
+     * Set to 20 to balance between performance and memory usage.
      *
      * @var int
      */

55-169: Consider breaking down the large method into smaller, focused methods.

The process_batch_reject_operation method is handling multiple responsibilities. Consider extracting the following into separate methods:

  • Product retrieval logic (lines 65-76)
  • Individual product processing (lines 82-137)
  • Batch scheduling logic (lines 149-158)

This would improve readability and maintainability.


127-136: Consider more specific exception handling.

The current catch block catches all Throwable instances. Consider catching specific exceptions that might occur during product processing (e.g., WC_Data_Exception for WooCommerce data operations).

Example:

-                } catch ( Throwable $e ) {
+                } catch ( WC_Data_Exception $e ) {
+                    dokan_log(
+                        sprintf(
+                            '[Product Status Rollback] Data error rolling back product #%d: %s',
+                            $product_id,
+                            $e->getMessage()
+                        ),
+                        'error'
+                    );
+                } catch ( Exception $e ) {
                     dokan_log(
                         sprintf(
                             '[Product Status Rollback] Error rolling back product #%d: %s',
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3407307 and cef3207.

📒 Files selected for processing (1)
  • includes/ProductStatusRollback.php (1 hunks)
🔇 Additional comments (2)
includes/ProductStatusRollback.php (2)

126-126: Fix coding standard violation: remove space between increment operator and variable

There should be no space between the increment operator and the variable.


89-97: LGTM! Well-documented filter hook.

The filter hook is well-documented with proper PHPDoc including @SInCE tag and parameter descriptions.

includes/ProductStatusRollback.php Outdated Show resolved Hide resolved
includes/ProductStatusRollback.php Show resolved Hide resolved
@mralaminahamed mralaminahamed changed the title feat: Rollback product statues on dokan pro activation and deactivation (integration) feat: Rollback product statues on dokan pro deactivation (integration) Dec 23, 2024
Copy link
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

🧹 Nitpick comments (1)
includes/ProductStatusRollback.php (1)

96-97: Consider using update_meta instead of add_meta_data

Using add_meta_data followed by save_meta_data requires two database operations. Consider using update_meta which is more efficient for single meta updates.

-    $product->add_meta_data( '_dokan_previous_status', $product->get_status(), true );
-    $product->save_meta_data();
+    update_post_meta( $product->get_id(), '_dokan_previous_status', $product->get_status() );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cef3207 and d30e215.

📒 Files selected for processing (1)
  • includes/ProductStatusRollback.php (1 hunks)
🔇 Additional comments (5)
includes/ProductStatusRollback.php (5)

1-8: LGTM: File structure and imports are well organized

The namespace and use statements follow PSR-4 standards and include all necessary dependencies.


27-28: Replace DOKAN_PRO_SINCE placeholder with actual version number

The @SInCE tags are using a placeholder value that needs to be replaced with the actual version number where this feature will be released.

Also applies to: 37-38


40-42: LGTM: Hook registration follows WordPress standards

The action hook registration is clean and follows WordPress coding standards.


56-62: Use $wpdb->posts instead of direct table reference

For better compatibility with custom WordPress table prefixes, use $wpdb->posts instead of directly referencing the table.


9-23: Verify batch size performance implications

The batch size of 10 items might need validation:

  • Small batch sizes can lead to more database operations
  • Large batch sizes can impact memory usage
    Consider benchmarking different batch sizes to find the optimal value.

Additionally, consider making the queue group identifier more specific to avoid potential conflicts, e.g., 'dokan-product-status-rollback-operation'.

✅ Verification successful

Let me gather more context about these batch operations to better understand their implementation and performance implications.


Batch size of 10 is consistent with similar operations

The batch size of 10 is well-aligned with other batch processing operations in the codebase:

  • It matches the batch size used in Update_Product_Commission and Update_Vendor_Commission
  • Only Update_Category_Commission uses a slightly larger batch size of 20

The queue group identifier 'dokan-product-status-rollback' is already sufficiently specific, as no other conflicting identifiers were found in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if batch size is configurable or hardcoded elsewhere
rg "BATCH_SIZE.*=.*\d+" --type php

# Check for other queue group identifiers to avoid conflicts
rg "QUEUE_GROUP.*=.*'dokan-" --type php

Length of output: 512


Script:

#!/bin/bash
# Check the implementation of batch processing in these files
ast-grep --pattern 'class $_ {
  $$$
  const BATCH_SIZE = $_;
  $$$
}'

# Look for any performance-related comments or documentation
rg -B2 -A2 "BATCH_SIZE" --type php

Length of output: 4589

includes/ProductStatusRollback.php Outdated Show resolved Hide resolved
includes/ProductStatusRollback.php Outdated Show resolved Hide resolved
@mrabbani mrabbani changed the title feat: Rollback product statues on dokan pro deactivation (integration) feat: Rollback product statuses on dokan pro deactivation (integration) Dec 31, 2024
includes/ProductStatusRollback.php Show resolved Hide resolved
includes/ProductStatusRollback.php Outdated Show resolved Hide resolved
Copy link
Member

@mrabbani mrabbani left a comment

Choose a reason for hiding this comment

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

Remove the composer.lock file from the changes.

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

♻️ Duplicate comments (5)
includes/ProductStatusRollback.php (5)

36-54: 🛠️ Refactor suggestion

Implement Hookable interface as suggested.

As per previous review, implement the WeDevs\Dokan\Contracts\Hookable interface to maintain consistency with the codebase architecture.

-class ProductStatusRollback {
+use WeDevs\Dokan\Contracts\Hookable;
+
+class ProductStatusRollback implements Hookable {
🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found


68-74: 🛠️ Refactor suggestion

Use proper table reference in SQL query.

Use {$wpdb->posts} instead of direct table reference for better compatibility with custom table prefixes.

🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found


123-123: ⚠️ Potential issue

Fix coding standard violation.

Remove space between increment operator and variable as per PHPCS.

-++ $processed;
++$processed;
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[failure] 123-123:
Expected no spaces between the increment operator and $processed; 1 found

🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found


66-78: 🛠️ Refactor suggestion

Add transaction handling for batch operations.

Wrap the batch operation in a database transaction to ensure data consistency in case of failures.

🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found


138-140: ⚠️ Potential issue

Prevent infinite loop in queue scheduling.

Check if there are more products to process before scheduling the next batch.

-            // Schedule next batch
-            WC()->queue()->add( 'dokan_rollback_product_status_reject_to_draft_schedule', array(), self::QUEUE_GROUP );
+            // Check if there are more products to process
+            $more_products = $wpdb->get_var(
+                $wpdb->prepare(
+                    "SELECT EXISTS (SELECT 1 FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = %s LIMIT 1)",
+                    'reject'
+                )
+            );
+            
+            if ( $more_products ) {
+                WC()->queue()->add( 'dokan_rollback_product_status_reject_to_draft_schedule', array(), self::QUEUE_GROUP );
+            }
🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found

🧹 Nitpick comments (1)
includes/ProductStatusRollback.php (1)

22-34: Document rationale for BATCH_SIZE value.

Consider adding a comment explaining why 10 was chosen as the batch size. This helps future maintainers understand if this value can be adjusted based on system resources or performance requirements.

🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 351819f and d7c23c3.

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • includes/ProductStatusRollback.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
includes/ProductStatusRollback.php

[failure] 123-123:
Expected no spaces between the increment operator and $processed; 1 found

🪛 GitHub Actions: Inspections
includes/ProductStatusRollback.php

[error] Expected no spaces between the increment operator and $processed; 1 found

🔇 Additional comments (2)
includes/ProductStatusRollback.php (2)

1-8: LGTM! Well-organized namespace and imports.

The file structure follows PHP best practices with proper namespace declaration and relevant use statements.

🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found


9-21: Enhance class documentation with package information.

While the documentation is good and includes use cases as requested, consider adding:

  • @package tag to indicate the package/module this class belongs to
  • Replace DOKAN_PRO_SINCE with actual version number
🧰 Tools
🪛 GitHub Actions: Inspections

[error] Expected no spaces between the increment operator and $processed; 1 found

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

🧹 Nitpick comments (1)
includes/ProductStatusRollback.php (1)

10-21: Enhance documentation to clarify timing of rollback operations

While the documentation clearly describes what the class does, it would be helpful to specify when these rollback operations occur (e.g., during plugin deactivation) and why products need to be rolled back from 'reject' to 'draft' status.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d7c23c3 and 99697ce.

📒 Files selected for processing (1)
  • includes/ProductStatusRollback.php (1 hunks)
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
includes/ProductStatusRollback.php

[failure] 124-124:
Expected no spaces between the increment operator and $processed; 1 found

🔇 Additional comments (7)
includes/ProductStatusRollback.php (7)

40-40: Replace DOKAN_PRO_SINCE placeholder with actual version number

The @SInCE tag is using a placeholder value that needs to be replaced with the actual version number where this feature will be released.


42-44: Constructor implementation looks good

While a past review suggested removing the constructor, I believe it's appropriate to keep it as it provides a clear initialization point for registering hooks when the class is instantiated. The implementation follows the Hookable interface contract correctly.


53-55: Hook registration looks good

The hook registration is clean, follows WordPress naming conventions, and properly sets up the batch processing callback.


124-124: Fix coding standard violation: remove space between increment operator and variable

According to the coding standards, there should be no space between the increment operator and the variable.

-++ $processed;
++$processed;
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[failure] 124-124:
Expected no spaces between the increment operator and $processed; 1 found


125-134: Error handling and logging implementation looks good

The implementation uses proper error handling with nested try-catch blocks and appropriate logging at both individual product and batch levels.

Also applies to: 141-149


69-75: 🛠️ Refactor suggestion

Optimize database query and add transaction handling

The database query could be improved in several ways:

  1. Use {$wpdb->posts} for better compatibility with custom table prefixes
  2. Add transaction handling for batch operations
  3. Use appropriate index hint for better performance
+        $wpdb->query('START TRANSACTION');
         $products = $wpdb->get_col(
             $wpdb->prepare(
-                "SELECT ID FROM $wpdb->posts WHERE post_type = 'product' AND post_status = %s ORDER BY ID LIMIT %d",
+                "SELECT ID FROM {$wpdb->posts} USE INDEX (type_status_date) WHERE post_type = 'product' AND post_status = %s ORDER BY ID LIMIT %d",
                 'reject',
                 self::BATCH_SIZE,
             )
         );

Likely invalid or redundant comment.


139-141: ⚠️ Potential issue

Prevent infinite loop in queue scheduling

The current implementation always schedules the next batch without checking if there are more products to process. This could lead to infinite scheduling if no products are found in the next batch.

-            // Schedule next batch
-            WC()->queue()->add( 'dokan_rollback_product_status_reject_to_draft_schedule', array(), self::QUEUE_GROUP );
+            // Check if there are more products to process before scheduling next batch
+            $more_products = $wpdb->get_var(
+                $wpdb->prepare(
+                    "SELECT EXISTS (SELECT 1 FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = %s LIMIT 1)",
+                    'reject'
+                )
+            );
+            
+            if ( $more_products ) {
+                WC()->queue()->add( 'dokan_rollback_product_status_reject_to_draft_schedule', array(), self::QUEUE_GROUP );
+            }

Likely invalid or redundant comment.

@mralaminahamed mralaminahamed force-pushed the feat/pending-product-rejection-integration branch from e8ea01e to c3d40f2 Compare January 6, 2025 04:18
Copy link
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 1

🧹 Nitpick comments (20)
tests/pw/tests/e2e/storeAppearance.spec.ts (5)

1-3: Use consistent imports & remove commented-out imports if no longer needed
Since CustomerPage is commented out, consider removing or uncommenting it if you plan to use it in the future. The new import for StoreAppearance is fine; just ensure your imports reflect the intended usage.


13-13: Follow up on the TODO
A TODO about removing default Dokan store sidebar content is noted. If this is part of the PR scope, address it before merging to prevent stale tasks.


16-19: Check performance overhead of new browser contexts
Creating a new browser context for the customer is valid, but be mindful of performance if scaling tests. Ensure you close this context if you create more context instances in the suite.


27-29: Add assertions to verify the map is actually hidden
After disabling the store map, it might help to add explicit verification that the map element is indeed removed or hidden.


37-39: Revisit skipped test for vendor info
This test is skipped, possibly for future debugging or development. Unskip or remove it if no longer needed; otherwise, ensure it’s revisited so vendor info coverage isn’t overlooked.

tests/pw/pages/storeAppearance.ts (2)

15-18: Consider adding an assertion after hiding the map
disableMapOnStoreSidebar ensures the element is not visible, but adding a small assertion to confirm the side effect (e.g., an alternative selector is displayed or a user-facing message) can make the test more robust.


20-23: Use consistent navigation methods
Here you use await this.goto, whereas in disableMapOnStoreSidebar, you use await this.goIfNotThere. Consider standardizing the navigation approach across all methods for consistency.

tests/pw/tests/e2e/privacyPolicy.spec.ts (2)

19-20: Remove or restore commented code
The calls to set the store contact form widget are commented out. If this is intentional, consider removing them or adding a clear comment explaining why they’re disabled, to avoid confusion.


44-44: Check thoroughness of new test
By no longer skipping this test, ensure it adequately verifies that the store contact form is indeed disabled on the storefront. If coverage is partial, consider adding additional checks.

tests/pw/tests/e2e/catalogmode.spec.ts (1)

58-62: Use a try/finally block to guarantee cleanup
Storing previousSettings and restoring it later is great. For added reliability, wrap the main test logic in a try/finally so your test always restores the previous state, even if the test fails.

tests/pw/e2e.config.ts (1)

28-28: Shortened default expectation timeout.
Decreasing the expect timeout from 15 to 10 seconds speeds up failing tests, but could increase transient failures in resource-heavy or slower CI environments. Consider monitoring test stability.

tests/pw/tests/e2e/euCompliance.spec.ts (1)

113-113: Check for synchronous fallback after resetting.
You're restoring the old settings with setOptionValue. Consider handling potential errors or concurrency issues that might occur if multiple tests attempt to modify the same settings simultaneously.

tests/pw/utils/dbData.ts (3)

233-234: Check map defaults.
store_map: 'on' and map_api_source: 'google_maps' are now the defaults. This can increase dependency on Google Maps APIs. Validate you have the proper keys and fallback logic for users without a Google Maps setup.


243-243: Disable or enable store sidebar with caution.
enable_theme_store_sidebar: 'off' helps keep a minimal interface, but ensure you have coverage for scenarios relying on a store sidebar.


1424-1429: Store contact form widget consistency.
Renaming or reorganizing this widget might break legacy references. Confirm that existing tests or pages referencing the contact form still function.

tests/pw/pages/selectors.ts (3)

1457-1460: Simplify selector paths for better maintainability

The following selectors have been updated to use more concise class-based selectors:

-upgradeToProText: 'div.modal-content p.upgrade-text',
-upgradeToPro: 'div.modal-content a.upgrade-button',
-proCard: 'div.modal-content div.promo-card',
-alreadyUpdated: 'div.modal-content a.already-updated',
+upgradeToProText: '.upgrade-text',
+upgradeToPro: '.upgrade-button', 
+proCard: '.promo-card',
+alreadyUpdated: '.already-updated',

This change makes the selectors more maintainable by:

  1. Removing unnecessary parent element references
  2. Using simpler class-based selectors
  3. Reducing selector specificity

7506-7522: Fix inconsistent indentation and remove redundant comments

The indentation is inconsistent in this section and there are some commented out lines that should be cleaned up:

- storeBanner: '.profile-info-img',

- profileInfoHead: '.profile-info-head',
- profileImage: '.profile-img.profile-img-circle',
- storeName: '.profile-info-head .store-name',
- verifiedIcon: '//div[@data-original-title="Verified"]',
- verifiedIconByIcon: (icon: string) => `//div[@data-original-title="Verified"]//i[@class="${icon}"]`,

- profileInfo: '.profile-info',
- storeInfo: '.dokan-store-info',
- storeAddress: '.dokan-store-address',
- storePhone: '.dokan-store-phone',
- storeEmail: '.dokan-store-email',
- // storeRating: '.dokan-store-rating',
- // storeOpenClose: '.dokan-store-open-close',
- storeSocial: '.store-social',

The code should be properly indented and commented out lines should be removed:

storeBanner: '.profile-info-img',
profileInfoHead: '.profile-info-head',
profileImage: '.profile-img.profile-img-circle', 
storeName: '.profile-info-head .store-name',
verifiedIcon: '//div[@data-original-title="Verified"]',
verifiedIconByIcon: (icon: string) => `//div[@data-original-title="Verified"]//i[@class="${icon}"]`,

profileInfo: '.profile-info',
storeInfo: '.dokan-store-info',
storeAddress: '.dokan-store-address', 
storePhone: '.dokan-store-phone',
storeEmail: '.dokan-store-email',
storeSocial: '.store-social',

7662-7662: Fix trailing comma style

The trailing comma is inconsistent with the rest of the codebase:

-storeMap: 'div#dokan-store-location',
-storeOpenCloseTime: 'div.dokan-store-open-close',
+storeMap: 'div#dokan-store-location',
+storeOpenCloseTime: 'div.dokan-store-open-close', // Add trailing comma

Add a trailing comma to maintain consistency with the codebase style.

.github/workflows/e2e_api_tests.yml (2)

200-200: Avoid leaving commented-out steps for clarity.

These lines for "Find PR comment by github-actions[bot]" are commented out. If they are no longer needed, consider removing them to avoid confusion.

-            # - name: Find PR comment by github-actions[bot]
-            #   uses: peter-evans/find-comment@v3
+            # (Optional) Remove commented block if no longer required

211-211: Avoid leaving commented-out steps for clarity.

Similarly, these lines for creating or updating PR comments are commented out. If unneeded, you may want to remove them, or if you intend to restore them in the future, note the reason with a comment.

🛑 Comments failed to post (1)
tests/pw/pages/storeAppearance.ts (1)

10-13: 🛠️ Refactor suggestion

Remove unnecessary constructor
The constructor is empty and flagged by the linter as unnecessary. Remove it to simplify the class definition, unless you plan to extend logic here soon.

 export class StoreAppearance extends BasePage {
-    constructor(page: Page) {
-        super(page);
-    }
+    // Simply rely on the parent class constructor if no special logic is needed
 }
📝 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.

export class StoreAppearance extends BasePage {
    // Simply rely on the parent class constructor if no special logic is needed
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 11-13: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

@mralaminahamed mralaminahamed force-pushed the feat/pending-product-rejection-integration branch from c3d40f2 to 8ab1b11 Compare January 6, 2025 04:28
Copy link
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

🧹 Nitpick comments (2)
includes/DependencyManagement/Providers/CommonServiceProvider.php (2)

69-71: Add a brief docblock explaining the purpose of the newly registered service.
It's helpful to maintain clarity on why the ProductStatusRollback service is being introduced, especially for future contributors who will refer to this code.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 70-70:
Found precision alignment of 1 spaces.


[warning] 71-71:
Found precision alignment of 1 spaces.


70-71: Align code formatting to address PHPCS warnings.
Adjust spacing to maintain consistent indentation.

Apply this diff to fix indentation:

-            ->addShared( \WeDevs\Dokan\ProductStatusRollback::class, \WeDevs\Dokan\ProductStatusRollback::class )
-            ->addTag( self::TAG );
+            ->addShared(\WeDevs\Dokan\ProductStatusRollback::class, \WeDevs\Dokan\ProductStatusRollback::class)
+            ->addTag(self::TAG);
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 70-70:
Found precision alignment of 1 spaces.


[warning] 71-71:
Found precision alignment of 1 spaces.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e8ea01e and 8ab1b11.

📒 Files selected for processing (2)
  • includes/DependencyManagement/Providers/CommonServiceProvider.php (1 hunks)
  • includes/ProductStatusRollback.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • includes/ProductStatusRollback.php
🧰 Additional context used
🪛 GitHub Check: Run PHPCS inspection
includes/DependencyManagement/Providers/CommonServiceProvider.php

[warning] 70-70:
Found precision alignment of 1 spaces.


[warning] 71-71:
Found precision alignment of 1 spaces.

@mrabbani mrabbani added 👍 Dev Review Done and removed Needs: Dev Review It requires a developer review and approval labels Jan 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs: Testing This requires further testing 👍 Dev Review Done
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants