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

fix: Uses guard instead of redirection to reach onboarding page when opening the mobile app #3438

Merged

Conversation

bistaastha
Copy link
Contributor

@bistaastha bistaastha commented Jan 23, 2025

This PR includes:

  • Changing the existing implementation for redirection to onboarding page
  • Refactoring code

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced an Onboarding Guard to control route access based on user and organization status.
    • Enhanced navigation logic to dynamically determine dashboard or onboarding redirections.
  • Improvements

    • Streamlined user navigation flow across multiple pages.
    • Simplified service methods for checking onboarding requirements.
    • Added more sophisticated checks for organization and user eligibility.
  • Changes

    • Modified default routing to redirect users to 'my_dashboard' as the new initial landing page.
    • Updated navigation methods in multiple components to use a centralized onboarding service.
    • Removed redundant navigation logic from the onboarding process.

Copy link

coderabbitai bot commented Jan 23, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

In a thunderous display of code prowess, this pull request transforms the application's onboarding and navigation logic! A new OnboardingGuard emerges, wielding the power to redirect users based on complex organizational settings. The routing modules and services are refactored to streamline the user journey, replacing multiple nested checks with a single, powerful checkForRedirectionToOnboarding method that decides the user's path with the precision of a superstar's punch!

Changes

File Change Summary
src/app/app-routing.module.ts Modified root route redirection from 'enterprise/spender_onboarding' to 'enterprise/my_dashboard'
src/app/auth/switch-org/switch-org.page.ts Simplified navigateToDashboard method using checkForRedirectionToOnboarding from SpenderOnboardingService
src/app/core/guards/onboarding.guard.ts Introduced OnboardingGuard to control access to routes based on onboarding status
src/app/core/services/spender-onboarding.service.ts Added checkForRedirectionToOnboarding method and several private helper methods for onboarding checks
src/app/fyle/fyle-routing.module.ts Applied OnboardingGuard to my_dashboard route
src/app/fyle/spender-onboarding/spender-onboarding.page.ts Removed navigateToDashboard method
src/app/post-verification/invited-user/invited-user.page.ts Simplified navigation logic using checkForRedirectionToOnboarding

Possibly related PRs

Suggested labels

size/L

Suggested reviewers

  • Chethan-Fyle
  • arjunaj5

Poem

Routing paths, a cosmic dance, 🌟
Onboarding guard with stylish stance! 💥
Code flows like a hero's might,
Redirecting users left and right! 🚀
Rajinikanth would surely say,
"Style is the way!" 😎


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fd6a096 and dfe9bc8.

📒 Files selected for processing (1)
  • src/app/app-routing.module.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@github-actions github-actions bot added the size/M Medium PR label Jan 23, 2025
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: 6

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1afe7f6 and f2443b3.

📒 Files selected for processing (7)
  • src/app/app-routing.module.ts (1 hunks)
  • src/app/auth/switch-org/switch-org.page.ts (1 hunks)
  • src/app/core/guards/onboarding.guard.ts (1 hunks)
  • src/app/core/services/spender-onboarding.service.ts (2 hunks)
  • src/app/fyle/fyle-routing.module.ts (1 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding.page.ts (0 hunks)
  • src/app/post-verification/invited-user/invited-user.page.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/app/fyle/spender-onboarding/spender-onboarding.page.ts
🧰 Additional context used
🪛 eslint
src/app/app-routing.module.ts

[error] 6-6: 'OnboardingGuard' is defined but never used.

(@typescript-eslint/no-unused-vars)

src/app/core/guards/onboarding.guard.ts

[error] 14-14: 'next' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 15-15: 'state' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Run linters
src/app/app-routing.module.ts

[failure] 6-6:
'OnboardingGuard' is defined but never used

src/app/core/guards/onboarding.guard.ts

[failure] 14-14:
'next' is defined but never used


[failure] 15-15:
'state' is defined but never used

🪛 GitHub Actions: Lint
src/app/app-routing.module.ts

[error] 6-6: 'OnboardingGuard' is defined but never used

🔇 Additional comments (2)
src/app/fyle/fyle-routing.module.ts (1)

5-5: Mind it! The routing configuration looks solid!

The OnboardingGuard is properly integrated with the my_dashboard route while maintaining the existing OptInGuard functionality. This is how we do it in style!

Also applies to: 11-11

src/app/auth/switch-org/switch-org.page.ts (1)

321-339: Let's verify our navigation style is consistent everywhere!

Check if all components use the new navigation pattern consistently.

✅ Verification successful

Mind it! Your navigation style is perfectly consistent, just like my style in movies!

The navigation pattern ['/', 'enterprise', ...] is followed religiously throughout the codebase, like a well-choreographed action sequence. Your code in switch-org.page.ts matches this pattern perfectly, making it a blockbuster implementation!

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all files that might contain navigation logic to ensure consistent implementation

# Look for potential navigation to dashboard or onboarding
rg -l "navigate.*(?:dashboard|onboarding)" --type ts

# Look for old navigation patterns that might need updating
rg -l "forkJoin.*orgSettingsService.*getOnboardingStatus" --type ts

Length of output: 2265


Script:

#!/bin/bash
# Search for enterprise route navigation patterns
rg "navigate.*enterprise" -A 2 -B 2 --type ts

# Also check for any router imports to ensure we're using the same navigation method
ast-grep --pattern 'import { $$ } from "@angular/router"'

Length of output: 66887

Comment on lines +124 to +126
private checkCCCEnabled(orgSettings: OrgSettings): boolean {
return !!orgSettings.corporate_credit_card_settings.allowed && !!orgSettings.corporate_credit_card_settings.enabled;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Careful! Null checks needed to prevent runtime errors.

If orgSettings.corporate_credit_card_settings is undefined, accessing its properties will cause a crash. Let's ensure we check for its existence before using it.

Apply this diff to add the null check:

 private checkCCCEnabled(orgSettings: OrgSettings): boolean {
-    return !!orgSettings.corporate_credit_card_settings.allowed && !!orgSettings.corporate_credit_card_settings.enabled;
+    return (
+      !!orgSettings.corporate_credit_card_settings &&
+      !!orgSettings.corporate_credit_card_settings.allowed &&
+      !!orgSettings.corporate_credit_card_settings.enabled
+    );
  }
📝 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.

Suggested change
private checkCCCEnabled(orgSettings: OrgSettings): boolean {
return !!orgSettings.corporate_credit_card_settings.allowed && !!orgSettings.corporate_credit_card_settings.enabled;
}
private checkCCCEnabled(orgSettings: OrgSettings): boolean {
return (
!!orgSettings.corporate_credit_card_settings &&
!!orgSettings.corporate_credit_card_settings.allowed &&
!!orgSettings.corporate_credit_card_settings.enabled
);
}

src/app/core/services/spender-onboarding.service.ts Outdated Show resolved Hide resolved
Comment on lines +14 to +15
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Unused parameters in canActivate method.

The parameters next and state are defined but not used, which causes linting errors.

You can fix this by prefixing the parameters with an underscore or removing them if they're not needed:

 canActivate(
-    next: ActivatedRouteSnapshot,
-    state: RouterStateSnapshot
+    _next: ActivatedRouteSnapshot,
+    _state: RouterStateSnapshot
 ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
📝 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.

Suggested change
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
_next: ActivatedRouteSnapshot,
_state: RouterStateSnapshot
🧰 Tools
🪛 eslint

[error] 14-14: 'next' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 15-15: 'state' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Run linters

[failure] 14-14:
'next' is defined but never used


[failure] 15-15:
'state' is defined but never used

@@ -3,11 +3,12 @@
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './core/guards/auth.guard';
import { VerifiedOrgAuthGuard } from './core/guards/verified-org-auth.guard';
import { OnboardingGuard } from './core/guards/onboarding.guard';
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

'OnboardingGuard' is imported but not used.

The OnboardingGuard is imported but not utilized in this file, leading to a linting error.

Either remove the unused import:

-import { OnboardingGuard } from './core/guards/onboarding.guard';

Or, if you intend to use it, add it to the appropriate route:

 {
   path: '',
-  redirectTo: 'enterprise/my_dashboard',
+  redirectTo: 'enterprise/my_dashboard',
+  canActivate: [OnboardingGuard],
   pathMatch: 'full',
 },

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

🧰 Tools
🪛 eslint

[error] 6-6: 'OnboardingGuard' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Run linters

[failure] 6-6:
'OnboardingGuard' is defined but never used

🪛 GitHub Actions: Lint

[error] 6-6: 'OnboardingGuard' is defined but never used

Comment on lines +99 to +110
this.spenderOnboardingService
.checkForRedirectionToOnboarding()
.pipe(
map((shouldProceedToOnboarding) => {
if (shouldProceedToOnboarding) {
this.router.navigate(['/', 'enterprise', 'spender_onboarding']);
} else {
this.router.navigate(['/', 'enterprise', 'my_dashboard']);
}
})
)
.subscribe();
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

What a transformation! But let's add some style to error handling, macha!

The simplified navigation logic using checkForRedirectionToOnboarding is clean and effective. However, we should handle potential errors with the same style we handle success!

Add error handling like this, superstar:

 this.spenderOnboardingService
   .checkForRedirectionToOnboarding()
   .pipe(
     map((shouldProceedToOnboarding) => {
       if (shouldProceedToOnboarding) {
         this.router.navigate(['/', 'enterprise', 'spender_onboarding']);
       } else {
         this.router.navigate(['/', 'enterprise', 'my_dashboard']);
       }
     }),
+    catchError((error) => {
+      console.error('Navigation failed:', error);
+      return this.router.navigate(['/', 'auth', 'login']);
+    })
   )
   .subscribe();
📝 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.

Suggested change
this.spenderOnboardingService
.checkForRedirectionToOnboarding()
.pipe(
map((shouldProceedToOnboarding) => {
if (shouldProceedToOnboarding) {
this.router.navigate(['/', 'enterprise', 'spender_onboarding']);
} else {
this.router.navigate(['/', 'enterprise', 'my_dashboard']);
}
})
)
.subscribe();
this.spenderOnboardingService
.checkForRedirectionToOnboarding()
.pipe(
map((shouldProceedToOnboarding) => {
if (shouldProceedToOnboarding) {
this.router.navigate(['/', 'enterprise', 'spender_onboarding']);
} else {
this.router.navigate(['/', 'enterprise', 'my_dashboard']);
}
}),
catchError((error) => {
console.error('Navigation failed:', error);
return this.router.navigate(['/', 'auth', 'login']);
})
)
.subscribe();

Comment on lines +321 to +339
this.spenderOnboardingService
.checkForRedirectionToOnboarding()
.pipe(
map((shouldProceedToOnboarding) => {
if (shouldProceedToOnboarding) {
this.router.navigate(['/', 'enterprise', 'spender_onboarding']);
} else {
this.router.navigate([
'/',
'enterprise',
'my_dashboard',
{
openSMSOptInDialog: openOptInDialog,
},
]);
}
})
)
.subscribe();
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Mind-blowing implementation, but let's add some punch with tests!

The navigation logic is perfectly aligned with the invited-user page implementation, and smoothly handles the SMS opt-in dialog. But every superstar needs a good backup!

Would you like me to generate unit tests for this navigation logic? We'll test scenarios like:

  • Redirection to onboarding
  • Redirection to dashboard with SMS opt-in
  • Error handling

Copy link
Contributor

@Chethan-Fyle Chethan-Fyle left a comment

Choose a reason for hiding this comment

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

One important comment.

Copy link
Contributor

@arjunaj5 arjunaj5 left a comment

Choose a reason for hiding this comment

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

2 comments

}
return true;
})
);
Copy link
Contributor

Choose a reason for hiding this comment

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

can we redirect to dashboard if the API throws some error?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure

Copy link
Contributor Author

Choose a reason for hiding this comment

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

will add this in a follow up


const routes: Routes = [
{
path: 'my_dashboard',
loadChildren: () => import('./dashboard/dashboard.module').then((m) => m.DashboardPageModule),
canActivate: [OnboardingGuard],
Copy link
Contributor

Choose a reason for hiding this comment

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

might have to check if this really solves the white screen that appears for few seconds in a low network.

If it is not solved, can we land the user to the dashboard and then check if user has to go to spender onboarding flow and redirect?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Going to the dashboard will still be jarring UI in this case, what I can do is try adding a loader with the guard over the white screen (same as before). The transition won't be as obvious as before though.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

or I can add a localstorage key to determine if onboarding is complete, even before checking the API calls

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Will add this in a follow up

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f2443b3 and fd6a096.

📒 Files selected for processing (1)
  • src/app/core/services/spender-onboarding.service.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build (12.x)
  • GitHub Check: gitStream.cm
🔇 Additional comments (3)
src/app/core/services/spender-onboarding.service.ts (3)

125-126: Mind the null, avoid the fall!

Boss, if orgSettings.corporate_credit_card_settings is undefined, accessing its properties will crash the app faster than a speeding bullet! Let's add a check to ensure it exists before we use it.

Apply this diff to add the null check:

 private checkCCCEnabled(orgSettings: OrgSettings): boolean {
+   return (
+     !!orgSettings.corporate_credit_card_settings &&
      !!orgSettings.corporate_credit_card_settings.allowed &&
      !!orgSettings.corporate_credit_card_settings.enabled
+   );
 }

145-150: Currency check sharper than my style, but let's think global!

We're checking if currency === 'USD' to proceed. Are we sure we want to limit this to USD only? Let's ensure we're not leaving out other currencies if that's not the intention.


109-110: ⚠️ Potential issue

Double power when single is enough!

We're using isCCCEnabled && isCardFeedEnabled to determine areCardsEnabled. Shouldn't we proceed if either one is enabled? Using || might be the way.

Apply this diff if that's the case:

 const shouldProceedToOnboarding = this.shouldProceedToOnboarding(
   eou.org.currency,
   restrictedOrgs,
-  isCCCEnabled && isCardFeedEnabled,
+  isCCCEnabled || isCardFeedEnabled,
   onboardingStatus
 );

Likely invalid or redundant comment.

}

private isRestrictedOrg(orgSettings: OrgSettings, isUserFromINCluster: boolean): boolean {
return orgSettings.org_id === 'orgp5onHZThs' || isUserFromINCluster;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Hardcoding org IDs? Let's keep it flexible like me!

Thalaiva, using a hardcoded org_id like 'orgp5onHZThs' is risky business. If that ID changes, our code breaks. Consider fetching this ID from a configuration or making it dynamic.

Comment on lines +103 to +107
this.orgSettingsService.get(),
this.getOnboardingStatus(),
from(this.utilityService.isUserFromINCluster()),
this.authService.getEou(),
]).pipe(
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Too many cooks spoil the broth, let's simplify!

Superstar, we're fetching multiple observables with forkJoin. Let's make sure all these are necessary and optimize our calls. Unnecessary calls can slow us down.

@bistaastha bistaastha merged commit 3516b3f into FYLE-86cx2t82k-base-feature-branch Jan 24, 2025
4 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/M Medium PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants