Browse Source

Merge commit 'f14f98f766d70dd6c9b5e2c13cf0d67ab927a33a' into feature/oidc-user-link

pull/6075/head
Germán Martín 4 weeks ago
parent
commit
8d841f49e5
  1. 12
      .vscode/launch.json
  2. 30
      CHANGELOG.md
  3. 6
      DEVELOPMENT.md
  4. 11
      apps/api/src/app/account/account.controller.ts
  5. 4
      apps/api/src/app/account/account.module.ts
  6. 36
      apps/api/src/app/admin/admin.service.ts
  7. 18
      apps/api/src/app/auth/auth.module.ts
  8. 2
      apps/api/src/app/endpoints/data-providers/ghostfolio/ghostfolio.module.ts
  9. 3
      apps/api/src/app/endpoints/data-providers/ghostfolio/ghostfolio.service.ts
  10. 4
      apps/api/src/app/endpoints/market-data/market-data.controller.ts
  11. 2
      apps/api/src/app/logo/logo.module.ts
  12. 22
      apps/api/src/app/logo/logo.service.ts
  13. 55
      apps/api/src/app/portfolio/portfolio.controller.ts
  14. 272
      apps/api/src/app/portfolio/portfolio.service.spec.ts
  15. 41
      apps/api/src/app/portfolio/portfolio.service.ts
  16. 31
      apps/api/src/app/user/user.service.ts
  17. 4
      apps/api/src/main.ts
  18. 52
      apps/api/src/services/data-provider/coingecko/coingecko.service.ts
  19. 3
      apps/api/src/services/data-provider/data-enhancer/data-enhancer.module.ts
  20. 13
      apps/api/src/services/data-provider/data-enhancer/openfigi/openfigi.service.ts
  21. 46
      apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.ts
  22. 2
      apps/api/src/services/data-provider/data-provider.module.ts
  23. 43
      apps/api/src/services/data-provider/eod-historical-data/eod-historical-data.service.ts
  24. 175
      apps/api/src/services/data-provider/financial-modeling-prep/financial-modeling-prep.service.ts
  25. 12
      apps/api/src/services/data-provider/ghostfolio/ghostfolio.service.ts
  26. 4
      apps/api/src/services/data-provider/manual/manual.service.ts
  27. 13
      apps/api/src/services/data-provider/rapid-api/rapid-api.service.ts
  28. 11
      apps/api/src/services/fetch/fetch.module.ts
  29. 205
      apps/api/src/services/fetch/fetch.service.ts
  30. 19
      apps/api/src/services/fetch/interfaces/web-fetch-route.interface.ts
  31. 2
      apps/api/src/services/queues/statistics-gathering/statistics-gathering.module.ts
  32. 66
      apps/api/src/services/queues/statistics-gathering/statistics-gathering.processor.ts
  33. 10
      apps/client/src/app/components/admin-market-data/admin-market-data.component.ts
  34. 16
      apps/client/src/app/components/admin-market-data/admin-market-data.html
  35. 30
      apps/client/src/app/components/admin-market-data/admin-market-data.service.ts
  36. 2
      apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.component.ts
  37. 2
      apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.html
  38. 10
      apps/client/src/app/components/home-watchlist/home-watchlist.component.ts
  39. 12
      apps/client/src/app/components/home-watchlist/home-watchlist.html
  40. 35
      apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.component.ts
  41. 2
      apps/client/src/app/components/user-account-access/create-or-update-access-dialog/interfaces/interfaces.ts
  42. 96
      apps/client/src/app/components/user-account-access/user-account-access.component.ts
  43. 12
      apps/client/src/app/components/user-account-access/user-account-access.html
  44. 12
      apps/client/src/app/core/auth.guard.ts
  45. 16
      apps/client/src/app/core/auth.interceptor.ts
  46. 45
      apps/client/src/app/core/http-response.interceptor.ts
  47. 24
      apps/client/src/app/directives/file-drop/file-drop.directive.ts
  48. 10
      apps/client/src/app/pages/accounts/accounts-page.component.ts
  49. 12
      apps/client/src/app/pages/accounts/accounts-page.html
  50. 11
      apps/client/src/app/pages/portfolio/activities/activities-page.component.ts
  51. 12
      apps/client/src/app/pages/portfolio/activities/activities-page.html
  52. 2
      apps/client/src/app/pages/portfolio/activities/create-or-update-activity-dialog/create-or-update-activity-dialog.component.ts
  53. 3
      apps/client/src/app/pages/portfolio/activities/import-activities-dialog/import-activities-dialog.component.ts
  54. 50
      apps/client/src/app/pages/portfolio/allocations/allocations-page.component.ts
  55. 153
      apps/client/src/app/pages/portfolio/analysis/analysis-page.component.ts
  56. 24
      apps/client/src/app/pages/portfolio/analysis/analysis-page.html
  57. 5
      apps/client/src/app/pages/public/public-page.component.ts
  58. 7
      apps/client/src/assets/oss-friends.json
  59. 11
      apps/client/src/styles.scss
  60. 1
      libs/common/src/lib/config.ts
  61. 30
      libs/common/src/lib/helper.ts
  62. 47
      libs/common/src/lib/interfaces/portfolio-position.interface.ts
  63. 41
      libs/ui/src/lib/assistant/assistant.component.ts
  64. 9
      libs/ui/src/lib/fab/fab.component.html
  65. 14
      libs/ui/src/lib/fab/fab.component.scss
  66. 21
      libs/ui/src/lib/fab/fab.component.ts
  67. 1
      libs/ui/src/lib/fab/index.ts
  68. 200
      libs/ui/src/lib/mocks/holdings.ts
  69. 6
      libs/ui/src/lib/page-tabs/page-tabs.component.scss
  70. 9
      libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.html
  71. 3
      libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.ts
  72. 10
      libs/ui/src/lib/services/data.service.ts
  73. 745
      package-lock.json
  74. 39
      package.json
  75. 4
      tools/load-env.ts

12
.vscode/launch.json

@ -18,12 +18,20 @@
"autoAttachChildProcesses": true, "autoAttachChildProcesses": true,
"console": "integratedTerminal", "console": "integratedTerminal",
"cwd": "${workspaceFolder}/apps/api", "cwd": "${workspaceFolder}/apps/api",
"envFile": "${workspaceFolder}/.env", "env": {
"GHOSTFOLIO_ENV_FILE": "${workspaceFolder}/.env"
},
"name": "Debug API", "name": "Debug API",
"outFiles": ["${workspaceFolder}/dist/apps/api/**/*.js"], "outFiles": ["${workspaceFolder}/dist/apps/api/**/*.js"],
"program": "${workspaceFolder}/apps/api/src/main.ts", "program": "${workspaceFolder}/apps/api/src/main.ts",
"request": "launch", "request": "launch",
"runtimeArgs": ["--nolazy", "-r", "ts-node/register"], "runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register",
"-r",
"${workspaceFolder}/tools/load-env.ts"
],
"skipFiles": [ "skipFiles": [
"${workspaceFolder}/node_modules/**/*.js", "${workspaceFolder}/node_modules/**/*.js",
"<node_internals>/**/*.js" "<node_internals>/**/*.js"

30
CHANGELOG.md

@ -5,6 +5,36 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 3.7.0 - 2026-06-02
### Added
- Added support for routing selected requests through the _OpenRouter_ `web_fetch` tool in the `FetchService`
### Changed
- Extended the countries mapping in the data enhancer for asset profile data via _Trackinsight_
- Removed the deprecated attributes (`assetClass`, `assetClassLabel`, `assetSubClass`, `assetSubClassLabel`, `countries`, `currency`, `dataSource`, `holdings`, `name`, `sectors`, `symbol` and `url`) from the holdings of the portfolio details endpoint response
- Upgraded `Nx` from version `22.7.2` to `22.7.5`
### Fixed
- Resolved an issue in the impersonation mode where the values did not match the owner’s currency
- Fixed the environment variable expansion in the `.env` file when debugging via _Visual Studio Code_
## 3.6.0 - 2026-05-28
### Added
- Added `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` environment variable support to outbound HTTP requests
- Added the `FetchService` to centralize outbound HTTP requests
### Changed
- Extracted the floating action buttons (FAB) to a reusable component
- Upgraded `nestjs` from version `11.1.19` to `11.1.21`
- Upgraded `yahoo-finance2` from version `3.14.0` to `3.14.2`
## 3.5.0 - 2026-05-24 ## 3.5.0 - 2026-05-24
### Added ### Added

6
DEVELOPMENT.md

@ -84,6 +84,12 @@ https://ghostfol.io/development/storybook
1. Run `npx npm-check-updates --upgrade --target "minor" --filter "/@angular.*/"` 1. Run `npx npm-check-updates --upgrade --target "minor" --filter "/@angular.*/"`
### NestJS
#### Upgrade (minor versions)
1. Run `npx npm-check-updates --upgrade --target "minor" --filter "/@nestjs.*/"`
### Nx ### Nx
#### Upgrade #### Upgrade

11
apps/api/src/app/account/account.controller.ts

@ -1,5 +1,6 @@
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service'; import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service';
import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service'; import { PortfolioService } from '@ghostfolio/api/app/portfolio/portfolio.service';
import { UserService } from '@ghostfolio/api/app/user/user.service';
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator';
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard';
import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor'; import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor';
@ -50,7 +51,8 @@ export class AccountController {
private readonly apiService: ApiService, private readonly apiService: ApiService,
private readonly impersonationService: ImpersonationService, private readonly impersonationService: ImpersonationService,
private readonly portfolioService: PortfolioService, private readonly portfolioService: PortfolioService,
@Inject(REQUEST) private readonly request: RequestWithUser @Inject(REQUEST) private readonly request: RequestWithUser,
private readonly userService: UserService
) {} ) {}
@Delete(':id') @Delete(':id')
@ -137,11 +139,14 @@ export class AccountController {
): Promise<AccountBalancesResponse> { ): Promise<AccountBalancesResponse> {
const impersonationUserId = const impersonationUserId =
await this.impersonationService.validateImpersonationId(impersonationId); await this.impersonationService.validateImpersonationId(impersonationId);
const userId = impersonationUserId || this.request.user.id;
const { settings } = await this.userService.user({ id: userId });
return this.accountBalanceService.getAccountBalances({ return this.accountBalanceService.getAccountBalances({
userId,
filters: [{ id, type: 'ACCOUNT' }], filters: [{ id, type: 'ACCOUNT' }],
userCurrency: this.request.user.settings.settings.baseCurrency, userCurrency: settings.settings.baseCurrency
userId: impersonationUserId || this.request.user.id
}); });
} }

4
apps/api/src/app/account/account.module.ts

@ -1,5 +1,6 @@
import { AccountBalanceModule } from '@ghostfolio/api/app/account-balance/account-balance.module'; import { AccountBalanceModule } from '@ghostfolio/api/app/account-balance/account-balance.module';
import { PortfolioModule } from '@ghostfolio/api/app/portfolio/portfolio.module'; import { PortfolioModule } from '@ghostfolio/api/app/portfolio/portfolio.module';
import { UserModule } from '@ghostfolio/api/app/user/user.module';
import { RedactValuesInResponseModule } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.module'; import { RedactValuesInResponseModule } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.module';
import { ApiModule } from '@ghostfolio/api/services/api/api.module'; import { ApiModule } from '@ghostfolio/api/services/api/api.module';
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module';
@ -23,7 +24,8 @@ import { AccountService } from './account.service';
ImpersonationModule, ImpersonationModule,
PortfolioModule, PortfolioModule,
PrismaModule, PrismaModule,
RedactValuesInResponseModule RedactValuesInResponseModule,
UserModule
], ],
providers: [AccountService] providers: [AccountService]
}) })

36
apps/api/src/app/admin/admin.service.ts

@ -576,8 +576,8 @@ export class AdminService {
} }
try { try {
Promise.all([ await Promise.all([
await this.symbolProfileService.updateAssetProfileIdentifier( this.symbolProfileService.updateAssetProfileIdentifier(
{ {
dataSource, dataSource,
symbol symbol
@ -587,7 +587,7 @@ export class AdminService {
symbol: newSymbol as string symbol: newSymbol as string
} }
), ),
await this.marketDataService.updateAssetProfileIdentifier( this.marketDataService.updateAssetProfileIdentifier(
{ {
dataSource, dataSource,
symbol symbol
@ -599,12 +599,15 @@ export class AdminService {
) )
]); ]);
return this.symbolProfileService.getSymbolProfiles([ const [updatedAssetProfile] =
{ await this.symbolProfileService.getSymbolProfiles([
dataSource: DataSource[newDataSource.toString()], {
symbol: newSymbol as string dataSource: DataSource[newDataSource.toString()],
} symbol: newSymbol as string
])?.[0]; }
]);
return updatedAssetProfile;
} catch { } catch {
throw new HttpException( throw new HttpException(
getReasonPhrase(StatusCodes.BAD_REQUEST), getReasonPhrase(StatusCodes.BAD_REQUEST),
@ -650,12 +653,15 @@ export class AdminService {
updatedSymbolProfile updatedSymbolProfile
); );
return this.symbolProfileService.getSymbolProfiles([ const [updatedAssetProfile] =
{ await this.symbolProfileService.getSymbolProfiles([
dataSource: dataSource as DataSource, {
symbol: symbol as string dataSource: dataSource as DataSource,
} symbol: symbol as string
])?.[0]; }
]);
return updatedAssetProfile;
} }
} }

18
apps/api/src/app/auth/auth.module.ts

@ -5,6 +5,8 @@ import { UserModule } from '@ghostfolio/api/app/user/user.module';
import { ApiKeyService } from '@ghostfolio/api/services/api-key/api-key.service'; import { ApiKeyService } from '@ghostfolio/api/services/api-key/api-key.service';
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module';
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; import { PropertyModule } from '@ghostfolio/api/services/property/property.module';
@ -24,6 +26,7 @@ import { OidcStrategy } from './oidc.strategy';
controllers: [AuthController], controllers: [AuthController],
imports: [ imports: [
ConfigurationModule, ConfigurationModule,
FetchModule,
JwtModule.register({ JwtModule.register({
secret: process.env.JWT_SECRET_KEY, secret: process.env.JWT_SECRET_KEY,
signOptions: { expiresIn: '180 days' } signOptions: { expiresIn: '180 days' }
@ -42,13 +45,20 @@ import { OidcStrategy } from './oidc.strategy';
JwtStrategy, JwtStrategy,
OidcStateStore, OidcStateStore,
{ {
inject: [AuthService, JwtService, OidcStateStore, ConfigurationService], inject: [
AuthService,
ConfigurationService,
FetchService,
JwtService,
OidcStateStore
],
provide: OidcStrategy, provide: OidcStrategy,
useFactory: async ( useFactory: async (
authService: AuthService, authService: AuthService,
configurationService: ConfigurationService,
fetchService: FetchService,
jwtService: JwtService, jwtService: JwtService,
stateStore: OidcStateStore, stateStore: OidcStateStore
configurationService: ConfigurationService
) => { ) => {
const isOidcEnabled = configurationService.get( const isOidcEnabled = configurationService.get(
'ENABLE_FEATURE_AUTH_OIDC' 'ENABLE_FEATURE_AUTH_OIDC'
@ -83,7 +93,7 @@ import { OidcStrategy } from './oidc.strategy';
userInfoURL = manualUserInfoUrl; userInfoURL = manualUserInfoUrl;
} else { } else {
try { try {
const response = await fetch( const response = await fetchService.fetch(
`${issuer}/.well-known/openid-configuration` `${issuer}/.well-known/openid-configuration`
); );

2
apps/api/src/app/endpoints/data-providers/ghostfolio/ghostfolio.module.ts

@ -12,6 +12,7 @@ import { GoogleSheetsService } from '@ghostfolio/api/services/data-provider/goog
import { ManualService } from '@ghostfolio/api/services/data-provider/manual/manual.service'; import { ManualService } from '@ghostfolio/api/services/data-provider/manual/manual.service';
import { RapidApiService } from '@ghostfolio/api/services/data-provider/rapid-api/rapid-api.service'; import { RapidApiService } from '@ghostfolio/api/services/data-provider/rapid-api/rapid-api.service';
import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service'; import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service';
import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module';
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module';
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module';
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; import { PropertyModule } from '@ghostfolio/api/services/property/property.module';
@ -27,6 +28,7 @@ import { GhostfolioService } from './ghostfolio.service';
imports: [ imports: [
CryptocurrencyModule, CryptocurrencyModule,
DataProviderModule, DataProviderModule,
FetchModule,
MarketDataModule, MarketDataModule,
PrismaModule, PrismaModule,
PropertyModule, PropertyModule,

3
apps/api/src/app/endpoints/data-providers/ghostfolio/ghostfolio.service.ts

@ -8,6 +8,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; import { PropertyService } from '@ghostfolio/api/services/property/property.service';
import { import {
@ -36,6 +37,7 @@ export class GhostfolioService {
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly dataProviderService: DataProviderService, private readonly dataProviderService: DataProviderService,
private readonly fetchService: FetchService,
private readonly prismaService: PrismaService, private readonly prismaService: PrismaService,
private readonly propertyService: PropertyService private readonly propertyService: PropertyService
) {} ) {}
@ -355,6 +357,7 @@ export class GhostfolioService {
private getDataProviderInfo(): DataProviderInfo { private getDataProviderInfo(): DataProviderInfo {
const ghostfolioDataProviderService = new GhostfolioDataProviderService( const ghostfolioDataProviderService = new GhostfolioDataProviderService(
this.configurationService, this.configurationService,
this.fetchService,
this.propertyService this.propertyService
); );

4
apps/api/src/app/endpoints/market-data/market-data.controller.ts

@ -120,10 +120,10 @@ export class MarketDataController {
if (!canReadAllAssetProfiles && !canReadOwnAssetProfile) { if (!canReadAllAssetProfiles && !canReadOwnAssetProfile) {
throw new HttpException( throw new HttpException(
assetProfile.userId assetProfile?.userId
? getReasonPhrase(StatusCodes.NOT_FOUND) ? getReasonPhrase(StatusCodes.NOT_FOUND)
: getReasonPhrase(StatusCodes.FORBIDDEN), : getReasonPhrase(StatusCodes.FORBIDDEN),
assetProfile.userId ? StatusCodes.NOT_FOUND : StatusCodes.FORBIDDEN assetProfile?.userId ? StatusCodes.NOT_FOUND : StatusCodes.FORBIDDEN
); );
} }

2
apps/api/src/app/logo/logo.module.ts

@ -1,5 +1,6 @@
import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module'; import { TransformDataSourceInRequestModule } from '@ghostfolio/api/interceptors/transform-data-source-in-request/transform-data-source-in-request.module';
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module';
import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module';
import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
@ -11,6 +12,7 @@ import { LogoService } from './logo.service';
controllers: [LogoController], controllers: [LogoController],
imports: [ imports: [
ConfigurationModule, ConfigurationModule,
FetchModule,
SymbolProfileModule, SymbolProfileModule,
TransformDataSourceInRequestModule TransformDataSourceInRequestModule
], ],

22
apps/api/src/app/logo/logo.service.ts

@ -1,4 +1,5 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces'; import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces';
@ -10,6 +11,7 @@ import { StatusCodes, getReasonPhrase } from 'http-status-codes';
export class LogoService { export class LogoService {
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService,
private readonly symbolProfileService: SymbolProfileService private readonly symbolProfileService: SymbolProfileService
) {} ) {}
@ -43,15 +45,17 @@ export class LogoService {
} }
private async getBuffer(aUrl: string) { private async getBuffer(aUrl: string) {
const blob = await fetch( const blob = await this.fetchService
`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${aUrl}&size=64`, .fetch(
{ `https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${aUrl}&size=64`,
headers: { 'User-Agent': 'request' }, {
signal: AbortSignal.timeout( headers: { 'User-Agent': 'request' },
this.configurationService.get('REQUEST_TIMEOUT') signal: AbortSignal.timeout(
) this.configurationService.get('REQUEST_TIMEOUT')
} )
).then((res) => res.blob()); }
)
.then((res) => res.blob());
return { return {
buffer: await blob.arrayBuffer().then((arrayBuffer) => { buffer: await blob.arrayBuffer().then((arrayBuffer) => {

55
apps/api/src/app/portfolio/portfolio.controller.ts

@ -1,4 +1,5 @@
import { ActivitiesService } from '@ghostfolio/api/app/activities/activities.service'; import { ActivitiesService } from '@ghostfolio/api/app/activities/activities.service';
import { UserService } from '@ghostfolio/api/app/user/user.service';
import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator';
import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard';
import { import {
@ -70,7 +71,8 @@ export class PortfolioController {
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly impersonationService: ImpersonationService, private readonly impersonationService: ImpersonationService,
private readonly portfolioService: PortfolioService, private readonly portfolioService: PortfolioService,
@Inject(REQUEST) private readonly request: RequestWithUser @Inject(REQUEST) private readonly request: RequestWithUser,
private readonly userService: UserService
) {} ) {}
@Get('details') @Get('details')
@ -144,10 +146,10 @@ export class PortfolioController {
.reduce((a, b) => a + b, 0); .reduce((a, b) => a + b, 0);
const totalValue = Object.values(holdings) const totalValue = Object.values(holdings)
.filter(({ assetClass, assetSubClass }) => { .filter(({ assetProfile }) => {
return ( return (
assetClass !== AssetClass.LIQUIDITY && assetProfile.assetClass !== AssetClass.LIQUIDITY &&
assetSubClass !== AssetSubClass.CASH assetProfile.assetSubClass !== AssetSubClass.CASH
); );
}) })
.map(({ valueInBaseCurrency }) => { .map(({ valueInBaseCurrency }) => {
@ -217,37 +219,41 @@ export class PortfolioController {
for (const [symbol, portfolioPosition] of Object.entries(holdings)) { for (const [symbol, portfolioPosition] of Object.entries(holdings)) {
holdings[symbol] = { holdings[symbol] = {
...portfolioPosition, ...portfolioPosition,
assetClass:
hasDetails || portfolioPosition.assetClass === AssetClass.LIQUIDITY
? portfolioPosition.assetClass
: undefined,
assetProfile: { assetProfile: {
...portfolioPosition.assetProfile, ...portfolioPosition.assetProfile,
assetClass:
hasDetails ||
portfolioPosition.assetProfile.assetClass === AssetClass.LIQUIDITY
? portfolioPosition.assetProfile.assetClass
: undefined,
assetClassLabel:
hasDetails ||
portfolioPosition.assetProfile.assetClass === AssetClass.LIQUIDITY
? portfolioPosition.assetProfile.assetClassLabel
: undefined,
assetSubClass:
hasDetails ||
portfolioPosition.assetProfile.assetSubClass === AssetSubClass.CASH
? portfolioPosition.assetProfile.assetSubClass
: undefined,
assetSubClassLabel:
hasDetails ||
portfolioPosition.assetProfile.assetSubClass === AssetSubClass.CASH
? portfolioPosition.assetProfile.assetSubClassLabel
: undefined,
...(hasDetails ...(hasDetails
? {} ? {}
: { : {
assetClass: undefined,
assetClassLabel: undefined,
assetSubClass: undefined,
assetSubClassLabel: undefined,
countries: [], countries: [],
currency: undefined, currency: undefined,
holdings: [], holdings: [],
sectors: [] sectors: []
}) })
}, },
assetSubClass:
hasDetails || portfolioPosition.assetSubClass === AssetSubClass.CASH
? portfolioPosition.assetSubClass
: undefined,
countries: hasDetails ? portfolioPosition.countries : [],
currency: hasDetails ? portfolioPosition.currency : undefined,
holdings: hasDetails ? portfolioPosition.holdings : [],
markets: hasDetails ? portfolioPosition.markets : undefined, markets: hasDetails ? portfolioPosition.markets : undefined,
marketsAdvanced: hasDetails marketsAdvanced: hasDetails
? portfolioPosition.marketsAdvanced ? portfolioPosition.marketsAdvanced
: undefined, : undefined
sectors: hasDetails ? portfolioPosition.sectors : []
}; };
} }
@ -336,7 +342,10 @@ export class PortfolioController {
const impersonationUserId = const impersonationUserId =
await this.impersonationService.validateImpersonationId(impersonationId); await this.impersonationService.validateImpersonationId(impersonationId);
const userCurrency = this.request.user.settings.settings.baseCurrency; const userId = impersonationUserId || this.request.user.id;
const { settings } = await this.userService.user({ id: userId });
const userCurrency = settings.settings.baseCurrency;
const { endDate, startDate } = getIntervalFromDateRange({ dateRange }); const { endDate, startDate } = getIntervalFromDateRange({ dateRange });
@ -345,7 +354,7 @@ export class PortfolioController {
filters, filters,
startDate, startDate,
userCurrency, userCurrency,
userId: impersonationUserId || this.request.user.id, userId,
types: ['DIVIDEND'] types: ['DIVIDEND']
}); });

272
apps/api/src/app/portfolio/portfolio.service.spec.ts

@ -0,0 +1,272 @@
import { AccountService } from '@ghostfolio/api/app/account/account.service';
import { CashDetails } from '@ghostfolio/api/app/account/interfaces/cash-details.interface';
import { ActivitiesService } from '@ghostfolio/api/app/activities/activities.service';
import { userDummyData } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils';
import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory';
import { UserService } from '@ghostfolio/api/app/user/user.service';
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation/impersonation.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { parseDate } from '@ghostfolio/common/helper';
import { Account, DataSource } from '@prisma/client';
import { Big } from 'big.js';
import { randomUUID } from 'node:crypto';
import { PortfolioService } from './portfolio.service';
describe('PortfolioService', () => {
let accountService: AccountService;
let activitiesService: ActivitiesService;
let configurationService: ConfigurationService;
let dataProviderService: DataProviderService;
let exchangeRateDataService: ExchangeRateDataService;
let impersonationService: ImpersonationService;
let portfolioCalculatorFactory: PortfolioCalculatorFactory;
let portfolioService: PortfolioService;
let symbolProfileService: SymbolProfileService;
let userService: UserService;
beforeEach(() => {
configurationService = new ConfigurationService();
dataProviderService = new DataProviderService(
configurationService,
null,
null,
null,
null,
null
);
exchangeRateDataService = new ExchangeRateDataService(
null,
null,
null,
null
);
accountService = new AccountService(
null,
null,
exchangeRateDataService,
null
);
activitiesService = new ActivitiesService(
null,
accountService,
null,
dataProviderService,
null,
exchangeRateDataService,
null,
null
);
impersonationService = new ImpersonationService(null, null);
portfolioCalculatorFactory = new PortfolioCalculatorFactory(
configurationService,
null,
exchangeRateDataService,
null,
null
);
symbolProfileService = new SymbolProfileService(null);
userService = new UserService(
null,
null,
null,
null,
null,
null,
null,
null
);
portfolioService = new PortfolioService(
null,
accountService,
activitiesService,
null,
portfolioCalculatorFactory,
dataProviderService,
exchangeRateDataService,
null,
impersonationService,
null,
null,
symbolProfileService,
userService
);
});
describe('getCashSymbolProfiles', () => {
it('should use the exchange-rate data source so the symbol-profile join in getDetails matches the calculator positions', () => {
jest
.spyOn(dataProviderService, 'getDataSourceForExchangeRates')
.mockReturnValue(DataSource.YAHOO);
const cashDetails: CashDetails = {
accounts: [
{
balance: 2000,
comment: null,
createdAt: parseDate('2024-01-01'),
currency: 'USD',
id: randomUUID(),
isExcluded: false,
name: 'USD',
platformId: null,
updatedAt: parseDate('2024-01-01'),
userId: userDummyData.id
}
],
balanceInBaseCurrency: 1820
};
const assetProfiles = (
portfolioService as unknown as {
getCashSymbolProfiles: (
aCashDetails: CashDetails
) => { dataSource: DataSource; symbol: string }[];
}
).getCashSymbolProfiles(cashDetails);
expect(assetProfiles).toHaveLength(1);
expect(assetProfiles[0].dataSource).toBe(DataSource.YAHOO);
expect(assetProfiles[0].symbol).toBe('USD');
});
});
describe('getDetails', () => {
it('should return cash holdings when the calculator emits cash positions with the exchange-rate data source', async () => {
const accountId = randomUUID();
const cashAccount: Account = {
balance: 2000,
comment: null,
createdAt: parseDate('2024-01-01'),
currency: 'USD',
id: accountId,
isExcluded: false,
name: 'USD',
platformId: null,
updatedAt: parseDate('2024-01-01'),
userId: userDummyData.id
};
jest.spyOn(accountService, 'getCashDetails').mockResolvedValue({
accounts: [cashAccount],
balanceInBaseCurrency: 1820
});
jest
.spyOn(activitiesService, 'getActivitiesForPortfolioCalculator')
.mockResolvedValue({ activities: [], count: 0 });
jest
.spyOn(dataProviderService, 'getDataSourceForExchangeRates')
.mockReturnValue(DataSource.YAHOO);
jest
.spyOn(impersonationService, 'validateImpersonationId')
.mockResolvedValue(null);
jest
.spyOn(symbolProfileService, 'getSymbolProfiles')
.mockResolvedValue([]);
jest.spyOn(userService, 'user').mockResolvedValue({
accessesGet: [],
accounts: [],
activityCount: 0,
dataProviderGhostfolioDailyRequests: 0,
id: userDummyData.id,
settings: {
settings: {
baseCurrency: 'CHF'
}
}
} as unknown as Awaited<ReturnType<typeof userService.user>>);
const usdPosition = {
activitiesCount: 1,
averagePrice: new Big(1),
currency: 'USD',
dataSource: DataSource.YAHOO,
dateOfFirstActivity: '2024-01-01',
dividend: new Big(0),
dividendInBaseCurrency: new Big(0),
fee: new Big(0),
feeInBaseCurrency: new Big(0),
grossPerformance: new Big(0),
grossPerformancePercentage: new Big(0),
grossPerformancePercentageWithCurrencyEffect: new Big(0),
grossPerformanceWithCurrencyEffect: new Big(0),
investment: new Big(1820),
investmentWithCurrencyEffect: new Big(1820),
marketPrice: 1,
marketPriceInBaseCurrency: 0.91,
netPerformance: new Big(0),
netPerformancePercentage: new Big(0),
netPerformancePercentageWithCurrencyEffectMap: {},
netPerformanceWithCurrencyEffectMap: {},
quantity: new Big(2000),
symbol: 'USD',
tags: [],
timeWeightedInvestment: new Big(0),
timeWeightedInvestmentWithCurrencyEffect: new Big(0),
valueInBaseCurrency: new Big(1820)
};
jest
.spyOn(portfolioCalculatorFactory, 'createCalculator')
.mockReturnValue({
getSnapshot: jest.fn().mockResolvedValue({
activitiesCount: 1,
createdAt: parseDate('2024-01-01'),
currentValueInBaseCurrency: new Big(1820),
errors: [],
hasErrors: false,
historicalData: [],
positions: [usdPosition],
totalFeesWithCurrencyEffect: new Big(0),
totalInterestWithCurrencyEffect: new Big(0),
totalInvestment: new Big(1820),
totalInvestmentWithCurrencyEffect: new Big(1820),
totalLiabilitiesWithCurrencyEffect: new Big(0)
})
} as unknown as ReturnType<
typeof portfolioCalculatorFactory.createCalculator
>);
jest
.spyOn(
portfolioService as unknown as {
getValueOfAccountsAndPlatforms: () => Promise<{
accounts: object;
platforms: object;
}>;
},
'getValueOfAccountsAndPlatforms'
)
.mockResolvedValue({ accounts: {}, platforms: {} });
const { holdings } = await portfolioService.getDetails({
filters: [],
impersonationId: userDummyData.id,
userId: userDummyData.id
});
expect(holdings['USD']).toBeDefined();
expect(holdings['USD'].assetProfile.dataSource).toBe(DataSource.YAHOO);
expect(holdings['USD'].assetProfile.symbol).toBe('USD');
});
});
});

41
apps/api/src/app/portfolio/portfolio.service.ts

@ -164,7 +164,7 @@ export class PortfolioService {
}; };
} }
const [accounts, details] = await Promise.all([ const [accounts, details, user] = await Promise.all([
this.accountService.accounts({ this.accountService.accounts({
where, where,
include: { include: {
@ -178,10 +178,11 @@ export class PortfolioService {
withExcludedAccounts, withExcludedAccounts,
impersonationId: userId, impersonationId: userId,
userId: this.request.user.id userId: this.request.user.id
}) }),
this.userService.user({ id: userId })
]); ]);
const userCurrency = this.request.user.settings.settings.baseCurrency; const userCurrency = this.getUserCurrency(user);
return Promise.all( return Promise.all(
accounts.map(async (account) => { accounts.map(async (account) => {
@ -584,7 +585,6 @@ export class PortfolioService {
for (const { for (const {
activitiesCount, activitiesCount,
currency,
dataSource, dataSource,
dateOfFirstActivity, dateOfFirstActivity,
dividend, dividend,
@ -638,16 +638,13 @@ export class PortfolioService {
holdings[symbol] = { holdings[symbol] = {
activitiesCount, activitiesCount,
currency,
markets, markets,
marketsAdvanced, marketsAdvanced,
marketPrice, marketPrice,
symbol,
tags, tags,
allocationInPercentage: filteredValueInBaseCurrency.eq(0) allocationInPercentage: filteredValueInBaseCurrency.eq(0)
? 0 ? 0
: valueInBaseCurrency.div(filteredValueInBaseCurrency).toNumber(), : valueInBaseCurrency.div(filteredValueInBaseCurrency).toNumber(),
assetClass: assetProfile.assetClass,
assetProfile: { assetProfile: {
assetClass: assetProfile.assetClass, assetClass: assetProfile.assetClass,
assetSubClass: assetProfile.assetSubClass, assetSubClass: assetProfile.assetSubClass,
@ -670,9 +667,6 @@ export class PortfolioService {
symbol: assetProfile.symbol, symbol: assetProfile.symbol,
url: assetProfile.url url: assetProfile.url
}, },
assetSubClass: assetProfile.assetSubClass,
countries: assetProfile.countries,
dataSource: assetProfile.dataSource,
dateOfFirstActivity: parseDate(dateOfFirstActivity), dateOfFirstActivity: parseDate(dateOfFirstActivity),
dividend: dividend?.toNumber() ?? 0, dividend: dividend?.toNumber() ?? 0,
grossPerformance: grossPerformance?.toNumber() ?? 0, grossPerformance: grossPerformance?.toNumber() ?? 0,
@ -681,19 +675,7 @@ export class PortfolioService {
grossPerformancePercentageWithCurrencyEffect?.toNumber() ?? 0, grossPerformancePercentageWithCurrencyEffect?.toNumber() ?? 0,
grossPerformanceWithCurrencyEffect: grossPerformanceWithCurrencyEffect:
grossPerformanceWithCurrencyEffect?.toNumber() ?? 0, grossPerformanceWithCurrencyEffect?.toNumber() ?? 0,
holdings: assetProfile.holdings.map(
({ allocationInPercentage, name }) => {
return {
allocationInPercentage,
name,
valueInBaseCurrency: valueInBaseCurrency
.mul(allocationInPercentage)
.toNumber()
};
}
),
investment: investment.toNumber(), investment: investment.toNumber(),
name: assetProfile.name,
netPerformance: netPerformance?.toNumber() ?? 0, netPerformance: netPerformance?.toNumber() ?? 0,
netPerformancePercent: netPerformancePercentage?.toNumber() ?? 0, netPerformancePercent: netPerformancePercentage?.toNumber() ?? 0,
netPerformancePercentWithCurrencyEffect: netPerformancePercentWithCurrencyEffect:
@ -703,8 +685,6 @@ export class PortfolioService {
netPerformanceWithCurrencyEffect: netPerformanceWithCurrencyEffect:
netPerformanceWithCurrencyEffectMap?.[dateRange]?.toNumber() ?? 0, netPerformanceWithCurrencyEffectMap?.[dateRange]?.toNumber() ?? 0,
quantity: quantity.toNumber(), quantity: quantity.toNumber(),
sectors: assetProfile.sectors,
url: assetProfile.url,
valueInBaseCurrency: valueInBaseCurrency.toNumber() valueInBaseCurrency: valueInBaseCurrency.toNumber()
}; };
} }
@ -1472,8 +1452,8 @@ export class PortfolioService {
for (const [, position] of Object.entries(holdings)) { for (const [, position] of Object.entries(holdings)) {
const value = position.valueInBaseCurrency; const value = position.valueInBaseCurrency;
if (position.assetClass !== AssetClass.LIQUIDITY) { if (position.assetProfile.assetClass !== AssetClass.LIQUIDITY) {
if (position.countries.length > 0) { if (position.assetProfile.countries.length > 0) {
markets.developedMarkets.valueInBaseCurrency += markets.developedMarkets.valueInBaseCurrency +=
position.markets.developedMarkets * value; position.markets.developedMarkets * value;
markets.emergingMarkets.valueInBaseCurrency += markets.emergingMarkets.valueInBaseCurrency +=
@ -1719,11 +1699,8 @@ export class PortfolioService {
currency: string; currency: string;
}): PortfolioPosition { }): PortfolioPosition {
return { return {
currency,
activitiesCount: 0, activitiesCount: 0,
allocationInPercentage: 0, allocationInPercentage: 0,
assetClass: AssetClass.LIQUIDITY,
assetSubClass: AssetSubClass.CASH,
assetProfile: { assetProfile: {
currency, currency,
assetClass: AssetClass.LIQUIDITY, assetClass: AssetClass.LIQUIDITY,
@ -1735,25 +1712,19 @@ export class PortfolioService {
sectors: [], sectors: [],
symbol: currency symbol: currency
}, },
countries: [],
dataSource: undefined,
dateOfFirstActivity: undefined, dateOfFirstActivity: undefined,
dividend: 0, dividend: 0,
grossPerformance: 0, grossPerformance: 0,
grossPerformancePercent: 0, grossPerformancePercent: 0,
grossPerformancePercentWithCurrencyEffect: 0, grossPerformancePercentWithCurrencyEffect: 0,
grossPerformanceWithCurrencyEffect: 0, grossPerformanceWithCurrencyEffect: 0,
holdings: [],
investment: balance, investment: balance,
marketPrice: 0, marketPrice: 0,
name: currency,
netPerformance: 0, netPerformance: 0,
netPerformancePercent: 0, netPerformancePercent: 0,
netPerformancePercentWithCurrencyEffect: 0, netPerformancePercentWithCurrencyEffect: 0,
netPerformanceWithCurrencyEffect: 0, netPerformanceWithCurrencyEffect: 0,
quantity: 0, quantity: 0,
sectors: [],
symbol: currency,
tags: [], tags: [],
valueInBaseCurrency: balance valueInBaseCurrency: balance
}; };

31
apps/api/src/app/user/user.service.ts

@ -49,7 +49,7 @@ import { PerformanceCalculationType } from '@ghostfolio/common/types/performance
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter'; import { EventEmitter2 } from '@nestjs/event-emitter';
import { Prisma, Role, User } from '@prisma/client'; import { Prisma, Role, Settings, User } from '@prisma/client';
import { differenceInDays, subDays } from 'date-fns'; import { differenceInDays, subDays } from 'date-fns';
import { without } from 'lodash'; import { without } from 'lodash';
import { createHmac } from 'node:crypto'; import { createHmac } from 'node:crypto';
@ -116,7 +116,14 @@ export class UserService {
thirdPartyId thirdPartyId
} = user; } = user;
const userData = await Promise.all([ const [
access,
accounts,
activitiesCount,
firstActivity,
impersonationUserSettings,
tagsForUser
] = await Promise.all([
this.prismaService.access.findMany({ this.prismaService.access.findMany({
include: { include: {
user: true user: true
@ -141,16 +148,17 @@ export class UserService {
}, },
where: { userId: impersonationUserId || user.id } where: { userId: impersonationUserId || user.id }
}), }),
impersonationUserId
? this.prismaService.settings.findUnique({
where: { userId: impersonationUserId }
})
: Promise.resolve<Settings>(null),
this.tagService.getTagsForUser(impersonationUserId || user.id) this.tagService.getTagsForUser(impersonationUserId || user.id)
]); ]);
const access = userData[0]; const baseCurrency =
const accounts = userData[1]; (impersonationUserSettings?.settings as UserSettings)?.baseCurrency ??
const activitiesCount = userData[2]; (settings.settings as UserSettings)?.baseCurrency;
const firstActivity = userData[3];
let tags = userData[4].filter((tag) => {
return tag.id !== TAG_ID_EXCLUDE_FROM_ANALYSIS;
});
let systemMessage: SystemMessage; let systemMessage: SystemMessage;
@ -163,6 +171,10 @@ export class UserService {
systemMessage = systemMessageProperty; systemMessage = systemMessageProperty;
} }
let tags = tagsForUser.filter((tag) => {
return tag.id !== TAG_ID_EXCLUDE_FROM_ANALYSIS;
});
if ( if (
this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') && this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION') &&
subscription.type === SubscriptionType.Basic subscription.type === SubscriptionType.Basic
@ -192,6 +204,7 @@ export class UserService {
dateOfFirstActivity: firstActivity?.date ?? new Date(), dateOfFirstActivity: firstActivity?.date ?? new Date(),
settings: { settings: {
...(settings.settings as UserSettings), ...(settings.settings as UserSettings),
baseCurrency,
locale: (settings.settings as UserSettings)?.locale ?? locale locale: (settings.settings as UserSettings)?.locale ?? locale
} }
}; };

4
apps/api/src/main.ts

@ -18,11 +18,15 @@ import type { NestExpressApplication } from '@nestjs/platform-express';
import cookieParser from 'cookie-parser'; import cookieParser from 'cookie-parser';
import { NextFunction, Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express';
import helmet from 'helmet'; import helmet from 'helmet';
import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
import { AppModule } from './app/app.module'; import { AppModule } from './app/app.module';
import { environment } from './environments/environment'; import { environment } from './environments/environment';
async function bootstrap() { async function bootstrap() {
// Respect HTTP_PROXY / HTTPS_PROXY / NO_PROXY for outbound HTTP requests
setGlobalDispatcher(new EnvHttpProxyAgent());
const configApp = await NestFactory.create(AppModule); const configApp = await NestFactory.create(AppModule);
const configService = configApp.get<ConfigService>(ConfigService); const configService = configApp.get<ConfigService>(ConfigService);
let customLogLevels: LogLevel[]; let customLogLevels: LogLevel[];

52
apps/api/src/services/data-provider/coingecko/coingecko.service.ts

@ -7,6 +7,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { DEFAULT_CURRENCY } from '@ghostfolio/common/config'; import { DEFAULT_CURRENCY } from '@ghostfolio/common/config';
import { DATE_FORMAT } from '@ghostfolio/common/helper'; import { DATE_FORMAT } from '@ghostfolio/common/helper';
import { import {
@ -32,7 +33,8 @@ export class CoinGeckoService implements DataProviderInterface, OnModuleInit {
private headers: HeadersInit = {}; private headers: HeadersInit = {};
public constructor( public constructor(
private readonly configurationService: ConfigurationService private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService
) {} ) {}
public onModuleInit() { public onModuleInit() {
@ -67,12 +69,14 @@ export class CoinGeckoService implements DataProviderInterface, OnModuleInit {
}; };
try { try {
const { name } = await fetch(`${this.apiUrl}/coins/${symbol}`, { const { name } = await this.fetchService
headers: this.headers, .fetch(`${this.apiUrl}/coins/${symbol}`, {
signal: AbortSignal.timeout( headers: this.headers,
this.configurationService.get('REQUEST_TIMEOUT') signal: AbortSignal.timeout(
) this.configurationService.get('REQUEST_TIMEOUT')
}).then((res) => res.json()); )
})
.then((res) => res.json());
response.name = name; response.name = name;
} catch (error) { } catch (error) {
@ -118,13 +122,15 @@ export class CoinGeckoService implements DataProviderInterface, OnModuleInit {
vs_currency: DEFAULT_CURRENCY.toLowerCase() vs_currency: DEFAULT_CURRENCY.toLowerCase()
}); });
const { error, prices, status } = await fetch( const { error, prices, status } = await this.fetchService
`${this.apiUrl}/coins/${symbol}/market_chart/range?${queryParams.toString()}`, .fetch(
{ `${this.apiUrl}/coins/${symbol}/market_chart/range?${queryParams.toString()}`,
headers: this.headers, {
signal: AbortSignal.timeout(requestTimeout) headers: this.headers,
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
if (error?.status) { if (error?.status) {
throw new Error(error.status.error_message); throw new Error(error.status.error_message);
@ -181,13 +187,12 @@ export class CoinGeckoService implements DataProviderInterface, OnModuleInit {
vs_currencies: DEFAULT_CURRENCY.toLowerCase() vs_currencies: DEFAULT_CURRENCY.toLowerCase()
}); });
const quotes = await fetch( const quotes = await this.fetchService
`${this.apiUrl}/simple/price?${queryParams.toString()}`, .fetch(`${this.apiUrl}/simple/price?${queryParams.toString()}`, {
{
headers: this.headers, headers: this.headers,
signal: AbortSignal.timeout(requestTimeout) signal: AbortSignal.timeout(requestTimeout)
} })
).then((res) => res.json()); .then((res) => res.json());
for (const symbol in quotes) { for (const symbol in quotes) {
response[symbol] = { response[symbol] = {
@ -230,13 +235,12 @@ export class CoinGeckoService implements DataProviderInterface, OnModuleInit {
query query
}); });
const { coins } = await fetch( const { coins } = await this.fetchService
`${this.apiUrl}/search?${queryParams.toString()}`, .fetch(`${this.apiUrl}/search?${queryParams.toString()}`, {
{
headers: this.headers, headers: this.headers,
signal: AbortSignal.timeout(requestTimeout) signal: AbortSignal.timeout(requestTimeout)
} })
).then((res) => res.json()); .then((res) => res.json());
items = coins.map(({ id: symbol, name }) => { items = coins.map(({ id: symbol, name }) => {
return { return {

3
apps/api/src/services/data-provider/data-enhancer/data-enhancer.module.ts

@ -3,6 +3,7 @@ import { CryptocurrencyModule } from '@ghostfolio/api/services/cryptocurrency/cr
import { OpenFigiDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/openfigi/openfigi.service'; import { OpenFigiDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/openfigi/openfigi.service';
import { TrackinsightDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/trackinsight/trackinsight.service'; import { TrackinsightDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/trackinsight/trackinsight.service';
import { YahooFinanceDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/yahoo-finance/yahoo-finance.service'; import { YahooFinanceDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/yahoo-finance/yahoo-finance.service';
import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module';
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
@ -16,7 +17,7 @@ import { DataEnhancerService } from './data-enhancer.service';
YahooFinanceDataEnhancerService, YahooFinanceDataEnhancerService,
'DataEnhancers' 'DataEnhancers'
], ],
imports: [ConfigurationModule, CryptocurrencyModule], imports: [ConfigurationModule, CryptocurrencyModule, FetchModule],
providers: [ providers: [
DataEnhancerService, DataEnhancerService,
OpenFigiDataEnhancerService, OpenFigiDataEnhancerService,

13
apps/api/src/services/data-provider/data-enhancer/openfigi/openfigi.service.ts

@ -1,5 +1,6 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { DataEnhancerInterface } from '@ghostfolio/api/services/data-provider/interfaces/data-enhancer.interface'; import { DataEnhancerInterface } from '@ghostfolio/api/services/data-provider/interfaces/data-enhancer.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { parseSymbol } from '@ghostfolio/common/helper'; import { parseSymbol } from '@ghostfolio/common/helper';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
@ -10,7 +11,8 @@ export class OpenFigiDataEnhancerService implements DataEnhancerInterface {
private static baseUrl = 'https://api.openfigi.com'; private static baseUrl = 'https://api.openfigi.com';
public constructor( public constructor(
private readonly configurationService: ConfigurationService private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService
) {} ) {}
public async enhance({ public async enhance({
@ -42,9 +44,8 @@ export class OpenFigiDataEnhancerService implements DataEnhancerInterface {
this.configurationService.get('API_KEY_OPEN_FIGI'); this.configurationService.get('API_KEY_OPEN_FIGI');
} }
const mappings = (await fetch( const mappings = (await this.fetchService
`${OpenFigiDataEnhancerService.baseUrl}/v3/mapping`, .fetch(`${OpenFigiDataEnhancerService.baseUrl}/v3/mapping`, {
{
body: JSON.stringify([ body: JSON.stringify([
{ exchCode: exchange, idType: 'TICKER', idValue: ticker } { exchCode: exchange, idType: 'TICKER', idValue: ticker }
]), ]),
@ -54,8 +55,8 @@ export class OpenFigiDataEnhancerService implements DataEnhancerInterface {
}, },
method: 'POST', method: 'POST',
signal: AbortSignal.timeout(requestTimeout) signal: AbortSignal.timeout(requestTimeout)
} })
).then((res) => res.json())) as any[]; .then((res) => res.json())) as any[];
if (mappings?.length === 1 && mappings[0].data?.length === 1) { if (mappings?.length === 1 && mappings[0].data?.length === 1) {
const { compositeFIGI, figi, shareClassFIGI } = mappings[0].data[0]; const { compositeFIGI, figi, shareClassFIGI } = mappings[0].data[0];

46
apps/api/src/services/data-provider/data-enhancer/trackinsight/trackinsight.service.ts

@ -1,5 +1,6 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { DataEnhancerInterface } from '@ghostfolio/api/services/data-provider/interfaces/data-enhancer.interface'; import { DataEnhancerInterface } from '@ghostfolio/api/services/data-provider/interfaces/data-enhancer.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { Holding } from '@ghostfolio/common/interfaces'; import { Holding } from '@ghostfolio/common/interfaces';
import { Country } from '@ghostfolio/common/interfaces/country.interface'; import { Country } from '@ghostfolio/common/interfaces/country.interface';
import { Sector } from '@ghostfolio/common/interfaces/sector.interface'; import { Sector } from '@ghostfolio/common/interfaces/sector.interface';
@ -12,7 +13,8 @@ import { countries } from 'countries-list';
export class TrackinsightDataEnhancerService implements DataEnhancerInterface { export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
private static baseUrl = 'https://www.trackinsight.com/data-api'; private static baseUrl = 'https://www.trackinsight.com/data-api';
private static countriesMapping = { private static countriesMapping = {
'Russian Federation': 'Russia' 'Russian Federation': 'Russia',
USA: 'United States'
}; };
private static holdingsWeightTreshold = 0.85; private static holdingsWeightTreshold = 0.85;
private static sectorsMapping = { private static sectorsMapping = {
@ -23,7 +25,8 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
}; };
public constructor( public constructor(
private readonly configurationService: ConfigurationService private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService
) {} ) {}
public async enhance({ public async enhance({
@ -60,12 +63,13 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
return response; return response;
} }
const profile = await fetch( const profile = await this.fetchService
`${TrackinsightDataEnhancerService.baseUrl}/funds/${trackinsightSymbol}.json`, .fetch(
{ `${TrackinsightDataEnhancerService.baseUrl}/funds/${trackinsightSymbol}.json`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
) }
)
.then((res) => res.json()) .then((res) => res.json())
.catch(() => { .catch(() => {
return {}; return {};
@ -83,12 +87,13 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
response.isin = isin; response.isin = isin;
} }
const holdings = await fetch( const holdings = await this.fetchService
`${TrackinsightDataEnhancerService.baseUrl}/holdings/${trackinsightSymbol}.json`, .fetch(
{ `${TrackinsightDataEnhancerService.baseUrl}/holdings/${trackinsightSymbol}.json`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
) }
)
.then((res) => res.json()) .then((res) => res.json())
.catch(() => { .catch(() => {
return {}; return {};
@ -182,12 +187,13 @@ export class TrackinsightDataEnhancerService implements DataEnhancerInterface {
requestTimeout: number; requestTimeout: number;
symbol: string; symbol: string;
}) { }) {
return fetch( return this.fetchService
`https://www.trackinsight.com/search-api/search_v2/${symbol}/_/ticker/default/0/3`, .fetch(
{ `https://www.trackinsight.com/search-api/search_v2/${symbol}/_/ticker/default/0/3`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
) }
)
.then((res) => res.json()) .then((res) => res.json())
.then((jsonRes) => { .then((jsonRes) => {
if ( if (

2
apps/api/src/services/data-provider/data-provider.module.ts

@ -10,6 +10,7 @@ import { GoogleSheetsService } from '@ghostfolio/api/services/data-provider/goog
import { ManualService } from '@ghostfolio/api/services/data-provider/manual/manual.service'; import { ManualService } from '@ghostfolio/api/services/data-provider/manual/manual.service';
import { RapidApiService } from '@ghostfolio/api/services/data-provider/rapid-api/rapid-api.service'; import { RapidApiService } from '@ghostfolio/api/services/data-provider/rapid-api/rapid-api.service';
import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service'; import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service';
import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module';
import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module';
import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module';
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; import { PropertyModule } from '@ghostfolio/api/services/property/property.module';
@ -26,6 +27,7 @@ import { DataProviderService } from './data-provider.service';
ConfigurationModule, ConfigurationModule,
CryptocurrencyModule, CryptocurrencyModule,
DataEnhancerModule, DataEnhancerModule,
FetchModule,
MarketDataModule, MarketDataModule,
PrismaModule, PrismaModule,
PropertyModule, PropertyModule,

43
apps/api/src/services/data-provider/eod-historical-data/eod-historical-data.service.ts

@ -7,6 +7,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { import {
DEFAULT_CURRENCY, DEFAULT_CURRENCY,
@ -41,6 +42,7 @@ export class EodHistoricalDataService
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService,
private readonly symbolProfileService: SymbolProfileService private readonly symbolProfileService: SymbolProfileService
) {} ) {}
@ -111,12 +113,11 @@ export class EodHistoricalDataService
[date: string]: DataProviderHistoricalResponse; [date: string]: DataProviderHistoricalResponse;
} = {}; } = {};
const historicalResult = await fetch( const historicalResult = await this.fetchService
`${this.URL}/div/${symbol}?${queryParams.toString()}`, .fetch(`${this.URL}/div/${symbol}?${queryParams.toString()}`, {
{
signal: AbortSignal.timeout(requestTimeout) signal: AbortSignal.timeout(requestTimeout)
} })
).then((res) => res.json()); .then((res) => res.json());
for (const { date, value } of historicalResult) { for (const { date, value } of historicalResult) {
response[date] = { response[date] = {
@ -158,12 +159,11 @@ export class EodHistoricalDataService
to: format(to, DATE_FORMAT) to: format(to, DATE_FORMAT)
}); });
const response = await fetch( const response = await this.fetchService
`${this.URL}/eod/${symbol}?${queryParams.toString()}`, .fetch(`${this.URL}/eod/${symbol}?${queryParams.toString()}`, {
{
signal: AbortSignal.timeout(requestTimeout) signal: AbortSignal.timeout(requestTimeout)
} })
).then((res) => res.json()); .then((res) => res.json());
return response.reduce( return response.reduce(
(result, { adjusted_close, date }) => { (result, { adjusted_close, date }) => {
@ -223,12 +223,14 @@ export class EodHistoricalDataService
s: eodHistoricalDataSymbols.join(',') s: eodHistoricalDataSymbols.join(',')
}); });
const realTimeResponse = await fetch( const realTimeResponse = await this.fetchService
`${this.URL}/real-time/${eodHistoricalDataSymbols[0]}?${queryParams.toString()}`, .fetch(
{ `${this.URL}/real-time/${eodHistoricalDataSymbols[0]}?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
const quotes: { const quotes: {
close: number; close: number;
@ -430,12 +432,11 @@ export class EodHistoricalDataService
api_token: this.apiKey api_token: this.apiKey
}); });
const response = await fetch( const response = await this.fetchService
`${this.URL}/search/${query}?${queryParams.toString()}`, .fetch(`${this.URL}/search/${query}?${queryParams.toString()}`, {
{
signal: AbortSignal.timeout(requestTimeout) signal: AbortSignal.timeout(requestTimeout)
} })
).then((res) => res.json()); .then((res) => res.json());
searchResult = response.map( searchResult = response.map(
({ Code, Currency, Exchange, ISIN: isin, Name: name, Type }) => { ({ Code, Currency, Exchange, ISIN: isin, Name: name, Type }) => {

175
apps/api/src/services/data-provider/financial-modeling-prep/financial-modeling-prep.service.ts

@ -9,6 +9,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { import {
DEFAULT_CURRENCY, DEFAULT_CURRENCY,
@ -59,6 +60,7 @@ export class FinancialModelingPrepService
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly cryptocurrencyService: CryptocurrencyService, private readonly cryptocurrencyService: CryptocurrencyService,
private readonly fetchService: FetchService,
private readonly prismaService: PrismaService private readonly prismaService: PrismaService
) {} ) {}
@ -96,12 +98,14 @@ export class FinancialModelingPrepService
apikey: this.apiKey apikey: this.apiKey
}); });
const [quote] = await fetch( const [quote] = await this.fetchService
`${this.getUrl({ version: 'stable' })}/quote?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/quote?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
response.assetClass = AssetClass.LIQUIDITY; response.assetClass = AssetClass.LIQUIDITY;
response.assetSubClass = AssetSubClass.CRYPTOCURRENCY; response.assetSubClass = AssetSubClass.CRYPTOCURRENCY;
@ -115,12 +119,14 @@ export class FinancialModelingPrepService
apikey: this.apiKey apikey: this.apiKey
}); });
const [assetProfile] = await fetch( const [assetProfile] = await this.fetchService
`${this.getUrl({ version: 'stable' })}/profile?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/profile?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
if (!assetProfile) { if (!assetProfile) {
throw new AssetProfileDelistedError( throw new AssetProfileDelistedError(
@ -143,12 +149,14 @@ export class FinancialModelingPrepService
apikey: this.apiKey apikey: this.apiKey
}); });
const etfCountryWeightings = await fetch( const etfCountryWeightings = await this.fetchService
`${this.getUrl({ version: 'stable' })}/etf/country-weightings?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/etf/country-weightings?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
response.countries = etfCountryWeightings response.countries = etfCountryWeightings
.filter(({ country: countryName }) => { .filter(({ country: countryName }) => {
@ -174,12 +182,14 @@ export class FinancialModelingPrepService
}; };
}); });
const etfHoldings = await fetch( const etfHoldings = await this.fetchService
`${this.getUrl({ version: 'stable' })}/etf/holdings?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/etf/holdings?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
const sortedTopHoldings = etfHoldings const sortedTopHoldings = etfHoldings
.sort((a, b) => { .sort((a, b) => {
@ -193,23 +203,27 @@ export class FinancialModelingPrepService
} }
); );
const [etfInformation] = await fetch( const [etfInformation] = await this.fetchService
`${this.getUrl({ version: 'stable' })}/etf/info?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/etf/info?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
if (etfInformation?.website) { if (etfInformation?.website) {
response.url = etfInformation.website; response.url = etfInformation.website;
} }
const etfSectorWeightings = await fetch( const etfSectorWeightings = await this.fetchService
`${this.getUrl({ version: 'stable' })}/etf/sector-weightings?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/etf/sector-weightings?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
response.sectors = etfSectorWeightings.map( response.sectors = etfSectorWeightings.map(
({ sector, weightPercentage }) => { ({ sector, weightPercentage }) => {
@ -286,12 +300,14 @@ export class FinancialModelingPrepService
[date: string]: DataProviderHistoricalResponse; [date: string]: DataProviderHistoricalResponse;
} = {}; } = {};
const dividends = await fetch( const dividends = await this.fetchService
`${this.getUrl({ version: 'stable' })}/dividends?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/dividends?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
dividends dividends
.filter(({ date }) => { .filter(({ date }) => {
@ -354,12 +370,14 @@ export class FinancialModelingPrepService
to: format(currentTo, DATE_FORMAT) to: format(currentTo, DATE_FORMAT)
}); });
const historical = await fetch( const historical = await this.fetchService
`${this.getUrl({ version: 'stable' })}/historical-price-eod/full?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/historical-price-eod/full?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
for (const { close, date } of historical) { for (const { close, date } of historical) {
if ( if (
@ -422,14 +440,17 @@ export class FinancialModelingPrepService
symbolTarget: { in: symbols } symbolTarget: { in: symbols }
} }
}), }),
fetch( this.fetchService
`${this.getUrl({ version: 'stable' })}/batch-quote-short?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/batch-quote-short?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then( }
(res) => res.json() as unknown as { price: number; symbol: string }[] )
) .then(
(res) =>
res.json() as unknown as { price: number; symbol: string }[]
)
]); ]);
for (const { currency, symbolTarget } of assetProfileResolutions) { for (const { currency, symbolTarget } of assetProfileResolutions) {
@ -525,12 +546,14 @@ export class FinancialModelingPrepService
isin: query.toUpperCase() isin: query.toUpperCase()
}); });
const result = await fetch( const result = await this.fetchService
`${this.getUrl({ version: 'stable' })}/search-isin?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/search-isin?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()); }
)
.then((res) => res.json());
await Promise.all( await Promise.all(
result.map(({ symbol }) => { result.map(({ symbol }) => {
@ -558,18 +581,22 @@ export class FinancialModelingPrepService
}); });
const [nameResults, symbolResults] = await Promise.all([ const [nameResults, symbolResults] = await Promise.all([
fetch( this.fetchService
`${this.getUrl({ version: 'stable' })}/search-name?${queryParams.toString()}`, .fetch(
{ `${this.getUrl({ version: 'stable' })}/search-name?${queryParams.toString()}`,
signal: AbortSignal.timeout(requestTimeout) {
} signal: AbortSignal.timeout(requestTimeout)
).then((res) => res.json()), }
fetch( )
`${this.getUrl({ version: 'stable' })}/search-symbol?${queryParams.toString()}`, .then((res) => res.json()),
{ this.fetchService
signal: AbortSignal.timeout(requestTimeout) .fetch(
} `${this.getUrl({ version: 'stable' })}/search-symbol?${queryParams.toString()}`,
).then((res) => res.json()) {
signal: AbortSignal.timeout(requestTimeout)
}
)
.then((res) => res.json())
]); ]);
const result = uniqBy( const result = uniqBy(

12
apps/api/src/services/data-provider/ghostfolio/ghostfolio.service.ts

@ -8,6 +8,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; import { PropertyService } from '@ghostfolio/api/services/property/property.service';
import { import {
HEADER_KEY_TOKEN, HEADER_KEY_TOKEN,
@ -38,6 +39,7 @@ export class GhostfolioService implements DataProviderInterface {
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService,
private readonly propertyService: PropertyService private readonly propertyService: PropertyService
) {} ) {}
@ -52,7 +54,7 @@ export class GhostfolioService implements DataProviderInterface {
let assetProfile: DataProviderGhostfolioAssetProfileResponse; let assetProfile: DataProviderGhostfolioAssetProfileResponse;
try { try {
const response = await fetch( const response = await this.fetchService.fetch(
`${this.URL}/v1/data-providers/ghostfolio/asset-profile/${symbol}`, `${this.URL}/v1/data-providers/ghostfolio/asset-profile/${symbol}`,
{ {
headers: await this.getRequestHeaders(), headers: await this.getRequestHeaders(),
@ -122,7 +124,7 @@ export class GhostfolioService implements DataProviderInterface {
to: format(to, DATE_FORMAT) to: format(to, DATE_FORMAT)
}); });
const response = await fetch( const response = await this.fetchService.fetch(
`${this.URL}/v2/data-providers/ghostfolio/dividends/${symbol}?${queryParams.toString()}`, `${this.URL}/v2/data-providers/ghostfolio/dividends/${symbol}?${queryParams.toString()}`,
{ {
headers: await this.getRequestHeaders(), headers: await this.getRequestHeaders(),
@ -174,7 +176,7 @@ export class GhostfolioService implements DataProviderInterface {
to: format(to, DATE_FORMAT) to: format(to, DATE_FORMAT)
}); });
const response = await fetch( const response = await this.fetchService.fetch(
`${this.URL}/v2/data-providers/ghostfolio/historical/${symbol}?${queryParams.toString()}`, `${this.URL}/v2/data-providers/ghostfolio/historical/${symbol}?${queryParams.toString()}`,
{ {
headers: await this.getRequestHeaders(), headers: await this.getRequestHeaders(),
@ -245,7 +247,7 @@ export class GhostfolioService implements DataProviderInterface {
symbols: symbols.join(',') symbols: symbols.join(',')
}); });
const response = await fetch( const response = await this.fetchService.fetch(
`${this.URL}/v2/data-providers/ghostfolio/quotes?${queryParams.toString()}`, `${this.URL}/v2/data-providers/ghostfolio/quotes?${queryParams.toString()}`,
{ {
headers: await this.getRequestHeaders(), headers: await this.getRequestHeaders(),
@ -302,7 +304,7 @@ export class GhostfolioService implements DataProviderInterface {
query query
}); });
const response = await fetch( const response = await this.fetchService.fetch(
`${this.URL}/v2/data-providers/ghostfolio/lookup?${queryParams.toString()}`, `${this.URL}/v2/data-providers/ghostfolio/lookup?${queryParams.toString()}`,
{ {
headers: await this.getRequestHeaders(), headers: await this.getRequestHeaders(),

4
apps/api/src/services/data-provider/manual/manual.service.ts

@ -8,6 +8,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service'; import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { import {
@ -32,6 +33,7 @@ import { addDays, format, isBefore } from 'date-fns';
export class ManualService implements DataProviderInterface { export class ManualService implements DataProviderInterface {
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService,
private readonly prismaService: PrismaService, private readonly prismaService: PrismaService,
private readonly symbolProfileService: SymbolProfileService private readonly symbolProfileService: SymbolProfileService
) {} ) {}
@ -292,7 +294,7 @@ export class ManualService implements DataProviderInterface {
}): Promise<number> { }): Promise<number> {
let locale = scraperConfiguration.locale; let locale = scraperConfiguration.locale;
const response = await fetch(scraperConfiguration.url, { const response = await this.fetchService.fetch(scraperConfiguration.url, {
headers: scraperConfiguration.headers as HeadersInit, headers: scraperConfiguration.headers as HeadersInit,
signal: AbortSignal.timeout( signal: AbortSignal.timeout(
this.configurationService.get('REQUEST_TIMEOUT') this.configurationService.get('REQUEST_TIMEOUT')

13
apps/api/src/services/data-provider/rapid-api/rapid-api.service.ts

@ -7,6 +7,7 @@ import {
GetQuotesParams, GetQuotesParams,
GetSearchParams GetSearchParams
} from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { import {
ghostfolioFearAndGreedIndexSymbol, ghostfolioFearAndGreedIndexSymbol,
ghostfolioFearAndGreedIndexSymbolStocks ghostfolioFearAndGreedIndexSymbolStocks
@ -26,7 +27,8 @@ import { format } from 'date-fns';
@Injectable() @Injectable()
export class RapidApiService implements DataProviderInterface { export class RapidApiService implements DataProviderInterface {
public constructor( public constructor(
private readonly configurationService: ConfigurationService private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService
) {} ) {}
public canHandle() { public canHandle() {
@ -142,9 +144,8 @@ export class RapidApiService implements DataProviderInterface {
oneYearAgo: { value: number; valueText: string }; oneYearAgo: { value: number; valueText: string };
}> { }> {
try { try {
const { fgi } = await fetch( const { fgi } = await this.fetchService
`https://fear-and-greed-index.p.rapidapi.com/v1/fgi`, .fetch(`https://fear-and-greed-index.p.rapidapi.com/v1/fgi`, {
{
headers: { headers: {
useQueryString: 'true', useQueryString: 'true',
'x-rapidapi-host': 'fear-and-greed-index.p.rapidapi.com', 'x-rapidapi-host': 'fear-and-greed-index.p.rapidapi.com',
@ -153,8 +154,8 @@ export class RapidApiService implements DataProviderInterface {
signal: AbortSignal.timeout( signal: AbortSignal.timeout(
this.configurationService.get('REQUEST_TIMEOUT') this.configurationService.get('REQUEST_TIMEOUT')
) )
} })
).then((res) => res.json()); .then((res) => res.json());
return fgi; return fgi;
} catch (error) { } catch (error) {

11
apps/api/src/services/fetch/fetch.module.ts

@ -0,0 +1,11 @@
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PropertyModule } from '@ghostfolio/api/services/property/property.module';
import { Module } from '@nestjs/common';
@Module({
exports: [FetchService],
imports: [PropertyModule],
providers: [FetchService]
})
export class FetchModule {}

205
apps/api/src/services/fetch/fetch.service.ts

@ -0,0 +1,205 @@
import { redactPaths } from '@ghostfolio/api/helper/object.helper';
import { PropertyService } from '@ghostfolio/api/services/property/property.service';
import {
PROPERTY_API_KEY_OPENROUTER,
PROPERTY_OPENROUTER_MODEL,
PROPERTY_WEB_FETCH_ROUTES
} from '@ghostfolio/common/config';
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { generateText, jsonSchema, tool } from 'ai';
import ms from 'ms';
import { WebFetchRoute } from './interfaces/web-fetch-route.interface';
@Injectable()
export class FetchService implements OnModuleInit {
private static readonly REDACTED_QUERY_PARAM_NAMES = ['apikey', 'api_token'];
private static readonly WEB_FETCH_TIMEOUT = ms('30 seconds');
private webFetchRoutes: WebFetchRoute[] = [];
public constructor(private readonly propertyService: PropertyService) {}
public async onModuleInit() {
this.webFetchRoutes =
(await this.propertyService.getByKey<WebFetchRoute[]>(
PROPERTY_WEB_FETCH_ROUTES
)) ?? [];
}
public async fetch(input: RequestInfo | URL, init?: RequestInit) {
const method = (
init?.method ??
(input instanceof Request ? input.method : undefined) ??
'GET'
).toUpperCase();
const url = input instanceof Request ? input.url : input.toString();
const urlRedacted = this.redactUrl(url);
Logger.debug(`${method} ${urlRedacted}`, 'FetchService');
if (method === 'GET') {
const webFetchRoute = this.getMatchingWebFetchRoute(url);
if (webFetchRoute) {
const response = await this.fetchViaWebFetchTool({
url,
webFetchRoute
});
if (response) {
return response;
}
}
}
try {
return await globalThis.fetch(input, init);
} catch (error) {
if (error instanceof Error) {
Logger.error(
`${method} ${urlRedacted} failed: [${error.name}] ${error.message}`,
'FetchService'
);
} else {
Logger.error(
`${method} ${urlRedacted} failed: ${String(error)}`,
'FetchService'
);
}
throw error;
}
}
private async fetchViaWebFetchTool({
url,
webFetchRoute
}: {
url: string;
webFetchRoute: WebFetchRoute;
}) {
const [openRouterApiKey, openRouterModel] = await Promise.all([
this.propertyService.getByKey<string>(PROPERTY_API_KEY_OPENROUTER),
this.propertyService.getByKey<string>(PROPERTY_OPENROUTER_MODEL)
]);
if (!openRouterApiKey || !openRouterModel) {
return undefined;
}
try {
const openRouterService = createOpenRouter({ apiKey: openRouterApiKey });
const { sources, text } = await generateText({
model: openRouterService.chat(openRouterModel),
prompt: [
'You have access to a web_fetch tool. You MUST call it to retrieve the URL below, do not answer from prior knowledge.',
'Return the fetched response body exactly as received: raw body only, no commentary, no Markdown, and no code fences.',
`URL: ${url}`
].join('\n'),
timeout: FetchService.WEB_FETCH_TIMEOUT,
tools: {
// Provider-defined tool: lets OpenRouter perform the actual web
// request server-side via its `web_fetch` engine. `id` and `args`
// are the OpenRouter-specific identifiers; the input schema is left
// open as the arguments are supplied by the model.
web_fetch: tool({
args: { engine: 'openrouter' },
id: 'openrouter.web_fetch',
inputSchema: jsonSchema({
additionalProperties: true,
type: 'object'
}),
type: 'provider'
})
}
});
const candidates = [
...(sources ?? []).map((source) => {
return source.providerMetadata?.openrouter?.content;
}),
text
];
for (const candidate of candidates) {
if (typeof candidate !== 'string') {
continue;
}
const body = candidate.trim();
if (!body) {
continue;
}
if (webFetchRoute.responseContentType?.includes('application/json')) {
try {
JSON.parse(body);
} catch {
continue;
}
}
Logger.debug(
`Routed ${this.redactUrl(url)} via web fetch tool`,
'FetchService'
);
return new Response(body, {
headers: webFetchRoute.responseContentType
? { 'content-type': webFetchRoute.responseContentType }
: undefined
});
}
return undefined;
} catch (error) {
Logger.error(
`Web fetch tool failed for ${this.redactUrl(url)}: ${
error instanceof Error ? error.message : String(error)
}`,
'FetchService'
);
return undefined;
}
}
private getMatchingWebFetchRoute(url: string) {
try {
const { hostname } = new URL(url);
return this.webFetchRoutes.find(({ domain }) => {
return hostname === domain || hostname.endsWith(`.${domain}`);
});
} catch {
return undefined;
}
}
private redactUrl(rawUrl: string): string {
try {
const url = new URL(rawUrl);
const redacted = redactPaths({
object: Object.fromEntries(url.searchParams),
paths: FetchService.REDACTED_QUERY_PARAM_NAMES
});
for (const [key, value] of Object.entries(redacted)) {
if (value === null) {
url.searchParams.set(key, '*******');
}
}
return url.toString();
} catch {
return rawUrl;
}
}
}

19
apps/api/src/services/fetch/interfaces/web-fetch-route.interface.ts

@ -0,0 +1,19 @@
/**
* Routes outgoing GET requests for a given domain through the OpenRouter
* `web_fetch` tool instead of a direct network request.
*
* Configured via the `WEB_FETCH_ROUTES` property as a JSON array, e.g.
*
* [
* {
* "domain": "example.com",
* "responseContentType": "application/json"
* }
* ]
*
* Matches the domain itself and its subdomains (e.g. `api.example.com`).
*/
export interface WebFetchRoute {
domain: string;
responseContentType?: string;
}

2
apps/api/src/services/queues/statistics-gathering/statistics-gathering.module.ts

@ -1,4 +1,5 @@
import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module';
import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module';
import { PropertyModule } from '@ghostfolio/api/services/property/property.module'; import { PropertyModule } from '@ghostfolio/api/services/property/property.module';
import { STATISTICS_GATHERING_QUEUE } from '@ghostfolio/common/config'; import { STATISTICS_GATHERING_QUEUE } from '@ghostfolio/common/config';
@ -29,6 +30,7 @@ import { StatisticsGatheringService } from './statistics-gathering.service';
name: STATISTICS_GATHERING_QUEUE name: STATISTICS_GATHERING_QUEUE
}), }),
ConfigurationModule, ConfigurationModule,
FetchModule,
PropertyModule PropertyModule
], ],
providers: [StatisticsGatheringProcessor, StatisticsGatheringService] providers: [StatisticsGatheringProcessor, StatisticsGatheringService]

66
apps/api/src/services/queues/statistics-gathering/statistics-gathering.processor.ts

@ -1,4 +1,5 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service';
import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service';
import { PropertyService } from '@ghostfolio/api/services/property/property.service'; import { PropertyService } from '@ghostfolio/api/services/property/property.service';
import { import {
GATHER_STATISTICS_DOCKER_HUB_PULLS_PROCESS_JOB_NAME, GATHER_STATISTICS_DOCKER_HUB_PULLS_PROCESS_JOB_NAME,
@ -28,6 +29,7 @@ import { format, subDays } from 'date-fns';
export class StatisticsGatheringProcessor { export class StatisticsGatheringProcessor {
public constructor( public constructor(
private readonly configurationService: ConfigurationService, private readonly configurationService: ConfigurationService,
private readonly fetchService: FetchService,
private readonly propertyService: PropertyService private readonly propertyService: PropertyService
) {} ) {}
@ -126,15 +128,14 @@ export class StatisticsGatheringProcessor {
private async countDockerHubPulls(): Promise<number> { private async countDockerHubPulls(): Promise<number> {
try { try {
const { pull_count } = (await fetch( const { pull_count } = (await this.fetchService
'https://hub.docker.com/v2/repositories/ghostfolio/ghostfolio', .fetch('https://hub.docker.com/v2/repositories/ghostfolio/ghostfolio', {
{
headers: { 'User-Agent': 'request' }, headers: { 'User-Agent': 'request' },
signal: AbortSignal.timeout( signal: AbortSignal.timeout(
this.configurationService.get('REQUEST_TIMEOUT') this.configurationService.get('REQUEST_TIMEOUT')
) )
} })
).then((res) => res.json())) as { pull_count: number }; .then((res) => res.json())) as { pull_count: number };
return pull_count; return pull_count;
} catch (error) { } catch (error) {
@ -146,11 +147,13 @@ export class StatisticsGatheringProcessor {
private async countGitHubContributors(): Promise<number> { private async countGitHubContributors(): Promise<number> {
try { try {
const body = await fetch('https://github.com/ghostfolio/ghostfolio', { const body = await this.fetchService
signal: AbortSignal.timeout( .fetch('https://github.com/ghostfolio/ghostfolio', {
this.configurationService.get('REQUEST_TIMEOUT') signal: AbortSignal.timeout(
) this.configurationService.get('REQUEST_TIMEOUT')
}).then((res) => res.text()); )
})
.then((res) => res.text());
const $ = cheerio.load(body); const $ = cheerio.load(body);
@ -174,15 +177,14 @@ export class StatisticsGatheringProcessor {
private async countGitHubStargazers(): Promise<number> { private async countGitHubStargazers(): Promise<number> {
try { try {
const { stargazers_count } = (await fetch( const { stargazers_count } = (await this.fetchService
'https://api.github.com/repos/ghostfolio/ghostfolio', .fetch('https://api.github.com/repos/ghostfolio/ghostfolio', {
{
headers: { 'User-Agent': 'request' }, headers: { 'User-Agent': 'request' },
signal: AbortSignal.timeout( signal: AbortSignal.timeout(
this.configurationService.get('REQUEST_TIMEOUT') this.configurationService.get('REQUEST_TIMEOUT')
) )
} })
).then((res) => res.json())) as { stargazers_count: number }; .then((res) => res.json())) as { stargazers_count: number };
return stargazers_count; return stargazers_count;
} catch (error) { } catch (error) {
@ -194,22 +196,24 @@ export class StatisticsGatheringProcessor {
private async getUptime(monitorId: string): Promise<number> { private async getUptime(monitorId: string): Promise<number> {
try { try {
const { data } = await fetch( const { data } = await this.fetchService
`https://uptime.betterstack.com/api/v2/monitors/${monitorId}/sla?from=${format( .fetch(
subDays(new Date(), 90), `https://uptime.betterstack.com/api/v2/monitors/${monitorId}/sla?from=${format(
DATE_FORMAT subDays(new Date(), 90),
)}&to${format(new Date(), DATE_FORMAT)}`, DATE_FORMAT
{ )}&to${format(new Date(), DATE_FORMAT)}`,
headers: { {
[HEADER_KEY_TOKEN]: `Bearer ${this.configurationService.get( headers: {
'API_KEY_BETTER_UPTIME' [HEADER_KEY_TOKEN]: `Bearer ${this.configurationService.get(
)}` 'API_KEY_BETTER_UPTIME'
}, )}`
signal: AbortSignal.timeout( },
this.configurationService.get('REQUEST_TIMEOUT') signal: AbortSignal.timeout(
) this.configurationService.get('REQUEST_TIMEOUT')
} )
).then((res) => res.json()); }
)
.then((res) => res.json());
return data.attributes.availability / 100; return data.attributes.availability / 100;
} catch (error) { } catch (error) {

10
apps/client/src/app/components/admin-market-data/admin-market-data.component.ts

@ -4,7 +4,10 @@ import {
DEFAULT_PAGE_SIZE, DEFAULT_PAGE_SIZE,
locale locale
} from '@ghostfolio/common/config'; } from '@ghostfolio/common/config';
import { getDateFormatString } from '@ghostfolio/common/helper'; import {
canDeleteAssetProfile,
getDateFormatString
} from '@ghostfolio/common/helper';
import { import {
AssetProfileIdentifier, AssetProfileIdentifier,
Filter, Filter,
@ -15,6 +18,7 @@ import { AdminMarketDataItem } from '@ghostfolio/common/interfaces/admin-market-
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { GfSymbolPipe } from '@ghostfolio/common/pipes'; import { GfSymbolPipe } from '@ghostfolio/common/pipes';
import { GfActivitiesFilterComponent } from '@ghostfolio/ui/activities-filter'; import { GfActivitiesFilterComponent } from '@ghostfolio/ui/activities-filter';
import { GfFabComponent } from '@ghostfolio/ui/fab';
import { translate } from '@ghostfolio/ui/i18n'; import { translate } from '@ghostfolio/ui/i18n';
import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator'; import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator';
import { AdminService, DataService } from '@ghostfolio/ui/services'; import { AdminService, DataService } from '@ghostfolio/ui/services';
@ -77,10 +81,10 @@ import { CreateAssetProfileDialogParams } from './create-asset-profile-dialog/in
@Component({ @Component({
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'has-fab' },
imports: [ imports: [
CommonModule, CommonModule,
GfActivitiesFilterComponent, GfActivitiesFilterComponent,
GfFabComponent,
GfPremiumIndicatorComponent, GfPremiumIndicatorComponent,
GfSymbolPipe, GfSymbolPipe,
GfValueComponent, GfValueComponent,
@ -101,6 +105,7 @@ import { CreateAssetProfileDialogParams } from './create-asset-profile-dialog/in
}) })
export class GfAdminMarketDataComponent implements AfterViewInit, OnInit { export class GfAdminMarketDataComponent implements AfterViewInit, OnInit {
protected readonly adminMarketDataService = inject(AdminMarketDataService); protected readonly adminMarketDataService = inject(AdminMarketDataService);
protected readonly allFilters: Filter[] = [ protected readonly allFilters: Filter[] = [
...Object.keys(AssetSubClass) ...Object.keys(AssetSubClass)
.filter((assetSubClass) => { .filter((assetSubClass) => {
@ -146,6 +151,7 @@ export class GfAdminMarketDataComponent implements AfterViewInit, OnInit {
type: 'PRESET_ID' as Filter['type'] type: 'PRESET_ID' as Filter['type']
} }
]; ];
protected readonly canDeleteAssetProfile = canDeleteAssetProfile;
protected dataSource = new MatTableDataSource<AdminMarketDataItem>(); protected dataSource = new MatTableDataSource<AdminMarketDataItem>();
protected defaultDateFormat: string; protected defaultDateFormat: string;
protected readonly displayedColumns: string[] = []; protected readonly displayedColumns: string[] = [];

16
apps/client/src/app/components/admin-market-data/admin-market-data.html

@ -52,7 +52,7 @@
<th *matHeaderCellDef class="px-1" mat-header-cell></th> <th *matHeaderCellDef class="px-1" mat-header-cell></th>
<td *matCellDef="let element" class="px-1" mat-cell> <td *matCellDef="let element" class="px-1" mat-cell>
@if ( @if (
adminMarketDataService.hasPermissionToDeleteAssetProfile({ canDeleteAssetProfile({
activitiesCount: element.activitiesCount, activitiesCount: element.activitiesCount,
isBenchmark: element.isBenchmark, isBenchmark: element.isBenchmark,
symbol: element.symbol, symbol: element.symbol,
@ -271,7 +271,7 @@
<button <button
mat-menu-item mat-menu-item
[disabled]=" [disabled]="
!adminMarketDataService.hasPermissionToDeleteAssetProfile({ !canDeleteAssetProfile({
activitiesCount: element.activitiesCount, activitiesCount: element.activitiesCount,
isBenchmark: element.isBenchmark, isBenchmark: element.isBenchmark,
symbol: element.symbol symbol: element.symbol
@ -332,15 +332,5 @@
</div> </div>
</div> </div>
<div class="fab-container"> <gf-fab [queryParams]="{ createAssetProfileDialog: true }" />
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[queryParams]="{ createAssetProfileDialog: true }"
[routerLink]="[]"
>
<ion-icon name="add-outline" size="large" />
</a>
</div>
</div> </div>

30
apps/client/src/app/components/admin-market-data/admin-market-data.service.ts

@ -1,14 +1,5 @@
import { ghostfolioScraperApiSymbolPrefix } from '@ghostfolio/common/config';
import { ConfirmationDialogType } from '@ghostfolio/common/enums'; import { ConfirmationDialogType } from '@ghostfolio/common/enums';
import { import { AssetProfileIdentifier } from '@ghostfolio/common/interfaces';
getCurrencyFromSymbol,
isDerivedCurrency,
isRootCurrency
} from '@ghostfolio/common/helper';
import {
AssetProfileIdentifier,
AdminMarketDataItem
} from '@ghostfolio/common/interfaces';
import { NotificationService } from '@ghostfolio/ui/notifications'; import { NotificationService } from '@ghostfolio/ui/notifications';
import { AdminService } from '@ghostfolio/ui/services'; import { AdminService } from '@ghostfolio/ui/services';
@ -68,23 +59,4 @@ export class AdminMarketDataService {
title: $localize`Do you really want to delete these profiles?` title: $localize`Do you really want to delete these profiles?`
}); });
} }
public hasPermissionToDeleteAssetProfile({
activitiesCount,
isBenchmark,
symbol,
watchedByCount
}: Pick<
AdminMarketDataItem,
'activitiesCount' | 'isBenchmark' | 'symbol' | 'watchedByCount'
>) {
return (
activitiesCount === 0 &&
!isBenchmark &&
!isDerivedCurrency(getCurrencyFromSymbol(symbol)) &&
!isRootCurrency(getCurrencyFromSymbol(symbol)) &&
!symbol.startsWith(ghostfolioScraperApiSymbolPrefix) &&
watchedByCount === 0
);
}
} }

2
apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.component.ts

@ -6,6 +6,7 @@ import {
} from '@ghostfolio/common/config'; } from '@ghostfolio/common/config';
import { UpdateAssetProfileDto } from '@ghostfolio/common/dtos'; import { UpdateAssetProfileDto } from '@ghostfolio/common/dtos';
import { import {
canDeleteAssetProfile,
DATE_FORMAT, DATE_FORMAT,
getCurrencyFromSymbol, getCurrencyFromSymbol,
isCurrency isCurrency
@ -188,6 +189,7 @@ export class GfAssetProfileDialogComponent implements OnInit {
} }
); );
protected readonly canDeleteAssetProfile = canDeleteAssetProfile;
protected canEditAssetProfile = true; protected canEditAssetProfile = true;
protected countries: { protected countries: {

2
apps/client/src/app/components/admin-market-data/asset-profile-dialog/asset-profile-dialog.html

@ -70,7 +70,7 @@
mat-menu-item mat-menu-item
type="button" type="button"
[disabled]=" [disabled]="
!adminMarketDataService.hasPermissionToDeleteAssetProfile({ !canDeleteAssetProfile({
activitiesCount: assetProfile?.activitiesCount, activitiesCount: assetProfile?.activitiesCount,
isBenchmark: isBenchmark, isBenchmark: isBenchmark,
symbol: data.symbol, symbol: data.symbol,

10
apps/client/src/app/components/home-watchlist/home-watchlist.component.ts

@ -8,6 +8,7 @@ import {
} from '@ghostfolio/common/interfaces'; } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { GfBenchmarkComponent } from '@ghostfolio/ui/benchmark'; import { GfBenchmarkComponent } from '@ghostfolio/ui/benchmark';
import { GfFabComponent } from '@ghostfolio/ui/fab';
import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator'; import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator';
import { DataService } from '@ghostfolio/ui/services'; import { DataService } from '@ghostfolio/ui/services';
@ -22,12 +23,8 @@ import {
OnInit OnInit
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { IonIcon } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { addOutline } from 'ionicons/icons';
import { DeviceDetectorService } from 'ngx-device-detector'; import { DeviceDetectorService } from 'ngx-device-detector';
import { GfCreateWatchlistItemDialogComponent } from './create-watchlist-item-dialog/create-watchlist-item-dialog.component'; import { GfCreateWatchlistItemDialogComponent } from './create-watchlist-item-dialog/create-watchlist-item-dialog.component';
@ -37,9 +34,8 @@ import { CreateWatchlistItemDialogParams } from './create-watchlist-item-dialog/
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ imports: [
GfBenchmarkComponent, GfBenchmarkComponent,
GfFabComponent,
GfPremiumIndicatorComponent, GfPremiumIndicatorComponent,
IonIcon,
MatButtonModule,
RouterModule RouterModule
], ],
schemas: [CUSTOM_ELEMENTS_SCHEMA], schemas: [CUSTOM_ELEMENTS_SCHEMA],
@ -108,8 +104,6 @@ export class GfHomeWatchlistComponent implements OnInit {
this.changeDetectorRef.markForCheck(); this.changeDetectorRef.markForCheck();
} }
}); });
addIcons({ addOutline });
} }
public ngOnInit() { public ngOnInit() {

12
apps/client/src/app/components/home-watchlist/home-watchlist.html

@ -22,15 +22,5 @@
</div> </div>
</div> </div>
@if (!hasImpersonationId && hasPermissionToCreateWatchlistItem) { @if (!hasImpersonationId && hasPermissionToCreateWatchlistItem) {
<div class="fab-container"> <gf-fab [queryParams]="{ createWatchlistItemDialog: true }" />
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[queryParams]="{ createWatchlistItemDialog: true }"
[routerLink]="[]"
>
<ion-icon name="add-outline" size="large" />
</a>
</div>
} }

35
apps/client/src/app/components/user-account-access/create-or-update-access-dialog/create-or-update-access-dialog.component.ts

@ -29,6 +29,7 @@ import {
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select'; import { MatSelectModule } from '@angular/material/select';
import { AccessPermission } from '@prisma/client';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import { EMPTY, catchError } from 'rxjs'; import { EMPTY, catchError } from 'rxjs';
@ -52,7 +53,7 @@ import { CreateOrUpdateAccessDialogParams } from './interfaces/interfaces';
}) })
export class GfCreateOrUpdateAccessDialogComponent implements OnInit { export class GfCreateOrUpdateAccessDialogComponent implements OnInit {
protected accessForm: FormGroup; protected accessForm: FormGroup;
protected mode: 'create' | 'update'; protected readonly mode: 'create' | 'update';
private readonly changeDetectorRef = inject(ChangeDetectorRef); private readonly changeDetectorRef = inject(ChangeDetectorRef);
@ -69,21 +70,25 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnInit {
private readonly notificationService = inject(NotificationService); private readonly notificationService = inject(NotificationService);
public constructor() { public constructor() {
this.mode = this.data.access?.id ? 'update' : 'create'; this.mode = this.data.access ? 'update' : 'create';
} }
public ngOnInit() { public ngOnInit() {
const isPublic = this.data.access.type === 'PUBLIC'; const access = this.data?.access;
const isPublic = access?.type === 'PUBLIC';
this.accessForm = this.formBuilder.group({ this.accessForm = this.formBuilder.group({
alias: [this.data.access.alias], alias: [access?.alias ?? ''],
granteeUserId: [ granteeUserId: [
this.data.access.grantee, access?.grantee ?? null,
isPublic ? null : Validators.required isPublic ? null : Validators.required
], ],
permissions: [this.data.access.permissions[0], Validators.required], permissions: [
access?.permissions[0] ?? AccessPermission.READ_RESTRICTED,
Validators.required
],
type: [ type: [
{ disabled: this.mode === 'update', value: this.data.access.type }, { disabled: this.mode === 'update', value: access?.type ?? 'PRIVATE' },
Validators.required Validators.required
] ]
}); });
@ -100,7 +105,9 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnInit {
} else { } else {
granteeUserIdControl?.clearValidators(); granteeUserIdControl?.clearValidators();
granteeUserIdControl?.setValue(null); granteeUserIdControl?.setValue(null);
permissionsControl?.setValue(this.data.access.permissions[0]); permissionsControl?.setValue(
access?.permissions[0] ?? AccessPermission.READ_RESTRICTED
);
} }
granteeUserIdControl?.updateValueAndValidity(); granteeUserIdControl?.updateValueAndValidity();
@ -109,11 +116,11 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnInit {
}); });
} }
public onCancel() { protected onCancel() {
this.dialogRef.close(); this.dialogRef.close();
} }
public async onSubmit() { protected async onSubmit() {
if (this.mode === 'create') { if (this.mode === 'create') {
await this.createAccess(); await this.createAccess();
} else { } else {
@ -158,10 +165,16 @@ export class GfCreateOrUpdateAccessDialogComponent implements OnInit {
} }
private async updateAccess() { private async updateAccess() {
const accessId = this.data.access?.id;
if (!accessId) {
return;
}
const access: UpdateAccessDto = { const access: UpdateAccessDto = {
alias: this.accessForm.get('alias')?.value, alias: this.accessForm.get('alias')?.value,
granteeUserId: this.accessForm.get('granteeUserId')?.value, granteeUserId: this.accessForm.get('granteeUserId')?.value,
id: this.data.access.id, id: accessId,
permissions: [this.accessForm.get('permissions')?.value] permissions: [this.accessForm.get('permissions')?.value]
}; };

2
apps/client/src/app/components/user-account-access/create-or-update-access-dialog/interfaces/interfaces.ts

@ -1,5 +1,5 @@
import { Access } from '@ghostfolio/common/interfaces'; import { Access } from '@ghostfolio/common/interfaces';
export interface CreateOrUpdateAccessDialogParams { export interface CreateOrUpdateAccessDialogParams {
access: Access; access?: Access;
} }

96
apps/client/src/app/components/user-account-access/user-account-access.component.ts

@ -4,6 +4,7 @@ import { CreateAccessDto } from '@ghostfolio/common/dtos';
import { ConfirmationDialogType } from '@ghostfolio/common/enums'; import { ConfirmationDialogType } from '@ghostfolio/common/enums';
import { Access, User } from '@ghostfolio/common/interfaces'; import { Access, User } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { GfFabComponent } from '@ghostfolio/ui/fab';
import { NotificationService } from '@ghostfolio/ui/notifications'; import { NotificationService } from '@ghostfolio/ui/notifications';
import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator'; import { GfPremiumIndicatorComponent } from '@ghostfolio/ui/premium-indicator';
import { DataService } from '@ghostfolio/ui/services'; import { DataService } from '@ghostfolio/ui/services';
@ -12,12 +13,19 @@ import {
ChangeDetectionStrategy, ChangeDetectionStrategy,
ChangeDetectorRef, ChangeDetectorRef,
Component, Component,
computed,
CUSTOM_ELEMENTS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA,
DestroyRef, DestroyRef,
inject,
OnInit OnInit
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms'; import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators
} from '@angular/forms';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
@ -35,9 +43,9 @@ import { CreateOrUpdateAccessDialogParams } from './create-or-update-access-dial
@Component({ @Component({
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'has-fab' },
imports: [ imports: [
GfAccessTableComponent, GfAccessTableComponent,
GfFabComponent,
GfPremiumIndicatorComponent, GfPremiumIndicatorComponent,
IonIcon, IonIcon,
MatButtonModule, MatButtonModule,
@ -53,30 +61,35 @@ import { CreateOrUpdateAccessDialogParams } from './create-or-update-access-dial
templateUrl: './user-account-access.html' templateUrl: './user-account-access.html'
}) })
export class GfUserAccountAccessComponent implements OnInit { export class GfUserAccountAccessComponent implements OnInit {
public accessesGet: Access[]; protected accessesGet: Access[];
public accessesGive: Access[]; protected accessesGive: Access[];
public deviceType: string; protected hasPermissionToCreateAccess: boolean;
public hasPermissionToCreateAccess: boolean; protected hasPermissionToDeleteAccess: boolean;
public hasPermissionToDeleteAccess: boolean; protected hasPermissionToUpdateOwnAccessToken: boolean;
public hasPermissionToUpdateOwnAccessToken: boolean; protected isAccessTokenHidden = true;
public isAccessTokenHidden = true; protected readonly updateOwnAccessTokenForm = new FormGroup({
public updateOwnAccessTokenForm = this.formBuilder.group({ accessToken: new FormControl<string>('', {
accessToken: ['', Validators.required] nonNullable: true,
validators: [Validators.required]
})
}); });
public user: User; protected user: User;
private readonly deviceType = computed(
() => this.deviceDetectorService.deviceInfo().deviceType
);
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 notificationService = inject(NotificationService);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly userService = inject(UserService);
public constructor( public constructor() {
private changeDetectorRef: ChangeDetectorRef,
private dataService: DataService,
private destroyRef: DestroyRef,
private deviceDetectorService: DeviceDetectorService,
private dialog: MatDialog,
private formBuilder: FormBuilder,
private notificationService: NotificationService,
private route: ActivatedRoute,
private router: Router,
private userService: UserService
) {
const { globalPermissions } = this.dataService.fetchInfo(); const { globalPermissions } = this.dataService.fetchInfo();
this.hasPermissionToDeleteAccess = hasPermission( this.hasPermissionToDeleteAccess = hasPermission(
@ -123,12 +136,10 @@ export class GfUserAccountAccessComponent implements OnInit {
} }
public ngOnInit() { public ngOnInit() {
this.deviceType = this.deviceDetectorService.getDeviceInfo().deviceType;
this.update(); this.update();
} }
public onDeleteAccess(aId: string) { protected onDeleteAccess(aId: string) {
this.dataService this.dataService
.deleteAccess(aId) .deleteAccess(aId)
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
@ -139,12 +150,13 @@ export class GfUserAccountAccessComponent implements OnInit {
}); });
} }
public onGenerateAccessToken() { protected onGenerateAccessToken() {
this.notificationService.confirm({ this.notificationService.confirm({
confirmFn: () => { confirmFn: () => {
this.dataService this.dataService
.updateOwnAccessToken({ .updateOwnAccessToken({
accessToken: this.updateOwnAccessTokenForm.get('accessToken').value accessToken:
this.updateOwnAccessTokenForm.controls.accessToken.value
}) })
.pipe( .pipe(
catchError(() => { catchError(() => {
@ -173,7 +185,7 @@ export class GfUserAccountAccessComponent implements OnInit {
}); });
} }
public onUpdateAccess(aId: string) { protected onUpdateAccess(aId: string) {
this.router.navigate([], { this.router.navigate([], {
queryParams: { accessId: aId, editDialog: true } queryParams: { accessId: aId, editDialog: true }
}); });
@ -184,17 +196,9 @@ export class GfUserAccountAccessComponent implements OnInit {
GfCreateOrUpdateAccessDialogComponent, GfCreateOrUpdateAccessDialogComponent,
CreateOrUpdateAccessDialogParams CreateOrUpdateAccessDialogParams
>(GfCreateOrUpdateAccessDialogComponent, { >(GfCreateOrUpdateAccessDialogComponent, {
data: { data: {} satisfies CreateOrUpdateAccessDialogParams,
access: { height: this.deviceType() === 'mobile' ? '98vh' : undefined,
alias: '', width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
grantee: null,
id: null,
permissions: ['READ_RESTRICTED'],
type: 'PRIVATE'
}
},
height: this.deviceType === 'mobile' ? '98vh' : undefined,
width: this.deviceType === 'mobile' ? '100vw' : '50rem'
}); });
dialogRef.afterClosed().subscribe((access: CreateAccessDto | null) => { dialogRef.afterClosed().subscribe((access: CreateAccessDto | null) => {
@ -222,14 +226,14 @@ export class GfUserAccountAccessComponent implements OnInit {
data: { data: {
access: { access: {
alias: access.alias, alias: access.alias,
grantee: access.grantee === 'Public' ? null : access.grantee, grantee: access.grantee === 'Public' ? undefined : access.grantee,
id: access.id, id: access.id,
permissions: access.permissions, permissions: access.permissions,
type: access.type type: access.type
} }
}, } satisfies CreateOrUpdateAccessDialogParams,
height: this.deviceType === 'mobile' ? '98vh' : undefined, height: this.deviceType() === 'mobile' ? '98vh' : undefined,
width: this.deviceType === 'mobile' ? '100vw' : '50rem' width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
}); });
dialogRef.afterClosed().subscribe((result) => { dialogRef.afterClosed().subscribe((result) => {
@ -244,9 +248,9 @@ export class GfUserAccountAccessComponent implements OnInit {
private update() { private update() {
this.accessesGet = this.user.access.map(({ alias, id, permissions }) => { this.accessesGet = this.user.access.map(({ alias, id, permissions }) => {
return { return {
alias,
id, id,
permissions, permissions,
alias: alias ?? '',
grantee: $localize`Me`, grantee: $localize`Me`,
type: 'PRIVATE' type: 'PRIVATE'
}; };

12
apps/client/src/app/components/user-account-access/user-account-access.html

@ -69,16 +69,6 @@
(accessToUpdate)="onUpdateAccess($event)" (accessToUpdate)="onUpdateAccess($event)"
/> />
@if (hasPermissionToCreateAccess) { @if (hasPermissionToCreateAccess) {
<div class="fab-container"> <gf-fab [queryParams]="{ createDialog: true }" />
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[queryParams]="{ createDialog: true }"
[routerLink]="[]"
>
<ion-icon name="add-outline" size="large" />
</a>
</div>
} }
</div> </div>

12
apps/client/src/app/core/auth.guard.ts

@ -3,7 +3,7 @@ import { UserService } from '@ghostfolio/client/services/user/user.service';
import { internalRoutes, publicRoutes } from '@ghostfolio/common/routes/routes'; import { internalRoutes, publicRoutes } from '@ghostfolio/common/routes/routes';
import { DataService } from '@ghostfolio/ui/services'; import { DataService } from '@ghostfolio/ui/services';
import { Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { import {
ActivatedRouteSnapshot, ActivatedRouteSnapshot,
Router, Router,
@ -14,12 +14,10 @@ import { catchError } from 'rxjs/operators';
@Injectable({ providedIn: 'root' }) @Injectable({ providedIn: 'root' })
export class AuthGuard { export class AuthGuard {
public constructor( private readonly dataService = inject(DataService);
private dataService: DataService, private readonly router = inject(Router);
private router: Router, private readonly settingsStorageService = inject(SettingsStorageService);
private settingsStorageService: SettingsStorageService, private readonly userService = inject(UserService);
private userService: UserService
) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const utmSource = route.queryParams?.utm_source; const utmSource = route.queryParams?.utm_source;

16
apps/client/src/app/core/auth.interceptor.ts

@ -13,20 +13,20 @@ import {
HttpInterceptor, HttpInterceptor,
HttpRequest HttpRequest
} from '@angular/common/http'; } from '@angular/common/http';
import { Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
@Injectable() @Injectable()
export class AuthInterceptor implements HttpInterceptor { export class AuthInterceptor implements HttpInterceptor {
public constructor( private readonly impersonationStorageService = inject(
private impersonationStorageService: ImpersonationStorageService, ImpersonationStorageService
private tokenStorageService: TokenStorageService );
) {} private readonly tokenStorageService = inject(TokenStorageService);
public intercept( public intercept<T>(
req: HttpRequest<any>, req: HttpRequest<T>,
next: HttpHandler next: HttpHandler
): Observable<HttpEvent<any>> { ): Observable<HttpEvent<T>> {
let request = req; let request = req;
if (request.headers.has(HEADER_KEY_SKIP_INTERCEPTOR)) { if (request.headers.has(HEADER_KEY_SKIP_INTERCEPTOR)) {

45
apps/client/src/app/core/http-response.interceptor.ts

@ -12,7 +12,7 @@ import {
HttpInterceptor, HttpInterceptor,
HttpRequest HttpRequest
} from '@angular/common/http'; } from '@angular/common/http';
import { Injectable } from '@angular/core'; import { inject, Injectable } from '@angular/core';
import { import {
MatSnackBar, MatSnackBar,
MatSnackBarRef, MatSnackBarRef,
@ -22,31 +22,28 @@ import { Router } from '@angular/router';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import ms from 'ms'; import ms from 'ms';
import { Observable, throwError } from 'rxjs'; import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators'; import { catchError } from 'rxjs/operators';
@Injectable() @Injectable()
export class HttpResponseInterceptor implements HttpInterceptor { export class HttpResponseInterceptor implements HttpInterceptor {
public info: InfoItem; private readonly info: InfoItem;
public snackBarRef: MatSnackBarRef<TextOnlySnackBar>; private snackBarRef: MatSnackBarRef<TextOnlySnackBar> | undefined;
public constructor( private readonly dataService = inject(DataService);
private dataService: DataService, private readonly router = inject(Router);
private router: Router, private readonly snackBar = inject(MatSnackBar);
private snackBar: MatSnackBar, private readonly userService = inject(UserService);
private userService: UserService, private readonly webAuthnService = inject(WebAuthnService);
private webAuthnService: WebAuthnService
) { public constructor() {
this.info = this.dataService.fetchInfo(); this.info = this.dataService.fetchInfo();
} }
public intercept( public intercept<T>(
request: HttpRequest<any>, request: HttpRequest<T>,
next: HttpHandler next: HttpHandler
): Observable<HttpEvent<any>> { ): Observable<HttpEvent<T>> {
return next.handle(request).pipe( return next.handle(request).pipe(
tap((event: HttpEvent<any>) => {
return event;
}),
catchError((error: HttpErrorResponse) => { catchError((error: HttpErrorResponse) => {
if (error.status === StatusCodes.FORBIDDEN) { if (error.status === StatusCodes.FORBIDDEN) {
if (!this.snackBarRef) { if (!this.snackBarRef) {
@ -61,7 +58,7 @@ export class HttpResponseInterceptor implements HttpInterceptor {
} }
); );
} else if ( } else if (
!error.url.includes(internalRoutes.auth.routerLink.join('')) !error.url?.includes(internalRoutes.auth.routerLink.join(''))
) { ) {
this.snackBarRef = this.snackBar.open( this.snackBarRef = this.snackBar.open(
$localize`This action is not allowed.`, $localize`This action is not allowed.`,
@ -72,11 +69,11 @@ export class HttpResponseInterceptor implements HttpInterceptor {
); );
} }
this.snackBarRef.afterDismissed().subscribe(() => { this.snackBarRef?.afterDismissed().subscribe(() => {
this.snackBarRef = undefined; this.snackBarRef = undefined;
}); });
this.snackBarRef.onAction().subscribe(() => { this.snackBarRef?.onAction().subscribe(() => {
this.router.navigate(publicRoutes.pricing.routerLink); this.router.navigate(publicRoutes.pricing.routerLink);
}); });
} }
@ -92,11 +89,11 @@ export class HttpResponseInterceptor implements HttpInterceptor {
} }
); );
this.snackBarRef.afterDismissed().subscribe(() => { this.snackBarRef?.afterDismissed().subscribe(() => {
this.snackBarRef = undefined; this.snackBarRef = undefined;
}); });
this.snackBarRef.onAction().subscribe(() => { this.snackBarRef?.onAction().subscribe(() => {
window.location.reload(); window.location.reload();
}); });
} }
@ -106,12 +103,12 @@ export class HttpResponseInterceptor implements HttpInterceptor {
$localize`Oops! It looks like you’re making too many requests. Please slow down a bit.` $localize`Oops! It looks like you’re making too many requests. Please slow down a bit.`
); );
this.snackBarRef.afterDismissed().subscribe(() => { this.snackBarRef?.afterDismissed().subscribe(() => {
this.snackBarRef = undefined; this.snackBarRef = undefined;
}); });
} }
} else if (error.status === StatusCodes.UNAUTHORIZED) { } else if (error.status === StatusCodes.UNAUTHORIZED) {
if (!error.url.includes('/data-providers/ghostfolio/status')) { if (!error.url?.includes('/data-providers/ghostfolio/status')) {
if (this.webAuthnService.isEnabled()) { if (this.webAuthnService.isEnabled()) {
this.router.navigate(internalRoutes.webauthn.routerLink); this.router.navigate(internalRoutes.webauthn.routerLink);
} else { } else {

24
apps/client/src/app/directives/file-drop/file-drop.directive.ts

@ -1,28 +1,34 @@
import { Directive, EventEmitter, HostListener, Output } from '@angular/core'; import { Directive, output } from '@angular/core';
@Directive({ @Directive({
host: {
'(dragenter)': 'onDragEnter($event)',
'(dragover)': 'onDragOver($event)',
'(drop)': 'onDrop($event)'
},
selector: '[gfFileDrop]' selector: '[gfFileDrop]'
}) })
export class GfFileDropDirective { export class GfFileDropDirective {
@Output() filesDropped = new EventEmitter<FileList>(); public readonly filesDropped = output<FileList>();
@HostListener('dragenter', ['$event']) onDragEnter(event: DragEvent) { public onDragEnter(event: DragEvent) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
} }
@HostListener('dragover', ['$event']) onDragOver(event: DragEvent) { public onDragOver(event: DragEvent) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
} }
@HostListener('drop', ['$event']) onDrop(event: DragEvent) { public onDrop(event: DragEvent) {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
// Prevent the browser's default behavior for handling the file drop if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'copy'; // Prevent the browser's default behavior for handling the file drop
event.dataTransfer.dropEffect = 'copy';
this.filesDropped.emit(event.dataTransfer.files); this.filesDropped.emit(event.dataTransfer.files);
}
} }
} }

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

@ -10,6 +10,7 @@ import {
import { User } from '@ghostfolio/common/interfaces'; import { User } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { GfAccountsTableComponent } from '@ghostfolio/ui/accounts-table'; import { GfAccountsTableComponent } from '@ghostfolio/ui/accounts-table';
import { GfFabComponent } from '@ghostfolio/ui/fab';
import { NotificationService } from '@ghostfolio/ui/notifications'; import { NotificationService } from '@ghostfolio/ui/notifications';
import { DataService } from '@ghostfolio/ui/services'; import { DataService } from '@ghostfolio/ui/services';
@ -20,12 +21,9 @@ import {
OnInit OnInit
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { Account as AccountModel } from '@prisma/client'; import { Account as AccountModel } from '@prisma/client';
import { addIcons } from 'ionicons';
import { addOutline } from 'ionicons/icons';
import { DeviceDetectorService } from 'ngx-device-detector'; import { DeviceDetectorService } from 'ngx-device-detector';
import { EMPTY, Subscription } from 'rxjs'; import { EMPTY, Subscription } from 'rxjs';
import { catchError } from 'rxjs/operators'; import { catchError } from 'rxjs/operators';
@ -36,8 +34,8 @@ import { TransferBalanceDialogParams } from './transfer-balance/interfaces/inter
import { GfTransferBalanceDialogComponent } from './transfer-balance/transfer-balance-dialog.component'; import { GfTransferBalanceDialogComponent } from './transfer-balance/transfer-balance-dialog.component';
@Component({ @Component({
host: { class: 'has-fab page' }, host: { class: 'page' },
imports: [GfAccountsTableComponent, MatButtonModule, RouterModule], imports: [GfAccountsTableComponent, GfFabComponent, RouterModule],
selector: 'gf-accounts-page', selector: 'gf-accounts-page',
styleUrls: ['./accounts-page.scss'], styleUrls: ['./accounts-page.scss'],
templateUrl: './accounts-page.html' templateUrl: './accounts-page.html'
@ -90,8 +88,6 @@ export class GfAccountsPageComponent implements OnInit {
this.openTransferBalanceDialog(); this.openTransferBalanceDialog();
} }
}); });
addIcons({ addOutline });
} }
public ngOnInit() { public ngOnInit() {

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

@ -26,16 +26,6 @@
hasPermissionToCreateAccount && hasPermissionToCreateAccount &&
!user.settings.isRestrictedView !user.settings.isRestrictedView
) { ) {
<div class="fab-container"> <gf-fab [queryParams]="{ createDialog: true }" />
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[queryParams]="{ createDialog: true }"
[routerLink]="[]"
>
<ion-icon name="add-outline" size="large" />
</a>
</div>
} }
</div> </div>

11
apps/client/src/app/pages/portfolio/activities/activities-page.component.ts

@ -12,6 +12,7 @@ import {
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { DateRange } from '@ghostfolio/common/types'; import { DateRange } from '@ghostfolio/common/types';
import { GfActivitiesTableComponent } from '@ghostfolio/ui/activities-table'; import { GfActivitiesTableComponent } from '@ghostfolio/ui/activities-table';
import { GfFabComponent } from '@ghostfolio/ui/fab';
import { DataService } from '@ghostfolio/ui/services'; import { DataService } from '@ghostfolio/ui/services';
import { import {
@ -21,17 +22,13 @@ import {
OnInit OnInit
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { PageEvent } from '@angular/material/paginator'; import { PageEvent } from '@angular/material/paginator';
import { MatSnackBarModule } from '@angular/material/snack-bar'; import { MatSnackBarModule } from '@angular/material/snack-bar';
import { Sort, SortDirection } from '@angular/material/sort'; import { Sort, SortDirection } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table'; import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { IonIcon } from '@ionic/angular/standalone';
import { format, parseISO } from 'date-fns'; import { format, parseISO } from 'date-fns';
import { addIcons } from 'ionicons';
import { addOutline } from 'ionicons/icons';
import { DeviceDetectorService } from 'ngx-device-detector'; import { DeviceDetectorService } from 'ngx-device-detector';
import { Subscription } from 'rxjs'; import { Subscription } from 'rxjs';
@ -41,11 +38,9 @@ import { GfImportActivitiesDialogComponent } from './import-activities-dialog/im
import { ImportActivitiesDialogParams } from './import-activities-dialog/interfaces/interfaces'; import { ImportActivitiesDialogParams } from './import-activities-dialog/interfaces/interfaces';
@Component({ @Component({
host: { class: 'has-fab' },
imports: [ imports: [
GfActivitiesTableComponent, GfActivitiesTableComponent,
IonIcon, GfFabComponent,
MatButtonModule,
MatSnackBarModule, MatSnackBarModule,
RouterModule RouterModule
], ],
@ -107,8 +102,6 @@ export class GfActivitiesPageComponent implements OnInit {
} }
} }
}); });
addIcons({ addOutline });
} }
public ngOnInit() { public ngOnInit() {

12
apps/client/src/app/pages/portfolio/activities/activities-page.html

@ -43,16 +43,6 @@
hasPermissionToCreateActivity && hasPermissionToCreateActivity &&
!user.settings.isRestrictedView !user.settings.isRestrictedView
) { ) {
<div class="fab-container"> <gf-fab [queryParams]="{ createDialog: true }" />
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[queryParams]="{ createDialog: true }"
[routerLink]="[]"
>
<ion-icon name="add-outline" size="large" />
</a>
</div>
} }
</div> </div>

2
apps/client/src/app/pages/portfolio/activities/create-or-update-activity-dialog/create-or-update-activity-dialog.component.ts

@ -139,7 +139,7 @@ export class GfCreateOrUpdateActivityDialogComponent {
return !['CASH'].includes(assetProfile.assetSubClass); return !['CASH'].includes(assetProfile.assetSubClass);
}) })
.sort((a, b) => { .sort((a, b) => {
return a.name?.localeCompare(b.name); return a.assetProfile.name?.localeCompare(b.assetProfile.name);
}) })
.map(({ assetProfile }) => { .map(({ assetProfile }) => {
return { return {

3
apps/client/src/app/pages/portfolio/activities/import-activities-dialog/import-activities-dialog.component.ts

@ -226,7 +226,8 @@ export class GfImportActivitiesDialogComponent {
this.assetProfileForm.controls.assetProfileIdentifier.disable(); this.assetProfileForm.controls.assetProfileIdentifier.disable();
const { dataSource, symbol } = const { dataSource, symbol } =
this.assetProfileForm.controls.assetProfileIdentifier.value ?? {}; this.assetProfileForm.controls.assetProfileIdentifier.value
?.assetProfile ?? {};
if (!dataSource || !symbol) { if (!dataSource || !symbol) {
return; return;

50
apps/client/src/app/pages/portfolio/allocations/allocations-page.component.ts

@ -73,15 +73,14 @@ export class GfAllocationsPageComponent implements OnInit {
public hasImpersonationId: boolean; public hasImpersonationId: boolean;
public holdings: { public holdings: {
[symbol: string]: Pick< [symbol: string]: Pick<
PortfolioPosition, PortfolioPosition['assetProfile'],
| 'assetClass' | 'assetClass'
| 'assetClassLabel' | 'assetClassLabel'
| 'assetSubClass' | 'assetSubClass'
| 'assetSubClassLabel' | 'assetSubClassLabel'
| 'currency' | 'currency'
| 'exchange'
| 'name' | 'name'
> & { etfProvider: string; value: number }; > & { etfProvider: string; exchange?: string; value: number };
}; };
public isLoading = false; public isLoading = false;
public markets: { public markets: {
@ -206,7 +205,7 @@ export class GfAllocationsPageComponent implements OnInit {
assetSubClass, assetSubClass,
name name
}: { }: {
assetSubClass: PortfolioPosition['assetSubClass']; assetSubClass: PortfolioPosition['assetProfile']['assetSubClass'];
name: string; name: string;
}) { }) {
if (assetSubClass === 'ETF') { if (assetSubClass === 'ETF') {
@ -333,24 +332,27 @@ export class GfAllocationsPageComponent implements OnInit {
this.holdings[symbol] = { this.holdings[symbol] = {
value, value,
assetClass: position.assetClass || (UNKNOWN_KEY as AssetClass), assetClass:
assetClassLabel: position.assetClassLabel || UNKNOWN_KEY, position.assetProfile.assetClass || (UNKNOWN_KEY as AssetClass),
assetSubClass: position.assetSubClass || (UNKNOWN_KEY as AssetSubClass), assetClassLabel: position.assetProfile.assetClassLabel || UNKNOWN_KEY,
assetSubClassLabel: position.assetSubClassLabel || UNKNOWN_KEY, assetSubClass:
currency: position.currency, position.assetProfile.assetSubClass || (UNKNOWN_KEY as AssetSubClass),
assetSubClassLabel:
position.assetProfile.assetSubClassLabel || UNKNOWN_KEY,
currency: position.assetProfile.currency,
etfProvider: this.extractEtfProvider({ etfProvider: this.extractEtfProvider({
assetSubClass: position.assetSubClass, assetSubClass: position.assetProfile.assetSubClass,
name: position.name name: position.assetProfile.name
}), }),
exchange: position.exchange, exchange: position.exchange,
name: position.name name: position.assetProfile.name
}; };
if (position.assetClass !== AssetClass.LIQUIDITY) { if (position.assetProfile.assetClass !== AssetClass.LIQUIDITY) {
// Prepare analysis data by continents, countries, holdings and sectors except for liquidity // Prepare analysis data by continents, countries, holdings and sectors except for liquidity
if (position.countries.length > 0) { if (position.assetProfile.countries.length > 0) {
for (const country of position.countries) { for (const country of position.assetProfile.countries) {
const { code, continent, name, weight } = country; const { code, continent, name, weight } = country;
if (this.continents[continent]?.value) { if (this.continents[continent]?.value) {
@ -401,12 +403,12 @@ export class GfAllocationsPageComponent implements OnInit {
: this.portfolioDetails.holdings[symbol].valueInPercentage; : this.portfolioDetails.holdings[symbol].valueInPercentage;
} }
if (position.holdings.length > 0) { if (position.assetProfile.holdings.length > 0) {
for (const { for (const {
allocationInPercentage, allocationInPercentage,
name, name,
valueInBaseCurrency valueInBaseCurrency
} of position.holdings) { } of position.assetProfile.holdings) {
const normalizedAssetName = this.normalizeAssetName(name); const normalizedAssetName = this.normalizeAssetName(name);
if (this.topHoldingsMap[normalizedAssetName]?.value) { if (this.topHoldingsMap[normalizedAssetName]?.value) {
@ -428,8 +430,8 @@ export class GfAllocationsPageComponent implements OnInit {
} }
} }
if (position.sectors.length > 0) { if (position.assetProfile.sectors.length > 0) {
for (const sector of position.sectors) { for (const sector of position.assetProfile.sectors) {
const { name, weight } = sector; const { name, weight } = sector;
if (this.sectors[name]?.value) { if (this.sectors[name]?.value) {
@ -463,8 +465,8 @@ export class GfAllocationsPageComponent implements OnInit {
} }
this.symbols[prettifySymbol(symbol)] = { this.symbols[prettifySymbol(symbol)] = {
dataSource: position.dataSource, dataSource: position.assetProfile.dataSource,
name: position.name, name: position.assetProfile.name,
symbol: prettifySymbol(symbol), symbol: prettifySymbol(symbol),
value: isNumber(position.valueInBaseCurrency) value: isNumber(position.valueInBaseCurrency)
? position.valueInBaseCurrency ? position.valueInBaseCurrency
@ -517,8 +519,8 @@ export class GfAllocationsPageComponent implements OnInit {
this.totalValueInEtf > 0 ? value / this.totalValueInEtf : 0, this.totalValueInEtf > 0 ? value / this.totalValueInEtf : 0,
parents: Object.entries(this.portfolioDetails.holdings) parents: Object.entries(this.portfolioDetails.holdings)
.map(([symbol, holding]) => { .map(([symbol, holding]) => {
if (holding.holdings.length > 0) { if (holding.assetProfile.holdings.length > 0) {
const currentParentHolding = holding.holdings.find( const currentParentHolding = holding.assetProfile.holdings.find(
(parentHolding) => { (parentHolding) => {
return ( return (
this.normalizeAssetName(parentHolding.name) === this.normalizeAssetName(parentHolding.name) ===
@ -531,7 +533,7 @@ export class GfAllocationsPageComponent implements OnInit {
? { ? {
allocationInPercentage: allocationInPercentage:
currentParentHolding.valueInBaseCurrency / value, currentParentHolding.valueInBaseCurrency / value,
name: holding.name, name: holding.assetProfile.name,
position: holding, position: holding,
symbol: prettifySymbol(symbol), symbol: prettifySymbol(symbol),
valueInBaseCurrency: valueInBaseCurrency:

153
apps/client/src/app/pages/portfolio/analysis/analysis-page.component.ts

@ -2,7 +2,10 @@ import { GfBenchmarkComparatorComponent } from '@ghostfolio/client/components/be
import { GfInvestmentChartComponent } from '@ghostfolio/client/components/investment-chart/investment-chart.component'; import { GfInvestmentChartComponent } from '@ghostfolio/client/components/investment-chart/investment-chart.component';
import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service'; import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service';
import { UserService } from '@ghostfolio/client/services/user/user.service'; import { UserService } from '@ghostfolio/client/services/user/user.service';
import { NUMERICAL_PRECISION_THRESHOLD_6_FIGURES } from '@ghostfolio/common/config'; import {
DEFAULT_DATE_RANGE,
NUMERICAL_PRECISION_THRESHOLD_6_FIGURES
} from '@ghostfolio/common/config';
import { import {
HistoricalDataItem, HistoricalDataItem,
InvestmentItem, InvestmentItem,
@ -24,9 +27,12 @@ import { Clipboard } from '@angular/cdk/clipboard';
import { import {
ChangeDetectorRef, ChangeDetectorRef,
Component, Component,
computed,
DestroyRef, DestroyRef,
inject,
OnInit, OnInit,
ViewChild signal,
viewChild
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
@ -64,53 +70,57 @@ import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
templateUrl: './analysis-page.html' templateUrl: './analysis-page.html'
}) })
export class GfAnalysisPageComponent implements OnInit { export class GfAnalysisPageComponent implements OnInit {
@ViewChild(MatMenuTrigger) actionsMenuButton!: MatMenuTrigger; protected benchmark?: Partial<SymbolProfile>;
protected benchmarkDataItems: HistoricalDataItem[] = [];
public benchmark: Partial<SymbolProfile>; protected readonly benchmarks: Partial<SymbolProfile>[];
public benchmarkDataItems: HistoricalDataItem[] = []; protected bottom3: PortfolioPosition[];
public benchmarks: Partial<SymbolProfile>[]; protected dividendsByGroup: InvestmentItem[];
public bottom3: PortfolioPosition[]; protected readonly dividendTimelineDataLabel = $localize`Dividend`;
public deviceType: string; protected hasImpersonationId: boolean;
public dividendsByGroup: InvestmentItem[]; protected hasPermissionToReadAiPrompt: boolean;
public dividendTimelineDataLabel = $localize`Dividend`; protected investments: InvestmentItem[];
public firstOrderDate: Date; protected readonly investmentTimelineDataLabel = $localize`Investment`;
public hasImpersonationId: boolean; protected investmentsByGroup: InvestmentItem[];
public hasPermissionToReadAiPrompt: boolean; protected isLoadingAnalysisPrompt: boolean;
public investments: InvestmentItem[]; protected isLoadingBenchmarkComparator: boolean;
public investmentTimelineDataLabel = $localize`Investment`; protected isLoadingDividendTimelineChart: boolean;
public investmentsByGroup: InvestmentItem[]; protected isLoadingInvestmentChart: boolean;
public isLoadingAnalysisPrompt: boolean; protected isLoadingInvestmentTimelineChart: boolean;
public isLoadingBenchmarkComparator: boolean; protected isLoadingPortfolioPrompt: boolean;
public isLoadingDividendTimelineChart: boolean; protected readonly mode = signal<GroupBy>('month');
public isLoadingInvestmentChart: boolean; protected readonly modeOptions: ToggleOption[] = [
public isLoadingInvestmentTimelineChart: boolean;
public isLoadingPortfolioPrompt: boolean;
public mode: GroupBy = 'month';
public modeOptions: ToggleOption[] = [
{ label: $localize`Monthly`, value: 'month' }, { label: $localize`Monthly`, value: 'month' },
{ label: $localize`Yearly`, value: 'year' } { label: $localize`Yearly`, value: 'year' }
]; ];
public performance: PortfolioPerformance; protected performance: PortfolioPerformance;
public performanceDataItems: HistoricalDataItem[]; protected performanceDataItems: HistoricalDataItem[];
public performanceDataItemsInPercentage: HistoricalDataItem[]; protected performanceDataItemsInPercentage: HistoricalDataItem[];
public portfolioEvolutionDataLabel = $localize`Investment`; protected readonly portfolioEvolutionDataLabel = $localize`Investment`;
public precision = 2; protected precision = 2;
public streaks: PortfolioInvestmentsResponse['streaks']; protected streaks: PortfolioInvestmentsResponse['streaks'];
public top3: PortfolioPosition[]; protected top3: PortfolioPosition[];
public unitCurrentStreak: string; protected unitCurrentStreak: string;
public unitLongestStreak: string; protected unitLongestStreak: string;
public user: User; protected user: User;
public constructor( private readonly actionsMenuButton = viewChild.required(MatMenuTrigger);
private changeDetectorRef: ChangeDetectorRef, private readonly deviceType = computed(
private clipboard: Clipboard, () => this.deviceDetectorService.deviceInfo().deviceType
private dataService: DataService, );
private destroyRef: DestroyRef, private firstOrderDate: Date;
private deviceDetectorService: DeviceDetectorService,
private impersonationStorageService: ImpersonationStorageService, private readonly changeDetectorRef = inject(ChangeDetectorRef);
private snackBar: MatSnackBar, private readonly clipboard = inject(Clipboard);
private userService: UserService private readonly dataService = inject(DataService);
) { private readonly destroyRef = inject(DestroyRef);
private readonly deviceDetectorService = inject(DeviceDetectorService);
private readonly impersonationStorageService = inject(
ImpersonationStorageService
);
private readonly snackBar = inject(MatSnackBar);
private readonly userService = inject(UserService);
public constructor() {
const { benchmarks } = this.dataService.fetchInfo(); const { benchmarks } = this.dataService.fetchInfo();
this.benchmarks = benchmarks; this.benchmarks = benchmarks;
@ -123,14 +133,16 @@ export class GfAnalysisPageComponent implements OnInit {
? undefined ? undefined
: this.user?.settings?.savingsRate; : this.user?.settings?.savingsRate;
return this.mode === 'year' if (savingsRatePerMonth === undefined) {
return undefined;
}
return this.mode() === 'year'
? savingsRatePerMonth * 12 ? savingsRatePerMonth * 12
: savingsRatePerMonth; : savingsRatePerMonth;
} }
public ngOnInit() { public ngOnInit() {
this.deviceType = this.deviceDetectorService.getDeviceInfo().deviceType;
this.impersonationStorageService this.impersonationStorageService
.onChangeHasImpersonation() .onChangeHasImpersonation()
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
@ -158,7 +170,7 @@ export class GfAnalysisPageComponent implements OnInit {
}); });
} }
public onChangeBenchmark(symbolProfileId: string) { protected onChangeBenchmark(symbolProfileId: string) {
this.dataService this.dataService
.putUserSetting({ benchmark: symbolProfileId }) .putUserSetting({ benchmark: symbolProfileId })
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
@ -174,12 +186,12 @@ export class GfAnalysisPageComponent implements OnInit {
}); });
} }
public onChangeGroupBy(aMode: GroupBy) { protected onChangeGroupBy(aMode: GroupBy) {
this.mode = aMode; this.mode.set(aMode);
this.fetchDividendsAndInvestments(); this.fetchDividendsAndInvestments();
} }
public onCopyPromptToClipboard(mode: AiPromptMode) { protected onCopyPromptToClipboard(mode: AiPromptMode) {
if (mode === 'analysis') { if (mode === 'analysis') {
this.isLoadingAnalysisPrompt = true; this.isLoadingAnalysisPrompt = true;
} else if (mode === 'portfolio') { } else if (mode === 'portfolio') {
@ -210,7 +222,7 @@ export class GfAnalysisPageComponent implements OnInit {
window.open('https://duck.ai', '_blank'); window.open('https://duck.ai', '_blank');
}); });
this.actionsMenuButton.closeMenu(); this.actionsMenuButton().closeMenu();
if (mode === 'analysis') { if (mode === 'analysis') {
this.isLoadingAnalysisPrompt = false; this.isLoadingAnalysisPrompt = false;
@ -227,8 +239,8 @@ export class GfAnalysisPageComponent implements OnInit {
this.dataService this.dataService
.fetchDividends({ .fetchDividends({
filters: this.userService.getFilters(), filters: this.userService.getFilters(),
groupBy: this.mode, groupBy: this.mode(),
range: this.user?.settings?.dateRange range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
}) })
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(({ dividends }) => { .subscribe(({ dividends }) => {
@ -242,15 +254,15 @@ export class GfAnalysisPageComponent implements OnInit {
this.dataService this.dataService
.fetchInvestments({ .fetchInvestments({
filters: this.userService.getFilters(), filters: this.userService.getFilters(),
groupBy: this.mode, groupBy: this.mode(),
range: this.user?.settings?.dateRange range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
}) })
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(({ investments, streaks }) => { .subscribe(({ investments, streaks }) => {
this.investmentsByGroup = investments; this.investmentsByGroup = investments;
this.streaks = streaks; this.streaks = streaks;
this.unitCurrentStreak = this.unitCurrentStreak =
this.mode === 'year' this.mode() === 'year'
? this.streaks?.currentStreak === 1 ? this.streaks?.currentStreak === 1
? translate('YEAR') ? translate('YEAR')
: translate('YEARS') : translate('YEARS')
@ -258,7 +270,7 @@ export class GfAnalysisPageComponent implements OnInit {
? translate('MONTH') ? translate('MONTH')
: translate('MONTHS'); : translate('MONTHS');
this.unitLongestStreak = this.unitLongestStreak =
this.mode === 'year' this.mode() === 'year'
? this.streaks?.longestStreak === 1 ? this.streaks?.longestStreak === 1
? translate('YEAR') ? translate('YEAR')
: translate('YEARS') : translate('YEARS')
@ -278,7 +290,7 @@ export class GfAnalysisPageComponent implements OnInit {
this.dataService this.dataService
.fetchPortfolioPerformance({ .fetchPortfolioPerformance({
filters: this.userService.getFilters(), filters: this.userService.getFilters(),
range: this.user?.settings?.dateRange range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE
}) })
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(({ chart, firstOrderDate, performance }) => { .subscribe(({ chart, firstOrderDate, performance }) => {
@ -298,13 +310,16 @@ export class GfAnalysisPageComponent implements OnInit {
valueInPercentage, valueInPercentage,
valueWithCurrencyEffect valueWithCurrencyEffect
} }
] of chart.entries()) { ] of (chart ?? []).entries()) {
// Ignore first item where value is 0
if (index > 0 || this.user?.settings?.dateRange === 'max') { if (index > 0 || this.user?.settings?.dateRange === 'max') {
// Ignore first item where value is 0 if (totalInvestmentValueWithCurrencyEffect !== undefined) {
this.investments.push({ this.investments.push({
date, date,
investment: totalInvestmentValueWithCurrencyEffect investment: totalInvestmentValueWithCurrencyEffect
}); });
}
this.performanceDataItems.push({ this.performanceDataItems.push({
date, date,
value: isNumber(valueWithCurrencyEffect) value: isNumber(valueWithCurrencyEffect)
@ -320,7 +335,7 @@ export class GfAnalysisPageComponent implements OnInit {
} }
if ( if (
this.deviceType === 'mobile' && this.deviceType() === 'mobile' &&
this.performance.currentValueInBaseCurrency >= this.performance.currentValueInBaseCurrency >=
NUMERICAL_PRECISION_THRESHOLD_6_FIGURES NUMERICAL_PRECISION_THRESHOLD_6_FIGURES
) { ) {
@ -387,7 +402,7 @@ export class GfAnalysisPageComponent implements OnInit {
dataSource, dataSource,
symbol, symbol,
filters: this.userService.getFilters(), filters: this.userService.getFilters(),
range: this.user?.settings?.dateRange, range: this.user?.settings?.dateRange ?? DEFAULT_DATE_RANGE,
startDate: this.firstOrderDate startDate: this.firstOrderDate
}) })
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))

24
apps/client/src/app/pages/portfolio/analysis/analysis-page.html

@ -310,13 +310,15 @@
<a <a
class="d-flex" class="d-flex"
[queryParams]="{ [queryParams]="{
dataSource: holding.dataSource, dataSource: holding.assetProfile.dataSource,
holdingDetailDialog: true, holdingDetailDialog: true,
symbol: holding.symbol symbol: holding.assetProfile.symbol
}" }"
[routerLink]="[]" [routerLink]="[]"
> >
<div class="flex-grow-1 mr-2">{{ holding.name }}</div> <div class="flex-grow-1 mr-2">
{{ holding.assetProfile.name }}
</div>
<div class="d-flex justify-content-end"> <div class="d-flex justify-content-end">
<gf-value <gf-value
class="justify-content-end" class="justify-content-end"
@ -359,13 +361,15 @@
<a <a
class="d-flex" class="d-flex"
[queryParams]="{ [queryParams]="{
dataSource: holding.dataSource, dataSource: holding.assetProfile.dataSource,
holdingDetailDialog: true, holdingDetailDialog: true,
symbol: holding.symbol symbol: holding.assetProfile.symbol
}" }"
[routerLink]="[]" [routerLink]="[]"
> >
<div class="flex-grow-1 mr-2">{{ holding.name }}</div> <div class="flex-grow-1 mr-2">
{{ holding.assetProfile.name }}
</div>
<div class="d-flex justify-content-end"> <div class="d-flex justify-content-end">
<gf-value <gf-value
class="justify-content-end" class="justify-content-end"
@ -438,7 +442,7 @@
</div> </div>
<gf-toggle <gf-toggle
class="d-none d-lg-block" class="d-none d-lg-block"
[defaultValue]="mode" [defaultValue]="mode()"
[isLoading]="false" [isLoading]="false"
[options]="modeOptions" [options]="modeOptions"
(valueChange)="onChangeGroupBy($event.value)" (valueChange)="onChangeGroupBy($event.value)"
@ -472,7 +476,7 @@
[benchmarkDataItems]="investmentsByGroup" [benchmarkDataItems]="investmentsByGroup"
[benchmarkDataLabel]="investmentTimelineDataLabel" [benchmarkDataLabel]="investmentTimelineDataLabel"
[currency]="user?.settings?.baseCurrency" [currency]="user?.settings?.baseCurrency"
[groupBy]="mode" [groupBy]="mode()"
[isInPercentage]=" [isInPercentage]="
hasImpersonationId || user.settings.isRestrictedView hasImpersonationId || user.settings.isRestrictedView
" "
@ -497,7 +501,7 @@
</div> </div>
<gf-toggle <gf-toggle
class="d-none d-lg-block" class="d-none d-lg-block"
[defaultValue]="mode" [defaultValue]="mode()"
[isLoading]="false" [isLoading]="false"
[options]="modeOptions" [options]="modeOptions"
(valueChange)="onChangeGroupBy($event.value)" (valueChange)="onChangeGroupBy($event.value)"
@ -509,7 +513,7 @@
[benchmarkDataItems]="dividendsByGroup" [benchmarkDataItems]="dividendsByGroup"
[benchmarkDataLabel]="dividendTimelineDataLabel" [benchmarkDataLabel]="dividendTimelineDataLabel"
[currency]="user?.settings?.baseCurrency" [currency]="user?.settings?.baseCurrency"
[groupBy]="mode" [groupBy]="mode()"
[isInPercentage]=" [isInPercentage]="
hasImpersonationId || user.settings.isRestrictedView hasImpersonationId || user.settings.isRestrictedView
" "

5
apps/client/src/app/pages/public/public-page.component.ts

@ -74,7 +74,10 @@ export class GfPublicPageComponent implements OnInit {
}; };
protected readonly pageSize = Number.MAX_SAFE_INTEGER; protected readonly pageSize = Number.MAX_SAFE_INTEGER;
protected positions: { protected positions: {
[symbol: string]: Pick<PortfolioPosition, 'currency' | 'name'> & { [symbol: string]: Pick<
PortfolioPosition['assetProfile'],
'currency' | 'name'
> & {
value: number; value: number;
}; };
}; };

7
apps/client/src/assets/oss-friends.json

@ -1,5 +1,5 @@
{ {
"createdAt": "2026-04-21T00:00:00.000Z", "createdAt": "2026-05-26T00:00:00.000Z",
"data": [ "data": [
{ {
"name": "Activepieces", "name": "Activepieces",
@ -101,6 +101,11 @@
"description": "Simplify working with databases. Build, optimize, and grow your app easily with an intuitive data model, type-safety, automated migrations, connection pooling, caching, and real-time db subscriptions.", "description": "Simplify working with databases. Build, optimize, and grow your app easily with an intuitive data model, type-safety, automated migrations, connection pooling, caching, and real-time db subscriptions.",
"href": "https://www.prisma.io" "href": "https://www.prisma.io"
}, },
{
"name": "Rallly",
"description": "Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.",
"href": "https://rallly.co"
},
{ {
"name": "Requestly", "name": "Requestly",
"description": "Makes frontend development cycle 10x faster with API Client, Mock Server, Intercept & Modify HTTP Requests and Session Replays.", "description": "Makes frontend development cycle 10x faster with API Client, Mock Server, Intercept & Modify HTTP Requests and Session Replays.",

11
apps/client/src/styles.scss

@ -360,10 +360,6 @@ ngx-skeleton-loader {
text-wrap: balance; text-wrap: balance;
} }
.has-fab {
padding-bottom: 3rem !important;
}
.has-info-message { .has-info-message {
// Restrict viewport height of tabbed views when the Live Demo or system announcements banner are displayed // Restrict viewport height of tabbed views when the Live Demo or system announcements banner are displayed
.page:has(gf-page-tabs) { .page:has(gf-page-tabs) {
@ -484,13 +480,6 @@ ngx-skeleton-loader {
padding-bottom: env(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom);
padding-bottom: constant(safe-area-inset-bottom); padding-bottom: constant(safe-area-inset-bottom);
.fab-container {
bottom: 2rem;
position: fixed;
right: 2rem;
z-index: 999;
}
// Restrict viewport height and layout boundaries only when the page hosts tab navigation // Restrict viewport height and layout boundaries only when the page hosts tab navigation
&:has(gf-page-tabs) { &:has(gf-page-tabs) {
height: calc(100svh - var(--mat-toolbar-standard-height)); height: calc(100svh - var(--mat-toolbar-standard-height));

1
libs/common/src/lib/config.ts

@ -256,6 +256,7 @@ export const PROPERTY_SLACK_COMMUNITY_USERS = 'SLACK_COMMUNITY_USERS';
export const PROPERTY_STRIPE_CONFIG = 'STRIPE_CONFIG'; export const PROPERTY_STRIPE_CONFIG = 'STRIPE_CONFIG';
export const PROPERTY_SYSTEM_MESSAGE = 'SYSTEM_MESSAGE'; export const PROPERTY_SYSTEM_MESSAGE = 'SYSTEM_MESSAGE';
export const PROPERTY_UPTIME = 'UPTIME'; export const PROPERTY_UPTIME = 'UPTIME';
export const PROPERTY_WEB_FETCH_ROUTES = 'WEB_FETCH_ROUTES';
export const QUEUE_JOB_STATUS_LIST = [ export const QUEUE_JOB_STATUS_LIST = [
'active', 'active',

30
libs/common/src/lib/helper.ts

@ -30,10 +30,17 @@ import { get, isNil, isString } from 'lodash';
import { import {
DEFAULT_CURRENCY, DEFAULT_CURRENCY,
DERIVED_CURRENCIES, DERIVED_CURRENCIES,
ghostfolioFearAndGreedIndexSymbol,
ghostfolioFearAndGreedIndexSymbolCryptocurrencies,
ghostfolioFearAndGreedIndexSymbolStocks,
ghostfolioScraperApiSymbolPrefix, ghostfolioScraperApiSymbolPrefix,
locale locale
} from './config'; } from './config';
import { AssetProfileIdentifier, Benchmark } from './interfaces'; import {
AdminMarketDataItem,
AssetProfileIdentifier,
Benchmark
} from './interfaces';
import { BenchmarkTrend, ColorScheme } from './types'; import { BenchmarkTrend, ColorScheme } from './types';
export const DATE_FORMAT = 'yyyy-MM-dd'; export const DATE_FORMAT = 'yyyy-MM-dd';
@ -93,6 +100,27 @@ export function calculateMovingAverage({
.toNumber(); .toNumber();
} }
export function canDeleteAssetProfile({
activitiesCount,
isBenchmark,
symbol,
watchedByCount
}: Pick<
AdminMarketDataItem,
'activitiesCount' | 'isBenchmark' | 'symbol' | 'watchedByCount'
>): boolean {
return (
activitiesCount === 0 &&
!isBenchmark &&
!isDerivedCurrency(getCurrencyFromSymbol(symbol)) &&
!isRootCurrency(getCurrencyFromSymbol(symbol)) &&
symbol !== ghostfolioFearAndGreedIndexSymbol &&
symbol !== ghostfolioFearAndGreedIndexSymbolCryptocurrencies &&
symbol !== ghostfolioFearAndGreedIndexSymbolStocks &&
watchedByCount === 0
);
}
export function capitalize(aString: string) { export function capitalize(aString: string) {
return aString.charAt(0).toUpperCase() + aString.slice(1).toLowerCase(); return aString.charAt(0).toUpperCase() + aString.slice(1).toLowerCase();
} }

47
libs/common/src/lib/interfaces/portfolio-position.interface.ts

@ -1,22 +1,12 @@
import { Market, MarketAdvanced } from '@ghostfolio/common/types'; import { Market, MarketAdvanced } from '@ghostfolio/common/types';
import { AssetClass, AssetSubClass, DataSource, Tag } from '@prisma/client'; import { Tag } from '@prisma/client';
import { Country } from './country.interface';
import { EnhancedSymbolProfile } from './enhanced-symbol-profile.interface'; import { EnhancedSymbolProfile } from './enhanced-symbol-profile.interface';
import { Holding } from './holding.interface';
import { Sector } from './sector.interface';
export interface PortfolioPosition { export interface PortfolioPosition {
activitiesCount: number; activitiesCount: number;
allocationInPercentage: number; allocationInPercentage: number;
/** @deprecated */
assetClass?: AssetClass;
/** @deprecated */
assetClassLabel?: string;
assetProfile: Pick< assetProfile: Pick<
EnhancedSymbolProfile, EnhancedSymbolProfile,
| 'assetClass' | 'assetClass'
@ -33,22 +23,6 @@ export interface PortfolioPosition {
assetClassLabel?: string; assetClassLabel?: string;
assetSubClassLabel?: string; assetSubClassLabel?: string;
}; };
/** @deprecated */
assetSubClass?: AssetSubClass;
/** @deprecated */
assetSubClassLabel?: string;
/** @deprecated */
countries: Country[];
/** @deprecated */
currency: string;
/** @deprecated */
dataSource: DataSource;
dateOfFirstActivity: Date; dateOfFirstActivity: Date;
dividend: number; dividend: number;
exchange?: string; exchange?: string;
@ -56,38 +30,19 @@ export interface PortfolioPosition {
grossPerformancePercent: number; grossPerformancePercent: number;
grossPerformancePercentWithCurrencyEffect: number; grossPerformancePercentWithCurrencyEffect: number;
grossPerformanceWithCurrencyEffect: number; grossPerformanceWithCurrencyEffect: number;
/** @deprecated */
holdings: Holding[];
investment: number; investment: number;
marketChange?: number; marketChange?: number;
marketChangePercent?: number; marketChangePercent?: number;
marketPrice: number; marketPrice: number;
markets?: { [key in Market]: number }; markets?: { [key in Market]: number };
marketsAdvanced?: { [key in MarketAdvanced]: number }; marketsAdvanced?: { [key in MarketAdvanced]: number };
/** @deprecated */
name: string;
netPerformance: number; netPerformance: number;
netPerformancePercent: number; netPerformancePercent: number;
netPerformancePercentWithCurrencyEffect: number; netPerformancePercentWithCurrencyEffect: number;
netPerformanceWithCurrencyEffect: number; netPerformanceWithCurrencyEffect: number;
quantity: number; quantity: number;
/** @deprecated */
sectors: Sector[];
/** @deprecated */
symbol: string;
tags?: Tag[]; tags?: Tag[];
type?: string; type?: string;
/** @deprecated */
url?: string;
valueInBaseCurrency?: number; valueInBaseCurrency?: number;
valueInPercentage?: number; valueInPercentage?: number;
} }

41
libs/ui/src/lib/assistant/assistant.component.ts

@ -504,11 +504,16 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
.pipe(takeUntilDestroyed(this.destroyRef)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(({ holdings }) => { .subscribe(({ holdings }) => {
this.holdings = holdings this.holdings = holdings
.filter(({ assetSubClass }) => { .filter(({ assetProfile }) => {
return assetSubClass && !['CASH'].includes(assetSubClass); return (
assetProfile.assetSubClass &&
!['CASH'].includes(assetProfile.assetSubClass)
);
}) })
.sort((a, b) => { .sort((a, b) => {
return a.name?.localeCompare(b.name); return (a.assetProfile.name ?? '').localeCompare(
b.assetProfile.name ?? ''
);
}); });
this.setPortfolioFilterFormValues(); this.setPortfolioFilterFormValues();
@ -530,11 +535,11 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
type: 'ASSET_CLASS' type: 'ASSET_CLASS'
}, },
{ {
id: filterValue?.holding?.dataSource ?? '', id: filterValue?.holding?.assetProfile?.dataSource ?? '',
type: 'DATA_SOURCE' type: 'DATA_SOURCE'
}, },
{ {
id: filterValue?.holding?.symbol ?? '', id: filterValue?.holding?.assetProfile?.symbol ?? '',
type: 'SYMBOL' type: 'SYMBOL'
}, },
{ {
@ -718,18 +723,16 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
return EMPTY; return EMPTY;
}), }),
map(({ holdings }) => { map(({ holdings }) => {
return holdings.map( return holdings.map(({ assetProfile }) => {
({ assetSubClass, currency, dataSource, name, symbol }) => { return {
return { assetSubClassString: translate(assetProfile.assetSubClass ?? ''),
currency, currency: assetProfile.currency ?? '',
dataSource, dataSource: assetProfile.dataSource,
name, mode: SearchMode.HOLDING as const,
symbol, name: assetProfile.name ?? '',
assetSubClassString: translate(assetSubClass ?? ''), symbol: assetProfile.symbol
mode: SearchMode.HOLDING as const };
}; });
}
);
}), }),
takeUntilDestroyed(this.destroyRef) takeUntilDestroyed(this.destroyRef)
); );
@ -777,8 +780,8 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
return ( return (
!!(dataSource && symbol) && !!(dataSource && symbol) &&
getAssetProfileIdentifier({ getAssetProfileIdentifier({
dataSource: holding.dataSource, dataSource: holding.assetProfile.dataSource,
symbol: holding.symbol symbol: holding.assetProfile.symbol
}) === getAssetProfileIdentifier({ dataSource, symbol }) }) === getAssetProfileIdentifier({ dataSource, symbol })
); );
}); });

9
libs/ui/src/lib/fab/fab.component.html

@ -0,0 +1,9 @@
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[queryParams]="queryParams()"
[routerLink]="[]"
>
<ion-icon name="add-outline" size="large" />
</a>

14
libs/ui/src/lib/fab/fab.component.scss

@ -0,0 +1,14 @@
:host {
bottom: calc(constant(safe-area-inset-bottom) + 2rem);
bottom: calc(env(safe-area-inset-bottom) + 2rem);
position: fixed;
right: 2rem;
z-index: 999;
}
:host-context(gf-page-tabs) {
@media (max-width: 575.98px) {
bottom: calc(constant(safe-area-inset-bottom) + 5rem);
bottom: calc(env(safe-area-inset-bottom) + 5rem);
}
}

21
libs/ui/src/lib/fab/fab.component.ts

@ -0,0 +1,21 @@
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { Params, RouterModule } from '@angular/router';
import { IonIcon } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { addOutline } from 'ionicons/icons';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [IonIcon, MatButtonModule, RouterModule],
selector: 'gf-fab',
styleUrls: ['./fab.component.scss'],
templateUrl: './fab.component.html'
})
export class GfFabComponent {
public readonly queryParams = input.required<Params>();
public constructor() {
addIcons({ addOutline });
}
}

1
libs/ui/src/lib/fab/index.ts

@ -0,0 +1 @@
export * from './fab.component';

200
libs/ui/src/lib/mocks/holdings.ts

@ -4,11 +4,11 @@ export const holdings: PortfolioPosition[] = [
{ {
activitiesCount: 1, activitiesCount: 1,
allocationInPercentage: 0.042990776363386086, allocationInPercentage: 0.042990776363386086,
assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetProfile: { assetProfile: {
assetClass: 'EQUITY', assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetSubClass: 'STOCK', assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [ countries: [
{ {
code: 'US', code: 'US',
@ -20,60 +20,40 @@ export const holdings: PortfolioPosition[] = [
currency: 'USD', currency: 'USD',
dataSource: 'YAHOO', dataSource: 'YAHOO',
holdings: [], holdings: [],
name: 'Apple Inc',
sectors: [ sectors: [
{ {
name: 'Technology', name: 'Technology',
weight: 1 weight: 1
} }
], ],
symbol: 'AAPL' symbol: 'AAPL',
url: 'https://www.apple.com'
}, },
assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [
{
code: 'US',
continent: 'North America',
name: 'United States',
weight: 1
}
],
currency: 'USD',
dataSource: 'YAHOO',
dateOfFirstActivity: new Date('2021-12-01T00:00:00.000Z'), dateOfFirstActivity: new Date('2021-12-01T00:00:00.000Z'),
dividend: 0, dividend: 0,
grossPerformance: 3856, grossPerformance: 3856,
grossPerformancePercent: 0.46047289228564603, grossPerformancePercent: 0.46047289228564603,
grossPerformancePercentWithCurrencyEffect: 0.46047289228564603, grossPerformancePercentWithCurrencyEffect: 0.46047289228564603,
grossPerformanceWithCurrencyEffect: 3856, grossPerformanceWithCurrencyEffect: 3856,
holdings: [],
investment: 8374, investment: 8374,
marketPrice: 244.6, marketPrice: 244.6,
name: 'Apple Inc',
netPerformance: 3855, netPerformance: 3855,
netPerformancePercent: 0.460353475041796, netPerformancePercent: 0.460353475041796,
netPerformancePercentWithCurrencyEffect: 0.036440677966101696, netPerformancePercentWithCurrencyEffect: 0.036440677966101696,
netPerformanceWithCurrencyEffect: 430, netPerformanceWithCurrencyEffect: 430,
quantity: 50, quantity: 50,
sectors: [
{
name: 'Technology',
weight: 1
}
],
symbol: 'AAPL',
tags: [], tags: [],
url: 'https://www.apple.com',
valueInBaseCurrency: 12230 valueInBaseCurrency: 12230
}, },
{ {
activitiesCount: 2, activitiesCount: 2,
allocationInPercentage: 0.02377401948293552, allocationInPercentage: 0.02377401948293552,
assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetProfile: { assetProfile: {
assetClass: 'EQUITY', assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetSubClass: 'STOCK', assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [ countries: [
{ {
code: 'DE', code: 'DE',
@ -85,60 +65,40 @@ export const holdings: PortfolioPosition[] = [
currency: 'EUR', currency: 'EUR',
dataSource: 'YAHOO', dataSource: 'YAHOO',
holdings: [], holdings: [],
name: 'Allianz SE',
sectors: [ sectors: [
{ {
name: 'Financial Services', name: 'Financial Services',
weight: 1 weight: 1
} }
], ],
symbol: 'ALV.DE' symbol: 'ALV.DE',
url: 'https://www.allianz.com'
}, },
assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [
{
code: 'DE',
continent: 'Europe',
name: 'Germany',
weight: 1
}
],
currency: 'EUR',
dataSource: 'YAHOO',
dateOfFirstActivity: new Date('2021-04-23T00:00:00.000Z'), dateOfFirstActivity: new Date('2021-04-23T00:00:00.000Z'),
dividend: 192, dividend: 192,
grossPerformance: 2226.700251889169, grossPerformance: 2226.700251889169,
grossPerformancePercent: 0.49083842309827874, grossPerformancePercent: 0.49083842309827874,
grossPerformancePercentWithCurrencyEffect: 0.29306136948826367, grossPerformancePercentWithCurrencyEffect: 0.29306136948826367,
grossPerformanceWithCurrencyEffect: 1532.8272791336772, grossPerformanceWithCurrencyEffect: 1532.8272791336772,
holdings: [],
investment: 4536.523929471033, investment: 4536.523929471033,
marketPrice: 322.2, marketPrice: 322.2,
name: 'Allianz SE',
netPerformance: 2222.2921914357685, netPerformance: 2222.2921914357685,
netPerformancePercent: 0.48986674069961134, netPerformancePercent: 0.48986674069961134,
netPerformancePercentWithCurrencyEffect: 0.034489367670592026, netPerformancePercentWithCurrencyEffect: 0.034489367670592026,
netPerformanceWithCurrencyEffect: 225.48257403052068, netPerformanceWithCurrencyEffect: 225.48257403052068,
quantity: 20, quantity: 20,
sectors: [
{
name: 'Financial Services',
weight: 1
}
],
symbol: 'ALV.DE',
tags: [], tags: [],
url: 'https://www.allianz.com',
valueInBaseCurrency: 6763.224181360202 valueInBaseCurrency: 6763.224181360202
}, },
{ {
activitiesCount: 1, activitiesCount: 1,
allocationInPercentage: 0.08038536990007467, allocationInPercentage: 0.08038536990007467,
assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetProfile: { assetProfile: {
assetClass: 'EQUITY', assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetSubClass: 'STOCK', assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [ countries: [
{ {
code: 'US', code: 'US',
@ -150,101 +110,73 @@ export const holdings: PortfolioPosition[] = [
currency: 'USD', currency: 'USD',
dataSource: 'YAHOO', dataSource: 'YAHOO',
holdings: [], holdings: [],
name: 'Amazon.com, Inc.',
sectors: [ sectors: [
{ {
name: 'Consumer Discretionary', name: 'Consumer Discretionary',
weight: 1 weight: 1
} }
], ],
symbol: 'AMZN' symbol: 'AMZN',
url: 'https://www.aboutamazon.com'
}, },
assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [
{
code: 'US',
continent: 'North America',
name: 'United States',
weight: 1
}
],
currency: 'USD',
dataSource: 'YAHOO',
dateOfFirstActivity: new Date('2018-10-01T00:00:00.000Z'), dateOfFirstActivity: new Date('2018-10-01T00:00:00.000Z'),
dividend: 0, dividend: 0,
grossPerformance: 12758.05, grossPerformance: 12758.05,
grossPerformancePercent: 1.2619300787837724, grossPerformancePercent: 1.2619300787837724,
grossPerformancePercentWithCurrencyEffect: 1.2619300787837724, grossPerformancePercentWithCurrencyEffect: 1.2619300787837724,
grossPerformanceWithCurrencyEffect: 12758.05, grossPerformanceWithCurrencyEffect: 12758.05,
holdings: [],
investment: 10109.95, investment: 10109.95,
marketPrice: 228.68, marketPrice: 228.68,
name: 'Amazon.com, Inc.',
netPerformance: 12677.26, netPerformance: 12677.26,
netPerformancePercent: 1.253938941339967, netPerformancePercent: 1.253938941339967,
netPerformancePercentWithCurrencyEffect: -0.037866008722316276, netPerformancePercentWithCurrencyEffect: -0.037866008722316276,
netPerformanceWithCurrencyEffect: -899.99926757812, netPerformanceWithCurrencyEffect: -899.99926757812,
quantity: 100, quantity: 100,
sectors: [
{
name: 'Consumer Discretionary',
weight: 1
}
],
symbol: 'AMZN',
tags: [], tags: [],
url: 'https://www.aboutamazon.com',
valueInBaseCurrency: 22868 valueInBaseCurrency: 22868
}, },
{ {
activitiesCount: 1, activitiesCount: 1,
allocationInPercentage: 0.19216416482928922, allocationInPercentage: 0.19216416482928922,
assetClass: 'LIQUIDITY',
assetClassLabel: 'Liquidity',
assetProfile: { assetProfile: {
assetClass: 'LIQUIDITY', assetClass: 'LIQUIDITY',
assetSubClass: 'CASH', assetClassLabel: 'Liquidity',
assetSubClass: 'CRYPTOCURRENCY',
assetSubClassLabel: 'Cryptocurrency',
countries: [], countries: [],
currency: 'USD', currency: 'USD',
dataSource: 'COINGECKO', dataSource: 'COINGECKO',
holdings: [], holdings: [],
name: 'Bitcoin',
sectors: [], sectors: [],
symbol: 'bitcoin' symbol: 'bitcoin',
url: undefined
}, },
assetSubClass: 'CRYPTOCURRENCY',
assetSubClassLabel: 'Cryptocurrency',
countries: [],
currency: 'USD',
dataSource: 'COINGECKO',
dateOfFirstActivity: new Date('2017-08-16T00:00:00.000Z'), dateOfFirstActivity: new Date('2017-08-16T00:00:00.000Z'),
dividend: 0, dividend: 0,
grossPerformance: 52666.7898248, grossPerformance: 52666.7898248,
grossPerformancePercent: 26.333394912400003, grossPerformancePercent: 26.333394912400003,
grossPerformancePercentWithCurrencyEffect: 26.333394912400003, grossPerformancePercentWithCurrencyEffect: 26.333394912400003,
grossPerformanceWithCurrencyEffect: 52666.7898248, grossPerformanceWithCurrencyEffect: 52666.7898248,
holdings: [],
investment: 1999.9999999999998, investment: 1999.9999999999998,
marketPrice: 97364, marketPrice: 97364,
name: 'Bitcoin',
netPerformance: 52636.8898248, netPerformance: 52636.8898248,
netPerformancePercent: 26.3184449124, netPerformancePercent: 26.3184449124,
netPerformancePercentWithCurrencyEffect: -0.04760906442310894, netPerformancePercentWithCurrencyEffect: -0.04760906442310894,
netPerformanceWithCurrencyEffect: -2732.737808972287, netPerformanceWithCurrencyEffect: -2732.737808972287,
quantity: 0.5614682, quantity: 0.5614682,
sectors: [],
symbol: 'bitcoin',
tags: [], tags: [],
url: undefined,
valueInBaseCurrency: 54666.7898248 valueInBaseCurrency: 54666.7898248
}, },
{ {
activitiesCount: 1, activitiesCount: 1,
allocationInPercentage: 0.04307127421937313, allocationInPercentage: 0.04307127421937313,
assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetProfile: { assetProfile: {
assetClass: 'EQUITY', assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetSubClass: 'STOCK', assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [ countries: [
{ {
code: 'US', code: 'US',
@ -256,60 +188,40 @@ export const holdings: PortfolioPosition[] = [
currency: 'USD', currency: 'USD',
dataSource: 'YAHOO', dataSource: 'YAHOO',
holdings: [], holdings: [],
name: 'Microsoft Corporation',
sectors: [ sectors: [
{ {
name: 'Technology', name: 'Technology',
weight: 1 weight: 1
} }
], ],
symbol: 'MSFT' symbol: 'MSFT',
url: 'https://www.microsoft.com'
}, },
assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [
{
code: 'US',
continent: 'North America',
name: 'United States',
weight: 1
}
],
currency: 'USD',
dataSource: 'YAHOO',
dateOfFirstActivity: new Date('2023-01-03T00:00:00.000Z'), dateOfFirstActivity: new Date('2023-01-03T00:00:00.000Z'),
dividend: 0, dividend: 0,
grossPerformance: 5065.5, grossPerformance: 5065.5,
grossPerformancePercent: 0.7047750229568411, grossPerformancePercent: 0.7047750229568411,
grossPerformancePercentWithCurrencyEffect: 0.7047750229568411, grossPerformancePercentWithCurrencyEffect: 0.7047750229568411,
grossPerformanceWithCurrencyEffect: 5065.5, grossPerformanceWithCurrencyEffect: 5065.5,
holdings: [],
investment: 7187.4, investment: 7187.4,
marketPrice: 408.43, marketPrice: 408.43,
name: 'Microsoft Corporation',
netPerformance: 5065.5, netPerformance: 5065.5,
netPerformancePercent: 0.7047750229568411, netPerformancePercent: 0.7047750229568411,
netPerformancePercentWithCurrencyEffect: -0.015973588391056275, netPerformancePercentWithCurrencyEffect: -0.015973588391056275,
netPerformanceWithCurrencyEffect: -198.899926757814, netPerformanceWithCurrencyEffect: -198.899926757814,
quantity: 30, quantity: 30,
sectors: [
{
name: 'Technology',
weight: 1
}
],
symbol: 'MSFT',
tags: [], tags: [],
url: 'https://www.microsoft.com',
valueInBaseCurrency: 12252.9 valueInBaseCurrency: 12252.9
}, },
{ {
activitiesCount: 1, activitiesCount: 1,
allocationInPercentage: 0.18762679306394897, allocationInPercentage: 0.18762679306394897,
assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetProfile: { assetProfile: {
assetClass: 'EQUITY', assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetSubClass: 'STOCK', assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [ countries: [
{ {
code: 'US', code: 'US',
@ -321,60 +233,40 @@ export const holdings: PortfolioPosition[] = [
currency: 'USD', currency: 'USD',
dataSource: 'YAHOO', dataSource: 'YAHOO',
holdings: [], holdings: [],
name: 'Tesla, Inc.',
sectors: [ sectors: [
{ {
name: 'Consumer Discretionary', name: 'Consumer Discretionary',
weight: 1 weight: 1
} }
], ],
symbol: 'TSLA' symbol: 'TSLA',
url: 'https://www.tesla.com'
}, },
assetSubClass: 'STOCK',
assetSubClassLabel: 'Stock',
countries: [
{
code: 'US',
continent: 'North America',
name: 'United States',
weight: 1
}
],
currency: 'USD',
dataSource: 'YAHOO',
dateOfFirstActivity: new Date('2017-01-03T00:00:00.000Z'), dateOfFirstActivity: new Date('2017-01-03T00:00:00.000Z'),
dividend: 0, dividend: 0,
grossPerformance: 51227.500000005, grossPerformance: 51227.500000005,
grossPerformancePercent: 23.843379101756675, grossPerformancePercent: 23.843379101756675,
grossPerformancePercentWithCurrencyEffect: 23.843379101756675, grossPerformancePercentWithCurrencyEffect: 23.843379101756675,
grossPerformanceWithCurrencyEffect: 51227.500000005, grossPerformanceWithCurrencyEffect: 51227.500000005,
holdings: [],
investment: 2148.499999995, investment: 2148.499999995,
marketPrice: 355.84, marketPrice: 355.84,
name: 'Tesla, Inc.',
netPerformance: 51197.500000005, netPerformance: 51197.500000005,
netPerformancePercent: 23.829415871596066, netPerformancePercent: 23.829415871596066,
netPerformancePercentWithCurrencyEffect: -0.12051410125545206, netPerformancePercentWithCurrencyEffect: -0.12051410125545206,
netPerformanceWithCurrencyEffect: -7314.00091552734, netPerformanceWithCurrencyEffect: -7314.00091552734,
quantity: 150, quantity: 150,
sectors: [
{
name: 'Consumer Discretionary',
weight: 1
}
],
symbol: 'TSLA',
tags: [], tags: [],
url: 'https://www.tesla.com',
valueInBaseCurrency: 53376 valueInBaseCurrency: 53376
}, },
{ {
activitiesCount: 5, activitiesCount: 5,
allocationInPercentage: 0.053051250766657634, allocationInPercentage: 0.053051250766657634,
assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetProfile: { assetProfile: {
assetClass: 'EQUITY', assetClass: 'EQUITY',
assetClassLabel: 'Equity',
assetSubClass: 'ETF', assetSubClass: 'ETF',
assetSubClassLabel: 'ETF',
countries: [ countries: [
{ {
code: 'US', code: 'US',
@ -386,50 +278,30 @@ export const holdings: PortfolioPosition[] = [
currency: 'USD', currency: 'USD',
dataSource: 'YAHOO', dataSource: 'YAHOO',
holdings: [], holdings: [],
name: 'Vanguard Total Stock Market Index Fund ETF Shares',
sectors: [ sectors: [
{ {
name: 'Equity', name: 'Equity',
weight: 1 weight: 1
} }
], ],
symbol: 'VTI' symbol: 'VTI',
url: 'https://www.vanguard.com'
}, },
assetSubClass: 'ETF',
assetSubClassLabel: 'ETF',
countries: [
{
code: 'US',
weight: 1,
continent: 'North America',
name: 'United States'
}
],
currency: 'USD',
dataSource: 'YAHOO',
dateOfFirstActivity: new Date('2019-03-01T00:00:00.000Z'), dateOfFirstActivity: new Date('2019-03-01T00:00:00.000Z'),
dividend: 0, dividend: 0,
grossPerformance: 6845.8, grossPerformance: 6845.8,
grossPerformancePercent: 1.0164758094605268, grossPerformancePercent: 1.0164758094605268,
grossPerformancePercentWithCurrencyEffect: 1.0164758094605268, grossPerformancePercentWithCurrencyEffect: 1.0164758094605268,
grossPerformanceWithCurrencyEffect: 6845.8, grossPerformanceWithCurrencyEffect: 6845.8,
holdings: [],
investment: 8246.2, investment: 8246.2,
marketPrice: 301.84, marketPrice: 301.84,
name: 'Vanguard Total Stock Market Index Fund ETF Shares',
netPerformance: 6746.3, netPerformance: 6746.3,
netPerformancePercent: 1.0017018833976383, netPerformancePercent: 1.0017018833976383,
netPerformancePercentWithCurrencyEffect: 0.01085061564051406, netPerformancePercentWithCurrencyEffect: 0.01085061564051406,
netPerformanceWithCurrencyEffect: 161.99969482422, netPerformanceWithCurrencyEffect: 161.99969482422,
quantity: 50, quantity: 50,
sectors: [
{
name: 'Equity',
weight: 1
}
],
symbol: 'VTI',
tags: [], tags: [],
url: 'https://www.vanguard.com',
valueInBaseCurrency: 15092 valueInBaseCurrency: 15092
} }
]; ];

6
libs/ui/src/lib/page-tabs/page-tabs.component.scss

@ -15,12 +15,6 @@
); );
::ng-deep { ::ng-deep {
.fab-container {
@media (max-width: 575.98px) {
bottom: 5rem;
}
}
.mat-mdc-tab-nav-panel { .mat-mdc-tab-nav-panel {
padding: 2rem 0; padding: 2rem 0;

9
libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.html

@ -29,18 +29,19 @@
[compareWith]="holdingComparisonFunction" [compareWith]="holdingComparisonFunction"
> >
<mat-select-trigger>{{ <mat-select-trigger>{{
filterForm.get('holding')?.value?.name filterForm.get('holding')?.value?.assetProfile?.name
}}</mat-select-trigger> }}</mat-select-trigger>
<mat-option [value]="null" /> <mat-option [value]="null" />
@for (holding of holdings(); track holding.name) { @for (holding of holdings(); track holding.assetProfile.name) {
<mat-option [value]="holding"> <mat-option [value]="holding">
<div class="line-height-1 text-truncate"> <div class="line-height-1 text-truncate">
<span <span
><b>{{ holding.name }}</b></span ><b>{{ holding.assetProfile.name }}</b></span
> >
<br /> <br />
<small class="text-muted" <small class="text-muted"
>{{ holding.symbol | gfSymbol }} · {{ holding.currency }}</small >{{ holding.assetProfile.symbol | gfSymbol }} ·
{{ holding.assetProfile.currency }}</small
> >
</div> </div>
</mat-option> </mat-option>

3
libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.ts

@ -109,7 +109,8 @@ export class GfPortfolioFilterFormComponent
} }
return ( return (
getAssetProfileIdentifier(option) === getAssetProfileIdentifier(value) getAssetProfileIdentifier(option.assetProfile) ===
getAssetProfileIdentifier(value.assetProfile)
); );
} }

10
libs/ui/src/lib/services/data.service.ts

@ -556,13 +556,11 @@ export class DataService {
map((response) => { map((response) => {
if (response.holdings) { if (response.holdings) {
for (const symbol of Object.keys(response.holdings)) { for (const symbol of Object.keys(response.holdings)) {
response.holdings[symbol].assetClassLabel = translate( response.holdings[symbol].assetProfile.assetClassLabel =
response.holdings[symbol].assetClass translate(response.holdings[symbol].assetProfile.assetClass);
);
response.holdings[symbol].assetSubClassLabel = translate( response.holdings[symbol].assetProfile.assetSubClassLabel =
response.holdings[symbol].assetSubClass translate(response.holdings[symbol].assetProfile.assetSubClass);
);
response.holdings[symbol].dateOfFirstActivity = response.holdings[ response.holdings[symbol].dateOfFirstActivity = response.holdings[
symbol symbol

745
package-lock.json

File diff suppressed because it is too large

39
package.json

@ -1,6 +1,6 @@
{ {
"name": "ghostfolio", "name": "ghostfolio",
"version": "3.5.0", "version": "3.7.0",
"homepage": "https://ghostfol.io", "homepage": "https://ghostfol.io",
"license": "AGPL-3.0", "license": "AGPL-3.0",
"repository": "https://github.com/ghostfolio/ghostfolio", "repository": "https://github.com/ghostfolio/ghostfolio",
@ -74,14 +74,14 @@
"@ionic/angular": "8.8.5", "@ionic/angular": "8.8.5",
"@keyv/redis": "5.1.6", "@keyv/redis": "5.1.6",
"@nestjs/bull": "11.0.4", "@nestjs/bull": "11.0.4",
"@nestjs/cache-manager": "3.1.0", "@nestjs/cache-manager": "3.1.2",
"@nestjs/common": "11.1.19", "@nestjs/common": "11.1.21",
"@nestjs/config": "4.0.4", "@nestjs/config": "4.0.4",
"@nestjs/core": "11.1.19", "@nestjs/core": "11.1.21",
"@nestjs/event-emitter": "3.0.1", "@nestjs/event-emitter": "3.1.0",
"@nestjs/jwt": "11.0.2", "@nestjs/jwt": "11.0.2",
"@nestjs/passport": "11.0.5", "@nestjs/passport": "11.0.5",
"@nestjs/platform-express": "11.1.19", "@nestjs/platform-express": "11.1.21",
"@nestjs/schedule": "6.1.3", "@nestjs/schedule": "6.1.3",
"@nestjs/serve-static": "5.0.5", "@nestjs/serve-static": "5.0.5",
"@openrouter/ai-sdk-provider": "2.9.0", "@openrouter/ai-sdk-provider": "2.9.0",
@ -138,7 +138,8 @@
"svgmap": "2.19.3", "svgmap": "2.19.3",
"tablemark": "4.1.0", "tablemark": "4.1.0",
"twitter-api-v2": "1.29.0", "twitter-api-v2": "1.29.0",
"yahoo-finance2": "3.14.0", "undici": "7.24.4",
"yahoo-finance2": "3.14.2",
"zone.js": "0.16.1" "zone.js": "0.16.1"
}, },
"devDependencies": { "devDependencies": {
@ -156,17 +157,17 @@
"@eslint/eslintrc": "3.3.1", "@eslint/eslintrc": "3.3.1",
"@eslint/js": "9.35.0", "@eslint/js": "9.35.0",
"@nestjs/schematics": "11.1.0", "@nestjs/schematics": "11.1.0",
"@nestjs/testing": "11.1.19", "@nestjs/testing": "11.1.21",
"@nx/angular": "22.7.2", "@nx/angular": "22.7.5",
"@nx/eslint-plugin": "22.7.2", "@nx/eslint-plugin": "22.7.5",
"@nx/jest": "22.7.2", "@nx/jest": "22.7.5",
"@nx/js": "22.7.2", "@nx/js": "22.7.5",
"@nx/module-federation": "22.7.2", "@nx/module-federation": "22.7.5",
"@nx/nest": "22.7.2", "@nx/nest": "22.7.5",
"@nx/node": "22.7.2", "@nx/node": "22.7.5",
"@nx/storybook": "22.7.2", "@nx/storybook": "22.7.5",
"@nx/web": "22.7.2", "@nx/web": "22.7.5",
"@nx/workspace": "22.7.2", "@nx/workspace": "22.7.5",
"@schematics/angular": "21.2.6", "@schematics/angular": "21.2.6",
"@storybook/addon-docs": "10.1.10", "@storybook/addon-docs": "10.1.10",
"@storybook/addon-themes": "10.1.10", "@storybook/addon-themes": "10.1.10",
@ -193,7 +194,7 @@
"jest": "30.2.0", "jest": "30.2.0",
"jest-environment-jsdom": "30.2.0", "jest-environment-jsdom": "30.2.0",
"jest-preset-angular": "16.0.0", "jest-preset-angular": "16.0.0",
"nx": "22.7.2", "nx": "22.7.5",
"prettier": "3.8.3", "prettier": "3.8.3",
"prettier-plugin-organize-attributes": "1.0.0", "prettier-plugin-organize-attributes": "1.0.0",
"prisma": "7.8.0", "prisma": "7.8.0",

4
tools/load-env.ts

@ -0,0 +1,4 @@
import { config } from 'dotenv';
import { expand } from 'dotenv-expand';
expand(config({ path: process.env.GHOSTFOLIO_ENV_FILE, quiet: true }));
Loading…
Cancel
Save