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

Add E2E tests for shortcode, commission, geolocation #2441

Merged
merged 9 commits into from
Nov 19, 2024

Conversation

shashwatahalder01
Copy link
Contributor

@shashwatahalder01 shashwatahalder01 commented Nov 18, 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)

  • Full PR Link

Closes

  • Closes #

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

Title

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

Release Notes

  • New Features

    • Introduced methods for viewing commission details and handling diagnostic notices in the admin interface.
    • Enhanced functionality for managing user consent for data collection.
    • Added vendor filtering capabilities based on status in the admin interface.
    • Added functionality to view advertised products using shortcodes.
    • Introduced geolocation features for managing map settings and product locations.
  • Bug Fixes

    • Added tests to ensure proper functionality of commission settings and diagnostic notices.
    • Improved handling of vendor status updates and interactions.
  • Documentation

    • Updated data structures to include new properties related to diagnostic notices and product advertisements.
  • Tests

    • Added new test suites to validate the rendering and functionality of diagnostic notices and commission meta-boxes.
    • Expanded tests for vendor management functionalities, particularly around vendor status filtering.
    • Introduced tests for customer interactions with advertised products.
    • Added tests for geolocation functionalities and settings management.

Copy link
Contributor

coderabbitai bot commented Nov 18, 2024

Walkthrough

The changes introduce new methods and properties across several files, enhancing functionality related to commission management and diagnostic notices in the application. Specifically, new methods for viewing commission details and handling diagnostic notices have been added, along with corresponding selectors and test cases to ensure their proper functionality. Additionally, a new database utility method for deleting option rows and a new interface for diagnostic notices have been introduced, expanding the overall structure and capabilities of the codebase.

Changes

File Change Summary
tests/pw/pages/commissionPage.ts Added method async viewCommissionMetaBox(orderId: string) to view commission metabox for specific orders.
tests/pw/pages/noticeAndPromotionPage.ts Added methods async dokanDiagnosticNoticeRenderProperly(diagnosticNotice: diagnosticNotice), async allowDiagnosticTracking(), and async disallowDiagnosticTracking() for handling diagnostic notices.
tests/pw/pages/selectors.ts Introduced new diagnostic section in selector object with properties: noticeDiv, allowCollectData, disallowCollectData, paragraph1, and paragraph2.
tests/pw/tests/e2e/commission.spec.ts Added const { PRODUCT_ID } = process.env;, and new test case: "admin can view commission meta-box on order details".
tests/pw/tests/e2e/diagnosticnotice.spec.ts Added new test suite for "Diagnostic notice" with tests for rendering and enabling/disabling diagnostic tracking.
tests/pw/utils/dbUtils.ts Added method async deleteOptionRow(optionNames: string[]) for deleting rows from the options table.
tests/pw/utils/interfaces.ts Added new interface diagnosticNotice with properties paragraph1 and paragraph2.
tests/pw/utils/testData.ts Introduced new diagnosticNotice object in data export with properties for diagnostic information, and added a URL parameter in backend for tracking opt-in status.
tests/pw/api.config.ts Updated testDir property from './tests/api' to 'tests/api'.
tests/pw/e2e.config.ts Updated testDir property from './tests/e2e' to 'tests/e2e'.
tests/pw/playwright.config.ts Updated testDir property from './tests/' to 'tests'.
tests/pw/feature-map/feature-map.yml Updated feature permissions, added new page for diagnostic notices, and modified existing permissions related to subscriptions and product advertisements.
tests/pw/pages/basePage.ts Updated methods goto, gotoUntilNetworkidle, and goIfNotThere to include a new optional parameter force.
tests/pw/pages/storesPage.ts Added method async filterVendors(filterBy: string) for filtering vendors by status and updated updateVendor method for enabling/disabling vendors.
tests/pw/tests/e2e/plugin.spec.ts Updated test names to clarify that actions are performed by an admin user.
tests/pw/tests/e2e/stores.spec.ts Introduced new tests for filtering vendors by 'pending' and 'approved' status.
tests/pw/tests/e2e/vendorAuction.spec.ts Activated a previously skipped test case for purchasing an auction product with a "buy it now" price, adding a skip message for clarity.
tests/pw/utils/apiUtils.ts Added method async updateStoreStatus(storeId: string, payload: object, auth?: auth) for updating store status via API.
tests/pw/pages/shortcodePage.ts Added method async viewAdvertisedProducts(link: string) to check visibility of product cards.
tests/pw/tests/e2e/shortcodes.spec.ts Added test case "customer can view advertised products (shortcode)" to verify functionality for viewing advertised products.
tests/pw/utils/payloads.ts Introduced new entry productAdvertisementShortcode in payloads with properties for product advertisement shortcode.
tests/pw/pages/adminPage.ts Updated setDokanSetupWizard method to replace click with clickAndAcceptAndWaitForResponseAndLoadState for improved navigation handling.
tests/pw/pages/geolocationPage.ts Added GeolocationPage class with methods for interacting with geolocation features.
tests/pw/pages/singleProductPage.ts Corrected a comment in the productLocation method.
tests/pw/tests/e2e/geolocation.spec.ts Introduced a new test suite for geolocation functionality with various tests validating geolocation settings.
tests/pw/utils/dbData.ts Added comments to clarify settings in the geolocationSettings section.

Possibly related PRs

Suggested labels

QA approved

🐰 In the land of code, where changes bloom,
New methods sprout, dispelling the gloom.
With diagnostics clear, and commissions in sight,
Our tests now dance, making everything right.
So hop along, let the features take flight,
For in this code garden, all feels just right! 🌼


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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 (13)
tests/pw/tests/e2e/diagnosticnotice.spec.ts (2)

10-21: Consider enhancing test setup reliability and cleanup.

While the current setup is functional, consider these improvements for better reliability:

  1. Add error handling in the setup
  2. Verify successful database cleanup
  3. Close the browser context in afterAll

Here's a suggested implementation:

 test.beforeAll(async ({ browser }) => {
+    try {
         const adminContext = await browser.newContext(data.auth.adminAuth);
         aPage = await adminContext.newPage();
         admin = new NoticeAndPromotionPage(aPage);

         // delete previous settings if exists
         await dbUtils.deleteOptionRow(['dokan_tracking_notice', 'dokan_allow_tracking']);
+        // verify cleanup
+        const verifyCleanup = await dbUtils.getOptionValue(['dokan_tracking_notice', 'dokan_allow_tracking']);
+        if (verifyCleanup.some(value => value !== null)) {
+            throw new Error('Failed to clean up previous settings');
+        }
+    } catch (error) {
+        console.error('Setup failed:', error);
+        throw error;
+    }
 });

 test.afterAll(async () => {
+    const context = aPage.context();
     await aPage.close();
+    await context.close();
 });

1-30: Consider implementing a custom test fixture for diagnostic notice tests.

To improve test maintainability and reduce code duplication in future diagnostic notice related tests, consider creating a custom test fixture that handles the common setup and teardown operations.

Example implementation:

// diagnosticFixture.ts
import { test as base } from '@playwright/test';
import { NoticeAndPromotionPage } from '@pages/noticeAndPromotionPage';

type DiagnosticFixture = {
    diagnosticPage: NoticeAndPromotionPage;
    cleanupSettings: () => Promise<void>;
};

export const test = base.extend<DiagnosticFixture>({
    diagnosticPage: async ({ browser }, use) => {
        const context = await browser.newContext(data.auth.adminAuth);
        const page = await context.newPage();
        const diagnosticPage = new NoticeAndPromotionPage(page);
        await use(diagnosticPage);
        await context.close();
    },
    cleanupSettings: async ({}, use) => {
        await use(async () => {
            await dbUtils.deleteOptionRow(['dokan_tracking_notice', 'dokan_allow_tracking']);
        });
    },
});

This would simplify the test file and make it more maintainable:

import { test } from './diagnosticFixture';

test('admin can view Dokan diagnostic notice', async ({ diagnosticPage, cleanupSettings }) => {
    await cleanupSettings();
    // test implementation
});
tests/pw/pages/noticeAndPromotionPage.ts (2)

79-85: Consider adding error handling and retry mechanism.

The diagnostic notice verification looks good but could be more robust:

  1. Add custom error messages for better debugging
  2. Consider adding retry mechanism for flaky tests
  3. Extract common navigation logic to reduce duplication

Example improvement:

 async dokanDiagnosticNoticeRenderProperly(diagnosticNotice: diagnosticNotice) {
-    await this.gotoUntilNetworkidle(data.subUrls.backend.adminDashboard);
+    await this.gotoAdminDashboard();
+    try {
         await this.toBeVisible(selector.admin.dokan.diagnostic.noticeDiv);
         await this.toContainText(selector.admin.dokan.diagnostic.paragraph1, diagnosticNotice.paragraph1);
         await this.toContainText(selector.admin.dokan.diagnostic.paragraph2, diagnosticNotice.paragraph2);
+    } catch (error) {
+        throw new Error(`Failed to verify diagnostic notice: ${error.message}`);
+    }
 }

+private async gotoAdminDashboard() {
+    await this.gotoUntilNetworkidle(data.subUrls.backend.adminDashboard);
+}

87-92: Add response validation for diagnostic tracking.

The tracking allowance looks good but could be more thorough:

  1. Validate the success response body/headers
  2. Add error handling for failed requests
  3. Consider adding a success message verification

Example improvement:

 async allowDiagnosticTracking() {
-    await this.gotoUntilNetworkidle(data.subUrls.backend.adminDashboard);
+    await this.gotoAdminDashboard();
+    try {
-        await this.clickAndWaitForResponse(data.subUrls.backend.diagnosticNotice, selector.admin.dokan.diagnostic.allowCollectData, 302);
+        const response = await this.clickAndWaitForResponse(
+            data.subUrls.backend.diagnosticNotice,
+            selector.admin.dokan.diagnostic.allowCollectData,
+            302
+        );
+        // Verify success response
+        const responseBody = await response.json();
+        if (!responseBody.success) {
+            throw new Error('Diagnostic tracking allowance failed');
+        }
         await this.notToBeVisible(selector.admin.dokan.diagnostic.noticeDiv);
+        // Verify success message if applicable
+        await this.toBeVisible(selector.admin.dokan.diagnostic.successMessage);
+    } catch (error) {
+        throw new Error(`Failed to allow diagnostic tracking: ${error.message}`);
+    }
 }
tests/pw/tests/e2e/commission.spec.ts (3)

Line range hint 26-31: Track technical debt for subscription functionality

There are multiple commented blocks related to subscription functionality. These should be tracked as technical debt to ensure they're properly implemented in the future.

Would you like me to create a GitHub issue to track the implementation of these subscription-related features?

Also applies to: 41-43


101-104: Enhance test robustness and coverage

The new test case could be improved in several ways:

  1. Consider testing with different order statuses to ensure the meta-box works in all scenarios
  2. Add explicit assertions in the viewCommissionMetaBox method
  3. Consider testing edge cases (e.g., orders with multiple products, different commission types)
 test('admin can view commission meta-box on order details', { tag: ['@lite', '@admin'] }, async () => {
-    const [, , orderId] = await apiUtils.createOrderWithStatus(PRODUCT_ID, payloads.createOrder, data.order.orderStatus.onhold, payloads.vendorAuth);
-    await admin.viewCommissionMetaBox(orderId);
+    for (const status of Object.values(data.order.orderStatus)) {
+        const [, , orderId] = await apiUtils.createOrderWithStatus(PRODUCT_ID, payloads.createOrder, status, payloads.vendorAuth);
+        await admin.viewCommissionMetaBox(orderId);
+        // TODO: Add assertions to verify commission calculations based on order status
+    }
 });

Based on the gathered evidence, I can now provide a final response:

Decimal separator issue is a known locale formatting conflict

The issue occurs because the test helper priceStringWithDecimal() is using Spanish locale formatting (es-ES and es-US) which uses comma (,) as decimal separator, but the application is expecting period (.) as the decimal separator. This is evident from:

  1. The helper function in tests/pw/utils/helpers.ts forces Spanish locale: Number(num).toLocaleString('es-ES')
  2. Some test data already has a workaround using 'US' locale with TODO comments: commissionFixed: helpers.priceStringWithDecimal(5, 'US'), // todo: change to ES when issue is fixed
  3. The application's decimal handling (from previous search) uses WooCommerce's decimal separator configuration

To fix this:

  • Either update the helper to use the application's configured decimal separator
  • Or ensure the application properly handles locale-specific decimal separators
🔗 Analysis chain

Line range hint 82-85: Track and fix decimal separator issue

The test is skipped due to a decimal separator issue where "," becomes ".". This should be investigated and fixed.


Based on the search results, I can see that the codebase handles decimal separators in multiple places, particularly in the context of price formatting and currency display. The key findings are:

  1. The decimal separator configuration is managed through WooCommerce's settings using wc_get_price_decimal_separator()
  2. There's a schema definition in tests/pw/utils/schemas.ts that includes decimal separator handling
  3. The frontend receives decimal separator configuration through localized data

Let me verify the specific test case by looking at the skipped test:


Let me check the commission data structure and related code to understand how the decimal values are handled:


Let me check the helper function that handles the decimal formatting:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related decimal handling code
rg -g '!{node_modules,vendor}/*' -A 3 'decimal_separator|number_format|wc_format_decimal'

Length of output: 38086


Script:

#!/bin/bash
# Find the skipped test case around line 82
rg -A 5 -B 5 "test\.skip.*decimal.*separator" tests/pw/tests/e2e/commission.spec.ts

Length of output: 787


Script:

#!/bin/bash
# Check the commission data structure and related test utilities
rg -g "*.ts" -A 5 "commission.*fixed" tests/pw/

Length of output: 22335


Script:

#!/bin/bash
# Check the helper function that handles price formatting
rg -g "*.ts" "priceStringWithDecimal" tests/pw/

Length of output: 1937

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

173-179: Enhance method documentation and error handling.

The basic functionality looks good, but consider these improvements:

  1. Add JSDoc documentation to match the style of other methods
  2. Add TypeScript return type annotation
  3. Add error handling for invalid orderId

Here's the suggested implementation:

-    // view commission metabox
-    async viewCommissionMetaBox(orderId: string) {
+    /**
+     * View commission metabox for a specific order
+     *
+     * @param {string} orderId - The ID of the order to view
+     * @returns {Promise<void>}
+     * @throws {Error} When order details page cannot be loaded
+     */
+    async viewCommissionMetaBox(orderId: string): Promise<void> {
+        if (!orderId) {
+            throw new Error('Order ID is required');
+        }
+
         await this.gotoUntilNetworkidle(data.subUrls.backend.orderDetails(orderId));
 
         // metabox elements are visible
         await this.multipleElementVisible(selector.admin.wooCommerce.orders.commissionMetaBox);
     }

Line range hint 1-179: Well-integrated with existing commission management functionality.

The new viewCommissionMetaBox method:

  • Follows established class patterns
  • Properly utilizes shared utilities and selectors
  • Complements existing commission management methods

Consider grouping related commission viewing methods together in the class structure if more viewing operations are added in the future.

tests/pw/utils/dbUtils.ts (2)

104-109: Good use of parameterized queries, but could use some improvements

The implementation correctly uses parameterized queries for SQL injection prevention, which is great. However, consider these improvements:

  1. Add input validation
  2. Use a more specific return type
  3. Add error handling for common scenarios

Consider this enhanced implementation:

-    async deleteOptionRow(optionNames: string[]): Promise<any> {
-        const query = `DELETE FROM ${dbPrefix}_options WHERE option_name IN (${optionNames.map(() => '?').join(',')})`;
-        const res = await dbUtils.dbQuery(query, optionNames);
-        return res;
-    },
+    async deleteOptionRow(optionNames: string[]): Promise<{ affectedRows: number }> {
+        if (!optionNames?.length) {
+            throw new Error('Option names array cannot be empty');
+        }
+        try {
+            const query = `DELETE FROM ${dbPrefix}_options WHERE option_name IN (${optionNames.map(() => '?').join(',')})`;
+            const res = await dbUtils.dbQuery(query, optionNames);
+            return res;
+        } catch (error) {
+            throw new Error(`Failed to delete option rows: ${error.message}`);
+        }
+    },

This enhancement:

  • Validates input to prevent SQL syntax errors
  • Uses a specific return type matching MySQL2's DELETE result
  • Adds error handling with meaningful messages

104-104: Add JSDoc documentation for test utility method

Since this is a test utility method, adding documentation would help other test authors understand its purpose and usage.

Consider adding this documentation:

+    /**
+     * Deletes multiple option rows from WordPress options table.
+     * Useful for cleaning up test data after E2E tests that modify WordPress options.
+     * 
+     * @param optionNames - Array of option names to delete
+     * @returns Promise resolving to the deletion result
+     * @throws Error if the option names array is empty
+     * 
+     * @example
+     * ```ts
+     * // Clean up test options after test
+     * await dbUtils.deleteOptionRow(['test_option_1', 'test_option_2']);
+     * ```
+     */
tests/pw/utils/interfaces.ts (1)

28-31: LGTM! Consider adding JSDoc comments.

The interface is well-structured and properly integrated. The property names are clear and self-explanatory.

Consider adding JSDoc comments to document the purpose of the interface and its properties:

+/**
+ * Interface representing the structure of a diagnostic notice.
+ */
 export interface diagnosticNotice {
+    /** The first paragraph of the diagnostic notice */
     paragraph1: string;
+    /** The second paragraph of the diagnostic notice */
     paragraph2: string;
 }
tests/pw/pages/selectors.ts (1)

2982-2988: LGTM! Consider adding a comment describing the commission meta box selectors.

The commission meta box selectors are well-structured and follow the existing patterns. The locators use appropriate CSS and XPath selectors to target the elements.

Consider adding a brief comment above the commissionMetaBox object to describe its purpose and usage, similar to other sections in the file. For example:

+ // Selectors for the order commission meta box that displays commission details
 commissionMetaBox: {
     metaBoxDiv: 'div#dokan_commission_box',
     commissionsText: '//h2[normalize-space()="Commissions"]',
     orderItemInfo: 'div#dokan_commission_box table.woocommerce_order_items',
     orderTotalInfo: 'div#dokan_commission_box div.wc-order-totals-items',
 },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 329da76 and 7cdcba5.

📒 Files selected for processing (8)
  • tests/pw/pages/commissionPage.ts (1 hunks)
  • tests/pw/pages/noticeAndPromotionPage.ts (2 hunks)
  • tests/pw/pages/selectors.ts (2 hunks)
  • tests/pw/tests/e2e/commission.spec.ts (2 hunks)
  • tests/pw/tests/e2e/diagnosticnotice.spec.ts (1 hunks)
  • tests/pw/utils/dbUtils.ts (1 hunks)
  • tests/pw/utils/interfaces.ts (1 hunks)
  • tests/pw/utils/testData.ts (2 hunks)
🔇 Additional comments (6)
tests/pw/tests/e2e/diagnosticnotice.spec.ts (1)

1-5: LGTM! Well-structured imports following best practices.

The imports demonstrate good separation of concerns by utilizing the page object pattern and dedicated utilities for test data and database operations.

tests/pw/pages/noticeAndPromotionPage.ts (1)

5-5: LGTM!

The import is properly organized and follows the project's import conventions.

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

Line range hint 11-104: Verify complete test coverage of commission features

Let's ensure all commission-related features are covered by these E2E tests.

tests/pw/utils/dbUtils.ts (1)

105-108: Implementation aligns well with existing patterns

The method maintains consistency with other database operations in the file by:

  • Using the shared database connection pool
  • Following the established error propagation pattern
  • Maintaining consistent coding style
tests/pw/utils/testData.ts (2)

131-135: LGTM! The diagnostic notice text is clear and informative.

The diagnostic notice object is well-structured with appropriate text content explaining data collection consent to users.


1011-1012: LGTM! The diagnostic notice URL parameter is properly implemented.

The URL parameter for tracking opt-in status is correctly placed in the backend URLs section.

tests/pw/tests/e2e/diagnosticnotice.spec.ts Outdated Show resolved Hide resolved
tests/pw/tests/e2e/commission.spec.ts 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: 9

🧹 Outside diff range and nitpick comments (14)
tests/pw/tests/e2e/diagnosticnotice.spec.ts (2)

7-8: Add type annotations for better type safety.

Consider adding explicit type annotations to improve code maintainability and catch potential type-related issues early.

-    let admin: NoticeAndPromotionPage;
-    let aPage: Page;
+    let admin: NoticeAndPromotionPage | undefined;
+    let aPage: Page | undefined;

1-35: Consider implementing a shared test utilities module.

To improve maintainability and reduce code duplication across E2E tests, consider:

  1. Creating shared assertion helpers for common verification patterns
  2. Implementing a test data cleanup utility
  3. Adding custom test fixtures for common setup/teardown operations

Example structure:

// testUtils.ts
export const assertNoticeContent = async (notice: any, expectedData: any) => {
    expect(notice.isVisible).toBeTruthy();
    expect(notice.title).toBe(expectedData.title);
    // ... more assertions
};

export const cleanupTestData = async (options: string[]) => {
    try {
        await dbUtils.deleteOptionRow(options);
    } catch (error) {
        console.error('Cleanup failed:', error);
        throw error;
    }
};

// Custom fixture
export const test = base.extend({
    adminPage: async ({ browser }, use) => {
        const context = await browser.newContext(data.auth.adminAuth);
        const page = await context.newPage();
        const admin = new NoticeAndPromotionPage(page);
        await use(admin);
        await page.close();
    }
});
tests/pw/tests/e2e/stores.spec.ts (1)

Line range hint 1-89: Consider reorganizing tests for better maintainability

The test file has a good structure, but consider these improvements:

  1. Group related tests using nested describe blocks (e.g., "Vendor Status Management", "Vendor Information Management")
  2. Consider extracting common setup/cleanup logic into helper functions
  3. Consider adding test data factories for creating stores with different statuses

Example organization:

test.describe('Stores test', () => {
    // ... setup code ...

    test.describe('Vendor Status Management', () => {
        // Filter tests
        // Enable/disable tests
    });

    test.describe('Vendor Information Management', () => {
        // View details
        // Edit info
        // Email vendor
    });

    test.describe('Vendor Listing Management', () => {
        // Search
        // Bulk actions
    });
});
tests/pw/tests/e2e/plugin.spec.ts (2)

50-63: Reduce code duplication in plugin test cases

The Lite plugin test cases duplicate the structure of Pro plugin tests. Consider refactoring to use a shared test factory:

const testPluginOperations = (pluginType: 'pro' | 'lite') => {
  const pluginName = pluginType === 'pro' ? data.plugin.pluginName.dokanPro : data.plugin.pluginName.dokanLite;
  const pluginPath = pluginType === 'pro' ? 'dokan-pro/dokan-pro' : 'dokan/dokan';
  const tag = pluginType === 'pro' ? '@pro' : '@lite';

  test(`admin can activate Dokan ${pluginType} plugin`, { tag: [tag, '@admin', '@serial'] }, async () => {
    await apiUtils.updatePlugin(pluginPath, { status: 'inactive' }, payloads.adminAuth);
    await admin.activatePlugin(pluginName);
    // Add assertions here
  });
  // ... other test cases
};

// Usage
testPluginOperations('pro');
testPluginOperations('lite');

74-75: Convert TODO comments to tracked issues

These TODO items represent important test scenarios that should be properly tracked:

  1. Plugin replacement test
  2. Plugin installation test

Would you like me to create GitHub issues to track these test implementations? I can help provide detailed acceptance criteria and test scenarios for each case.

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

Line range hint 1-116: Consider optimizing test configuration for better reliability.

While reviewing the configuration, I noticed some potential improvements that could enhance test reliability and performance:

  1. The test timeout in CI (15s) is shorter than local (20s), which could lead to flaky tests. Consider making CI timeout >= local timeout.
  2. Fixed worker count (4) might not be optimal for all CI environments. Consider using a dynamic value based on available CPU cores.
  3. The commented-out fullyParallel and forbidOnly options could improve test execution and catch common mistakes.

Consider these adjustments:

-    timeout: CI ? 15 * 1000 : 20 * 1000,
+    timeout: 20 * 1000,

-    workers: CI ? 4 : 4,
+    workers: CI ? process.env.CI_WORKERS || 4 : 4,

-    // fullyParallel  : true,
-    // forbidOnly     : !!CI,
+    fullyParallel: true,
+    forbidOnly: !!CI,
tests/pw/playwright.config.ts (1)

Line range hint 1-120: Consider enhancing the E2E test configuration.

The configuration provides a solid foundation for E2E testing. Consider these enhancements to improve robustness and maintainability:

  1. Enable fullyParallel with appropriate workers count to speed up test execution
  2. Add globalSetup for common setup tasks like authentication
  3. Consider using trace: 'retain-on-failure' instead of 'on-first-retry' to aid in debugging failed tests
  4. Add custom test fixtures for common operations

Example implementation for a custom test fixture:

// fixtures.ts
import { test as base } from '@playwright/test';

type CustomFixtures = {
  authenticatedPage: Page;
};

export const test = base.extend<CustomFixtures>({
  authenticatedPage: async ({ page }, use) => {
    // Add authentication logic here
    await use(page);
  },
});
tests/pw/pages/storesPage.ts (1)

238-239: Add JSDoc documentation for the filterVendors method

Add comprehensive documentation to improve maintainability and clarity.

Add this documentation:

/**
 * Filters vendors based on their status.
 * @param filterBy - The status to filter vendors by ('pending' or 'approved')
 * @throws {Error} If an invalid filter value is provided
 * @example
 * ```typescript
 * await storesPage.filterVendors('pending');
 * ```
 */
tests/pw/feature-map/feature-map.yml (2)

416-422: Review diagnostic data collection practices.

The new diagnostic notice features involve tracking capabilities. Ensure:

  1. User privacy is maintained
  2. Diagnostic data collection is transparent
  3. Users can opt-out easily

Consider implementing:

  • Clear user consent mechanisms
  • Data anonymization
  • Configurable data retention policies

988-999: Ensure subscription state transitions are atomic.

The new subscription management features should handle state transitions atomically to prevent inconsistencies.

Consider implementing:

  • Transaction-based state changes
  • Rollback mechanisms for failed operations
  • Audit logging for subscription changes
tests/pw/pages/basePage.ts (2)

46-50: Add JSDoc documentation for the force parameter.

The implementation looks good, but could benefit from documentation explaining when to use the force parameter.

Add JSDoc documentation like:

+/**
+ * Navigate to a URL path
+ * @param subPath The URL path to navigate to
+ * @param options Navigation options
+ * @param force Whether to force reload the page after navigation
+ */
async goto(subPath: string, options: {...}, force = false): Promise<void> {

54-58: Consider refactoring to avoid code duplication.

The force reload logic is duplicated between goto and gotoUntilNetworkidle. Consider refactoring to reuse the logic.

You could refactor like this:

async gotoUntilNetworkidle(subPath: string, options: {...} = { waitUntil: 'networkidle' }, force = false): Promise<void> {
-    await this.goto(subPath, options);
-    if (force) {
-        await this.reload(); 
-    }
+    await this.goto(subPath, options, force);
}
tests/pw/utils/apiUtils.ts (1)

264-268: LGTM with a minor suggestion for error handling consistency.

The implementation looks good and follows the established patterns. Consider adding explicit error handling similar to other update methods in the class for consistency.

 async updateStoreStatus(storeId: string, payload: object, auth?: auth): Promise<responseBody> {
-    const [, responseBody] = await this.put(endPoints.updateStoreStatus(storeId), { data: payload, headers: auth });
+    const [response, responseBody] = await this.put(endPoints.updateStoreStatus(storeId), { data: payload, headers: auth }, false);
+    if (responseBody.code) {
+        expect(response.status()).toBe(400);
+        console.log('Failed to update store status:', responseBody.message);
+    } else {
+        expect(response.ok()).toBeTruthy();
+    }
     return responseBody;
 }
tests/pw/pages/selectors.ts (1)

2983-2989: Consider adding more specific selectors for commission meta box elements.

While the basic structure is good, consider adding more granular selectors for individual commission elements within the meta box (e.g., commission rates, totals, etc.) to improve test maintainability.

commissionMetaBox: {
    metaBoxDiv: 'div#dokan_commission_box',
    commissionsText: '//h2[normalize-space()="Commissions"]',
    orderItemInfo: 'div#dokan_commission_box table.woocommerce_order_items',
    orderTotalInfo: 'div#dokan_commission_box div.wc-order-totals-items',
+   commissionRate: 'div#dokan_commission_box .commission-rate',
+   commissionAmount: 'div#dokan_commission_box .commission-amount',
+   vendorEarnings: 'div#dokan_commission_box .vendor-earnings',
+   adminCommission: 'div#dokan_commission_box .admin-commission'
},
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7cdcba5 and ec8bdef.

📒 Files selected for processing (13)
  • tests/pw/api.config.ts (1 hunks)
  • tests/pw/e2e.config.ts (1 hunks)
  • tests/pw/feature-map/feature-map.yml (15 hunks)
  • tests/pw/pages/basePage.ts (1 hunks)
  • tests/pw/pages/noticeAndPromotionPage.ts (2 hunks)
  • tests/pw/pages/selectors.ts (3 hunks)
  • tests/pw/pages/storesPage.ts (1 hunks)
  • tests/pw/playwright.config.ts (1 hunks)
  • tests/pw/tests/e2e/diagnosticnotice.spec.ts (1 hunks)
  • tests/pw/tests/e2e/plugin.spec.ts (1 hunks)
  • tests/pw/tests/e2e/stores.spec.ts (1 hunks)
  • tests/pw/tests/e2e/vendorAuction.spec.ts (1 hunks)
  • tests/pw/utils/apiUtils.ts (1 hunks)
🔇 Additional comments (17)
tests/pw/tests/e2e/diagnosticnotice.spec.ts (2)

1-5: LGTM! Imports are well-organized.

The imports follow TypeScript best practices and include all necessary dependencies for the test suite.


23-34: 🛠️ Refactor suggestion

Enhance test robustness and documentation.

The test implementation needs improvements in several areas:

  1. Add explicit assertions to verify expected outcomes
  2. Include error handling
  3. Add JSDoc documentation
  4. Consider edge cases

Here's a suggested implementation for the first test case (apply similar patterns to others):

+/**
+ * @description Verifies that the Dokan diagnostic notice renders correctly for admin users
+ * @expectation Notice should display with correct title, message, and action buttons
+ */
 test('admin can view Dokan diagnostic notice', { tag: ['@lite', '@admin'] }, async () => {
+    try {
+        const result = await admin.dokanDiagnosticNoticeRenderProperly(data.diagnosticNotice);
+        
+        // Verify notice content
+        expect(result.isVisible).toBeTruthy();
+        expect(result.title).toBe(data.diagnosticNotice.title);
+        expect(result.message).toContain(data.diagnosticNotice.paragraph1);
+        expect(result.message).toContain(data.diagnosticNotice.paragraph2);
+        
+        // Verify action buttons
+        expect(result.allowButton).toBeTruthy();
+        expect(result.disallowButton).toBeTruthy();
+    } catch (error) {
+        console.error('Test failed:', error);
+        throw error;
+    }
 });

Consider adding these test cases:

  1. Verify notice persistence after page reload
  2. Test notice dismissal behavior
  3. Validate tracking status after allow/disallow actions
tests/pw/tests/e2e/stores.spec.ts (1)

60-68: ⚠️ Potential issue

Improve test cleanup and verification

The enable/disable vendor tests need improvements:

  1. Add cleanup to prevent test data pollution
  2. Add assertions to verify the final store status
  3. Use consistent destructuring pattern between tests

Here's a suggested implementation:

 test("admin can enable vendor's selling capability", { tag: ['@lite', '@admin'] }, async () => {
-    const [, sellerId, storeName] = await apiUtils.createStore(payloads.createStore(), payloads.adminAuth);
+    const [, sellerId] = await apiUtils.createStore(payloads.createStore(), payloads.adminAuth);
     await apiUtils.updateStoreStatus(sellerId, { status: 'inactive' }, payloads.adminAuth);
-    await admin.updateVendor(storeName, 'enable');
+    await admin.updateVendor(sellerId, 'enable');
+    // Add assertion
+    const storeStatus = await apiUtils.getStoreStatus(sellerId, payloads.adminAuth);
+    expect(storeStatus).toBe('active');
+    // Cleanup
+    await apiUtils.deleteStore(sellerId, payloads.adminAuth);
 });

 test("admin can disable vendor's selling capability", { tag: ['@lite', '@admin'] }, async () => {
-    const [, , storeName] = await apiUtils.createStore(payloads.createStore(), payloads.adminAuth);
-    await admin.updateVendor(storeName, 'disable');
+    const [, sellerId] = await apiUtils.createStore(payloads.createStore(), payloads.adminAuth);
+    await admin.updateVendor(sellerId, 'disable');
+    // Add assertion
+    const storeStatus = await apiUtils.getStoreStatus(sellerId, payloads.adminAuth);
+    expect(storeStatus).toBe('inactive');
+    // Cleanup
+    await apiUtils.deleteStore(sellerId, payloads.adminAuth);
 });

Let's verify if the required API methods exist:

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

Line range hint 9-9: Remove .skip from test suite to enable plugin functionality tests

The entire test suite is currently skipped. If these tests are ready for execution, consider removing the .skip modifier to ensure plugin functionality is properly tested.

✅ Verification successful

Let me gather more information to understand if there are other plugin-related tests that might be covering this functionality.


Let me check the actual plugin test implementations to understand if this is the only test suite for plugin functionality and why it might be skipped.


Keep the test suite skipped as it's part of a larger maintenance pattern

The .skip modifier should remain in place as this appears to be part of a broader test suite maintenance pattern. Several test suites are currently skipped, including settings, store appearance, and vendor RMA tests. The plugin tests themselves are well-structured with proper setup/teardown and cover both Dokan Pro and Lite functionality. The skipped status seems intentional as part of a larger testing strategy rather than an oversight.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are other test suites testing similar functionality
rg -l "Plugin functionality test" --type ts

Length of output: 79


Script:

#!/bin/bash
# Search for other plugin-related test files and their content
rg -l "plugin" --type ts tests/

Length of output: 575


Script:

#!/bin/bash
# Check if there are any active plugin tests in the codebase
rg "test\.describe\(['\"].*plugin.*['\"]" --type ts -A 1

Length of output: 62


Script:

#!/bin/bash
# Look for TODO comments related to plugin tests
rg "TODO.*plugin" --type ts

Length of output: 29


Script:

#!/bin/bash
# Check the content of plugin.spec.ts to understand test coverage
cat tests/pw/tests/e2e/plugin.spec.ts

Length of output: 3528


Script:

#!/bin/bash
# Look for test.describe with skip in the codebase
rg "test\.describe\.skip" --type ts

Length of output: 565


Script:

#!/bin/bash
# Check pluginPage.ts for any related functionality
cat tests/pw/pages/pluginPage.ts

Length of output: 2117

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

93-95: ⚠️ Potential issue

Critical: "Buy it now" functionality is not being tested due to API issue

The test is being skipped due to an API issue where the "buy it now" price is not being saved. This indicates a potential regression or unresolved backend issue that needs attention, as it affects a critical business functionality.

Let's verify the API issue:

Would you like me to:

  1. Create a GitHub issue to track this API bug?
  2. Help implement the API fix for saving the "buy it now" price?
tests/pw/pages/noticeAndPromotionPage.ts (3)

5-5: LGTM: Clean import statement addition

The import of the diagnosticNotice interface is properly placed and necessary for the new diagnostic notice functionality.


79-85: LGTM: Well-structured diagnostic notice validation

The method properly validates both the visibility and content of the diagnostic notice, with good use of async/await and proper type checking.


87-92: LGTM: Robust allow tracking implementation

Good implementation with proper network idle waiting and response code validation. The method ensures the notice disappears after the action.

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

7-7: LGTM! Path simplification is valid.

The change from './tests/' to 'tests' is a valid simplification that maintains the same functionality.

tests/pw/pages/storesPage.ts (1)

238-255: Verify test coverage for the filterVendors functionality

Since this is part of the E2E test suite, ensure there are corresponding test cases that exercise this filtering functionality.

✅ Verification successful

Test coverage for filterVendors is adequate

The functionality is well covered with dedicated test cases:

  • Test for filtering pending vendors: creates a vendor, sets it to inactive, and verifies filtering
  • Test for filtering approved vendors: verifies filtering of approved vendors
  • Additional related test (skipped) for filtering by seller badge
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test cases using the filterVendors method

# Look for test files that might use this functionality
echo "Searching for test files using filterVendors..."
rg -l "filterVendors" tests/pw/tests/

# Look for specific test cases
echo "Searching for specific test cases..."
rg "test\(.*filterVendors" tests/pw/tests/

Length of output: 344


Script:

#!/bin/bash
# Let's examine the content of the files that reference filterVendors
echo "Content of stores.spec.ts:"
rg -A 10 -B 10 "filterVendors" tests/pw/tests/e2e/stores.spec.ts

echo -e "\nContent of sellerBadges.spec.ts:"
rg -A 10 -B 10 "filterVendors" tests/pw/tests/e2e/sellerBadges.spec.ts

Length of output: 2775

tests/pw/feature-map/feature-map.yml (6)

545-545: Validate bulk action implementations.

Multiple bulk action capabilities have been enabled for marketplace features. Ensure proper validation and error handling.

#!/bin/bash
# Description: Check bulk action implementations
# Test: Search for bulk action handlers and validation

# Check for bulk action handlers
ast-grep --pattern 'function $_(bulk|handle_bulk)($_) {
  $$$
}'

# Check for nonce verification in bulk actions
rg -A 3 "check_ajax_referer|wp_verify_nonce.*bulk"

Also applies to: 608-608, 939-939


649-652: Review license activation/deactivation security.

The license management features should implement proper security measures.

#!/bin/bash
# Description: Check license management security
# Test: Search for license validation and security measures

# Check for license validation
rg -A 3 "verify_license|validate_license|check_license"

# Check for nonce usage in license operations
rg -A 3 "wp_verify_nonce.*license|check_ajax_referer.*license"

1087-1088: Verify seller badge filtering performance.

The addition of seller badge filtering should be optimized for performance, especially with large datasets.


350-350: Verify commission meta-box visibility permissions.

The addition of commission meta-box visibility should be properly restricted to admin users only.


321-322: Ensure vendor status filtering is consistent with database schema.

The addition of vendor status filtering capabilities should align with the existing vendor status values in the database.


5-13: Verify plugin deactivation handling.

The changes enable admin capabilities for managing Dokan plugins. However, ensure proper cleanup and data handling during plugin deactivation.

✅ Verification successful

Plugin deactivation handling is properly implemented.

The codebase has comprehensive deactivation and uninstall handling:

  • Proper deactivation hook registration in dokan-class.php
  • Clean uninstall process in uninstall.php with data removal safeguards
  • Settings option data_clear_on_uninstall to control data cleanup
  • Transient cleanup on deactivation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for deactivation cleanup handlers
# Test: Search for deactivation hooks and cleanup functions

# Check for deactivation hooks
rg -A 5 "register_(de)?activation_hook|add_action.*deactivat" 

# Check for cleanup functions
ast-grep --pattern 'function $_(deactivate|cleanup|uninstall)($_) {
  $$$
}'

Length of output: 217


Script:

#!/bin/bash
# Let's try a different approach to find deactivation-related code

# Search for deactivation-related files and functions
rg -i "deactivat|uninstall" --type php -A 5

# Look for plugin lifecycle hooks
rg "register_(de)?activation_hook" --type php

# Search for cleanup or uninstall related files
fd -e php -e inc "(deactivat|uninstall|cleanup)"

# Check for plugin main class destructors
ast-grep --pattern 'class $_ {
  $$$
  function __destruct() {
    $$$
  }
  $$$
}'

Length of output: 10837

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

240-246: LGTM! Well-structured diagnostic notice selectors.

The diagnostic notice selectors are well organized and use appropriate XPath expressions for targeting specific elements. The naming is clear and follows consistent conventions.

tests/pw/tests/e2e/diagnosticnotice.spec.ts Show resolved Hide resolved
tests/pw/tests/e2e/stores.spec.ts Show resolved Hide resolved
tests/pw/tests/e2e/plugin.spec.ts Show resolved Hide resolved
tests/pw/tests/e2e/plugin.spec.ts Show resolved Hide resolved
tests/pw/pages/noticeAndPromotionPage.ts Show resolved Hide resolved
tests/pw/pages/noticeAndPromotionPage.ts Show resolved Hide resolved
tests/pw/api.config.ts Show resolved Hide resolved
tests/pw/e2e.config.ts Show resolved Hide resolved
tests/pw/pages/storesPage.ts 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: 1

🧹 Outside diff range and nitpick comments (3)
tests/pw/tests/e2e/shortcodes.spec.ts (1)

90-95: Add error handling for API calls.

The test makes multiple API calls but doesn't handle potential failures. Consider wrapping the API calls in try-catch blocks or using test.fail() for better error reporting.

Example implementation:

 test('customer can view advertised products (shortcode)', { tag: ['@pro', '@admin'] }, async ({ test }) => {
+    let adResponse, pageId;
+    try {
-        const [adResponse] = await apiUtils.createProductAdvertisement(payloads.createProduct(), payloads.adminAuth);
-        const [responseBody, pageId] = await apiUtils.createPage(payloads.productAdvertisementShortcode, payloads.adminAuth);
+        [adResponse] = await apiUtils.createProductAdvertisement(payloads.createProduct(), payloads.adminAuth);
+        const [responseBody, id] = await apiUtils.createPage(payloads.productAdvertisementShortcode, payloads.adminAuth);
+        pageId = id;
         await customer.viewAdvertisedProducts(responseBody.link);
+    } catch (error) {
+        test.fail(error instanceof Error ? error.message : 'Test failed during API operations');
+    } finally {
         await apiUtils.deletePage(pageId, payloads.adminAuth);
+        if (adResponse?.id) {
+            await apiUtils.deleteProductAdvertisement(adResponse.id, payloads.adminAuth);
+        }
+    }
 });
tests/pw/pages/shortcodePage.ts (1)

144-157: Consider refactoring duplicated product validation logic.

The implementation looks good, but there's an opportunity to reduce code duplication. The product card validation logic is identical to the viewProducts method.

Consider extracting the shared validation logic into a private method:

+ private async validateProductCards() {
+   const productCount = await this.getElementCount(shopCustomer.productCard.card);
+   if (productCount) {
+     // product card elements are visible
+     await this.notToHaveCount(shopCustomer.productCard.card, 0);
+     await this.notToHaveCount(shopCustomer.productCard.productDetailsLink, 0);
+     await this.notToHaveCount(shopCustomer.productCard.productTitle, 0);
+     await this.notToHaveCount(shopCustomer.productCard.productPrice, 0);
+     await this.notToHaveCount(shopCustomer.productCard.addToCart, 0);
+   }
+ }

  async viewProducts(link: string) {
    await this.goto(link);
-   const productCount = await this.getElementCount(shopCustomer.productCard.card);
-   if (productCount) {
-     // product card elements are visible
-     await this.notToHaveCount(shopCustomer.productCard.card, 0);
-     await this.notToHaveCount(shopCustomer.productCard.productDetailsLink, 0);
-     await this.notToHaveCount(shopCustomer.productCard.productTitle, 0);
-     await this.notToHaveCount(shopCustomer.productCard.productPrice, 0);
-     await this.notToHaveCount(shopCustomer.productCard.addToCart, 0);
-   }
+   await this.validateProductCards();
  }

  async viewAdvertisedProducts(link: string) {
    await this.goto(link);
-   const productCount = await this.getElementCount(shopCustomer.productCard.card);
-   if (productCount) {
-     // product card elements are visible
-     await this.notToHaveCount(shopCustomer.productCard.card, 0);
-     await this.notToHaveCount(shopCustomer.productCard.productDetailsLink, 0);
-     await this.notToHaveCount(shopCustomer.productCard.productTitle, 0);
-     await this.notToHaveCount(shopCustomer.productCard.productPrice, 0);
-     await this.notToHaveCount(shopCustomer.productCard.addToCart, 0);
-   }
+   await this.validateProductCards();
  }
tests/pw/feature-map/feature-map.yml (1)

416-421: New diagnostic tracking feature requires privacy consideration.

The new diagnostic notice and tracking features may have privacy implications. Ensure:

  1. User consent is obtained before enabling tracking
  2. Clear documentation about what data is collected
  3. Compliance with privacy regulations (GDPR, CCPA, etc.)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ec8bdef and 868e48c.

📒 Files selected for processing (4)
  • tests/pw/feature-map/feature-map.yml (17 hunks)
  • tests/pw/pages/shortcodePage.ts (1 hunks)
  • tests/pw/tests/e2e/shortcodes.spec.ts (1 hunks)
  • tests/pw/utils/payloads.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/pw/utils/payloads.ts
🔇 Additional comments (8)
tests/pw/tests/e2e/shortcodes.spec.ts (1)

90-95: Verify assertions in viewAdvertisedProducts method.

The test calls viewAdvertisedProducts but we need to verify that it contains proper assertions to validate the advertised products are actually visible.

✅ Verification successful

Let me check the implementation of viewAdvertisedProducts in the found files.


The viewAdvertisedProducts method contains proper assertions

The implementation in tests/pw/pages/shortcodePage.ts includes comprehensive assertions that verify:

  • Product cards are present (not zero count)
  • Product details links are visible
  • Product titles are visible
  • Product prices are visible
  • Add to cart buttons are visible
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check implementation of viewAdvertisedProducts method

# Search for the method implementation
ast-grep --pattern 'viewAdvertisedProducts(link: string) {
  $$$
}'

# Alternatively, search the entire codebase
rg -l "viewAdvertisedProducts"

Length of output: 170


Script:

#!/bin/bash
# Check implementation in both files
rg -A 10 "viewAdvertisedProducts" tests/pw/pages/shortcodePage.ts tests/pw/tests/e2e/shortcodes.spec.ts

Length of output: 2087

tests/pw/feature-map/feature-map.yml (7)

321-322: Enhanced vendor filtering capabilities added.

The addition of status-based vendor filtering improves vendor management functionality.


988-999: Comprehensive subscription management features added.

The changes introduce a complete set of subscription management capabilities for vendors and customers, improving the subscription workflow.


1087-1088: Seller badge filtering enhances vendor management.

The addition of seller badge filtering capabilities improves vendor discovery and management.


5-13: ⚠️ Potential issue

Review plugin management permissions carefully.

The changes grant extensive plugin management capabilities to admin users. While this provides necessary administrative control, ensure these permissions align with your security policies.


361-361: Commented out date filtering features need attention.

There are commented-out date filtering features for withdrawals and reverse withdrawals. Consider:

  1. Why these features are commented out
  2. If there's a plan to implement them
  3. Impact on user experience without date filtering

Would you like me to help implement these date filtering features?

Also applies to: 383-383


1238-1238: Verify subscription reactivation logic.

The admin can reactive recurring subscription feature is set to false when there's an active period. This might need clarification or documentation about the intended behavior.

✅ Verification successful

Let me search for more context about the subscription reactivation logic, particularly focusing on admin-related functionality.


Feature flag correctly reflects intended subscription reactivation behavior

The feature flag admin can reactive recurring subscription (has active period): false is consistent with the system's design. The flag explicitly indicates that admins should not be able to reactivate subscriptions that still have an active period, which is a logical business rule to prevent duplicate active periods. This is in contrast to the customer reactivation flow (customer can reactivate subscription: true) which likely has different validation rules.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for subscription reactivation implementation

# Test: Search for subscription reactivation logic
rg -A 5 "reactivate.*subscription"

Length of output: 2251


Script:

#!/bin/bash
# Search for admin-related subscription reactivation patterns
rg -A 5 -i "admin.*subscription.*reactivat|reactivat.*admin.*subscription"

# Search for any reactivation-related tests or configurations
rg -A 5 "reactivat" tests/pw/feature-map/

# Look for subscription status or period-related logic
rg -A 5 "active.?period.*subscription|subscription.*active.?period"

Length of output: 1281


649-652: License management workflow needs verification.

The license management features seem to follow a logical flow (can't activate with incorrect key -> can activate -> can refresh -> can deactivate), but verify the implementation ensures this sequence.

✅ Verification successful

The previous ast-grep pattern had syntax issues. Let's try to find the license management implementation and test files to verify the workflow sequence.


License management workflow implementation verified successfully

The implementation in tests/pw/tests/e2e/license.spec.ts and tests/pw/pages/licensePage.ts confirms the correct sequence of license management operations:

  • Validates incorrect key activation fails first
  • Implements proper license activation with correct key
  • Ensures refresh functionality is available after activation
  • Implements deactivation with proper cleanup

The code also includes proper state checks and validations:

  • Checks for already activated state before activation
  • Verifies success messages after operations
  • Ensures refresh button visibility after activation
  • Confirms refresh button is hidden after deactivation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify license management implementation sequence

# Test: Search for license management implementation
ast-grep --pattern 'function $_(license|activate|deactivate)'

Length of output: 2251


Script:

#!/bin/bash
# Let's search for license-related implementations with ripgrep
rg -A 5 "(activate|deactivate).*license" --type ts

# Also search for license management test files
fd "license.*\.(ts|js|spec|test)" --type f

Length of output: 4568

tests/pw/tests/e2e/shortcodes.spec.ts 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: 5

🧹 Outside diff range and nitpick comments (15)
tests/pw/tests/e2e/geolocation.spec.ts (3)

11-20: Consider enhancing test cleanup robustness.

While the basic cleanup is in place, consider these improvements:

  1. Add try-catch blocks in afterAll for more resilient cleanup
  2. Consider cleaning up any test data created during tests
  3. Verify the successful reset of geolocation settings
 test.afterAll(async () => {
+    try {
       await dbUtils.setOptionValue(dbData.dokan.optionName.geolocation, dbData.dokan.geolocationSettings);
+      // Verify reset was successful
+      const settings = await dbUtils.getOptionValue(dbData.dokan.optionName.geolocation);
+      console.log('Cleanup verification:', settings);
+    } catch (error) {
+      console.error('Cleanup failed:', error);
+    } finally {
       await aPage.close();
+    }
 });

37-37: Fix typo in test description.

There's a double space in the test description between "can" and "filters".

-        test(`admin can ${status}  filters before location map`, { tag: ['@pro', '@admin'] }, async () => {
+        test(`admin can ${status} filters before location map`, { tag: ['@pro', '@admin'] }, async () => {

1-49: Consider implementing test data management patterns.

While the test structure is good, consider these architectural improvements:

  1. Create a dedicated test data factory for geolocation settings
  2. Implement snapshot testing for complex map configurations
  3. Consider separating the tests into smaller, more focused files (e.g., map-position.spec.ts, map-display.spec.ts)
  4. Add integration with a visual testing tool for map rendering verification

This will improve test maintainability and make it easier to add new test cases in the future.

tests/pw/pages/geolocationPage.ts (4)

8-10: Remove unnecessary constructor

The constructor can be removed since it only calls the parent constructor with the same parameter, which TypeScript will do automatically when extending a class.

-    constructor(page: Page) {
-        super(page);
-    }
🧰 Tools
🪛 Biome

[error] 8-10: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


12-14: Add input validation for productName parameter

Consider adding validation to ensure productName is not empty or undefined before navigation.

 async goToProductDetails(productName: string): Promise<void> {
+    if (!productName?.trim()) {
+        throw new Error('Product name cannot be empty');
+    }
     await this.gotoUntilNetworkidle(data.subUrls.frontend.productDetails(helpers.slugify(productName)));
 }

38-64: Refactor viewMap for better maintainability

Consider extracting the visibility checks into separate private methods to improve readability and maintainability.

+private async checkMapVisibility(page: string, shouldBeVisible: boolean): Promise<void> {
+    await this.gotoUntilNetworkidle(page);
+    if (shouldBeVisible) {
+        await this.toBeVisible(selector.customer.cStoreList.map.locationMap);
+    } else {
+        await this.notToBeVisible(selector.customer.cStoreList.map.locationMap);
+    }
+}

 async viewMap(position: 'all' | 'store_listing' | 'shop'): Promise<void> {
     switch (position) {
         case 'all':
-            await this.gotoUntilNetworkidle(data.subUrls.frontend.shop);
-            await this.toBeVisible(selector.customer.cStoreList.map.locationMap);
-            await this.gotoUntilNetworkidle(data.subUrls.frontend.storeListing);
-            await this.toBeVisible(selector.customer.cStoreList.map.locationMap);
+            await this.checkMapVisibility(data.subUrls.frontend.shop, true);
+            await this.checkMapVisibility(data.subUrls.frontend.storeListing, true);
             break;
         // Similar refactoring for other cases

84-99: Reduce code duplication in viewProductLocationTab

The method can be simplified by extracting the common navigation logic.

 async viewProductLocationTab(productName: string, status: 'enable' | 'disable'): Promise<void> {
+    await this.goToProductDetails(productName);
     switch (status) {
         case 'enable':
-            await this.goToProductDetails(productName);
             await this.toBeVisible(selector.customer.cSingleProduct.menus.location);
             break;
         case 'disable':
-            await this.goToProductDetails(productName);
             await this.notToBeVisible(selector.customer.cSingleProduct.menus.location);
             break;
         default:
-            break;
+            throw new Error(`Invalid status: ${status}`);
     }
 }
tests/pw/pages/adminPage.ts (3)

120-120: LGTM! Consider removing commented code.

The enhanced navigation handling with clickAndAcceptAndWaitForResponseAndLoadState improves test reliability by properly waiting for the network response and page load. However, the commented out skipThisStep line below could be removed for cleaner code.


Line range hint 138-141: Consider documenting payment method roadmap.

The commented out payment method toggles (wirecard, stripe) might indicate planned features. Consider:

  1. Adding a TODO comment explaining why these are commented out
  2. Creating GitHub issues to track their implementation
  3. Adding inline documentation about the payment method support roadmap

The navigation enhancement itself looks good.

Also applies to: 147-147


Line range hint 120-147: Great improvement to E2E test reliability!

The consistent use of clickAndAcceptAndWaitForResponseAndLoadState across all wizard steps is a significant improvement that will:

  • Reduce test flakiness by properly waiting for responses and page loads
  • Verify correct navigation through status code checks
  • Make test failures more meaningful by failing fast on navigation issues

Consider adding a comment at the start of the setDokanSetupWizard method documenting this navigation pattern for future maintainers.

tests/pw/feature-map/feature-map.yml (1)

1093-1094: Consider performance optimization for badge filtering.

While the seller badge filtering enhances vendor management, ensure efficient query performance with large datasets.

Consider implementing:

  • Pagination for badge-filtered results
  • Caching for frequently accessed badge-vendor associations
  • Indexed queries for better performance
tests/pw/pages/commissionPage.ts (4)

22-22: Remove redundant commented-out code

The commented-out line // await this.selectByValue(setupWizardAdmin.commissionType, commission.commissionType); is no longer needed since the commission type is already selected at line 20. Removing unused code improves readability.

Apply this diff to remove the commented-out line:

-// await this.selectByValue(setupWizardAdmin.commissionType, commission.commissionType);

25-25: Address the TODO comment

The comment //todo: need to resolve indicates an unresolved issue. To maintain code quality, please address this TODO or create a task to track its resolution.

Would you like assistance in resolving this issue or creating a task to track it?


29-29: Remove redundant commented-out code

The commented-out line // await this.selectByValueAndWaitForResponse(...) is obsolete and should be removed to keep the code clean.

Apply this diff to remove the commented-out line:

-// await this.selectByValueAndWaitForResponse(data.subUrls.api.dokan.multistepCategories, setupWizardAdmin.commissionType, commission.commissionType);

82-82: Replace magic number with descriptive constant

Using the magic number 302 can reduce code clarity. Consider defining a descriptive constant for the status code to improve maintainability.

Apply this diff:

+const HTTP_STATUS_FOUND = 302;
...
- await this.clickAndWaitForResponseAndLoadState(data.subUrls.backend.dokan.setupWizardCommission, setupWizardAdmin.continue, 302);
+ await this.clickAndWaitForResponseAndLoadState(data.subUrls.backend.dokan.setupWizardCommission, setupWizardAdmin.continue, HTTP_STATUS_FOUND);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 868e48c and e29b0bb.

📒 Files selected for processing (10)
  • tests/pw/feature-map/feature-map.yml (20 hunks)
  • tests/pw/pages/adminPage.ts (2 hunks)
  • tests/pw/pages/commissionPage.ts (7 hunks)
  • tests/pw/pages/geolocationPage.ts (1 hunks)
  • tests/pw/pages/selectors.ts (5 hunks)
  • tests/pw/pages/singleProductPage.ts (1 hunks)
  • tests/pw/tests/e2e/commission.spec.ts (2 hunks)
  • tests/pw/tests/e2e/geolocation.spec.ts (1 hunks)
  • tests/pw/utils/dbData.ts (1 hunks)
  • tests/pw/utils/testData.ts (6 hunks)
✅ Files skipped from review due to trivial changes (2)
  • tests/pw/pages/singleProductPage.ts
  • tests/pw/utils/dbData.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/pw/tests/e2e/commission.spec.ts
🧰 Additional context used
🪛 Biome
tests/pw/pages/geolocationPage.ts

[error] 8-10: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

🔇 Additional comments (16)
tests/pw/tests/e2e/geolocation.spec.ts (1)

1-5: LGTM! Well-structured imports following best practices.

The imports demonstrate good separation of concerns by utilizing the Page Object Model pattern and dedicated utilities for database and test data management.

tests/pw/pages/geolocationPage.ts (1)

1-100: Overall implementation looks good!

The E2E test implementation is comprehensive and well-structured, covering all major geolocation features. The suggested improvements focus on maintainability and robustness but the current implementation is already functional and follows good testing practices.

🧰 Tools
🪛 Biome

[error] 8-10: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

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

126-126: Same comment applies here regarding commented code.


133-133: LGTM! Robust handling of commission setup navigation.

The enhanced navigation handling is particularly important here as commission setup is a critical part of the wizard.

tests/pw/feature-map/feature-map.yml (3)

317-322: LGTM! Improved vendor management capabilities.

The rename from 'Stores' to 'Vendors' provides better terminology consistency. The added filtering capabilities by vendor status (pending/approved) enhance admin workflow.


994-1005: Verify subscription state transitions and edge cases.

The subscription management capabilities are comprehensive but require careful handling of:

  1. Subscription state transitions
  2. Payment method changes
  3. Address updates
  4. Cancellation/reactivation flows
#!/bin/bash
# Description: Verify subscription management implementation.

# Check for subscription state handling
rg -A 5 "subscription.*status"

# Check for subscription-related hooks
rg -A 5 "subscription.*(cancel|reactivate|renew)"

350-350: Verify commission meta-box implementation.

The ability to view commission meta-box on order details is crucial for commission management.

tests/pw/utils/testData.ts (4)

918-918: LGTM: Consistent price formatting.

Good use of the priceStringWithDecimal() helper function to ensure consistent decimal handling across different commission types.

Also applies to: 927-928, 937-938


1011-1012: LGTM: Clear and standard URL parameter.

The URL parameter dokan_tracker_optin=true follows standard query string format and clearly indicates its purpose.


1027-1030: LGTM: Well-structured setup wizard URLs.

The setup wizard URLs follow a consistent and logical pattern, making the flow easy to understand and maintain.


131-135: Verify privacy notice content with legal team.

The diagnostic notice contains sensitive information about data collection. Please ensure:

  1. The privacy notice accurately reflects the actual data being collected
  2. The text complies with privacy regulations (GDPR, CCPA, etc.)
  3. The Appsero data collection details are up-to-date
✅ Verification successful

Privacy notice content is consistent with documented data collection practices

The diagnostic notice content accurately reflects the documented data collection practices as evidenced in multiple places:

  1. The data points mentioned in the notice match exactly with what's disclosed in readme.txt and README.md:

    • Server environment details
    • Number of users
    • Site language
    • Active/inactive plugins
    • Site name and URL
    • Name and email address
  2. The Appsero integration is properly documented:

    • Uses Appsero SDK v2.0.2 for telemetry
    • Only collects data after explicit user consent
    • Has proper privacy policy links to Appsero's documentation
  3. The privacy implementation is robust with dedicated privacy classes and settings that handle GDPR compliance (includes/Privacy.php)

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if privacy policy and terms are properly referenced
# Look for related privacy policy files or documentation
fd -t f -e md -e txt "privacy|terms" docs/

Length of output: 44


Script:

#!/bin/bash
# Search for any references to privacy policy, terms, or Appsero in the codebase
rg -i "appsero|privacy|data collection" -g '!{node_modules,dist,build}/*'

# Also check for any configuration files that might contain Appsero settings
fd -t f -e json -e yaml -e yml -e config "appsero|config" .

Length of output: 27558

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

240-246: LGTM! Well-structured diagnostic selectors.

The diagnostic selectors are well-organized and follow consistent XPath patterns. The naming is clear and descriptive, making the selectors easy to understand and maintain.


2983-2989: LGTM! Commission meta box selectors follow established patterns.

The commission meta box selectors are properly organized and follow the existing selector patterns in the codebase. The mix of CSS and XPath selectors is appropriate for the target elements.

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

111-111: LGTM

Using clickAndWaitForLoadState ensures the page is fully loaded before proceeding. This improves test reliability.


165-165: LGTM

Replacing goto with gotoUntilNetworkidle enhances navigation reliability by waiting for the network to be idle before proceeding.


183-189: New method viewCommissionMetaBox is well-implemented

The viewCommissionMetaBox method correctly navigates to the order details page and verifies the visibility of the commission metabox elements. This addition enhances test coverage for commission functionalities.

tests/pw/tests/e2e/geolocation.spec.ts Show resolved Hide resolved
tests/pw/pages/geolocationPage.ts Show resolved Hide resolved
tests/pw/pages/geolocationPage.ts Show resolved Hide resolved
tests/pw/feature-map/feature-map.yml Show resolved Hide resolved
tests/pw/pages/commissionPage.ts Show resolved Hide resolved
@shashwatahalder01 shashwatahalder01 added the QA approved This PR is approved by the QA team label Nov 19, 2024
@shashwatahalder01 shashwatahalder01 changed the title Add E2E tests Add E2E tests for shortcode, commission, geolocation Nov 19, 2024
@shashwatahalder01 shashwatahalder01 merged commit 3d3c9d3 into getdokan:develop Nov 19, 2024
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
QA approved This PR is approved by the QA team Test Automation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant