Skip to content

Open Source Wealth Management Software. Angular + NestJS + Prisma + Nx + TypeScript 🀍

12.9 KB
Raw Blame
import {
  getBackgroundColor,
  getCssVariable,
  isDarkColorScheme
} from '@ghostfolio/common/helper';
import {
  AssetProfileIdentifier,
  InfoItem,
  User
} from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { internalRoutes, publicRoutes } from '@ghostfolio/common/routes/routes';
import { ColorScheme } from '@ghostfolio/common/types';
import { NotificationService } from '@ghostfolio/ui/notifications';
import { DataService } from '@ghostfolio/ui/services';

import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  DestroyRef,
  DOCUMENT,
  HostBinding,
  inject,
  OnInit
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { DateAdapter } from '@angular/material/core';
import { MatDialog } from '@angular/material/dialog';
import { Title } from '@angular/platform-browser';
import {
  ActivatedRoute,
  NavigationEnd,
  PRIMARY_OUTLET,
  Router,
  RouterLink,
  RouterOutlet
} from '@angular/router';
import { Chart } from 'chart.js';
import { addIcons } from 'ionicons';
import { openOutline } from 'ionicons/icons';
import { DeviceDetectorService } from 'ngx-device-detector';
import { distinctUntilChanged, filter, map } from 'rxjs/operators';

import { GfFooterComponent } from './components/footer/footer.component';
import { GfHeaderComponent } from './components/header/header.component';
import { GfHoldingDetailDialogComponent } from './components/holding-detail-dialog/holding-detail-dialog.component';
import { HoldingDetailDialogResult } from './components/holding-detail-dialog/interfaces/interfaces';
import { GfAppQueryParams } from './interfaces/interfaces';
import { ImpersonationStorageService } from './services/impersonation-storage.service';
import { UserService } from './services/user/user.service';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [GfFooterComponent, GfHeaderComponent, RouterLink, RouterOutlet],
  selector: 'gf-root',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html'
})
export class GfAppComponent implements OnInit {
  public canCreateAccount: boolean;
  public currentRoute: string;
  public currentSubRoute: string;
  public deviceType: string;
  public hasInfoMessage: boolean;
  public hasPermissionToChangeDateRange: boolean;
  public hasPermissionToChangeFilters: boolean;
  public hasPromotion = false;
  public hasTabs = false;
  public impersonationId: string | null;
  public info: InfoItem;
  public pageTitle: string;
  public routerLinkRegister = publicRoutes.register.routerLink;
  public showFooter = false;
  public user: User | undefined;

  private readonly changeDetectorRef = inject(ChangeDetectorRef);
  private readonly dataService = inject(DataService);
  private readonly dateAdapter = inject<DateAdapter<Date, string>>(DateAdapter);
  private readonly destroyRef = inject(DestroyRef);
  private readonly deviceDetectorService = inject(DeviceDetectorService);
  private readonly dialog = inject(MatDialog);
  private readonly document = inject(DOCUMENT);
  private readonly impersonationStorageService = inject(
    ImpersonationStorageService
  );
  private readonly notificationService = inject(NotificationService);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly title = inject(Title);
  private readonly userService = inject(UserService);

  public constructor() {
    this.initializeTheme();
    this.user = undefined;

    this.route.queryParams
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(
        ({ dataSource, holdingDetailDialog, symbol }: GfAppQueryParams) => {
          if (dataSource && holdingDetailDialog && symbol) {
            this.openHoldingDetailDialog({
              dataSource,
              symbol
            });
          }
        }
      );

    addIcons({ openOutline });
  }

  @HostBinding('class.has-info-message') get getHasMessage() {
    return this.hasInfoMessage;
  }

  public ngOnInit() {
    this.deviceType = this.deviceDetectorService.getDeviceInfo().deviceType;
    this.info = this.dataService.fetchInfo();

    this.impersonationStorageService
      .onChangeHasImpersonation()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((impersonationId) => {
        this.impersonationId = impersonationId;
      });

    this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe(() => {
        const urlTree = this.router.parseUrl(this.router.url);
        const urlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
        const urlSegments = urlSegmentGroup.segments;
        this.currentRoute = urlSegments[0].path;
        this.currentSubRoute = urlSegments[1]?.path;

        if (
          ((this.currentRoute === internalRoutes.home.path &&
            !this.currentSubRoute) ||
            (this.currentRoute === internalRoutes.home.path &&
              this.currentSubRoute ===
                internalRoutes.home.subRoutes?.holdings.path) ||
            (this.currentRoute === internalRoutes.portfolio.path &&
              !this.currentSubRoute) ||
            (this.currentRoute === internalRoutes.portfolio.path &&
              this.currentSubRoute ===
                internalRoutes.portfolio.subRoutes?.activities.path)) &&
          this.user?.settings?.viewMode !== 'ZEN'
        ) {
          this.hasPermissionToChangeDateRange = true;
        } else {
          this.hasPermissionToChangeDateRange = false;
        }

        if (
          (this.currentRoute === internalRoutes.accounts.path &&
            this.currentSubRoute !==
              internalRoutes.accounts.subRoutes.create.path) ||
          (this.currentRoute === internalRoutes.home.path &&
            this.currentSubRoute ===
              internalRoutes.home.subRoutes?.holdings.path) ||
          (this.currentRoute === internalRoutes.portfolio.path &&
            !this.currentSubRoute) ||
          (this.currentRoute === internalRoutes.portfolio.path &&
            this.currentSubRoute ===
              internalRoutes.portfolio.subRoutes?.activities.path) ||
          (this.currentRoute === internalRoutes.portfolio.path &&
            this.currentSubRoute ===
              internalRoutes.portfolio.subRoutes?.allocations.path) ||
          (this.currentRoute === internalRoutes.zen.path &&
            this.currentSubRoute ===
              internalRoutes.home.subRoutes?.holdings.path)
        ) {
          this.hasPermissionToChangeFilters = true;
        } else {
          this.hasPermissionToChangeFilters = false;
        }

        this.hasTabs =
          (this.currentRoute === publicRoutes.about.path ||
            this.currentRoute === publicRoutes.faq.path ||
            this.currentRoute === publicRoutes.resources.path ||
            this.currentRoute === internalRoutes.account.path ||
            this.currentRoute === internalRoutes.adminControl.path ||
            this.currentRoute === internalRoutes.home.path ||
            this.currentRoute === internalRoutes.portfolio.path ||
            this.currentRoute === internalRoutes.zen.path) &&
          this.deviceType !== 'mobile';

        this.showFooter =
          (this.currentRoute === publicRoutes.blog.path ||
            this.currentRoute === publicRoutes.features.path ||
            this.currentRoute === publicRoutes.markets.path ||
            this.currentRoute === publicRoutes.openStartup.path ||
            this.currentRoute === publicRoutes.public.path ||
            this.currentRoute === publicRoutes.pricing.path ||
            this.currentRoute === publicRoutes.register.path ||
            this.currentRoute === publicRoutes.start.path) &&
          this.deviceType !== 'mobile';

        if (this.deviceType === 'mobile') {
          setTimeout(() => {
            const index = this.title.getTitle().indexOf('–');
            const title =
              index === -1
                ? ''
                : this.title.getTitle().substring(0, index).trim();
            this.pageTitle = title.length <= 15 ? title : 'Ghostfolio';

            this.changeDetectorRef.markForCheck();
          });
        }

        this.changeDetectorRef.markForCheck();
      });

    this.userService.stateChanged
      .pipe(
        map(({ user }) => {
          return user?.settings.locale;
        }),
        distinctUntilChanged(),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe((locale) => {
        if (locale) {
          this.dateAdapter.setLocale(locale);
        }
      });

    this.userService.stateChanged
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((state) => {
        this.user = state.user;

        this.canCreateAccount = hasPermission(
          this.user?.permissions,
          permissions.createUserAccount
        );

        this.hasInfoMessage =
          this.canCreateAccount || !!this.user?.systemMessage;

        this.hasPromotion = this.user
          ? !!this.user.subscription?.offer?.coupon ||
            !!this.user.subscription?.offer?.durationExtension
          : !!this.info?.subscriptionOffer?.coupon ||
            !!this.info?.subscriptionOffer?.durationExtension;

        this.toggleTheme(this.user?.settings.colorScheme);

        this.changeDetectorRef.markForCheck();
      });
  }

  public onClickSystemMessage() {
    const systemMessage = this.user?.systemMessage;

    if (!systemMessage) {
      return;
    }

    if (systemMessage.routerLink) {
      void this.router.navigate(systemMessage.routerLink);
    } else {
      this.notificationService.alert({
        title: systemMessage.message
      });
    }
  }

  public onCreateAccount() {
    this.userService.signOut();
  }

  public onSignOut() {
    this.userService.signOut();

    document.location.href = `/${document.documentElement.lang}`;
  }

  private initializeTheme() {
    this.toggleTheme();

    // Default chart styles
    Chart.defaults.font.family = getCssVariable('--font-family-sans-serif');

    window
      .matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', () => {
        if (!this.user?.settings.colorScheme) {
          this.toggleTheme();
        }
      });
  }

  private openHoldingDetailDialog({
    dataSource,
    symbol
  }: AssetProfileIdentifier) {
    this.userService
      .get()
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((user) => {
        this.user = user;

        const dialogRef = this.dialog.open(GfHoldingDetailDialogComponent, {
          autoFocus: false,
          data: {
            dataSource,
            symbol,
            baseCurrency: this.user?.settings?.baseCurrency,
            colorScheme: this.user?.settings?.colorScheme,
            deviceType: this.deviceType,
            hasPermissionToAccessAdminControl: hasPermission(
              this.user?.permissions,
              permissions.accessAdminControl
            ),
            hasPermissionToCreateActivity:
              !this.impersonationId &&
              hasPermission(
                this.user?.permissions,
                permissions.createActivity
              ) &&
              !this.user?.settings?.isRestrictedView,
            hasPermissionToReportDataGlitch: hasPermission(
              this.user?.permissions,
              permissions.reportDataGlitch
            ),
            hasPermissionToUpdateActivity:
              !this.impersonationId &&
              hasPermission(
                this.user?.permissions,
                permissions.updateActivity
              ) &&
              !this.user?.settings?.isRestrictedView,
            impersonationId: this.impersonationId,
            locale: this.user?.settings?.locale
          },
          height: this.deviceType === 'mobile' ? '98vh' : '80vh',
          width: this.deviceType === 'mobile' ? '100vw' : '50rem'
        });

        dialogRef
          .afterClosed()
          .pipe(takeUntilDestroyed(this.destroyRef))
          .subscribe((result: HoldingDetailDialogResult) => {
            if (result?.isNavigating) {
              return;
            }

            void this.router.navigate([], {
              queryParams: {
                dataSource: null,
                holdingDetailDialog: null,
                symbol: null
              },
              queryParamsHandling: 'merge',
              relativeTo: this.route
            });
          });
      });
  }

  private toggleTheme(userPreferredColorScheme?: ColorScheme) {
    if (isDarkColorScheme(userPreferredColorScheme)) {
      this.document.body.classList.add('theme-dark');
      this.document.body.classList.remove('theme-light');
      this.document.documentElement.setAttribute('data-bs-theme', 'dark');
    } else {
      this.document.body.classList.add('theme-light');
      this.document.body.classList.remove('theme-dark');
      this.document.documentElement.setAttribute('data-bs-theme', 'light');
    }

    this.document
      .querySelector('meta[name="theme-color"]')
      ?.setAttribute('content', getBackgroundColor(userPreferredColorScheme));
  }
}