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

Refactor/vendor balance raw query #2430

Merged

Conversation

mrabbani
Copy link
Member

@mrabbani mrabbani commented Nov 8, 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 the VendorBalance model for managing vendor financial data.
    • Added VendorBalanceStore for handling vendor balance data retrieval and manipulation.
    • Implemented a new method to calculate total vendor balance on a specified date.
  • Bug Fixes

    • Corrected method names related to order quantity.
  • Documentation

    • Updated documentation for the Dokan Model and Data Store, detailing functionality and usage.
  • Tests

    • Added a comprehensive suite of unit tests for the VendorBalance model, covering various functionalities.
  • Chores

    • Deprecated several functions to streamline the API and enhance maintainability.

Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Walkthrough

The changes in this pull request introduce several new classes and methods within the Dokan framework, focusing on data management for vendor balances and the overall data store structure. Key additions include the BaseModel and BaseDataStore classes, which provide foundational functionalities for CRUD operations. The VendorBalance and VendorBalanceStore classes encapsulate vendor balance management, while various methods facilitate data manipulation and retrieval. Additionally, the documentation for the Dokan Model and Data Store has been updated to reflect these changes.

Changes

File Change Summary
docs/data-store.md Added documentation for Department, DepartmentStore, and methods for data manipulation.
includes/Commission.php Refactored calculate_gateway_fee method to use VendorBalance::update_by_transaction.
includes/Models/BaseModel.php Introduced BaseModel class with methods for saving, deleting, and managing metadata.
includes/Models/DataStore/BaseDataStore.php Added BaseDataStore class for managing database interactions with abstract and concrete methods.
includes/Models/DataStore/DataStoreInterface.php Created DataStoreInterface defining methods for data management.
includes/Models/DataStore/VendorBalanceStore.php Introduced VendorBalanceStore class for managing vendor balance data with specific methods.
includes/Models/VendorBalance.php Added VendorBalance class with transaction constants and methods for managing vendor balances.
includes/Order/Hooks.php Refactored on_order_status_change to use VendorBalance::update_by_transaction.
includes/Order/functions.php Updated dokan_sync_insert_order to use VendorBalance object methods; deprecated several functions.
includes/Vendor/Vendor.php Refactored get_earnings to retrieve vendor balance using VendorBalance::get_total_balance_by_vendor.
tests/php/src/CustomAssertion/DBAssertionTrait.php Added assertDatabaseMissing method for enhanced database assertions.
tests/php/src/Models/VendorBalanceModelTest.php Created unit tests for VendorBalance model functionalities.

Possibly related PRs

Suggested labels

:+1: Dev Review Done, Need Dev Review Only, Upcoming Release

Suggested reviewers

  • shohag121

Poem

🐰 In the land of code where rabbits play,
New models and stores brighten the day.
With balances tracked and data so neat,
Our Dokan's now ready, oh what a treat!
Hops of joy for changes so grand,
A better framework, just as we planned! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 059cd02 and d348e0c.

📒 Files selected for processing (12)
  • docs/data-store.md (1 hunks)
  • includes/Commission.php (2 hunks)
  • includes/Models/BaseModel.php (1 hunks)
  • includes/Models/DataStore/BaseDataStore.php (1 hunks)
  • includes/Models/DataStore/DataStoreInterface.php (1 hunks)
  • includes/Models/DataStore/VendorBalanceStore.php (1 hunks)
  • includes/Models/VendorBalance.php (1 hunks)
  • includes/Order/Hooks.php (2 hunks)
  • includes/Order/functions.php (2 hunks)
  • includes/Vendor/Vendor.php (2 hunks)
  • tests/php/src/CustomAssertion/DBAssertionTrait.php (1 hunks)
  • tests/php/src/Models/VendorBalanceModelTest.php (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/data-store.md

[uncategorized] ~20-~20: Loose punctuation mark.
Context: ..., such as product. - protected $data: Holds the default data for the object. ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~105-~105: Loose punctuation mark.
Context: ...e following methods: - get_table_name: Defines the table name in the database....

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~106-~106: Loose punctuation mark.
Context: ...the database. - get_fields_with_format: Returns the fields with format as an ar...

(UNLIKELY_OPENING_PUNCTUATION)


[typographical] ~106-~106: Two consecutive dots
Context: ...he db field name and value is the format.. Sample implementation: ```php class D...

(DOUBLE_PUNCTUATION)


[style] ~165-~165: ‘New Record’ might be wordy. Consider a shorter alternative.
Context: ... ## Uses of Models ### Create a New Record ```php $department = new Department(); ...

(EN_WORDINESS_PREMIUM_NEW_RECORD)


[uncategorized] ~191-~191: Loose punctuation mark.
Context: ..._to_db_data( BaseModel &$model ): array`: Prepare data for saving a BaseModel to ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~192-~192: Loose punctuation mark.
Context: ...e database. - map_db_raw_to_model_data: Maps database raw data to model data.

(UNLIKELY_OPENING_PUNCTUATION)

🪛 GitHub Check: Run PHPCS inspection
includes/Models/DataStore/BaseDataStore.php

[warning] 82-82:
Replacement variables found, but no valid placeholders found in the query.


[warning] 88-88:
Use placeholders and $wpdb->prepare(); found $this


[warning] 88-88:
Use placeholders and $wpdb->prepare(); found get_query_statement


[warning] 257-257:
Replacement variables found, but no valid placeholders found in the query.

includes/Models/DataStore/VendorBalanceStore.php

[warning] 89-89:
Use placeholders and $wpdb->prepare(); found $query_statement

tests/php/src/CustomAssertion/DBAssertionTrait.php

[warning] 81-81:
json_encode() is discouraged. Use wp_json_encode() instead.

🔇 Additional comments (13)
includes/Models/DataStore/DataStoreInterface.php (2)

1-6: LGTM! Namespace and imports are well-structured.

The namespace follows PSR-4 autoloading standard and the BaseModel import is appropriate for the interface requirements.


70-92: Verify the status of commented-out methods.

The interface includes commented-out methods (get, query, count) that seem essential for data retrieval operations. Please clarify:

  1. Are these methods planned for future implementation?
  2. Should they be part of a separate interface for query operations?
  3. What's the timeline for implementing these methods?
includes/Order/Hooks.php (2)

7-7: LGTM!

The import statement for the VendorBalance model is properly placed and follows PSR-4 autoloading standards.


129-132: Great refactoring of vendor balance update logic!

The replacement of direct database queries with the VendorBalance model's update_by_transaction method improves:

  • Code maintainability by encapsulating DB logic
  • Testability by allowing mocking of the model
  • Type safety by using constants for transaction types

Let's verify that this refactoring pattern is consistently applied across the codebase:

✅ Verification successful

Let me check the actual implementation of these usages to ensure consistency.


Let me check one final thing to ensure there are no direct SQL updates in the VendorBalance class itself.


Based on the comprehensive analysis, I can now provide the final response:

Refactoring pattern is consistently applied across the codebase

The VendorBalance model is properly encapsulating all balance updates through its model layer:

  • All balance updates are using VendorBalance::update_by_transaction
  • No direct SQL updates to dokan_vendor_balance table found
  • The model follows proper ORM patterns with a dedicated DataStore class
  • Test coverage exists validating the model's behavior
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct updates to dokan_vendor_balance table
rg "UPDATE.*dokan_vendor_balance" --type php

# Search for other usages of VendorBalance::update_by_transaction
rg "VendorBalance::update_by_transaction" --type php

Length of output: 348


Script:

#!/bin/bash
# Check the implementation context of VendorBalance::update_by_transaction calls
rg "VendorBalance::update_by_transaction" -B 5 -A 5 --type php

# Also check if there are any other methods in VendorBalance class that might be doing balance updates
ast-grep --pattern 'class VendorBalance {
  $$$
  public static function $_($$$) {
    $$$
    UPDATE $$$
    $$$
  }
  $$$
}'

Length of output: 2252


Script:

#!/bin/bash
# Check the VendorBalance class implementation
rg "class VendorBalance" -A 50 --type php

# Also check for any remaining raw SQL updates in the codebase
rg "wpdb.*UPDATE.*balance" --type php

Length of output: 10645

includes/Vendor/Vendor.php (1)

8-8: Verify VendorBalance model integration.

Let's ensure the VendorBalance model is properly integrated across the codebase.

✅ Verification successful

Let me gather more information about the VendorBalance model implementation.


Let me check one final aspect to verify the complete integration.


VendorBalance model integration is properly implemented and consistent

The VendorBalance model is well-integrated across the codebase with:

  • Proper model implementation with defined transaction types (ORDERS, WITHDRAW, REFUND)
  • Consistent usage in vendor earnings calculations and order processing
  • Comprehensive test coverage in VendorBalanceModelTest
  • Clean abstraction of database operations through VendorBalanceStore
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify VendorBalance model implementation and usage

# Test 1: Check if VendorBalance model exists
echo "Checking VendorBalance model implementation..."
ast-grep --pattern 'class VendorBalance'

# Test 2: Check usage of get_total_balance_by_vendor method
echo "Checking get_total_balance_by_vendor usage..."
rg "VendorBalance::get_total_balance_by_vendor"

# Test 3: Check for any remaining raw vendor balance queries
echo "Checking for remaining raw vendor balance queries..."
rg "dokan_vendor_balance"

Length of output: 3063


Script:

#!/bin/bash
# Check VendorBalance model implementation and its methods
echo "Checking VendorBalance model implementation..."
ast-grep --pattern 'class VendorBalance {
  $$$
}'

# Check for references to VendorBalance in test files
echo "Checking test coverage..."
rg -A 5 "class VendorBalanceModelTest"

# Check for any direct database queries that might bypass the model
echo "Checking direct balance queries..."
rg -A 2 "SELECT.*dokan_vendor_balance" --type php

Length of output: 1435


Script:

#!/bin/bash
# Check VendorBalance model's store implementation
echo "Checking VendorBalance store implementation..."
ast-grep --pattern 'class VendorBalanceStore {
  $$$
}'

# Check for model usage in other classes
echo "Checking VendorBalance usage..."
rg "use WeDevs\\Dokan\\Models\\VendorBalance"

# Check for any model method calls
echo "Checking model method calls..."
rg "VendorBalance::" -A 2

Length of output: 5378

includes/Models/DataStore/VendorBalanceStore.php (3)

21-30: Data Type Verification: Confirm Format Specifiers Match Field Types

In the get_fields_with_format() method, ensure that the format specifiers correspond correctly to the data types of each field. Accurate format specifiers are crucial for data integrity during database operations.

Please review the format specifiers:

  • %d for integers (e.g., 'vendor_id', 'trn_id')
  • %s for strings (e.g., 'trn_type', 'particulars', 'status', 'trn_date', 'balance_date')
  • %f for floating-point numbers (e.g., 'debit', 'credit')

Confirm that each field's data type matches its format specifier to prevent potential data handling issues.


65-66: Potential Redundancy: Verify 'approved' Status Inclusion

You are appending 'approved' to the $earning_status array:

$earning_status = dokan_withdraw_get_active_order_status();
$earning_status[] = 'approved';

Ensure that the 'approved' status is not already included in the array returned by dokan_withdraw_get_active_order_status(). Adding it twice could lead to unnecessary duplication, which might affect query results.

Consider checking:

if ( ! in_array( 'approved', $earning_status, true ) ) {
    $earning_status[] = 'approved';
}

14-94: Overall Implementation: Adheres to Coding Standards and Best Practices

The VendorBalanceStore class is well-structured and follows object-oriented principles effectively. Extending BaseDataStore and properly overriding methods ensures consistency within the codebase. The use of type hints and return types enhances code readability and maintainability.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 89-89:
Use placeholders and $wpdb->prepare(); found $query_statement

includes/Models/VendorBalance.php (1)

283-295: Ensure cache keys are unique and consistent

The cache key and group in get_total_balance_by_vendor use the vendor ID and date:

$cache_group = "seller_order_data_{$vendor_id}";
$cache_key   = "seller_earnings_{$vendor_id}_{$on_date->format('Y_m_d')}";

Verify that these keys are unique enough to prevent collisions and that they align with the caching strategy used elsewhere in the application.

Run the following script to check for potential cache key collisions:

This will help identify any overlapping cache keys that might cause unexpected behavior.

✅ Verification successful

Let me correct the syntax and search more broadly for cache-related patterns to verify the caching strategy.


Based on the analysis of the cache usage patterns in the codebase, I can now provide a final response:

Cache keys are well-structured and follow consistent patterns

The cache implementation in get_total_balance_by_vendor follows the established patterns used throughout the codebase:

  • The cache group seller_order_data_{$vendor_id} is consistently used across vendor-specific data
  • The cache key format seller_earnings_{$vendor_id}_{date} includes sufficient uniqueness with vendor ID and date
  • The implementation properly handles cache invalidation through the Cache class abstraction

The codebase shows similar patterns in other vendor-related caching:

  • Vendor products: seller_product_data_{$vendor_id}
  • Vendor taxonomies: seller_taxonomy_widget_data_{$vendor_id}
  • Vendor reports: report_data_seller_{$vendor_id}
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for cache key usages to ensure uniqueness.

# Expectation: Cache keys for vendor earnings are unique and consistent.
rg -A 2 "Cache::(get|set)" --php

Length of output: 442


Script:

#!/bin/bash
# Search for cache key usages to ensure uniqueness
rg "Cache::(get|set)" -A 2

# Also search for alternative cache implementations
rg "cache_[gs]et|wp_cache|transient" -A 2

Length of output: 36476

includes/Models/DataStore/BaseDataStore.php (3)

87-89: Verify Safe Execution of get_query_statement().

The method $wpdb->get_row( $this->get_query_statement() ) executes the query returned by get_query_statement(). It's important to ensure that this query is properly prepared and safe from SQL injection vulnerabilities.

Consider reviewing the get_query_statement() method to confirm that it returns a securely prepared statement.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 88-88:
Use placeholders and $wpdb->prepare(); found $this


[warning] 88-88:
Use placeholders and $wpdb->prepare(); found get_query_statement


277-287: ⚠️ Potential issue

Ensure Correct Format Handling in $wpdb->insert().

The static analysis tool warns about replacement variables without valid placeholders. Verify that the $format parameter in $wpdb->insert() accurately corresponds to the $data array keys.

Ensure that the $format array provides the correct format specifiers for each field in $data.


253-261: ⚠️ Potential issue

Potential SQL Injection Risk in prepare_where_clause().

When constructing the WHERE clause, column names ($key) are inserted directly into the SQL string without sanitization. If $key could be influenced by user input, this poses a SQL injection risk.

Apply this diff to sanitize the column names:

                 // Generate the WHERE clause securely using $wpdb->prepare() with placeholders.
-                $where[] = $wpdb->prepare( "{$key} IN ({$placeholders})", ...$value );
+                $where[] = $wpdb->prepare( "%i IN ({$placeholders})", $key, ...$value );

Alternatively, ensure that $key is validated against a list of known column names before use.

Likely invalid or redundant comment.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 257-257:
Replacement variables found, but no valid placeholders found in the query.

includes/Order/functions.php (1)

4-4: LGTM

The import of VendorBalance is appropriate for the added functionality.


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.

@mrabbani mrabbani changed the base branch from develop to feat/data-store-and-models November 8, 2024 03:10
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: 17

🧹 Outside diff range and nitpick comments (36)
includes/Models/DataStore/DataStoreInterface.php (3)

7-12: Replace "DOKAN_SINCE" placeholder with actual version number.

The @SInCE tag contains a placeholder "DOKAN_SINCE" which should be replaced with the actual version number where this interface is introduced.


25-34: Fix incorrect documentation in read() method.

The PHPDoc comment mentions "download permission" which appears to be copied from another context and should be updated to reflect the generic nature of this interface.


23-58: Enhance type safety and exception handling documentation.

Consider the following improvements:

  1. Add return type declarations to methods (void)
  2. Standardize exception documentation:
    • Use @throws instead of @throw
    • Specify the exception class being thrown

Here's how the methods should be declared:

-    public function create( BaseModel &$model );
+    public function create( BaseModel &$model ): void;

-    public function read( BaseModel &$model );
+    public function read( BaseModel &$model ): void;

-    public function update( BaseModel &$model );
+    public function update( BaseModel &$model ): void;

-    public function delete( BaseModel &$model );
+    public function delete( BaseModel &$model ): void;
tests/php/src/CustomAssertion/DBAssertionTrait.php (1)

78-78: Add PHPDoc documentation for the new method.

For consistency with other methods in the trait, please add a PHPDoc block documenting the purpose, parameters, and return type of the assertDatabaseMissing method.

Add this documentation block above the method:

+    /**
+     * Assert that a table does not contain any rows matching the specified criteria.
+     *
+     * @param string $table The name of the table (without the prefix).
+     * @param array  $data  An associative array of field-value pairs to match.
+     * @return void
+     */
     public function assertDatabaseMissing( string $table, array $data = [] ): void {
docs/data-store.md (6)

9-13: Enhance the overview section with WooCommerce context.

The overview effectively introduces the data layer abstraction. Consider adding a brief explanation of how this architecture aligns with or differs from WooCommerce's data layer, since you're following a similar pattern to WC_Product.


90-90: Fix parameter name in PHPDoc.

The parameter name in the PHPDoc comment is incorrect. It shows $date_created but the method uses $date_updated.

-* @param string|int|DateTime $date_created
+* @param string|int|DateTime $date_updated

54-56: Add validation in setter methods.

Consider adding validation in the setter methods to ensure data integrity. For example, the set_name method should validate that the name is not empty and meets any length requirements.

 public function set_name( $name ) {
+    if ( empty( $name ) ) {
+        throw new \InvalidArgumentException( 'Department name cannot be empty.' );
+    }
+    if ( strlen( $name ) > 100 ) {
+        throw new \InvalidArgumentException( 'Department name cannot exceed 100 characters.' );
+    }
     return $this->set_prop( 'name', $name );
 }

155-163: Remove unnecessary empty lines.

Multiple consecutive empty lines don't add value to the documentation. Consider removing them to maintain consistency.


165-183: Enhance usage examples with error handling.

Consider adding examples that demonstrate:

  • Error handling for failed operations
  • Bulk operations
  • Common queries and filters

Example addition:

try {
    $department = new Department( $department_id );
    $department->set_name('Department 2');
    $department->save();
} catch (\InvalidArgumentException $e) {
    // Handle validation errors
} catch (\Exception $e) {
    // Handle other errors
}
🧰 Tools
🪛 LanguageTool

[style] ~165-~165: ‘New Record’ might be wordy. Consider a shorter alternative.
Context: ... ## Uses of Models ### Create a New Record ```php $department = new Department(); ...

(EN_WORDINESS_PREMIUM_NEW_RECORD)


188-192: Consider fixing the database field typo.

While the current solution elegantly handles the perticulars typo through the data store layer, it would be better to fix the typo in the database schema to prevent confusion and maintain code quality.

Would you like help creating a migration script to fix this typo?

🧰 Tools
🪛 LanguageTool

[uncategorized] ~191-~191: Loose punctuation mark.
Context: ..._to_db_data( BaseModel &$model ): array`: Prepare data for saving a BaseModel to ...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~192-~192: Loose punctuation mark.
Context: ...e database. - map_db_raw_to_model_data: Maps database raw data to model data.

(UNLIKELY_OPENING_PUNCTUATION)

tests/php/src/Models/VendorBalanceModelTest.php (4)

8-8: Remove unused import.

The WeDevs\DokanPro\Modules\DeliveryTime\StorePickup\Vendor class is imported but never used in the test file.


15-32: Uncomment the debit assertion and fix formatting.

  1. The commented out debit assertion should be included to ensure the debit value is correctly persisted:
 $this->assertDatabaseCount(
     'dokan_vendor_balance', 1, [
         'id' => $vendor_balance->get_id(),
-        // 'debit' => 100,
+        'debit' => 100,
         'trn_id' => 1,
         'trn_type' => VendorBalance::TRN_TYPE_DOKAN_ORDERS,
     ]
 );
  1. The assertion parameters should be properly aligned for better readability.

63-88: Consider using data providers for comprehensive test coverage.

The test thoroughly verifies all fields, but could be enhanced by using PHPUnit data providers to test different scenarios (e.g., different dates, statuses, transaction types). This would make the test more maintainable and comprehensive.

Example structure:

/**
 * @dataProvider provideVendorBalanceData
 */
public function test_read_method($particulars, $debit, $status, $date) {
    // Test implementation
}

public function provideVendorBalanceData() {
    return [
        'completed_order' => ['Order #123', 100, 'wc-completed', '2020-01-01'],
        'pending_order' => ['Order #124', 200, 'wc-pending', '2020-01-02'],
        // Add more test cases
    ];
}

90-110: Enhance test coverage for update_by_transaction method.

The test only verifies updating the debit amount. Consider adding test cases for:

  1. Updating other fields (credit, status, etc.)
  2. Error cases (invalid transaction ID, type)
  3. Edge cases (zero amounts, null values)
includes/Commission.php (4)

9-9: Remove unused import.

The Vendor class is imported but not used in the code.

-use WeDevs\DokanPro\Modules\DeliveryTime\StorePickup\Vendor;

102-105: LGTM! Consider extracting the transaction type to a constant.

The refactoring improves code maintainability by moving database operations to the VendorBalance model. However, the transaction type 'dokan_orders' could be extracted to a constant for better maintainability.

+    private const TRANSACTION_TYPE_ORDERS = 'dokan_orders';
+
     public function calculate_gateway_fee( $order_id ) {
         // ... existing code ...
         VendorBalance::update_by_transaction(
             $tmp_order->get_id(),
-            'dokan_orders',
+            self::TRANSACTION_TYPE_ORDERS,
             [ 'debit' => (float) $net_amount ]
         );

Line range hint 13-24: Fix indentation in if-else blocks.

The indentation in the if-else blocks is inconsistent, making the code harder to read.

 if loyalty_years >= 5:
   discount = 0.15
-    elif loyalty_years >= 3:
-      discount = 0.1
-    else:
-      discount = 0
-    discounted_amount = amount - (amount * discount)
-    if discount > 0:
-      final_amount = discounted_amount + 20
-    else:
-      final_amount = discounted_amount
-    return final_amount
+ elif loyalty_years >= 3:
+   discount = 0.1
+ else:
+   discount = 0
+ discounted_amount = amount - (amount * discount)
+ if discount > 0:
+   final_amount = discounted_amount + 20
+ else:
+   final_amount = discounted_amount
+ return final_amount

Based on the search results, I can now provide a final response since we have found all occurrences of the misspelled methods:

Fix typo in method names set_order_qunatity and get_order_qunatity

The following methods in includes/Commission.php have spelling errors and need to be renamed to use the correct spelling "quantity":

  • set_order_qunatity()set_order_quantity()
  • get_order_qunatity()get_order_quantity()

The misspelled methods are used in 6 locations within the same file:

  • Method declarations (lines 99-108)
  • Usage in get_earning_by_order() method
  • Usage in prepare_for_calculation() method
🔗 Analysis chain

Line range hint 1-1000: Fix typo in method names.

The methods set_order_qunatity and get_order_qunatity have a typo in their names (should be "quantity" instead of "qunatity").

Let's verify the usage of these methods to ensure we catch all occurrences:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all occurrences of the misspelled methods
rg -i "qunatity" --type php

Length of output: 562

includes/Vendor/Vendor.php (2)

790-790: LGTM! Good refactoring of vendor balance logic.

The change effectively moves the vendor balance calculation to the VendorBalance model, improving code organization and maintainability.

This architectural change:

  • Improves separation of concerns by moving balance logic to a dedicated model
  • Makes the code more maintainable by centralizing vendor balance calculations
  • Reduces duplication by reusing the VendorBalance model's functionality

Line range hint 813-875: Consider refactoring get_balance method to use VendorBalance model.

For consistency with the get_earnings refactoring, consider moving the balance calculation logic to the VendorBalance model in a future update.

Benefits:

  • Maintains consistency with the new architecture
  • Centralizes all balance-related calculations in the VendorBalance model
  • Makes the code more maintainable
includes/Models/BaseModel.php (6)

14-14: Remove the unnecessary comment on line 14

The comment // wc_get_product() appears unrelated to the save() method and may have been left unintentionally. Consider removing it to keep the code clean.


23-23: Correct the typographical error "THe" to "The" in documentation

In the docblocks on lines 23 and 37, "THe data store" should be corrected to "The data store" for proper grammar.

Also applies to: 37-37


47-47: Typo in parameter description: "date" should be "data"

In the documentation for the delete method, correct the typo in the parameter description:

- * @param  bool $force_delete Should the date be deleted permanently.
+ * @param  bool $force_delete Should the data be deleted permanently.

55-55: Correct the type hint in documentation

In the docblock, replace Data with WC_Data for accurate type hinting:

- * @param Data $this The data object being deleted.
+ * @param WC_Data $this The data object being deleted.

76-76: Typographical error in documentation: "raws" should be "rows"

In the docblock summary for the delete_by method, correct the typo:

- * Delete raws from the database.
+ * Delete rows from the database.

78-78: Ensure consistent quoting in array key examples

In the parameter description for the delete_by method, add quotes around 'status' for consistency:

- * @param array $data Array of args to delete an object, e.g. `array( 'id' => 1, status => ['draft', 'cancelled'] )` or `array( 'id' => 1, 'status' => 'publish' )`.
+ * @param array $data Array of args to delete an object, e.g. `array( 'id' => 1, 'status' => ['draft', 'cancelled'] )` or `array( 'id' => 1, 'status' => 'publish' )`.
includes/Models/VendorBalance.php (3)

141-143: Validate transaction type in set_trn_type method

The set_trn_type method currently does not validate the transaction type being set. It's important to ensure that only valid transaction types are assigned to prevent potential errors or inconsistencies.

Consider adding validation to check that $type is one of the allowed constants:

if ( ! in_array( $type, [
    self::TRN_TYPE_DOKAN_ORDERS,
    self::TRN_TYPE_DOKAN_WITHDRAW,
    self::TRN_TYPE_DOKAN_REFUND
], true ) ) {
    throw new \InvalidArgumentException( 'Invalid transaction type provided.' );
}
$this->set_prop( 'trn_type', $type );

This ensures that only predefined transaction types are accepted and helps maintain data integrity.


49-52: Review redundant call to $this->set_id( $id ) in the constructor

In the constructor, the ID is being set twice: once in the parent constructor and again using $this->set_id( $id );. This may be redundant if the parent constructor already handles the ID assignment.

Verify if the parent BaseModel constructor sets the ID. If it does, you can remove the redundant call:

public function __construct( int $id = 0 ) {
    parent::__construct( $id );
-   $this->set_id( $id );
    $this->data_store = apply_filters( $this->get_hook_prefix() . 'data_store', new VendorBalanceStore() );

    if ( $this->get_id() > 0 ) {
        $this->data_store->read( $this );
    }
}

This simplifies the constructor and avoids unnecessary method calls.


221-223: Consider adding validation for status in set_status method

The set_status method does not currently validate the status being set. To prevent invalid statuses from being assigned, it's advisable to implement validation.

Add validation to check if $status is one of the allowed values:

$allowed_statuses = ['pending', 'completed', 'cancelled']; // Replace with actual allowed statuses
if ( ! in_array( $status, $allowed_statuses, true ) ) {
    throw new \InvalidArgumentException( 'Invalid status provided.' );
}
$this->set_prop( 'status', $status );

This ensures consistency and reliability in the status values assigned to vendor balances.

Also applies to: 231-233

includes/Models/DataStore/BaseDataStore.php (6)

7-7: Remove Unused Use Statement Automattic\WooCommerce\Pinterest\API\Base.

The use statement for Automattic\WooCommerce\Pinterest\API\Base is not utilized within this file. Removing it will clean up the code and prevent any confusion.

Apply this diff to remove the unused use statement:

 use Automattic\WooCommerce\Admin\API\Reports\SqlQuery;
-use Automattic\WooCommerce\Pinterest\API\Base;
 use Exception;

57-59: Selective PHPCS Disablement Recommended.

The comment @phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared disables PHPCS checks for the entire method. It's better to disable it only for the specific lines where necessary to avoid missing other potential issues.

Apply this change to selectively disable PHPCS:

-     * @phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
      *
+     * @phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared.WordPress
      * @throws Exception Throw exception if invalid entity is passed.
      */

Then, re-enable PHPCS after the specific code block.


310-312: Use instanceof Operator for Type Checking.

Using is_a() for type checking can be less performant and is generally discouraged in favor of the instanceof operator.

Apply this diff to use instanceof:

             if ( is_a( $val, 'WC_DateTime' ) ) {
+            if ( $val instanceof \WC_DateTime ) {
                 $val = $val->date( $this->get_date_format_for_field( $db_field_name ) );
             }

This provides a more standard and efficient type check.


403-405: Remove Redundant Comment in get_id_field_name().

The comment // 'id'; seems redundant and may have been left unintentionally.

Apply this diff to remove the redundant comment:

         return apply_filters( $this->get_hook_prefix() . 'id_field_name', 'id' ); // 'id';
-        return apply_filters( $this->get_hook_prefix() . 'id_field_name', 'id' );

65-67: Provide More Descriptive Exception Messages.

The exception message 'Invalid entity item.' may not provide sufficient information for debugging.

Consider enhancing the exception message to include the entity ID or other relevant details, ensuring sensitive information is not exposed.

             $message = $this->get_hook_prefix() . ' : ' . __( 'Invalid entity item with ID: ', 'dokan-lite' ) . $model->get_id();

349-351: Unused Parameter $db_field_name in get_date_format_for_field().

The parameter $db_field_name is not utilized within the method. If this method is intended to support different date formats for different fields, implement the necessary logic; otherwise, consider removing the parameter.

Apply this diff to remove the unused parameter:

-    protected function get_date_format_for_field( string $db_field_name ): string {
+    protected function get_date_format_for_field(): string {
         return 'Y-m-d H:i:s';
     }

Also, update any method calls accordingly.

includes/Order/functions.php (1)

273-281: Localize the 'New order' string

To support internationalization, wrap the 'New order' string in a localization function to allow for translations.

Apply this diff to localize the string:

- $vendor_balance->set_particulars( 'New order' );
+ $vendor_balance->set_particulars( __( 'New order', 'dokan-lite' ) );
🛑 Comments failed to post (17)
tests/php/src/CustomAssertion/DBAssertionTrait.php (2)

79-81: ⚠️ Potential issue

Fix incorrect assertion logic.

The current implementation uses assertGreaterThanOrEqual(0, $rows_count) which will always pass since a count cannot be negative. To assert that records are missing, we should verify that the count equals zero.

Apply this fix:

     public function assertDatabaseMissing( string $table, array $data = [] ): void {
         $rows_count = $this->getDatabaseCount( $table, $data );
 
-        $this->assertGreaterThanOrEqual( 0, $rows_count, "{$rows_count} rows found in `$table` for given data " . json_encode( $data ) );
+        $this->assertEquals( 0, $rows_count, "Found {$rows_count} unexpected rows in `$table` matching " . json_encode( $data ) );
     }
📝 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.

        $rows_count = $this->getDatabaseCount( $table, $data );

        $this->assertEquals( 0, $rows_count, "Found {$rows_count} unexpected rows in `$table` matching " . json_encode( $data ) );
🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 81-81:
json_encode() is discouraged. Use wp_json_encode() instead.


81-81: 💡 Codebase verification

🛠️ Refactor suggestion

Replace all instances of json_encode() with wp_json_encode() in DBAssertionTrait

Found 3 instances where json_encode() should be replaced with wp_json_encode():

  • Line: $this->assertGreaterThanOrEqual( 1, $rows_count, "No rows found in $table for given data " . json_encode( $data ) );
  • Line: $this->assertEquals( $count, $rows_count, "No rows found in $table for given data " . json_encode( $data ) );
  • Line: $this->assertGreaterThanOrEqual( 0, $rows_count, "{$rows_count} rows found in $table for given data " . json_encode( $data ) );
🔗 Analysis chain

Use wp_json_encode() instead of json_encode().

WordPress provides wp_json_encode() as a safer alternative to json_encode(). It includes additional checks and filters.

Let's check for other occurrences of json_encode() in the trait:

Apply this change consistently across all methods:

-        $this->assertGreaterThanOrEqual( 0, $rows_count, "{$rows_count} rows found in `$table` for given data " . json_encode( $data ) );
+        $this->assertGreaterThanOrEqual( 0, $rows_count, "{$rows_count} rows found in `$table` for given data " . wp_json_encode( $data ) );
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other json_encode usages in this file
rg "json_encode" "tests/php/src/CustomAssertion/DBAssertionTrait.php"

Length of output: 452

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 81-81:
json_encode() is discouraged. Use wp_json_encode() instead.

docs/data-store.md (1)

116-127: ⚠️ Potential issue

Fix inconsistent field names in DepartmentStore.

There's an inconsistency in the field names:

  • get_fields_with_format uses updated_at
  • The getter method is named get_date_updated
  • The model uses date_updated

This inconsistency could lead to issues with data mapping.

 public function get_fields_with_format(): array {
     return [
         'name' => '%s',
         'date_created' => '%s',
-        'updated_at' => '%s',
+        'date_updated' => '%s',
     ];
 }
📝 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.

    public function get_fields_with_format(): array {
        return [
            'name' => '%s',
            'date_created' => '%s',
            'date_updated' => '%s',
        ];
    }

    public function get_date_updated( $context = 'view' ) {
        return $this->get_prop('date_updated', $context);
    }
}
tests/php/src/Models/VendorBalanceModelTest.php (4)

112-137: 🛠️ Refactor suggestion

Add tearDown cleanup for Mockery.

To prevent memory leaks and ensure proper test isolation, add Mockery cleanup in tearDown:

protected function tearDown(): void {
    Mockery::close();
    parent::tearDown();
}

13-13: 🛠️ Refactor suggestion

Improve test data management.

Consider adding:

  1. A setUp method to handle common test data
  2. Helper methods for creating vendor balance objects
  3. Constants for common test values

Example:

private const TEST_VENDOR_ID = 1;
private const TEST_DEBIT = 100;

protected function setUp(): void {
    parent::setUp();
    $this->vendor_balance = $this->createTestVendorBalance();
}

private function createTestVendorBalance(array $overrides = []): VendorBalance {
    $defaults = [
        'particulars' => 'test',
        'debit' => self::TEST_DEBIT,
        'vendor_id' => self::TEST_VENDOR_ID,
        // ... other default values
    ];
    
    $data = array_merge($defaults, $overrides);
    $balance = new VendorBalance();
    
    foreach ($data as $key => $value) {
        $method = "set_$key";
        $balance->$method($value);
    }
    
    return $balance;
}

34-50: ⚠️ Potential issue

Fix spelling error in column name.

The column name 'perticulars' is misspelled in the assertion. It should be 'particulars':

 $this->assertDatabaseHas(
     'dokan_vendor_balance', [
-        'perticulars' => 'test123',
+        'particulars' => 'test123',
     ]
 );
📝 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.

    public function test_update_method() {
        $vendor_balance = new VendorBalance();
        $vendor_balance->save();

        $this->assertEmpty( $vendor_balance->get_particulars() );

        // Change the particulars
        $vendor_balance->set_particulars( 'test123' );
        $vendor_balance->save();

        // Assert changes are applied to the database.
        $this->assertDatabaseHas(
            'dokan_vendor_balance', [
				'particulars' => 'test123',
			]
        );
    }

139-181: ⚠️ Potential issue

Use exact assertion for balance calculation.

The current test uses assertGreaterThan(110, $total_balance) which could pass even if the calculation is incorrect. Since we know the exact expected value from the transactions:

  • Order 1: +100 (debit)
  • Order 2: +60 (debit)
  • Refund: -20 (credit)
  • Withdraw: -30 (credit)
    Total: 110

Replace with an exact assertion:

- $this->assertGreaterThan(110, $total_balance);
+ $this->assertEquals(110, $total_balance);
📝 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.

    public function test_get_total_balance_by_vendor_method() {

        $trn_id = 1;

        $vendor_balance = new VendorBalance();
        $vendor_balance->set_particulars( 'test' );
        $vendor_balance->set_debit( 100 );
        $vendor_balance->set_status( 'wc-completed' );
        $vendor_balance->set_trn_id( $trn_id++ );
        $vendor_balance->set_trn_type( VendorBalance::TRN_TYPE_DOKAN_ORDERS );
        $vendor_balance->set_vendor_id( $this->seller_id1 );
        $vendor_balance->set_trn_date( '2020-01-01' );
        $vendor_balance->set_balance_date( '2020-01-01' );
        $vendor_balance->save();

        $vendor_balance->set_id( 0 );
        $vendor_balance->set_debit( 0 );

        $vendor_balance_2 = clone $vendor_balance;
        $vendor_balance_2->set_trn_id( $trn_id++ );
        $vendor_balance_2->set_debit( 60 );
        $vendor_balance_2->save();

        $vendor_balance_refund = clone $vendor_balance;
        $vendor_balance_refund->set_trn_id( $trn_id++ );
        $vendor_balance_refund->set_trn_type( VendorBalance::TRN_TYPE_DOKAN_REFUND );
        $vendor_balance_refund->set_status( 'approved' );
        $vendor_balance_refund->set_credit( 20 );
        $vendor_balance_refund->save();

        $vendor_balance_withdraw = clone $vendor_balance;
        $vendor_balance_withdraw->set_trn_id( $trn_id++ );
        $vendor_balance_withdraw->set_trn_type( VendorBalance::TRN_TYPE_DOKAN_WITHDRAW );
        $vendor_balance_withdraw->set_status( 'approved' );
        $vendor_balance_withdraw->set_credit( 30 );
        $vendor_balance_withdraw->save();

        $total_balance = VendorBalance::get_total_balance_by_vendor(
            $this->seller_id1
        );
        // 100 + 60 - 20 - 30 = 110
        $this->assertEquals(110, $total_balance);
    }
includes/Models/DataStore/VendorBalanceStore.php (2)

68-68: ⚠️ Potential issue

Security Concern: Use $wpdb->prepare() for SQL Query Construction

The SQL query in get_total_balance() incorporates dynamic variables that, while partially sanitized using esc_sql(), may still be vulnerable to SQL injection. It's recommended to use $wpdb->prepare() for all dynamic parts of the query to ensure proper sanitization.

Consider refactoring the query to utilize placeholders with $wpdb->prepare(). Here's how you might adjust the code:

Replace the construction of $statuses_str and $trn_types_str:

- $statuses_str = "'" . implode( "', '", esc_sql( $earning_status ) ) . "'";
- $trn_types_str = "'" . implode( "', '", esc_sql( $trn_types ) ) . "'";
+ $statuses_placeholders = implode( ',', array_fill( 0, count( $earning_status ), '%s' ) );
+ $trn_types_placeholders = implode( ',', array_fill( 0, count( $trn_types ), '%s' ) );

Modify the where clauses to use $wpdb->prepare():

- $this->add_sql_clause( 'where', " AND trn_type IN ($trn_types_str)" );
- $this->add_sql_clause( 'where', " AND status IN ($statuses_str)" );
+ $this->add_sql_clause( 'where', $wpdb->prepare( " AND trn_type IN ( $trn_types_placeholders )", $trn_types ) );
+ $this->add_sql_clause( 'where', $wpdb->prepare( " AND status IN ( $statuses_placeholders )", $earning_status ) );

By incorporating these changes, you ensure that all dynamic values are properly escaped, enhancing the security of your SQL queries.

Also applies to: 76-84, 86-91


24-24: ⚠️ Potential issue

Typographical Error: Correct 'perticulars' to 'particulars'

The term 'perticulars' appears to be misspelled throughout the code. The correct spelling is 'particulars'. Ensuring accurate spelling enhances code readability and prevents confusion.

Apply the following changes to correct the spelling:

Update the field name in get_fields_with_format():

- 'perticulars' => '%s',
+ 'particulars' => '%s',

Update the method name and its usage:

- protected function get_perticulars( VendorBalance $model, string $context = 'edit' ): string {
+ protected function get_particulars( VendorBalance $model, string $context = 'edit' ): string {

  return $model->get_particulars( $context );
}

Update the documentation comments:

-  * Used to get perticulars through the get_perticulars method by the DataStore.
+  * Used to get particulars through the get_particulars method by the DataStore.

Also applies to: 43-44, 49-50

includes/Models/BaseModel.php (1)

60-60: ⚠️ Potential issue

Validate $this->object_type before using in filter name

Ensure that $this->object_type contains only expected values to prevent any unintended behavior or security issues when constructing the filter name in apply_filters. Consider sanitizing or validating the property before use.

includes/Models/VendorBalance.php (2)

36-36: ⚠️ Potential issue

Correct the misspelling of 'perticulars' to 'particulars'

The property name 'perticulars' is misspelled throughout the code. The correct spelling is 'particulars'. This misspelling can lead to confusion and potential bugs when other developers interact with the code.

Apply the following diff to correct the misspellings:

- 'perticulars' => '',
+ 'particulars' => '',

Update all occurrences in method definitions and usages:

- return $this->get_prop( 'perticulars', $context );
+ return $this->get_prop( 'particulars', $context );

- $this->set_prop( 'perticulars', $note );
+ $this->set_prop( 'particulars', $note );

Ensure that all references to 'perticulars' are updated to 'particulars' throughout the codebase.

Also applies to: 151-153, 161-163, 171-173


284-284: ⚠️ Potential issue

Potential issue with date modification using modify( $on_date )

The usage of modify( $on_date ) on the dokan_current_datetime() object may not set $on_date to the intended date. Instead, it may modify the current datetime relative to $on_date, leading to unexpected results.

Consider creating a new DateTime instance with the provided date:

- $on_date = $on_date && strtotime( $on_date ) ? dokan_current_datetime()->modify( $on_date ) : dokan_current_datetime();
+ $on_date = $on_date && strtotime( $on_date ) ? dokan_current_datetime( new \DateTime( $on_date ) ) : dokan_current_datetime();

Or directly instantiate a DateTime object:

- $on_date = $on_date && strtotime( $on_date ) ? dokan_current_datetime()->modify( $on_date ) : dokan_current_datetime();
+ $on_date = $on_date && strtotime( $on_date ) ? new \DateTime( $on_date ) : dokan_current_datetime();

Ensure that $on_date accurately represents the intended date for balance calculation.

Committable suggestion skipped: line range outside the PR's diff.

includes/Models/DataStore/BaseDataStore.php (4)

257-257: 🛠️ Refactor suggestion

PHPCS Warning: Replacement Variables Without Valid Placeholders.

The static analysis tool warns about replacement variables without valid placeholders. Ensure that all placeholders in the query match the variables provided.

Review the placeholders in the $wpdb->prepare() statement to match the number and type of variables.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 257-257:
Replacement variables found, but no valid placeholders found in the query.


198-205: ⚠️ Potential issue

Correct Variable Name for Field Formats.

There is an inconsistency in variable naming. $field_format is used instead of $fields_format, which may lead to undefined variable issues.

Apply this diff to correct the variable name:

         $fields_format = $this->get_fields_with_format();
-        $field_format[ $this->get_id_field_name() ] = $this->get_id_field_format();
+        $fields_format[ $this->get_id_field_name() ] = $this->get_id_field_format();

         $data_format = [];

Ensure that $fields_format is used consistently throughout the method.

📝 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.

		$fields_format = $this->get_fields_with_format();
		$fields_format[ $this->get_id_field_name() ] = $this->get_id_field_format();

		$data_format = [];

		foreach ( $data_to_update as $key => $value ) {
			$data_format[] = $fields_format[ $key ];
		}

394-396: ⚠️ Potential issue

Compatibility Issue with str_starts_with().

The function str_starts_with() is available from PHP 8.0 onwards. If the project supports older PHP versions, this could cause compatibility issues.

Apply this diff to use strpos() instead:

         if ( ! str_starts_with( $table_name, $wpdb->prefix ) ) {
+        if ( strpos( $table_name, $wpdb->prefix ) !== 0 ) {
             $table_name = $wpdb->prefix . $table_name;
         }

This ensures compatibility with PHP versions earlier than 8.0.

Committable suggestion skipped: line range outside the PR's diff.


81-85: ⚠️ Potential issue

Ensure Correct Use of Placeholders in $wpdb->prepare.

In the WHERE clause, the format variable $format is inserted directly into the query string. This can lead to improper placeholder usage. Instead, use a standard placeholder like %d or %s.

Apply this diff to fix the placeholder:

             $this->add_sql_clause(
                 'where',
                 $wpdb->prepare(
-                    " AND {$id_field_name} = $format",
+                    " AND {$id_field_name} = {$format}",
                     $model->get_id()
                 )
             );

Ensure that $format contains a valid placeholder like %d or %s.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Check: Run PHPCS inspection

[warning] 82-82:
Replacement variables found, but no valid placeholders found in the query.

includes/Order/functions.php (1)

281-281: 🛠️ Refactor suggestion

Add error handling for the save() method

Ensure that the save() method's success or failure is properly handled to prevent data inconsistencies.

Consider checking the return value of save() and handling potential errors:

if ( ! $vendor_balance->save() ) {
    // Handle the error, e.g., log the error or throw an exception
}

@mrabbani mrabbani merged commit 45965a3 into feat/data-store-and-models Nov 8, 2024
1 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 8, 2024
12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant