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

filter subscriptions for disabled plans #470

Merged
merged 2 commits into from
Dec 18, 2024

Conversation

Nithishprem
Copy link
Contributor

@Nithishprem Nithishprem commented Dec 17, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced subscription data retrieval with improved filtering based on service offerings.
    • Support for asynchronous operations in fetching user subscriptions.
  • Bug Fixes

    • Resolved issues with subscription filtering when no service ID is provided.

Copy link
Contributor

coderabbitai bot commented Dec 17, 2024

Walkthrough

The useUserSubscriptions hook in the project has been refactored to support asynchronous data fetching and filtering of user subscriptions. The primary change involves modifying the query function to use async/await, enabling more dynamic retrieval and filtering of subscriptions based on service offerings. The hook now supports conditional filtering by service ID, dynamically fetching and matching product tiers across different service offerings.

Changes

File Change Summary
src/hooks/query/useUserSubscriptions.js - Converted queryFn to an asynchronous function
- Added logic to filter subscriptions based on serviceId
- Implemented dynamic service offering retrieval
- Modified select function to return raw response

Sequence Diagram

sequenceDiagram
    participant Hook as useUserSubscriptions
    participant API as Service API
    participant Filter as Subscription Filter

    alt ServiceId Provided
        Hook->>API: getServiceOffering(serviceId)
        API-->>Hook: Return Service Offering
        Hook->>Filter: Filter Subscriptions by ProductTierId
    else No ServiceId
        Hook->>API: getServiceOfferingIds()
        API-->>Hook: Return Available Services
        Hook->>Filter: Filter Subscriptions by ServiceId and ProductTierId
    end

    Filter-->>Hook: Return Filtered Subscriptions
Loading

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
src/hooks/query/useUserSubscriptions.js (3)

15-43: Add error handling for API calls

The asynchronous functions within queryFn are making API calls without error handling. While React Query handles errors by moving the query into an error state, adding try-catch blocks around your API calls can provide more granular control and allow for custom error messages or fallback logic.

Example refactor:

queryFn: async () => {
  try {
    const response = await listSubscriptions({ serviceId, environmentType });
    const subscriptions = response.data.subscriptions || [];

    if (serviceId) {
      const serviceOfferingRes = await getServiceOffering(serviceId, environmentType);
      const existingProductTierIds = serviceOfferingRes?.data?.offerings?.map(
        (offering) => offering?.productTierID
      );
      return subscriptions?.filter((subscription) =>
        existingProductTierIds?.includes(subscription?.productTierId)
      );
    } else {
      const servicesRes = await getServiceOfferingIds(environmentType);
      const services = servicesRes?.data?.services;
      return subscriptions?.filter((subscription) =>
        services?.find(
          (service) =>
            service?.serviceId === subscription?.serviceId &&
            service?.offerings?.find(
              (offering) =>
                offering?.productTierID === subscription.productTierId
            )
        )
      );
    }
  } catch (error) {
    // Handle error appropriately, e.g., log or transform error
    throw error;
  }
},

31-42: Optimize filtering logic for better performance

The current implementation uses nested .filter() and .find() methods, which can lead to performance issues with larger datasets due to higher time complexity. Consider optimizing this logic by converting the services and their offerings into a lookup map or set for faster access times.

Example refactor:

// Create a Map for quick lookup of serviceId to a Set of productTierIDs
const serviceOfferingsMap = new Map();
services?.forEach((service) => {
  const offeringsSet = new Set(service?.offerings?.map((offering) => offering?.productTierID));
  serviceOfferingsMap.set(service?.serviceId, offeringsSet);
});

return subscriptions?.filter((subscription) => {
  const offeringsSet = serviceOfferingsMap.get(subscription?.serviceId);
  return offeringsSet?.has(subscription?.productTierId);
});

46-46: Redundant 'select' function can be omitted

The select option in useQuery is used to transform or derive data from the query result. Since select: (response) => response doesn't modify the response, it can be omitted to simplify the code.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c613b7c and 15eacae.

📒 Files selected for processing (1)
  • src/hooks/query/useUserSubscriptions.js (1 hunks)
🔇 Additional comments (2)
src/hooks/query/useUserSubscriptions.js (2)

38-39: [Duplicate] Inconsistent property naming: 'productTierID' vs 'productTierId'

This inconsistency also appears here between offering?.productTierID and subscription.productTierId. Ensure that property names are used consistently throughout the codebase.


31-32: Possible missing 'environmentType' parameter in 'getServiceOfferingIds'

The function getServiceOffering is called with environmentType (lines 19-22), but getServiceOfferingIds is called without it. If environmentType is necessary for fetching service offerings, consider passing it to getServiceOfferingIds as well to ensure consistent behavior across different environments.

src/hooks/query/useUserSubscriptions.js Show resolved Hide resolved
@Nithishprem Nithishprem merged commit 8677fb6 into master Dec 18, 2024
6 checks passed
@Nithishprem Nithishprem deleted the bugfix/subscriptions-for-disabled-plans branch December 18, 2024 03:53
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.

2 participants