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

Space Creation - Remove Plans Table + remove the query on init load #7624

Merged
merged 5 commits into from
Feb 7, 2025

Conversation

bobbykolev
Copy link
Collaborator

@bobbykolev bobbykolev commented Feb 6, 2025

  • Space Creation:
    • now there's only one modal in the flow, loading button, and disabled state while creating;
    • The Plans logic was extracted in a hook.
    • After space creation we cached the spaceId in the LS;
  • Space Dash:
    On space change (if cache available) a new SpaceWelcomeDialog is shown;
  • VC Flow:
    • bugfix - fix the condition for creation of community if the user has none;
    • PlansTable queries removed from the flow;

A few TODOs were left:

  • decide whether we want to allow cancel of the space creation flow (currently disabled);
  • In the usePlans implement the logic to work with Account (not only with the current user). This should happen after we split the UserProvider and the AccounProvider.

Summary by CodeRabbit

  • New Features

    • Introduced a welcome dialog in the space dashboard that provides users with clear setup instructions and an easy way to contact support.
    • Enhanced the space creation experience with improved feedback during submission, helping prevent interactions while operations are pending.
  • Improvements

    • Adjusted community interaction by refining the enabling/disabling logic of the "Add to Community" button for a more intuitive workflow.
    • Streamlined plan management to simplify user navigation during space setup.

Copy link

coderabbitai bot commented Feb 6, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • src/core/apollo/generated/graphql-schema.ts is excluded by !**/generated/**

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request adds new localization keys to the translation file, including a support email and a space welcome dialog. The welcome dialog is integrated within the space dashboard and managed via cache utilities. The create space dialog now features updated state logic with a loading button and invokes caching upon successful creation. New GraphQL queries and custom hooks for determining plan availability and managing space plans have been introduced, while deprecated hooks and unused imports are removed. Additionally, the virtual contributor wizard’s logic is simplified by removing plan-related checks.

Changes

File(s) Change Summary
src/core/i18n/en/translation.en.json Added new keys: "supportEmail": "support@alkem.io" and a "spaceWelcomeDialog" section with title, description, and button.
src/domain/journey/space/SpaceDashboard/SpaceDashboardView.tsx
src/domain/journey/space/SpaceDashboard/SpaceWelcomeDialog.tsx
Integrated a new welcome dialog in the space dashboard with state management and cache utilities (getSpaceWelcomeCache, removeSpaceWelcomeCache).
src/domain/journey/space/createSpace/CreateSpaceDialog.tsx
src/domain/journey/space/createSpace/PlansTable.graphql
Updated create space dialog: replaced Material-UI components with LoadingButton, modified state handling, and added FreePlanAvailability GraphQL query.
src/domain/journey/space/createSpace/plansTable/PlansTableDialog.tsx
(removed) src/domain/journey/space/createSpace/plansTable/usePlanAvailability.ts
src/domain/journey/space/createSpace/usePlanAvailability.ts
Deprecated the old plans table hook, updated import paths, and introduced a new usePlanAvailability hook.
src/domain/journey/space/createSpace/useSpacePlans.ts Added new custom hook useSpacePlans to manage and filter available space plans.
src/domain/journey/space/createSpace/utils.ts Introduced cache utility functions (addSpaceWelcomeCache, getSpaceWelcomeCache, removeSpaceWelcomeCache) for space creation.
src/main/topLevelPages/myDashboard/newVirtualContributorWizard/ChooseCommunity.tsx
src/main/topLevelPages/myDashboard/newVirtualContributorWizard/useVirtualContributorWizard.tsx
Modified button disabling logic and removed plan availability checks in the virtual contributor wizard.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant SD as SpaceDashboardView
  participant WS as SpaceWelcomeDialog
  participant LS as LocalStorage (Cache Utils)

  U->>SD: Navigate to space dashboard
  SD->>LS: getSpaceWelcomeCache()
  LS-->>SD: Return cached space id (if any)
  SD->>SD: Validate spaceId and cache\nset openWelcome = true
  SD->>WS: Render welcome dialog
  U->>WS: Click "Get Started"
  WS->>SD: Trigger onCloseWelcome()
  SD->>LS: removeSpaceWelcomeCache()
  SD->>SD: Hide welcome dialog
Loading
sequenceDiagram
  participant U as User
  participant CSD as CreateSpaceDialog
  participant CA as Cache Utils

  U->>CSD: Fill in details & submit form
  CSD->>CSD: Validate form & set creatingLoading
  CSD->>CA: addSpaceWelcomeCache(spaceId)
  CSD-->>U: Confirm space creation and close dialog
Loading

Possibly related PRs

  • Optimize the Contributor Account Tab and VC flow  #7444: The changes in the main PR, which add new key-value pairs and sections to the translation.en.json file, are related to the modifications in the retrieved PR that also involve updates to the same JSON file for loading messages.
  • Ability to select SpaceLevel2 on create VC #7386: The changes in the main PR, which add new key-value pairs and sections to the translation.en.json file, are related to the modifications in the retrieved PR that also involve updates to the same file, specifically adding a new error message under the createVirtualContributorWizard section.
  • Contributors Page - VCs block #7279: The changes in the main PR, which involve adding a support email and a welcome dialog in the translation file, are related to the modifications in the retrieved PR that also updates the translation.en.json file with new keys and values for virtual contributors.

Suggested labels

client

Suggested reviewers

  • ccanos

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.

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.

@bobbykolev bobbykolev marked this pull request as ready for review February 6, 2025 14:50
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: 1

🧹 Nitpick comments (10)
src/domain/journey/space/createSpace/utils.ts (2)

1-1: Consider using a more specific cache key.

The current key 'SP_WELCOME' could be more descriptive. Consider using a more specific key like 'SPACE_WELCOME_DIALOG' to better indicate its purpose.

-const SPACE_CREATION_CACHE_KEY = 'SP_WELCOME';
+const SPACE_CREATION_CACHE_KEY = 'SPACE_WELCOME_DIALOG';

3-9: Add error handling for localStorage operations.

localStorage operations can fail in various scenarios (e.g., private browsing mode, storage quota exceeded). Consider adding try-catch blocks to handle these cases gracefully.

 export const addSpaceWelcomeCache = (id: string) => {
-  localStorage.setItem(SPACE_CREATION_CACHE_KEY, id);
+  try {
+    localStorage.setItem(SPACE_CREATION_CACHE_KEY, id);
+  } catch (error) {
+    console.warn('Failed to store space welcome cache:', error);
+  }
 };

 export const getSpaceWelcomeCache = () => {
-  return localStorage.getItem(SPACE_CREATION_CACHE_KEY);
+  try {
+    return localStorage.getItem(SPACE_CREATION_CACHE_KEY);
+  } catch (error) {
+    console.warn('Failed to retrieve space welcome cache:', error);
+    return null;
+  }
 };
src/domain/journey/space/SpaceDashboard/SpaceWelcomeDialog.tsx (2)

7-9: Consider adding more descriptive props interface.

The onClose prop could benefit from a more descriptive name and JSDoc comment to better indicate its purpose.

 interface SpaceWelcomeDialogProps {
+  /** Callback fired when the dialog is closed by the user */
-  onClose: () => void;
+  onDialogClose: () => void;
 }

15-34: Enhance dialog accessibility.

The dialog could benefit from improved accessibility attributes.

-    <DialogWithGrid open onClose={onClose} columns={6}>
+    <DialogWithGrid 
+      open 
+      onClose={onClose} 
+      columns={6}
+      aria-labelledby="space-welcome-dialog-title"
+      aria-describedby="space-welcome-dialog-description"
+    >
-      <DialogHeader title={t('components.spaceWelcomeDialog.title')} onClose={onClose} />
+      <DialogHeader 
+        title={t('components.spaceWelcomeDialog.title')} 
+        onClose={onClose}
+        id="space-welcome-dialog-title"
+      />
       <DialogContent>
-        <Caption alignSelf="center">
+        <Caption alignSelf="center" id="space-welcome-dialog-description">
src/domain/journey/space/createSpace/useSpacePlans.ts (2)

24-27: Add error handling for GraphQL queries.

The hook should handle potential GraphQL errors gracefully.

-  const { data, loading: plansLoading } = usePlansTableQuery({ skip });
+  const { data, loading: plansLoading, error: plansError } = usePlansTableQuery({ skip });
-  const { isPlanAvailable, loading } = usePlanAvailability({ skip, accountId });
+  const { isPlanAvailable, loading, error: availabilityError } = usePlanAvailability({ skip, accountId });

+  if (plansError || availabilityError) {
+    console.error('Failed to load plans:', plansError || availabilityError);
+  }

28-41: Optimize performance with useMemo.

The filtering and sorting logic is complex and could benefit from memoization to prevent unnecessary recalculations.

+  const filteredPlans = useMemo(
+    () =>
+      data?.platform.licensingFramework.plans
+        .filter(plan => plan.type === LicensingCredentialBasedPlanType.SpacePlan)
+        .filter(plan => plan.enabled) ?? [],
+    [data]
+  );

   const availablePlans = useMemo(
     () =>
-      (
-        data?.platform.licensingFramework.plans
-          .filter(plan => plan.type === LicensingCredentialBasedPlanType.SpacePlan)
-          .filter(plan => plan.enabled)
+      (filteredPlans
           .filter(plan => isPlanAvailable(plan))
           .sort((a, b) => a.sortOrder - b.sortOrder) ?? []
       ).map(plan => ({
         id: plan.id,
         name: plan.name,
       })),
-    [data, isPlanAvailable]
+    [filteredPlans, isPlanAvailable]
   );
src/domain/journey/space/createSpace/usePlanAvailability.ts (2)

26-26: Implement accountId feature.

The TODO comment indicates missing functionality for account-level privileges.

Would you like me to help implement the account privileges feature? I can generate the necessary GraphQL query and hook implementation.


30-54: Simplify plan availability checks using a lookup map.

The current implementation uses multiple if-else statements. Consider using a lookup map for better maintainability.

+  const PLAN_REQUIREMENTS = {
+    [LicensingCredentialBasedCredentialType.SpaceLicenseFree]: LicenseEntitlementType.AccountSpaceFree,
+    [LicensingCredentialBasedCredentialType.SpaceLicensePlus]: LicenseEntitlementType.AccountSpacePlus,
+    [LicensingCredentialBasedCredentialType.SpaceLicensePremium]: LicenseEntitlementType.AccountSpacePremium,
+  };

   const isPlanAvailable = (plan: { name: string }) => {
     if (loadingUser || loadingMeData || !currentUser?.user?.id) {
       return false;
     }

-    //TODO: Add or remove explicit checks if needed
-    if (plan.name === LicensingCredentialBasedCredentialType.SpaceLicenseFree) {
-      return (
-        myPrivileges.includes(AuthorizationPrivilege.CreateSpace) &&
-        entitlements.includes(LicenseEntitlementType.AccountSpaceFree)
-      );
-    } else if (plan.name === LicensingCredentialBasedCredentialType.SpaceLicensePlus) {
-      return (
-        myPrivileges.includes(AuthorizationPrivilege.CreateSpace) &&
-        entitlements.includes(LicenseEntitlementType.AccountSpacePlus)
-      );
-    } else if (plan.name === LicensingCredentialBasedCredentialType.SpaceLicensePremium) {
-      return (
-        myPrivileges.includes(AuthorizationPrivilege.CreateSpace) &&
-        entitlements.includes(LicenseEntitlementType.AccountSpacePremium)
-      );
-    } else {
+    const requiredEntitlement = PLAN_REQUIREMENTS[plan.name];
+    if (!requiredEntitlement) {
       return false; // switch from available to unavailable when we stopped using PlansTable
     }
+    return (
+      myPrivileges.includes(AuthorizationPrivilege.CreateSpace) &&
+      entitlements.includes(requiredEntitlement)
+    );
   };
src/domain/journey/space/createSpace/plansTable/PlansTableDialog.tsx (1)

33-35: Consider removing this deprecated component.

Since this component is marked as deprecated and not used, consider removing it to reduce technical debt. If you need to reference this implementation in the future, you can always find it in the git history.

src/domain/journey/space/createSpace/CreateSpaceDialog.tsx (1)

81-84: Add confirmation dialog for canceling during creation.

The TODO comment indicates a missing confirmation dialog when attempting to close during creation.

Would you like me to generate the confirmation dialog implementation to prevent accidental cancellation during space creation?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 12b87cc and dd035d3.

⛔ Files ignored due to path filters (2)
  • src/core/apollo/generated/apollo-hooks.ts is excluded by !**/generated/**
  • src/core/apollo/generated/graphql-schema.ts is excluded by !**/generated/**
📒 Files selected for processing (12)
  • src/core/i18n/en/translation.en.json (2 hunks)
  • src/domain/journey/space/SpaceDashboard/SpaceDashboardView.tsx (5 hunks)
  • src/domain/journey/space/SpaceDashboard/SpaceWelcomeDialog.tsx (1 hunks)
  • src/domain/journey/space/createSpace/CreateSpaceDialog.tsx (7 hunks)
  • src/domain/journey/space/createSpace/PlansTable.graphql (1 hunks)
  • src/domain/journey/space/createSpace/plansTable/PlansTableDialog.tsx (2 hunks)
  • src/domain/journey/space/createSpace/plansTable/usePlanAvailability.ts (0 hunks)
  • src/domain/journey/space/createSpace/usePlanAvailability.ts (1 hunks)
  • src/domain/journey/space/createSpace/useSpacePlans.ts (1 hunks)
  • src/domain/journey/space/createSpace/utils.ts (1 hunks)
  • src/main/topLevelPages/myDashboard/newVirtualContributorWizard/ChooseCommunity.tsx (1 hunks)
  • src/main/topLevelPages/myDashboard/newVirtualContributorWizard/useVirtualContributorWizard.tsx (0 hunks)
💤 Files with no reviewable changes (2)
  • src/domain/journey/space/createSpace/plansTable/usePlanAvailability.ts
  • src/main/topLevelPages/myDashboard/newVirtualContributorWizard/useVirtualContributorWizard.tsx
🧰 Additional context used
📓 Path-based instructions (3)
`src/**/*.{graphql,gql}`: Review the GraphQL schema and quer...

src/**/*.{graphql,gql}: Review the GraphQL schema and queries for best practices, potential bugs, and adherence to the project's GraphQL standards.
Ensure that the schema is well-defined and queries are optimized.
Check for security vulnerabilities.

  • src/domain/journey/space/createSpace/PlansTable.graphql
`src/**/*.{ts,tsx,js}`: Review the React.js/TypeScript/JavaS...

src/**/*.{ts,tsx,js}: Review the React.js/TypeScript/JavaScript code for best practices and potential bugs.
Ensure that the code adheres to TypeScript's typing system and modern standards.
Use the following code guide documentation in the codebase: 'docs/code-guidelines.md'.
Ensure sufficient error handling and logging is present, but note:

  • We have a global error handler in place. So local try/catch blocks are not required unless they provide value beyond what the global error handler already covers.
  • Avoid flagging the absence of local error handling in cases where the global error handler suffices.
  • Avoid flagging the absence of logging in cases where the global logger is already in place (graphql usage).

Inform about the recommendation of not using non-null assertion,
except on GraphQL queries where the variable is asserted non-null and followed by a
skip: with the same variable.
Examples:

  • Not Required: there's a skip
    {
    variables: { templateId: templateId! },
    skip: !templateId,
    }

Check for common security vulnerabilities such as:

  • SQL Injection
  • XSS (Cross-Site Scripting)
  • CSRF (Cross-Site Request Forgery)
  • Insecure dependencies
  • Sensitive data exposure
  • src/main/topLevelPages/myDashboard/newVirtualContributorWizard/ChooseCommunity.tsx
  • src/domain/journey/space/createSpace/plansTable/PlansTableDialog.tsx
  • src/domain/journey/space/createSpace/useSpacePlans.ts
  • src/domain/journey/space/SpaceDashboard/SpaceWelcomeDialog.tsx
  • src/domain/journey/space/SpaceDashboard/SpaceDashboardView.tsx
  • src/domain/journey/space/createSpace/utils.ts
  • src/domain/journey/space/createSpace/CreateSpaceDialog.tsx
  • src/domain/journey/space/createSpace/usePlanAvailability.ts
`src/**/*.json`: Review the JSON files for correct syntax an...

src/**/*.json: Review the JSON files for correct syntax and structure.
Ensure that the configuration and data are accurate and follow the project's standards.
Check for sensitive data exposure and ensure that the data is properly validated.

  • src/core/i18n/en/translation.en.json
🔇 Additional comments (12)
src/main/topLevelPages/myDashboard/newVirtualContributorWizard/ChooseCommunity.tsx (1)

107-107: LGTM! The button disable condition is now more logical.

The updated condition correctly enforces space selection when spaces are available, improving the user experience by providing clearer feedback.

src/domain/journey/space/createSpace/plansTable/PlansTableDialog.tsx (1)

16-16: LGTM! Import path updated correctly.

The import path has been updated to use the parent directory path.

src/domain/journey/space/SpaceDashboard/SpaceDashboardView.tsx (5)

39-40: LGTM! Required imports added.

The imports for cache utilities and SpaceWelcomeDialog component are correctly added.


93-93: LGTM! State management for welcome dialog.

The state is correctly initialized for managing the welcome dialog visibility.


111-114: LGTM! Welcome dialog close handler.

The close handler correctly updates the state and cleans up the cache.


128-135: LGTM! Welcome dialog initialization logic.

The useEffect hook correctly checks for cached welcome state when spaceId changes.


212-212: LGTM! Welcome dialog rendering.

The SpaceWelcomeDialog is correctly rendered based on spaceId and openWelcome state.

src/domain/journey/space/createSpace/CreateSpaceDialog.tsx (2)

64-68: LGTM! Improved state management.

The state management has been improved with separate states for loading, terms acceptance, and tutorial callouts.


267-275: LGTM! Enhanced loading state feedback.

The LoadingButton component provides better visual feedback during space creation.

src/domain/journey/space/createSpace/PlansTable.graphql (1)

33-35: Review: Validate New License Field Inclusion

The new license field with availableEntitlements has been added inside the account object of the me query. Please confirm that the backend schema supports this field and that the associated resolver handles possible null or missing values gracefully.

src/core/i18n/en/translation.en.json (2)

496-497: Review: New Support Email Localization Key

The "supportEmail": "support@alkem.io" key has been introduced to provide a consistent support contact across the application. Verify that its placement within the JSON structure aligns with the overall localization strategy and that all UI components referencing this key correctly handle the string.


1690-1693: Review: New Space Welcome Dialog Localization

The addition of the "spaceWelcomeDialog" section—with its title, detailed HTML-formatted description, and button text—enhances the onboarding and user experience during space creation. Please ensure that the HTML tags (e.g., <contact>) are parsed correctly in the target UI components and that this section is consistently integrated with the other translation keys.

Copy link
Contributor

@reactoholic reactoholic left a comment

Choose a reason for hiding this comment

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

Very good, just one small comment + update from base branch.

@reactoholic reactoholic merged commit 32861d6 into develop Feb 7, 2025
3 checks passed
@reactoholic reactoholic deleted the client-7607-optimized-plans branch February 7, 2025 12:07
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