-
Notifications
You must be signed in to change notification settings - Fork 533
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
Conversation
WalkthroughThe changes introduce a new Changes
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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:
- Add URL validation to mitigate potential security risks from malicious redirects.
- 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 fromhasPermissions
methodWhile you're using
catchError
to handle errors from thehasPermissions
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
📒 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 inindex.ts
appropriately includes theExternalRedirectGuard
, 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 catLength 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 withprovidedIn: '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 ofActivatedRouteSnapshot
import align well with the changes in the route configuration and removal ofexternalUrlProvider
.
43-43
: LGTM: Provider changes are consistent.The addition of
ExternalRedirectGuard
to the module providers and the removal ofexternalUrlProvider
are consistent with the changes made to the route configuration.
8-8
:⚠️ Potential issueRemove 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 issueVerify the external redirect route configuration.
The changes to the external redirect route raise a few concerns:
- Using
ExternalRedirectGuard
as both the component and incanActivate
is unconventional. Please verify if this is the intended behavior.- The
resolve
property still referencesexternalUrlProvider
, 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:
☁️ Nx Cloud ReportCI 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
Sent with 💌 from NxCloud. |
There was a problem hiding this 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:
- Could you explain the purpose of the ExternalRedirectComponent and how it relates to the ImportExportModule?
- 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 unnecessarytry...catch
block around the observable pipelineThe
try...catch
block wrapping the observable chain inonMigrateIntoCloud
is redundant because errors are already handled within the observable pipeline usingcatchError
.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 inswitchMap
In the
switchMap
, checkingif (response['status'])
may not be reliable ifresponse
does not contain astatus
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 thatswitchMap
processes only validIAuthResponse
objects. Remove redundant status checks withinswitchMap
.
Line range hint
143-150
: Avoid mutating input parameters inmapOrganization
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 usingasync
functions inside RxJS operatorsUsing an
async
function withinconcatMap
can cause issues becauseconcatMap
expects an observable, not a Promise.Refactor the code to return an observable from
concatMap
. Usefrom
to convert the Promise returned by anasync
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 usingsetTimeout
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
📒 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 theImportExportModule
and is appropriately used within theimport-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 usedThe consolidated imports improve readability, and all imported services are utilized within the component.
36-36
: Template URL update aligns with Angular standardsUpdating the
templateUrl
to'./import-export.component.html'
follows Angular's style guide and enhances consistency.
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
ExternalRedirectComponent
for handling external URL redirection.ExternalRedirectGuard
to manage external URL redirects effectively.PermissionsGuard
for better permission-checking logic.ImportExportComponent
for improved organization.