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] Import/Export Page Not Working #8446

Merged
merged 6 commits into from
Oct 17, 2024

Conversation

samuelmbabhazi
Copy link
Contributor

@samuelmbabhazi samuelmbabhazi commented Oct 16, 2024

PR

Please note: we will close your PR without comment if you do not check the boxes above and provide ALL requested information.


Summary by CodeRabbit

  • New Features
    • Introduced ExternalRedirectComponent for handling external URL redirection.
    • Added ExternalRedirectGuard to manage external URL redirects effectively.
  • Improvements
    • Enhanced PermissionsGuard for better permission-checking logic.
    • Updated template URL in ImportExportComponent for improved organization.
  • Bug Fixes
    • Streamlined routing configuration by removing unnecessary providers.

@samuelmbabhazi samuelmbabhazi self-assigned this Oct 16, 2024
@samuelmbabhazi samuelmbabhazi linked an issue Oct 16, 2024 that may be closed by this pull request
@samuelmbabhazi samuelmbabhazi marked this pull request as ready for review October 16, 2024 15:25
Copy link

coderabbitai bot commented Oct 16, 2024

Caution

Review failed

The head commit changed during the review from d7633ce to a7d17af.

Walkthrough

The changes introduce a new ExternalRedirectGuard to streamline the handling of external redirects in the routing configuration of the application. The ImportExportRoutingModule has been updated to use this guard directly, removing the previous externalUrlProvider. Additionally, a new ExternalRedirectComponent has been created, and the ImportExportComponent has had its template URL updated. The PermissionsGuard has been enhanced to improve its permission-checking logic, allowing for dynamic permission retrieval. The index.ts file has been modified to export the new guard, making it publicly accessible.

Changes

File Path Change Summary
apps/gauzy/src/app/pages/import-export/... Modified routing to use ExternalRedirectComponent and ExternalRedirectGuard, removed externalUrlProvider.
apps/gauzy/src/app/pages/import-export/... Updated template URL in ImportExportComponent and reorganized imports. Enhanced error handling in onMigrateIntoCloud.
apps/gauzy/src/app/pages/import-export/... Added ExternalRedirectComponent to ImportExportModule declarations.
packages/ui-core/core/src/lib/guards/external-redirect.guard.ts Introduced ExternalRedirectGuard implementing CanActivate, checks for redirect parameter, opens external URL in a new tab if present.
packages/ui-core/core/src/lib/guards/index.ts Added export for ExternalRedirectGuard.
packages/ui-core/core/src/lib/guards/permission.guard.ts Enhanced PermissionsGuard to include type checks for permissions.only and validation for requiredPermissions.

Poem

In the garden of code, where rabbits play,
A guard now stands to light the way.
With permissions checked and redirects clear,
Hop along, dear friends, there's nothing to fear!
Through the routes we bounce, with joy in our heart,
Each change a new adventure, a fresh work of art! 🐇✨


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.

@samuelmbabhazi
Copy link
Contributor Author

samuelmbabhazi commented Oct 16, 2024

Capture d’écran du 2024-10-16 16-32-30

Capture d’écran du 2024-10-16 17-26-20

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: 3

🧹 Outside diff range and nitpick comments (2)
packages/ui-core/core/src/lib/guards/external-redirect.guard.ts (1)

8-15: Approve implementation with suggestions for improvement.

The canActivate method effectively handles external redirects:

  • It correctly checks for the 'redirect' parameter and opens external URLs in a new tab.
  • The navigation control (returning false for external URLs and true otherwise) is implemented correctly.

However, consider the following improvements:

  1. Add URL validation to mitigate potential security risks from malicious redirects.
  2. Implement error handling for the window.open call to manage potential failures gracefully.

Here's a suggested implementation with these improvements:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ExternalRedirectGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const externalUrl = route.paramMap.get('redirect');
    if (externalUrl && this.isValidUrl(externalUrl)) {
      try {
        const newWindow = window.open(externalUrl, '_blank');
        if (!newWindow || newWindow.closed || typeof newWindow.closed == 'undefined') {
          console.error('Failed to open external URL: Popup blocked');
          // Handle popup blocked scenario (e.g., show a notification to the user)
        }
      } catch (error) {
        console.error('Failed to open external URL:', error);
        // Handle other potential errors
      }
      return false; // Prevent navigation to the external redirect route
    }
    return true; // Allow navigation if no valid external URL is found
  }

  private isValidUrl(url: string): boolean {
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  }
}

This implementation adds URL validation and error handling, enhancing the security and robustness of the guard.

packages/ui-core/core/src/lib/guards/permission.guard.ts (1)

65-65: Handle potential errors from hasPermissions method

While you're using catchError to handle errors from the hasPermissions observable, consider logging the error details to assist in debugging if the permissions check fails unexpectedly.

Apply this diff to log errors:

 return this._authService.hasPermissions(...requiredPermissions).pipe(
   map((hasPermission) => {
     if (hasPermission) {
       return true;
     } else {
       this._router.navigate([redirectTo || defaultRedirectTo]);
       return false;
     }
   }),
-  catchError(() => {
+  catchError((error) => {
+    console.error('Error occurred while checking permissions:', error);
     this._router.navigate([redirectTo || defaultRedirectTo]);
     return of(false);
   })
 );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0656dc2 and 5057948.

📒 Files selected for processing (4)
  • apps/gauzy/src/app/pages/import-export/import-export-routing.module.ts (2 hunks)
  • packages/ui-core/core/src/lib/guards/external-redirect.guard.ts (1 hunks)
  • packages/ui-core/core/src/lib/guards/index.ts (1 hunks)
  • packages/ui-core/core/src/lib/guards/permission.guard.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (7)
packages/ui-core/core/src/lib/guards/index.ts (1)

4-4: LGTM! Verify the existence of the new guard file.

The addition of the external-redirect.guard export is consistent with the existing pattern and likely relates to the PR's objective of addressing Import/Export page issues.

Let's verify the existence of the new guard file:

Consider adding a brief comment at the top of this file to explain its purpose, e.g.:

// This index file exports all guard modules from the current directory

This can improve maintainability and make the file's purpose clear to other developers.

✅ Verification successful

: The external-redirect.guard.ts file exists in the specified directory and is implemented correctly. The new export in index.ts appropriately includes the ExternalRedirectGuard, aligning with the existing module structure and the PR's objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the external-redirect.guard file

# Test: Check if the file exists
fd -t f "external-redirect.guard.ts" packages/ui-core/core/src/lib/guards

# Test: If the file exists, display its content
fd -t f "external-redirect.guard.ts" packages/ui-core/core/src/lib/guards -x cat

Length of output: 791

packages/ui-core/core/src/lib/guards/external-redirect.guard.ts (2)

1-2: LGTM: Imports are correct and concise.

The necessary Angular dependencies for implementing a route guard are correctly imported. There are no unused imports, which is good for maintaining clean code.


4-7: LGTM: Class declaration and decorator are well-structured.

The ExternalRedirectGuard class is correctly declared:

  • It implements the CanActivate interface, which is appropriate for a route guard.
  • The @Injectable decorator with providedIn: 'root' ensures the guard is available application-wide.
  • The naming convention follows Angular best practices.
apps/gauzy/src/app/pages/import-export/import-export-routing.module.ts (4)

5-5: LGTM: Import changes are consistent with usage.

The addition of ExternalRedirectGuard import and removal of ActivatedRouteSnapshot import align well with the changes in the route configuration and removal of externalUrlProvider.


43-43: LGTM: Provider changes are consistent.

The addition of ExternalRedirectGuard to the module providers and the removal of externalUrlProvider are consistent with the changes made to the route configuration.


8-8: ⚠️ Potential issue

Remove unused constant externalUrlProvider.

The externalUrlProvider constant is no longer used in the routing configuration or providers. To maintain code cleanliness and prevent confusion, it should be removed.

Remove the following line:

const externalUrlProvider = new InjectionToken('externalUrlRedirectResolver');

To ensure this constant is not used elsewhere in the project, run the following script:


32-36: ⚠️ Potential issue

Verify the external redirect route configuration.

The changes to the external redirect route raise a few concerns:

  1. Using ExternalRedirectGuard as both the component and in canActivate is unconventional. Please verify if this is the intended behavior.
  2. The resolve property still references externalUrlProvider, which has been removed. This may cause runtime errors.

Consider updating the route configuration to resolve these inconsistencies:

{
  path: 'external-redirect',
  canActivate: [ExternalRedirectGuard]
}

If additional logic is needed for URL resolution, consider implementing it within the ExternalRedirectGuard.

To ensure no other parts of the codebase rely on the previous implementation, run the following script:

packages/ui-core/core/src/lib/guards/permission.guard.ts Outdated Show resolved Hide resolved
packages/ui-core/core/src/lib/guards/permission.guard.ts Outdated Show resolved Hide resolved
packages/ui-core/core/src/lib/guards/permission.guard.ts Outdated Show resolved Hide resolved
Copy link

nx-cloud bot commented Oct 16, 2024

☁️ Nx Cloud Report

CI is running/has finished running commands for commit 5057948. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this CI Pipeline Execution


🟥 Failed Commands
nx serve api -c=production --prod

Sent with 💌 from NxCloud.

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

🧹 Outside diff range and nitpick comments (7)
apps/gauzy/src/app/pages/import-export/external-redirect/external-redirect.component.ts (1)

7-8: Remove unnecessary empty constructor.

The empty constructor doesn't serve any purpose and can be safely removed to improve code cleanliness.

Apply this diff to remove the empty constructor:

 export class ExternalRedirectComponent implements OnInit {
-	constructor() {}
🧰 Tools
🪛 Biome

[error] 8-8: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

apps/gauzy/src/app/pages/import-export/import-export.module.ts (1)

Line range hint 1-26: Summary: ExternalRedirectComponent successfully integrated into ImportExportModule.

The changes in this file correctly introduce the ExternalRedirectComponent to the ImportExportModule. Both the import statement and the addition to the declarations array are implemented correctly, following Angular best practices.

To provide more context for this change:

  1. Could you explain the purpose of the ExternalRedirectComponent and how it relates to the ImportExportModule?
  2. Are there any specific use cases or scenarios where this new component will be utilized within the import/export functionality?

This additional information would help reviewers better understand the architectural decisions behind these changes and ensure they align with the overall project goals.

apps/gauzy/src/app/pages/import-export/import-export.component.ts (5)

Line range hint 109-153: Remove unnecessary try...catch block around the observable pipeline

The try...catch block wrapping the observable chain in onMigrateIntoCloud is redundant because errors are already handled within the observable pipeline using catchError.

Consider removing the outer try...catch block to simplify error handling:

onMigrateIntoCloud(password: string) {
    const {
        id: sourceId,
        firstName,
        lastName,
        username,
        thirdPartyId,
        email,
        imageUrl,
        preferredComponentLayout,
        preferredLanguage,
        tenant: { id: tenantId, name }
    } = this.user;
    const register: IUserRegistrationInput = {
        user: {
            firstName,
            lastName,
            username,
            thirdPartyId,
            email,
            preferredComponentLayout,
            preferredLanguage,
            imageUrl
        },
        isImporting: true,
        sourceId,
        password,
        confirmPassword: password
    };

    this.loading = true;
-   try {
        this.gauzyCloudService
            .migrateIntoCloud(register)
            .pipe(
                // existing operators
            )
            .subscribe();
-   } catch (error) {
-       this.toastrService.danger(error);
-   }
}

Line range hint 115-131: Ensure proper handling of error responses in switchMap

In the switchMap, checking if (response['status']) may not be reliable if response does not contain a status property in successful responses. This might lead to unintended behavior.

Consider refactoring the error handling to manage HTTP errors within the catchError operator and ensure that switchMap processes only valid IAuthResponse objects. Remove redundant status checks within switchMap.


Line range hint 143-150: Avoid mutating input parameters in mapOrganization

Deleting properties from the organization object can lead to side effects if the object is used elsewhere.

Create a copy of the organization object before modifying it to prevent unintended mutations:

mapOrganization(
    organization: IOrganization,
    tenant: ITenant,
    userOrganizationSourceId: IUserOrganization['id']
): IOrganizationCreateInput {
+   const orgCopy = { ...organization };
    const { currency, defaultValueDateType, bonusType, imageUrl, id: sourceId } = orgCopy;
-   delete organization['id'];
-   delete organization['contactId'];
+   delete orgCopy['id'];
+   delete orgCopy['contactId'];

    return {
-       ...organization,
+       ...orgCopy,
        imageUrl,
        tenant,
        tenantId: tenant.id,
        currency: currency as CurrenciesEnum,
        defaultValueDateType: defaultValueDateType as DefaultValueDateTypeEnum,
        bonusType: bonusType as BonusTypeEnum,
        isImporting: true,
        sourceId,
        userOrganizationSourceId
    };
}

Line range hint 133-141: Avoid using async functions inside RxJS operators

Using an async function within concatMap can cause issues because concatMap expects an observable, not a Promise.

Refactor the code to return an observable from concatMap. Use from to convert the Promise returned by an async function into an observable:

- concatMap(async (tenant: ITenant) => {
-     if (tenant) {
-         for await (const { id: userOrganizationSourceId, organization } of this.userOrganizations) {
-             await firstValueFrom(
-                 this.gauzyCloudService.migrateOrganization(
-                     {
-                         ...this.mapOrganization(organization, tenant, userOrganizationSourceId)
-                     },
-                     this.token
-                 )
-             );
-         }
-         return await firstValueFrom(observableOf(tenant));
-     }
-     return await firstValueFrom(observableOf(EMPTY));
- }),
+ concatMap((tenant: ITenant) => {
+     if (tenant) {
+         return from(this.processTenantMigration(tenant));
+     }
+     return EMPTY;
+ }),

// Define the method outside
private async processTenantMigration(tenant: ITenant): Promise<ITenant> {
    for (const { id: userOrganizationSourceId, organization } of this.userOrganizations) {
        await firstValueFrom(
            this.gauzyCloudService.migrateOrganization(
                {
                    ...this.mapOrganization(organization, tenant, userOrganizationSourceId)
                },
                this.token
            )
        );
    }
    return tenant;
}

Line range hint 186-194: Refine redirection logic without using setTimeout

Using setTimeout for navigation can lead to unpredictable user experiences and is generally discouraged.

Consider chaining the navigation logic directly after the asynchronous operations complete without artificial delays:

- setTimeout(() => {
    this.router.navigate(['/pages/settings/import-export/external-redirect', { redirect }]);
- }, 1500);
+ this.router.navigate(['/pages/settings/import-export/external-redirect', { redirect }]);

If a delay is necessary to ensure that all processes have completed, it's better to manage this within the observable chain rather than relying on setTimeout.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5057948 and f39612a.

📒 Files selected for processing (6)
  • apps/gauzy/src/app/pages/import-export/external-redirect/external-redirect.component.ts (1 hunks)
  • apps/gauzy/src/app/pages/import-export/import-export-routing.module.ts (2 hunks)
  • apps/gauzy/src/app/pages/import-export/import-export.component.ts (1 hunks)
  • apps/gauzy/src/app/pages/import-export/import-export.module.ts (2 hunks)
  • packages/ui-core/core/src/lib/guards/external-redirect.guard.ts (1 hunks)
  • packages/ui-core/core/src/lib/guards/permission.guard.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/gauzy/src/app/pages/import-export/import-export-routing.module.ts
  • packages/ui-core/core/src/lib/guards/external-redirect.guard.ts
  • packages/ui-core/core/src/lib/guards/permission.guard.ts
🧰 Additional context used
🪛 Biome
apps/gauzy/src/app/pages/import-export/external-redirect/external-redirect.component.ts

[error] 8-8: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

🔇 Additional comments (5)
apps/gauzy/src/app/pages/import-export/external-redirect/external-redirect.component.ts (1)

1-6: Imports and component decorator look good, but clarify the empty template.

The imports and component decorator are correctly implemented. However, the empty template (template: '') is unusual.

Could you clarify the intended use of this component? If it's meant for programmatic use only (e.g., for redirection), consider adding a comment explaining this to improve code readability.

apps/gauzy/src/app/pages/import-export/import-export.module.ts (2)

9-9: LGTM: Import statement for ExternalRedirectComponent is correct.

The import statement follows Angular's best practices and correctly imports the ExternalRedirectComponent from its relative path.


23-23: LGTM: ExternalRedirectComponent correctly added to module declarations.

The ExternalRedirectComponent is properly added to the module's declarations array, which is necessary for Angular to recognize and use the component within this module.

To ensure the new component is being utilized, please run the following script to check for its usage within the module:

✅ Verification successful

LGTM: ExternalRedirectComponent correctly added and utilized within the routing module.

The ExternalRedirectComponent is properly declared in the ImportExportModule and is appropriately used within the import-export-routing.module.ts. There are no additional usages in template or TypeScript files, ensuring that the component is correctly scoped and utilized as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of ExternalRedirectComponent within the ImportExportModule

# Test: Search for ExternalRedirectComponent usage in template files
echo "Searching for ExternalRedirectComponent usage in template files:"
rg --type html '<app-external-redirect' apps/gauzy/src/app/pages/import-export

# Test: Search for ExternalRedirectComponent usage in TypeScript files (excluding the component and module definition)
echo "Searching for ExternalRedirectComponent usage in TypeScript files:"
rg --type ts 'ExternalRedirectComponent' apps/gauzy/src/app/pages/import-export | grep -v 'external-redirect.component.ts' | grep -v 'import-export.module.ts'

Length of output: 792

apps/gauzy/src/app/pages/import-export/import-export.component.ts (2)

24-31: Imports are correctly organized and used

The consolidated imports improve readability, and all imported services are utilized within the component.


36-36: Template URL update aligns with Angular standards

Updating the templateUrl to './import-export.component.html' follows Angular's style guide and enhances consistency.

@rahul-rocket rahul-rocket merged commit 2975fe6 into develop Oct 17, 2024
12 of 18 checks passed
@rahul-rocket rahul-rocket deleted the fix/#8442-import-export-page branch October 17, 2024 07:05
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.

[Fix] Import/Export Page Not Working
2 participants