Browse Source

Migrate account dialogs to dedicated routes

pull/7473/head
Thomas Kaul 1 month ago
parent
commit
a0ee4f0ffe
  1. 263
      apps/client/src/app/pages/accounts/account-dialog-host/account-dialog-host.component.ts
  2. 1
      apps/client/src/app/pages/accounts/account-dialog-host/types/account-dialog-mode.type.ts
  3. 189
      apps/client/src/app/pages/accounts/accounts-page.component.ts
  4. 7
      apps/client/src/app/pages/accounts/accounts-page.html
  5. 28
      apps/client/src/app/pages/accounts/accounts-page.routes.ts
  6. 21
      libs/common/src/lib/routes/routes.ts
  7. 14
      libs/ui/src/lib/accounts-table/accounts-table.component.html
  8. 26
      libs/ui/src/lib/accounts-table/accounts-table.component.stories.ts
  9. 30
      libs/ui/src/lib/accounts-table/accounts-table.component.ts
  10. 9
      libs/ui/src/lib/assistant/assistant-list-item/assistant-list-item.component.ts

263
apps/client/src/app/pages/accounts/account-dialog-host/account-dialog-host.component.ts

@ -0,0 +1,263 @@
import { GfAccountDetailDialogComponent } from '@ghostfolio/client/components/account-detail-dialog/account-detail-dialog.component';
import {
AccountDetailDialogParams,
AccountDetailDialogResult
} from '@ghostfolio/client/components/account-detail-dialog/interfaces/interfaces';
import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service';
import { UserService } from '@ghostfolio/client/services/user/user.service';
import { CreateAccountDto, UpdateAccountDto } from '@ghostfolio/common/dtos';
import { AccountResponse, User } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { internalRoutes } from '@ghostfolio/common/routes/routes';
import { DataService } from '@ghostfolio/ui/services';
import {
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
OnDestroy,
OnInit,
inject
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { DeviceDetectorService } from 'ngx-device-detector';
import { Observable, of } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { GfCreateOrUpdateAccountDialogComponent } from '../create-or-update-account-dialog/create-or-update-account-dialog.component';
import { CreateOrUpdateAccountDialogParams } from '../create-or-update-account-dialog/interfaces/interfaces';
import { AccountDialogMode } from './types/account-dialog-mode.type';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'gf-account-dialog-host',
template: ''
})
export class GfAccountDialogHostComponent implements OnDestroy, OnInit {
private dialogRef: MatDialogRef<unknown>;
private readonly deviceType = computed(() => {
return this.deviceDetectorService.deviceInfo().deviceType;
});
private readonly dataService = inject(DataService);
private readonly destroyRef = inject(DestroyRef);
private readonly deviceDetectorService = inject(DeviceDetectorService);
private readonly dialog = inject(MatDialog);
private readonly impersonationStorageService = inject(
ImpersonationStorageService
);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly userService = inject(UserService);
public ngOnInit() {
const mode = this.route.snapshot.data.mode as AccountDialogMode;
const accountId = this.route.snapshot.paramMap.get('accountId');
const account$: Observable<AccountResponse | undefined> =
mode === 'update' && accountId
? this.dataService.fetchAccount(accountId)
: of(undefined);
this.userService
.get()
.pipe(
switchMap((user) => {
return account$.pipe(
map((account) => {
return { account, user };
})
);
}),
takeUntilDestroyed(this.destroyRef)
)
.subscribe({
error: () => {
this.navigateBack();
},
next: ({ account, user }) => {
if (mode === 'detail') {
this.openAccountDetailDialog({ user });
return;
}
if (mode === 'update') {
if (!account) {
this.navigateBack();
return;
}
const {
balance,
comment,
currency,
id,
isExcluded,
name,
platformId,
tags
} = account;
this.openCreateOrUpdateAccountDialog({
user,
account: {
balance,
comment,
currency,
id,
isExcluded,
name,
platformId,
tags
},
isUpdate: true
});
return;
}
if (!hasPermission(user?.permissions, permissions.createAccount)) {
this.navigateBack();
return;
}
this.openCreateOrUpdateAccountDialog({
user,
account: {
balance: 0,
comment: null,
currency: user?.settings?.baseCurrency ?? null,
id: null,
isExcluded: false,
name: null,
platformId: null,
tags: []
},
isUpdate: false
});
}
});
}
public ngOnDestroy() {
// The dialog lives in an overlay outside of this component, so it needs to
// be closed explicitly when leaving the route (for example via the browser
// navigation)
this.dialogRef?.close();
}
private navigateBack() {
void this.router.navigate(internalRoutes.accounts.routerLink);
}
private openAccountDetailDialog({ user }: { user: User }) {
const accountId = this.route.snapshot.paramMap.get('accountId');
if (!accountId) {
this.navigateBack();
return;
}
const hasImpersonationId = !!this.impersonationStorageService.getId();
const dialogRef = this.dialog.open<
GfAccountDetailDialogComponent,
AccountDetailDialogParams,
AccountDetailDialogResult
>(GfAccountDetailDialogComponent, {
autoFocus: false,
data: {
accountId,
hasImpersonationId,
deviceType: this.deviceType(),
hasPermissionToCreateActivity:
!hasImpersonationId &&
hasPermission(user?.permissions, permissions.createActivity) &&
!user?.settings?.isRestrictedView
},
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
});
this.dialogRef = dialogRef;
dialogRef
.afterClosed()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((result) => {
if (result?.isNavigating) {
return;
}
// Deliberately not bound to the destroy reference: navigating back
// destroys this component and the refreshed user is what makes the
// accounts page reload its data, which may have been changed in the
// dialog (for example the cash balances)
this.userService.get(true).subscribe();
this.navigateBack();
});
}
private openCreateOrUpdateAccountDialog({
account,
isUpdate,
user
}: {
account: CreateOrUpdateAccountDialogParams['account'];
isUpdate: boolean;
user: User;
}) {
const dialogRef = this.dialog.open<
GfCreateOrUpdateAccountDialogComponent,
CreateOrUpdateAccountDialogParams,
CreateAccountDto | UpdateAccountDto | null
>(GfCreateOrUpdateAccountDialogComponent, {
data: {
account,
user
},
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
});
this.dialogRef = dialogRef;
dialogRef
.afterClosed()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((result) => {
if (!result) {
this.navigateBack();
return;
}
const request$: Observable<unknown> = isUpdate
? this.dataService.putAccount(result as UpdateAccountDto)
: this.dataService.postAccount(result as CreateAccountDto);
request$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
error: () => {
this.navigateBack();
},
next: () => {
// Deliberately not bound to the destroy reference: navigating back
// destroys this component and the refreshed user is what makes the
// accounts page reload its data
this.userService.get(true).subscribe();
this.navigateBack();
}
});
});
}
}

1
apps/client/src/app/pages/accounts/account-dialog-host/types/account-dialog-mode.type.ts

@ -0,0 +1 @@
export type AccountDialogMode = 'create' | 'detail' | 'update';

189
apps/client/src/app/pages/accounts/accounts-page.component.ts

@ -1,17 +1,9 @@
import { GfAccountDetailDialogComponent } from '@ghostfolio/client/components/account-detail-dialog/account-detail-dialog.component';
import {
AccountDetailDialogParams,
AccountDetailDialogResult
} from '@ghostfolio/client/components/account-detail-dialog/interfaces/interfaces';
import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service';
import { UserService } from '@ghostfolio/client/services/user/user.service';
import {
CreateAccountDto,
TransferBalanceDto,
UpdateAccountDto
} from '@ghostfolio/common/dtos';
import { TransferBalanceDto } from '@ghostfolio/common/dtos';
import { User } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { internalRoutes } from '@ghostfolio/common/routes/routes';
import { AccountWithValue } from '@ghostfolio/common/types';
import { GfAccountsTableComponent } from '@ghostfolio/ui/accounts-table';
import { GfFabComponent } from '@ghostfolio/ui/fab';
@ -30,13 +22,10 @@ import {
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { Tag } from '@prisma/client';
import { DeviceDetectorService } from 'ngx-device-detector';
import { EMPTY } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { GfCreateOrUpdateAccountDialogComponent } from './create-or-update-account-dialog/create-or-update-account-dialog.component';
import { CreateOrUpdateAccountDialogParams } from './create-or-update-account-dialog/interfaces/interfaces';
import { TransferBalanceDialogParams } from './transfer-balance/interfaces/interfaces';
import { GfTransferBalanceDialogComponent } from './transfer-balance/transfer-balance-dialog.component';
@ -54,6 +43,7 @@ export class GfAccountsPageComponent implements OnInit {
protected hasPermissionToCreateAccount: boolean;
protected hasPermissionToUpdateAccount: boolean;
protected impersonationId: string | null;
protected readonly internalRoutes = internalRoutes;
protected totalBalanceInBaseCurrency = 0;
protected totalValueInBaseCurrency = 0;
protected user: User;
@ -79,26 +69,7 @@ export class GfAccountsPageComponent implements OnInit {
this.route.queryParams
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
if (params['accountId'] && params['accountDetailDialog']) {
this.openAccountDetailDialog(params['accountId']);
} else if (
params['createDialog'] &&
this.hasPermissionToCreateAccount
) {
this.openCreateAccountDialog();
} else if (params['editDialog']) {
if (this.accounts) {
const account = this.accounts.find(({ id }) => {
return id === params['accountId'];
});
if (account) {
this.openUpdateAccountDialog(account);
}
} else {
this.router.navigate(['.'], { relativeTo: this.route });
}
} else if (params['transferBalanceDialog']) {
if (params['transferBalanceDialog']) {
this.openTransferBalanceDialog();
}
});
@ -130,12 +101,12 @@ export class GfAccountsPageComponent implements OnInit {
this.user.permissions,
permissions.updateAccount
);
this.fetchAccounts();
}
this.changeDetectorRef.markForCheck();
});
this.fetchAccounts();
}
protected onDeleteAccount(aId: string) {
@ -160,12 +131,6 @@ export class GfAccountsPageComponent implements OnInit {
});
}
protected onUpdateAccount(aAccount: AccountWithValue) {
this.router.navigate([], {
queryParams: { accountId: aAccount.id, editDialog: true }
});
}
private fetchAccounts() {
this.dataService
.fetchAccounts()
@ -182,8 +147,10 @@ export class GfAccountsPageComponent implements OnInit {
this.totalBalanceInBaseCurrency = totalBalanceInBaseCurrency;
this.totalValueInBaseCurrency = totalValueInBaseCurrency;
if (this.accounts?.length <= 0) {
this.router.navigate([], { queryParams: { createDialog: true } });
if (this.hasPermissionToCreateAccount && this.accounts?.length <= 0) {
void this.router.navigate(
internalRoutes.accounts.subRoutes.create.routerLink
);
}
this.changeDetectorRef.markForCheck();
@ -191,142 +158,6 @@ export class GfAccountsPageComponent implements OnInit {
);
}
private openUpdateAccountDialog({
balance,
comment,
currency,
id,
name,
platformId,
tags
}: AccountWithValue & { tags?: Tag[] }) {
const dialogRef = this.dialog.open<
GfCreateOrUpdateAccountDialogComponent,
CreateOrUpdateAccountDialogParams
>(GfCreateOrUpdateAccountDialogComponent, {
data: {
account: {
balance,
comment,
currency,
id,
name,
platformId,
tags
},
user: this.user
},
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
});
dialogRef
.afterClosed()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((account: UpdateAccountDto | null) => {
if (account) {
this.reset();
this.dataService
.putAccount(account)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.userService
.get(true)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
this.fetchAccounts();
});
this.changeDetectorRef.markForCheck();
}
this.router.navigate(['.'], { relativeTo: this.route });
});
}
private openAccountDetailDialog(aAccountId: string) {
const dialogRef = this.dialog.open<
GfAccountDetailDialogComponent,
AccountDetailDialogParams,
AccountDetailDialogResult
>(GfAccountDetailDialogComponent, {
autoFocus: false,
data: {
accountId: aAccountId,
deviceType: this.deviceType(),
hasPermissionToCreateActivity:
!this.hasImpersonationId &&
hasPermission(this.user?.permissions, permissions.createActivity) &&
!this.user?.settings?.isRestrictedView,
impersonationId: this.impersonationId
},
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
});
dialogRef
.afterClosed()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((result) => {
if (result?.isNavigating) {
return;
}
this.fetchAccounts();
this.router.navigate(['.'], { relativeTo: this.route });
});
}
private openCreateAccountDialog() {
const dialogRef = this.dialog.open<
GfCreateOrUpdateAccountDialogComponent,
CreateOrUpdateAccountDialogParams
>(GfCreateOrUpdateAccountDialogComponent, {
data: {
account: {
balance: 0,
comment: null,
currency: this.user?.settings?.baseCurrency ?? null,
id: null,
name: null,
platformId: null,
tags: []
},
user: this.user
} satisfies CreateOrUpdateAccountDialogParams,
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
});
dialogRef
.afterClosed()
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((account: CreateAccountDto | null) => {
if (account) {
this.reset();
this.dataService
.postAccount(account)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.userService
.get(true)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
this.fetchAccounts();
});
this.changeDetectorRef.markForCheck();
}
this.router.navigate(['.'], { relativeTo: this.route });
});
}
private openTransferBalanceDialog() {
const dialogRef = this.dialog.open<
GfTransferBalanceDialogComponent,

7
apps/client/src/app/pages/accounts/accounts-page.html

@ -15,7 +15,6 @@
[totalBalanceInBaseCurrency]="totalBalanceInBaseCurrency"
[totalValueInBaseCurrency]="totalValueInBaseCurrency"
(accountDeleted)="onDeleteAccount($event)"
(accountToUpdate)="onUpdateAccount($event)"
(transferBalance)="onTransferBalance()"
/>
</div>
@ -26,6 +25,10 @@
hasPermissionToCreateAccount &&
!user.settings.isRestrictedView
) {
<gf-fab [queryParams]="{ createDialog: true }" />
<gf-fab
[routerLink]="internalRoutes.accounts.subRoutes.create.routerLink"
/>
}
</div>
<router-outlet />

28
apps/client/src/app/pages/accounts/accounts-page.routes.ts

@ -3,11 +3,39 @@ import { internalRoutes } from '@ghostfolio/common/routes/routes';
import { Routes } from '@angular/router';
import { GfAccountDialogHostComponent } from './account-dialog-host/account-dialog-host.component';
import { GfAccountsPageComponent } from './accounts-page.component';
const { create, detail, update } = internalRoutes.accounts.subRoutes;
export const routes: Routes = [
{
canActivate: [AuthGuard],
children: [
{
component: GfAccountDialogHostComponent,
data: { mode: 'create' },
path: create.path,
title: create.title
},
{
children: [
{
component: GfAccountDialogHostComponent,
data: { mode: 'detail' },
path: '',
title: detail.title
},
{
component: GfAccountDialogHostComponent,
data: { mode: 'update' },
path: update.path,
title: update.title
}
],
path: ':accountId'
}
],
component: GfAccountsPageComponent,
path: '',
title: internalRoutes.accounts.title

21
libs/common/src/lib/routes/routes.ts

@ -66,6 +66,27 @@ export const internalRoutes = {
accounts: {
path: 'accounts',
routerLink: ['/accounts'],
subRoutes: {
create: {
path: 'create',
routerLink: ['/accounts', 'create'],
title: $localize`Add Account`
},
detail: {
path: undefined, // Default sub route
routerLink: (aAccountId: string) => {
return ['/accounts', aAccountId];
},
title: $localize`Account`
},
update: {
path: 'update',
routerLink: (aAccountId: string) => {
return ['/accounts', aAccountId, 'update'];
},
title: $localize`Update Account`
}
},
title: $localize`Accounts`
},
api: {

14
libs/ui/src/lib/accounts-table/accounts-table.component.html

@ -307,18 +307,24 @@
<ion-icon name="ellipsis-horizontal" />
</button>
<mat-menu #accountMenu="matMenu" xPosition="before">
<button mat-menu-item (click)="onOpenAccountDetailDialog(element.id)">
<a
mat-menu-item
[routerLink]="accountDialogRouterLinks().get(element.id)?.detail"
>
<span class="align-items-center d-flex">
<ion-icon class="mr-2" name="wallet-outline" />
<span><ng-container i18n>View Details</ng-container>...</span>
</span>
</button>
<button mat-menu-item (click)="onUpdateAccount(element)">
</a>
<a
mat-menu-item
[routerLink]="accountDialogRouterLinks().get(element.id)?.update"
>
<span class="align-items-center d-flex">
<ion-icon class="mr-2" name="create-outline" />
<span><ng-container i18n>Edit</ng-container>...</span>
</span>
</button>
</a>
<hr class="m-0" />
<button
mat-menu-item

26
libs/ui/src/lib/accounts-table/accounts-table.component.stories.ts

@ -5,9 +5,9 @@ import { MatButtonModule } from '@angular/material/button';
import { MatMenuModule } from '@angular/material/menu';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { RouterModule } from '@angular/router';
import { provideRouter, RouterModule } from '@angular/router';
import { IonIcon } from '@ionic/angular/standalone';
import { moduleMetadata } from '@storybook/angular';
import { applicationConfig, moduleMetadata } from '@storybook/angular';
import type { Meta, StoryObj } from '@storybook/angular';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
@ -92,6 +92,9 @@ export default {
title: 'Accounts Table',
component: GfAccountsTableComponent,
decorators: [
applicationConfig({
providers: [provideRouter([])]
}),
moduleMetadata({
imports: [
CommonModule,
@ -147,6 +150,25 @@ export const Default: Story = {
}
};
export const Actions: Story = {
args: {
accounts,
activitiesCount: 12,
baseCurrency: 'USD',
hasPermissionToOpenDetails: true,
locale: 'en-US',
showActions: true,
showActivitiesCount: true,
showAllocationInPercentage: false,
showBalance: true,
showFooter: true,
showValue: true,
showValueInBaseCurrency: true,
totalBalanceInBaseCurrency: 12428.2,
totalValueInBaseCurrency: 107971.70321466809
}
};
export const WithoutFooter: Story = {
args: {
accounts,

30
libs/ui/src/lib/accounts-table/accounts-table.component.ts

@ -4,6 +4,7 @@ import {
getLowercase,
isAccountExcluded
} from '@ghostfolio/common/helper';
import { internalRoutes } from '@ghostfolio/common/routes/routes';
import { AccountWithValue } from '@ghostfolio/common/types';
import { GfEntityLogoComponent } from '@ghostfolio/ui/entity-logo';
import { NotificationService } from '@ghostfolio/ui/notifications';
@ -71,11 +72,28 @@ export class GfAccountsTableComponent {
public readonly totalValueInBaseCurrency = input<number>();
public readonly accountDeleted = output<string>();
public readonly accountToUpdate = output<AccountWithValue>();
public readonly transferBalance = output<void>();
public readonly sort = viewChild.required(MatSort);
protected readonly accountDialogRouterLinks = computed(() => {
const { detail, update } = internalRoutes.accounts.subRoutes;
const routerLinks = new Map<
string,
{ detail: string[]; update: string[] }
>();
for (const { id } of this.accounts() ?? []) {
routerLinks.set(id, {
detail: detail.routerLink(id),
update: update.routerLink(id)
});
}
return routerLinks;
});
protected readonly dataSource = new MatTableDataSource<AccountWithValue>([]);
protected readonly displayedColumns = computed(() => {
@ -159,9 +177,9 @@ export class GfAccountsTableComponent {
protected onOpenAccountDetailDialog(accountId: string) {
if (this.hasPermissionToOpenDetails()) {
this.router.navigate([], {
queryParams: { accountId, accountDetailDialog: true }
});
void this.router.navigate(
internalRoutes.accounts.subRoutes.detail.routerLink(accountId)
);
}
}
@ -174,8 +192,4 @@ export class GfAccountsTableComponent {
protected onTransferBalance() {
this.transferBalance.emit();
}
protected onUpdateAccount(aAccount: AccountWithValue) {
this.accountToUpdate.emit(aAccount);
}
}

9
libs/ui/src/lib/assistant/assistant-list-item/assistant-list-item.component.ts

@ -52,12 +52,11 @@ export class GfAssistantListItemComponent
public ngOnChanges() {
if (this.item?.mode === SearchMode.ACCOUNT) {
this.queryParams = {
accountDetailDialog: true,
accountId: this.item.id
};
this.queryParams = {};
this.routerLink = internalRoutes.accounts.routerLink;
this.routerLink = internalRoutes.accounts.subRoutes.detail.routerLink(
this.item.id
);
} else if (this.item?.mode === SearchMode.ASSET_PROFILE) {
this.queryParams = {
assetProfileDialog: true,

Loading…
Cancel
Save