Skip to content

[Woo POS][Coupons] Refactor WooPosVariationsDataSource to Use BaseDataSource for Improved Maintainability #13766

New issue

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

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

Already on GitHub? # to your account

Conversation

AnirudhBhat
Copy link
Contributor

@AnirudhBhat AnirudhBhat commented Mar 14, 2025

Closes: #137

Description

This PR refactors the WooPosVariationsDataSource to extend the newly introduced WooPosBaseDataSource, consolidating common data-fetching logic to reduce duplication and improve maintainability.

Why This Refactor?

Previously, data sources like WooPosVariationsDataSource contained repetitive logic for:

  1. Handling cached data retrieval
  2. Remote data fetching
  3. Error handling
  4. Cache updates

By introducing WooPosBaseDataSource, this refactor:

  1. Reduces Duplication - Centralises shared logic for caching, fetching, and error handling.
  2. The WooPosVariationsDataSource now focuses only on variation-specific details.

What's Changed?

  1. Introduced WooPosBaseDataSource to manage common data-fetching logic.
  2. Refactored WooPosVariationsDataSource to extend WooPosBaseDataSource, removing redundant logic.
  3. Updated unit tests to align with the refactored structure.

Impact

  1. No change in behaviour.
  2. Easier maintenance by consolidating data source logic.

Next Steps

  1. A separate PR will improve pagination logic across data sources similarly.
  2. We will be applying similar improvements to WooPosCouponsDataSource while implementing Coupons feature in POS.

Testing information

Ensure that there is not change in Items screen behaviour. This refactoring should not have any visible impact on end users.

  1. Ensure Variations load correctly
  2. Ensure Pagination works in Variations screen
  3. Ensure Empty state works in Variations screen
  4. Ensure network error is handled as expected in Variations screen
  5. Ensure pagination error is handled in Variations screen

The tests that have been performed

All the scenarios listed above.

Images/gif

  • I have considered if this change warrants release notes and have added them to RELEASE-NOTES.txt if necessary. Use the "[Internal]" label for non-user-facing changes.

Reviewer (or Author, in the case of optional code reviews):

Please make sure these conditions are met before approving the PR, or request changes if the PR needs improvement:

  • The PR is small and has a clear, single focus, or a valid explanation is provided in the description. If needed, please request to split it into smaller PRs.
  • Ensure Adequate Unit Test Coverage: The changes are reasonably covered by unit tests or an explanation is provided in the PR description.
  • Manual Testing: The author listed all the tests they ran, including smoke tests when needed (e.g., for refactorings). The reviewer confirmed that the PR works as expected on big (tablet) and small (phone) in case of UI changes, and no regressions are added.

@AnirudhBhat AnirudhBhat added type: task An internally driven task. feature: point of sale POS project labels Mar 14, 2025
@AnirudhBhat AnirudhBhat added this to the 22.0 milestone Mar 14, 2025
@AnirudhBhat AnirudhBhat changed the title Issue/13763 refactor variations data source [Woo POS][Coupons] Refactor WooPosVariationsDataSource to Use BaseDataSource for Improved Maintainability Mar 14, 2025
@wpmobilebot
Copy link
Collaborator

wpmobilebot commented Mar 14, 2025

📲 You can test the changes from this Pull Request in WooCommerce-Wear Android by scanning the QR code below to install the corresponding build.
App Name WooCommerce-Wear Android
Platform⌚️ Wear OS
FlavorJalapeno
Build TypeDebug
Commite240d0e
Direct Downloadwoocommerce-wear-prototype-build-pr13766-e240d0e.apk

@wpmobilebot
Copy link
Collaborator

wpmobilebot commented Mar 14, 2025

📲 You can test the changes from this Pull Request in WooCommerce Android by scanning the QR code below to install the corresponding build.

App Name WooCommerce Android
Platform📱 Mobile
FlavorJalapeno
Build TypeDebug
Commite240d0e
Direct Downloadwoocommerce-prototype-build-pr13766-e240d0e.apk

@codecov-commenter
Copy link

codecov-commenter commented Mar 14, 2025

Codecov Report

Attention: Patch coverage is 64.28571% with 10 lines in your changes missing coverage. Please review.

Project coverage is 38.17%. Comparing base (7f7782f) to head (e240d0e).

Files with missing lines Patch % Lines
...ome/items/variations/WooPosVariationsDataSource.kt 60.86% 4 Missing and 5 partials ⚠️
...home/items/variations/WooPosVariationsViewModel.kt 80.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@                                  Coverage Diff                                  @@
##             issue/13746-refactor-data-source-business-logic   #13766      +/-   ##
=====================================================================================
- Coverage                                              38.17%   38.17%   -0.01%     
- Complexity                                              9312     9316       +4     
=====================================================================================
  Files                                                   2087     2087              
  Lines                                                 115109   115109              
  Branches                                               14664    14658       -6     
=====================================================================================
- Hits                                                   43940    43939       -1     
- Misses                                                 67167    67169       +2     
+ Partials                                                4002     4001       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@wpmobilebot wpmobilebot modified the milestones: 22.0, 22.1 Mar 21, 2025
@wpmobilebot
Copy link
Collaborator

Version 22.0 has now entered code-freeze, so the milestone of this PR has been updated to 22.1.

@AnirudhBhat AnirudhBhat requested a review from samiuelson April 2, 2025 06:03
@AnirudhBhat AnirudhBhat marked this pull request as ready for review April 2, 2025 06:03
@samiuelson samiuelson self-assigned this Apr 2, 2025
@samiuelson
Copy link
Contributor

@coderabbitai review

Copy link

coderabbitai bot commented Apr 2, 2025

📝 Walkthrough

Walkthrough

The pull request refactors the variations data fetching logic across production and test code. In the data source, the class now extends a common base and renames methods (e.g., updating updateCache to updateVariationCache) while adding new methods for fetching data from cache and remote sources using a unified FetchOptions parameter. The view model and corresponding tests have been updated to use a consolidated fetchData method, and tests now include a check for missing product IDs.

Changes

File(s) Change Summary
WooCommerce/src/main/kotlin/.../variations/WooPosVariationsDataSource.kt Extended WooPosBaseDataSource<ProductVariation>; renamed updateCache to updateVariationCache; added fetchFromCache, fetchFromRemote, and updated updateCache to use FetchOptions; removed fetchFirstPage and the FetchResult sealed class.
WooCommerce/src/main/kotlin/.../variations/WooPosVariationsViewModel.kt Replaced fetchFirstPage with fetchData accepting a FetchOptions object; updated imports to use Cached and Remote from a common package.
WooCommerce/src/test/kotlin/.../variations/WooPosVariationsDataSourceTest.kt Updated tests to use fetchData with FetchOptions; added a test case verifying an IllegalArgumentException when productId is null; adjusted assertions accordingly.
WooCommerce/src/test/kotlin/.../variations/WooPosVariationsViewModelTest.kt Updated mocks and method calls to use fetchData with FetchOptions instead of fetchFirstPage; modified verification of method parameters.

Sequence Diagram(s)

sequenceDiagram
    participant VM as VariationsViewModel
    participant DS as VariationsDataSource
    participant Cache as LocalCache
    participant Remote as RemoteSource

    VM->>DS: fetchData(FetchOptions)
    alt Valid productId provided
        DS->>Cache: fetchFromCache(FetchOptions)
        DS->>Remote: fetchFromRemote(FetchOptions)
        DS-->>VM: List<ProductVariation>
    else Missing productId
        DS-->>VM: throw IllegalArgumentException
    end
Loading

Assessment against linked issues

Objective (Issue) Addressed Explanation
Customer information (#137) PR does not implement functionality for customer contact or shipping info.

Suggested labels

category: tooling, category: unit tests

Suggested reviewers

  • AnirudhBhat
  • atorresveiga

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 plan to trigger planning for file edits and PR creation.
  • @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.

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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/home/variations/WooPosVariationsViewModelTest.kt (1)

64-64: Consider verifying productId argument
When using any() in whenever(), we lose explicit verification of product ID. For safer testing, consider using eq(productId) to ensure correct arguments.

WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/home/variations/WooPosVariationsDataSourceTest.kt (1)

80-83: Multiple sequential fetch calls
Consider storing the repeated fetch calls in local variables or a setup function to reduce duplication. Otherwise, the test intent is clear.

WooCommerce/src/main/kotlin/com/woocommerce/android/ui/woopos/home/items/variations/WooPosVariationsDataSource.kt (1)

21-21: Refactor to base data source
Inheriting from WooPosBaseDataSource clarifies caching and remote fetching logic. The repeated checks for null productId with thrown IllegalArgumentException is acceptable. Consider consolidating argument checks into a single helper to reduce repetition.

Also applies to: 62-94

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f7782f and e240d0e.

📒 Files selected for processing (4)
  • WooCommerce/src/main/kotlin/com/woocommerce/android/ui/woopos/home/items/variations/WooPosVariationsDataSource.kt (3 hunks)
  • WooCommerce/src/main/kotlin/com/woocommerce/android/ui/woopos/home/items/variations/WooPosVariationsViewModel.kt (2 hunks)
  • WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/home/variations/WooPosVariationsDataSourceTest.kt (15 hunks)
  • WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/home/variations/WooPosVariationsViewModelTest.kt (13 hunks)
🔇 Additional comments (35)
WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/home/variations/WooPosVariationsViewModelTest.kt (11)

12-13: New imports aligned with updated fetch approach
These imports for FetchOptions and FetchResult are consistent with the new data fetching pattern. No issues found.


87-87: Same suggestion as line 64


110-110: Same suggestion as line 64


130-130: Same suggestion as line 64


146-146: Same suggestion as line 64


167-167: Same suggestion as line 64


176-176: Explicitly verifying fetch options
Great that FetchOptions(productId = 123L, forceRefresh = true) is explicitly used. This ensures correct coverage in your verification.


181-181: Same suggestion as line 64


201-202: Same suggestion as line 64


228-229: Same suggestion as line 64


361-369: Good validation test for missing productId
This new test effectively ensures that fetchData throws an IllegalArgumentException when productId is null, improving error handling coverage.

WooCommerce/src/main/kotlin/com/woocommerce/android/ui/woopos/home/items/variations/WooPosVariationsViewModel.kt (2)

16-18: New imports for common fetch logic
These imports indicate usage of the new FetchOptions and FetchResult patterns, aligning with the base data source approach. Looks good.


82-122: Refined data fetching logic
Replacing fetchFirstPage with fetchData clarifies how local and remote results are handled. The usage of Cached and Remote states is well-structured. No issues found.

WooCommerce/src/test/kotlin/com/woocommerce/android/ui/woopos/home/variations/WooPosVariationsDataSourceTest.kt (20)

4-8: Refined imports
Adding ProductStatus, FetchOptions, FetchResult, and any() from org.mockito.kotlin aligns with the new data fetching logic. No concerns.

Also applies to: 20-20


86-86: Same suggestion as lines 80-83


90-90: Same suggestion as lines 80-83


126-126: Same suggestion as lines 80-83


129-129: Same suggestion as lines 80-83


152-152: Same suggestion as lines 80-83


167-167: Same suggestion as lines 80-83


191-191: Same suggestion as lines 80-83


193-193: Same suggestion as lines 80-83


200-200: Same suggestion as lines 80-83


201-201: Same suggestion as lines 80-83


202-202: Same suggestion as lines 80-83


228-228: Same suggestion as lines 80-83


229-229: Same suggestion as lines 80-83


237-237: Same suggestion as lines 80-83


238-238: Same suggestion as lines 80-83


260-260: Same suggestion as lines 80-83


267-267: Same suggestion as lines 80-83


268-268: Same suggestion as lines 80-83


361-369: Test coverage for null productId
Verifying that an appropriate exception is thrown helps ensure robust parameter validation. Great addition.

WooCommerce/src/main/kotlin/com/woocommerce/android/ui/woopos/home/items/variations/WooPosVariationsDataSource.kt (2)

4-7: New import statements
These imports align with the new usage of ProductStatus, FetchOptions, and WooPosBaseDataSource. Implementation looks straightforward.


26-26: Renaming ensures clarity
Renaming updateCache to updateVariationCache clarifies the function's purpose and reduces confusion.

@wpmobilebot wpmobilebot modified the milestones: 22.1, 22.2 Apr 4, 2025
@wpmobilebot
Copy link
Collaborator

Version 22.1 has now entered code-freeze, so the milestone of this PR has been updated to 22.2.

@malinajirka
Copy link
Contributor

Closing after an internal discussion, more info on #13764.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
feature: point of sale POS project type: task An internally driven task.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants