Skip to content

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

19.5 KB
Raw Blame
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 { MAX_TOP_HOLDINGS, UNKNOWN_KEY } from '@ghostfolio/common/config';
import {
  canOpenHoldingDetail,
  convertValuesToPercentagesOfTotal,
  getAssetProfileIdentifier,
  getCountryName,
  getHoldingName,
  isCashPosition
} from '@ghostfolio/common/helper';
import {
  HoldingWithParents,
  PortfolioDetails,
  PortfolioPosition,
  User
} from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { hasScope, scopes } from '@ghostfolio/common/scopes';
import { MarketAdvanced } from '@ghostfolio/common/types';
import type { Account, Platform } from '@ghostfolio/prisma/browser';
import {
  AssetClass,
  AssetSubClass,
  DataSource
} from '@ghostfolio/prisma/enums';
import { translate } from '@ghostfolio/ui/i18n';
import {
  GfPortfolioProportionChartComponent,
  PortfolioProportionChartClickEvent
} from '@ghostfolio/ui/portfolio-proportion-chart';
import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator';
import { DataService } from '@ghostfolio/ui/services';
import { GfTopHoldingsComponent } from '@ghostfolio/ui/top-holdings';
import { GfValueComponent } from '@ghostfolio/ui/value';
import { GfWorldMapChartComponent } from '@ghostfolio/ui/world-map-chart';

import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  computed,
  DestroyRef,
  inject,
  OnInit
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatCardModule } from '@angular/material/card';
import { MatDialog } from '@angular/material/dialog';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { ActivatedRoute, Router } from '@angular/router';
import { isNumber } from 'lodash-es';
import { DeviceDetectorService } from 'ngx-device-detector';
import { filter, switchMap, tap } from 'rxjs';

import { AllocationsPageParams } from './interfaces/interfaces';

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    GfPortfolioProportionChartComponent,
    GfPremiumIndicatorComponent,
    GfTopHoldingsComponent,
    GfValueComponent,
    GfWorldMapChartComponent,
    MatCardModule,
    MatProgressBarModule
  ],
  selector: 'gf-allocations-page',
  styleUrls: ['./allocations-page.scss'],
  templateUrl: './allocations-page.html'
})
export class GfAllocationsPageComponent implements OnInit {
  protected accounts: {
    [id: string]: Pick<Account, 'name'> & {
      id: string;
      value: number;
    };
  };
  protected continents: {
    [code: string]: { name: string; value: number };
  };
  protected countries: {
    [code: string]: { name: string; value: number };
  };
  protected readonly deviceType = computed(
    () => this.deviceDetectorService.deviceInfo().deviceType
  );
  protected holdings: {
    [assetProfileIdentifier: string]: Pick<
      PortfolioPosition['assetProfile'],
      | 'assetClass'
      | 'assetClassLabel'
      | 'assetSubClass'
      | 'assetSubClassLabel'
      | 'currency'
      | 'name'
    > & { etfProvider: string; value: number };
  };
  protected impersonationId: string | null;
  protected isLoading = false;
  protected markets: PortfolioDetails['markets'];
  protected marketsAdvanced: {
    [key in MarketAdvanced]: {
      id: MarketAdvanced;
      name: string;
      value: number;
    };
  };
  protected platforms: {
    [id: string]: Pick<Platform, 'name'> & {
      id: string;
      value: number;
    };
  };
  protected portfolioDetails: PortfolioDetails;
  protected sectors: {
    [name: string]: { name: string; value: number };
  };
  protected symbols: {
    [symbol: string]: {
      dataSource?: DataSource;
      isClickable?: boolean;
      name: string;
      symbol: string;
      value: number;
    };
  };
  protected topHoldings: HoldingWithParents[] | undefined;
  protected readonly UNKNOWN_KEY = UNKNOWN_KEY;
  protected user: User;

  private readonly changeDetectorRef = inject(ChangeDetectorRef);
  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 constructor() {
    this.route.queryParams
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(
        ({ accountId, accountDetailDialog }: AllocationsPageParams) => {
          if (accountId && accountDetailDialog) {
            this.openAccountDetailDialog(accountId);
          }
        }
      );
  }

  protected get worldMapChartFormat(): string {
    return this.showValuesInPercentage()
      ? '{0}%'
      : `{0} ${this.user?.settings?.baseCurrency}`;
  }

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

        this.changeDetectorRef.markForCheck();
      });

    this.userService.stateChanged
      .pipe(
        filter((state) => !!state?.user),
        tap((state) => {
          this.user = state.user;

          this.isLoading = true;

          this.initialize();

          this.changeDetectorRef.markForCheck();
        }),
        switchMap(() => this.fetchPortfolioDetails()),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe((portfolioDetails) => {
        this.initialize();

        this.portfolioDetails = portfolioDetails;

        this.initializeAllocationsData();

        this.isLoading = false;

        this.changeDetectorRef.markForCheck();
      });

    this.initialize();
  }

  protected onAccountChartClicked(event: PortfolioProportionChartClickEvent) {
    const accountId = 'accountId' in event ? event.accountId : undefined;

    if (accountId && accountId !== UNKNOWN_KEY) {
      void this.router.navigate([], {
        queryParams: { accountId, accountDetailDialog: true }
      });
    }
  }

  protected onSymbolChartClicked(event: PortfolioProportionChartClickEvent) {
    const { dataSource, symbol } = 'symbol' in event ? event : {};

    if (dataSource && symbol) {
      void this.router.navigate([], {
        queryParams: { dataSource, symbol, holdingDetailDialog: true }
      });
    }
  }

  protected showValuesInPercentage() {
    return (
      !hasScope(this.user?.scopes, scopes.portfolioReadValues) ||
      this.user?.settings?.isRestrictedView
    );
  }

  private extractCurrency({
    assetClass,
    assetSubClass,
    currency
  }: {
    assetClass: PortfolioPosition['assetProfile']['assetClass'];
    assetSubClass: PortfolioPosition['assetProfile']['assetSubClass'];
    currency?: PortfolioPosition['assetProfile']['currency'];
  }) {
    if (
      assetClass === AssetClass.COMMODITY ||
      assetSubClass === AssetSubClass.CRYPTOCURRENCY
    ) {
      // Commodities and cryptocurrencies have no meaningful currency exposure
      return UNKNOWN_KEY;
    }

    return currency;
  }

  private extractEtfProvider({
    assetSubClass,
    name
  }: {
    assetSubClass: PortfolioPosition['assetProfile']['assetSubClass'];
    name?: string;
  }) {
    if (assetSubClass === 'ETF' && name) {
      const [firstWord] = name.split(' ');
      return firstWord;
    }

    return UNKNOWN_KEY;
  }

  private extractValue({
    valueInBaseCurrency,
    valueInPercentage
  }: {
    valueInBaseCurrency?: PortfolioPosition['valueInBaseCurrency'];
    valueInPercentage?: PortfolioPosition['valueInPercentage'];
  }) {
    return (
      (isNumber(valueInBaseCurrency)
        ? valueInBaseCurrency
        : valueInPercentage) ?? 0
    );
  }

  private fetchPortfolioDetails() {
    return this.dataService.fetchPortfolioDetails({
      filters: this.userService.getFilters(),
      withMarkets: true
    });
  }

  private initialize() {
    this.accounts = {};
    this.continents = {
      [UNKNOWN_KEY]: {
        name: UNKNOWN_KEY,
        value: 0
      }
    };
    this.countries = {
      [UNKNOWN_KEY]: {
        name: UNKNOWN_KEY,
        value: 0
      }
    };
    this.holdings = {};
    this.marketsAdvanced = {
      [UNKNOWN_KEY]: {
        id: UNKNOWN_KEY,
        name: UNKNOWN_KEY,
        value: 0
      },
      asiaPacific: {
        id: 'asiaPacific',
        name: translate('Asia-Pacific'),
        value: 0
      },
      emergingMarkets: {
        id: 'emergingMarkets',
        name: translate('Emerging Markets'),
        value: 0
      },
      europe: {
        id: 'europe',
        name: translate('Europe'),
        value: 0
      },
      japan: {
        id: 'japan',
        name: translate('Japan'),
        value: 0
      },
      northAmerica: {
        id: 'northAmerica',
        name: translate('North America'),
        value: 0
      },
      otherMarkets: {
        id: 'otherMarkets',
        name: translate('Other Markets'),
        value: 0
      }
    };
    this.platforms = {};
    this.portfolioDetails = {
      accounts: {},
      createdAt: new Date(),
      holdings: [],
      platforms: {},
      summary: undefined
    };
    this.sectors = {
      [UNKNOWN_KEY]: {
        name: UNKNOWN_KEY,
        value: 0
      }
    };
    this.symbols = {
      [UNKNOWN_KEY]: {
        name: UNKNOWN_KEY,
        symbol: UNKNOWN_KEY,
        value: 0
      }
    };
    this.topHoldings = undefined;
  }

  private initializeAllocationsData() {
    for (const [
      id,
      { name, valueInBaseCurrency, valueInPercentage }
    ] of Object.entries(this.portfolioDetails.accounts)) {
      let value = 0;

      if (this.showValuesInPercentage()) {
        value = valueInPercentage ?? 0;
      } else {
        value = valueInBaseCurrency;
      }

      this.accounts[id] = {
        id,
        name,
        value
      };
    }

    const topHoldingsMap: {
      [name: string]: { name: string; value: number };
    } = {};

    let totalValueExcludingCashPositions = 0;
    let totalValueInFunds = 0;

    for (const position of this.portfolioDetails.holdings) {
      const assetProfileIdentifier = getAssetProfileIdentifier(
        position.assetProfile
      );

      this.holdings[assetProfileIdentifier] = {
        assetClass:
          position.assetProfile.assetClass || (UNKNOWN_KEY as AssetClass),
        assetClassLabel: position.assetProfile.assetClassLabel ?? UNKNOWN_KEY,
        assetSubClass:
          position.assetProfile.assetSubClass || (UNKNOWN_KEY as AssetSubClass),
        assetSubClassLabel:
          position.assetProfile.assetSubClassLabel ?? UNKNOWN_KEY,
        currency: this.extractCurrency(position.assetProfile),
        etfProvider: this.extractEtfProvider({
          assetSubClass: position.assetProfile.assetSubClass,
          name: position.assetProfile.name
        }),
        name: position.assetProfile.name,
        value: this.showValuesInPercentage()
          ? position.allocationInPercentage
          : (position.valueInBaseCurrency ?? 0)
      };

      if (!isCashPosition(position.assetProfile)) {
        // Prepare analysis data by continents, countries, holdings and sectors
        // except for cash

        totalValueExcludingCashPositions += this.extractValue(position);

        if (position.assetProfile.countries.length > 0) {
          for (const country of position.assetProfile.countries) {
            const { code, continent, weight } = country;
            const value = this.extractValue(position);

            const continentData = this.continents[continent];

            if (continentData) {
              continentData.value += weight * value;
            } else {
              this.continents[continent] = {
                name: translate(continent),
                value: weight * value
              };
            }

            const countryData = this.countries[code];

            if (countryData) {
              countryData.value += weight * value;
            } else {
              this.countries[code] = {
                name: getCountryName({ code }),
                value: weight * value
              };
            }
          }
        } else {
          const value = this.extractValue(position);

          const continentData = this.continents[UNKNOWN_KEY];

          if (continentData) {
            continentData.value += value;
          }

          const countryData = this.countries[UNKNOWN_KEY];

          if (countryData) {
            countryData.value += value;
          }
        }

        if (position.assetProfile.holdings.length > 0) {
          totalValueInFunds += this.holdings[assetProfileIdentifier].value;

          for (const {
            allocationInPercentage,
            name,
            valueInBaseCurrency
          } of position.assetProfile.holdings) {
            const normalizedAssetName = this.normalizeAssetName(name);
            const value = isNumber(valueInBaseCurrency)
              ? valueInBaseCurrency
              : allocationInPercentage * (position.valueInPercentage ?? 0);

            const holdingData = topHoldingsMap[normalizedAssetName];

            if (holdingData) {
              holdingData.value += value;
            } else {
              topHoldingsMap[normalizedAssetName] = {
                name,
                value
              };
            }
          }
        }

        if (position.assetProfile.sectors.length > 0) {
          for (const sector of position.assetProfile.sectors) {
            const { name, weight } = sector;
            const value = this.extractValue(position);

            const sectorData = this.sectors[name];

            if (sectorData) {
              sectorData.value += weight * value;
            } else {
              this.sectors[name] = {
                name: translate(name),
                value: weight * value
              };
            }
          }
        } else {
          const value = this.extractValue(position);

          const sectorData = this.sectors[UNKNOWN_KEY];

          if (sectorData) {
            sectorData.value += value;
          }
        }
      }

      const symbol = position.assetProfile.symbol;

      const value = this.extractValue(position);

      const symbolData = this.symbols[symbol];

      if (symbolData) {
        // Aggregate holdings with the same symbol from different data sources
        symbolData.dataSource = undefined;
        symbolData.isClickable = false;
        symbolData.value += value;
      } else {
        this.symbols[symbol] = {
          symbol,
          value,
          dataSource: position.assetProfile.dataSource,
          isClickable: canOpenHoldingDetail(position),
          name: getHoldingName(position.assetProfile)
        };
      }
    }

    if (this.showValuesInPercentage()) {
      // The values are percentages of the whole portfolio, but the analysis
      // data does not contain the cash positions
      for (const values of [this.continents, this.countries, this.sectors]) {
        convertValuesToPercentagesOfTotal({
          values,
          total: totalValueExcludingCashPositions
        });
      }
    }

    this.markets = this.portfolioDetails.markets;

    if (this.portfolioDetails.marketsAdvanced) {
      Object.values(this.portfolioDetails.marketsAdvanced).forEach(
        ({ id, valueInBaseCurrency, valueInPercentage }) => {
          this.marketsAdvanced[id].value = isNumber(valueInBaseCurrency)
            ? valueInBaseCurrency
            : valueInPercentage;
        }
      );
    }

    for (const [
      id,
      { name, valueInBaseCurrency, valueInPercentage }
    ] of Object.entries(this.portfolioDetails.platforms)) {
      let value = 0;

      if (this.showValuesInPercentage()) {
        value = valueInPercentage ?? 0;
      } else {
        value = valueInBaseCurrency;
      }

      this.platforms[id] = {
        id,
        name,
        value
      };
    }

    this.topHoldings = Object.values(topHoldingsMap)
      .map(({ name, value }): HoldingWithParents => {
        if (this.showValuesInPercentage()) {
          return {
            name,
            allocationInPercentage: value
          };
        }

        return {
          name,
          allocationInPercentage:
            totalValueInFunds > 0 ? value / totalValueInFunds : 0,
          parents: this.portfolioDetails.holdings
            .map((holding) => {
              if (holding.assetProfile.holdings.length > 0) {
                const currentParentHolding = holding.assetProfile.holdings.find(
                  (parentHolding) => {
                    return (
                      this.normalizeAssetName(parentHolding.name) ===
                      this.normalizeAssetName(name)
                    );
                  }
                );

                return currentParentHolding &&
                  isNumber(currentParentHolding.valueInBaseCurrency)
                  ? {
                      allocationInPercentage:
                        value > 0
                          ? currentParentHolding.valueInBaseCurrency / value
                          : 0,
                      name: holding.assetProfile.name ?? '',
                      position: holding,
                      symbol: holding.assetProfile.symbol,
                      valueInBaseCurrency:
                        currentParentHolding.valueInBaseCurrency
                    }
                  : null;
              }

              return null;
            })
            .filter((item) => {
              return item !== null;
            })
            .sort((a, b) => {
              return b.allocationInPercentage - a.allocationInPercentage;
            }),
          valueInBaseCurrency: value
        };
      })
      .sort((a, b) => {
        return b.allocationInPercentage - a.allocationInPercentage;
      });

    if (this.topHoldings.length > MAX_TOP_HOLDINGS) {
      this.topHoldings = this.topHoldings.slice(0, MAX_TOP_HOLDINGS);
    }
  }

  private normalizeAssetName(name: string) {
    if (!name) {
      return '';
    }

    return name.trim().toLowerCase();
  }

  private openAccountDetailDialog(aAccountId: string) {
    const dialogRef = this.dialog.open<
      GfAccountDetailDialogComponent,
      AccountDetailDialogParams,
      AccountDetailDialogResult
    >(GfAccountDetailDialogComponent, {
      autoFocus: false,
      data: {
        accountId: aAccountId,
        deviceType: this.deviceType(),
        hasPermissionToCreateActivity:
          !this.impersonationId &&
          hasPermission(this.user?.permissions, permissions.createActivity) &&
          !this.user?.settings?.isRestrictedView,
        hasPermissionToUpdateActivity:
          !this.impersonationId &&
          hasPermission(this.user?.permissions, permissions.updateActivity) &&
          !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;
        }

        void this.router.navigate(['.'], { relativeTo: this.route });
      });
  }
}