Compare commits

..

1 Commits

Author SHA1 Message Date
b23f3a8a81 Release 0.93.0 2021-04-26 21:55:51 +02:00
200 changed files with 1727 additions and 3891 deletions

2
.env
View File

@ -11,6 +11,6 @@ POSTGRES_DB=ghostfolio-db
ACCESS_TOKEN_SALT=GHOSTFOLIO
ALPHA_VANTAGE_API_KEY=
DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}?sslmode=prefer
DATABASE_URL=postgresql://user:password@localhost:5432/ghostfolio-db?sslmode=prefer
JWT_SECRET_KEY=123456
PORT=3333

View File

@ -1,10 +0,0 @@
language: node_js
git:
depth: false
node_js:
- 14
before_script:
- yarn
script:
- yarn format:check
- yarn test

View File

@ -5,152 +5,6 @@ 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/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 1.7.0 - 22.05.2021
### Changed
- Hid footer on mobile (except on landing page)
### Fixed
- Fixed the internal navigation of the _Zen Mode_ in combination with a query parameter
## 1.6.0 - 22.05.2021
### Added
- Added an index in the user table of the admin control panel
### Changed
- Improved the alignment in the user table of the admin control panel
## 1.5.0 - 22.05.2021
### Added
- Added _Zen Mode_: the distraction-free view
## 1.4.0 - 20.05.2021
### Added
- Added filtering by year in the transaction filtering component
### Changed
- Renamed _Ghostfolio Account_ to _My Ghostfolio_
- Hid unknown exchange in the position overview
- Disable the base currency selector for the demo user
- Refactored the portfolio unit tests to work without database
- Refactored the search functionality of the data management (aligned with data source)
- Renamed shared helper to `@ghostfolio/common/helper`
- Moved shared interfaces to `@ghostfolio/common/interfaces`
- Moved shared types to `@ghostfolio/common/types`
## 1.3.0 - 15.05.2021
### Changed
- Refactored the active menu item state by parsing the current url
- Used a desaturated background color for unknown types in pie charts
- Renamed the columns _Initial Share_ and _Current Share_ to _Initial Allocation_ and _Current Allocation_ in the positions table
### Fixed
- Fixed the link to the pricing page
## 1.2.1 - 14.05.2021
### Changed
- Updated the sitemap
## 1.2.0 - 14.05.2021
### Changed
- Harmonized the style of various tables
- Keep the color per type when switching between _Initial_ and _Current_ in pie charts
- Upgraded `chart.js` from version `3.0.2` to `3.2.1`
- Moved the pricing section to a dedicated page
- Improved the style of the transaction filtering component
### Fixed
- Fixed the tooltips when switching between _Initial_ and _Current_ in pie charts
## 1.1.0 - 11.05.2021
### Added
- Added a button to fetch the current market price in the create or edit transaction dialog
### Changed
- Improved the transaction filtering with multi filter support
### Fixed
- Fixed the filtering by account name in the transactions table
- Fixed the active menu item state when a modal has opened
## 1.0.0 - 05.05.2021
### Added
- Added the functionality to clone a transaction
- Added a _Google Play_ badge on the landing page
### Changed
- Changed to maskable icons
## 0.99.0 - 03.05.2021
### Added
- Added support for deleting users in the admin control panel
### Changed
- Eliminated the platform attribute from the transaction model
## 0.98.0 - 02.05.2021
### Added
- Added the logic to create and update accounts
## 0.97.0 - 01.05.2021
### Added
- Added an account page as a preparation for the multi accounts support
## 0.96.0 - 30.04.2021
### Added
- Added the absolute change to the position detail dialog
- Added the number of transactions to the position detail dialog
### Changed
- Harmonized the slogan to "Open Source Portfolio Tracker"
## 0.95.0 - 28.04.2021
### Added
- Added a data source attribute to the transactions model
## 0.94.0 - 27.04.2021
### Added
- Added the generic scraper symbols to the symbol lookup results
## 0.93.0 - 26.04.2021
### Changed

View File

@ -7,11 +7,8 @@
<a href="https://ghostfol.io"><strong>Live Demo</strong></a>
</p>
<p>
<a href="https://travis-ci.org/github/ghostfolio/ghostfolio" rel="nofollow">
<img src="https://travis-ci.org/ghostfolio/ghostfolio.svg?branch=main" alt="Build Status"/>
</a>
<a href="https://www.gnu.org/licenses/agpl-3.0" rel="nofollow">
<img src="https://img.shields.io/badge/License-AGPL%20v3-blue.svg" alt="License: AGPL v3"/>
<img src="https://img.shields.io/badge/License-AGPL%20v3-blue.svg" alt="License: AGPL v3">
</a>
</p>
</div>
@ -71,18 +68,19 @@ The frontend is built with [Angular](https://angular.io).
### Setup
1. Run `yarn install`
1. Run `cd docker`
1. Run `docker compose up -d` to start [PostgreSQL](https://www.postgresql.org) and [Redis](https://redis.io)
1. Run `cd -` to go back to the project root directory
1. Run `yarn setup:database` to initialize the database schema and populate your database with (example) data
1. Start server and client (see [_Development_](#Development))
1. Login as _Admin_ with the following _Security Token_: `ae76872ae8f3419c6d6f64bf51888ecbcc703927a342d815fafe486acdb938da07d0cf44fca211a0be74a423238f535362d390a41e81e633a9ce668a6e31cdf9`
1. Go to the _Admin Control Panel_ and press _Gather All Data_ to fetch historical data
1. Press _Sign out_ and check out the _Live Demo_
2. Run `cd docker`
3. Run `docker compose build`
4. Run `docker compose up -d` to start [PostgreSQL](https://www.postgresql.org) and [Redis](https://redis.io)
5. Run `cd -` to go back to the project root directory
6. Run `yarn setup:database` to initialize the database schema and populate your database with (example) data
7. Start server and client (see _Development_)
8. Login as _Admin_ with the following _Security Token_: `ae76872ae8f3419c6d6f64bf51888ecbcc703927a342d815fafe486acdb938da07d0cf44fca211a0be74a423238f535362d390a41e81e633a9ce668a6e31cdf9`
9. Go to the _Admin Control Panel_ and press _Gather All Data_ to fetch historical data
10. Press _Sign out_ and check out the _Live Demo_
## Development
Please make sure you have completed the instructions from [_Setup_](#Setup)
Please make sure you have completed the instructions from _Setup_
### Start server

View File

@ -208,22 +208,22 @@
}
}
},
"common": {
"root": "libs/common",
"sourceRoot": "libs/common/src",
"helper": {
"root": "libs/helper",
"sourceRoot": "libs/helper/src",
"projectType": "library",
"architect": {
"lint": {
"builder": "@nrwl/linter:eslint",
"options": {
"lintFilePatterns": ["libs/common/**/*.ts"]
"lintFilePatterns": ["libs/helper/**/*.ts"]
}
},
"test": {
"builder": "@nrwl/jest:jest",
"outputs": ["coverage/libs/common"],
"outputs": ["coverage/libs/helper"],
"options": {
"jestConfig": "libs/common/jest.config.js",
"jestConfig": "libs/helper/jest.config.js",
"passWithNoTests": true
}
}

View File

@ -1,10 +1,10 @@
import { Access } from '@ghostfolio/common/interfaces';
import { RequestWithUser } from '@ghostfolio/common/types';
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import { Controller, Get, Inject, UseGuards } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { AccessService } from './access.service';
import { Access } from './interfaces/access.interface';
@Controller('access')
export class AccessController {

View File

@ -1,8 +1,9 @@
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { AccessWithGranteeUser } from '@ghostfolio/common/types';
import { Injectable } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { AccessWithGranteeUser } from './interfaces/access-with-grantee-user.type';
@Injectable()
export class AccessService {
public constructor(private prisma: PrismaService) {}

View File

@ -1,241 +0,0 @@
import { nullifyValuesInObjects } from '@ghostfolio/api/helper/object.helper';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation.service';
import {
getPermissions,
hasPermission,
permissions
} from '@ghostfolio/common/permissions';
import { RequestWithUser } from '@ghostfolio/common/types';
import {
Body,
Controller,
Delete,
Get,
Headers,
HttpException,
Inject,
Param,
Post,
Put,
UseGuards
} from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { Account as AccountModel } from '@prisma/client';
import { StatusCodes, getReasonPhrase } from 'http-status-codes';
import { AccountService } from './account.service';
import { CreateAccountDto } from './create-account.dto';
import { UpdateAccountDto } from './update-account.dto';
@Controller('account')
export class AccountController {
public constructor(
private readonly accountService: AccountService,
private readonly impersonationService: ImpersonationService,
@Inject(REQUEST) private readonly request: RequestWithUser
) {}
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
public async deleteAccount(@Param('id') id: string): Promise<AccountModel> {
if (
!hasPermission(
getPermissions(this.request.user.role),
permissions.deleteAccount
)
) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
const account = await this.accountService.accountWithOrders(
{
id_userId: {
id,
userId: this.request.user.id
}
},
{ Order: true }
);
if (account?.isDefault || account?.Order.length > 0) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
return this.accountService.deleteAccount(
{
id_userId: {
id,
userId: this.request.user.id
}
},
this.request.user.id
);
}
@Get()
@UseGuards(AuthGuard('jwt'))
public async getAllAccounts(
@Headers('impersonation-id') impersonationId
): Promise<AccountModel[]> {
const impersonationUserId = await this.impersonationService.validateImpersonationId(
impersonationId,
this.request.user.id
);
let accounts = await this.accountService.accounts({
include: { Order: true, Platform: true },
orderBy: { name: 'asc' },
where: { userId: impersonationUserId || this.request.user.id }
});
if (
impersonationUserId &&
!hasPermission(
getPermissions(this.request.user.role),
permissions.readForeignPortfolio
)
) {
accounts = nullifyValuesInObjects(accounts, [
'fee',
'quantity',
'unitPrice'
]);
}
return accounts;
}
@Get(':id')
@UseGuards(AuthGuard('jwt'))
public async getAccountById(@Param('id') id: string): Promise<AccountModel> {
return this.accountService.account({
id_userId: {
id,
userId: this.request.user.id
}
});
}
@Post()
@UseGuards(AuthGuard('jwt'))
public async createAccount(
@Body() data: CreateAccountDto
): Promise<AccountModel> {
if (
!hasPermission(
getPermissions(this.request.user.role),
permissions.createAccount
)
) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
if (data.platformId) {
const platformId = data.platformId;
delete data.platformId;
return this.accountService.createAccount(
{
...data,
Platform: { connect: { id: platformId } },
User: { connect: { id: this.request.user.id } }
},
this.request.user.id
);
} else {
delete data.platformId;
return this.accountService.createAccount(
{
...data,
User: { connect: { id: this.request.user.id } }
},
this.request.user.id
);
}
}
@Put(':id')
@UseGuards(AuthGuard('jwt'))
public async update(@Param('id') id: string, @Body() data: UpdateAccountDto) {
if (
!hasPermission(
getPermissions(this.request.user.role),
permissions.updateAccount
)
) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
const originalAccount = await this.accountService.account({
id_userId: {
id,
userId: this.request.user.id
}
});
if (!originalAccount) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
if (data.platformId) {
const platformId = data.platformId;
delete data.platformId;
return this.accountService.updateAccount(
{
data: {
...data,
Platform: { connect: { id: platformId } },
User: { connect: { id: this.request.user.id } }
},
where: {
id_userId: {
id,
userId: this.request.user.id
}
}
},
this.request.user.id
);
} else {
// platformId is null, remove it
delete data.platformId;
return this.accountService.updateAccount(
{
data: {
...data,
Platform: originalAccount.platformId
? { disconnect: true }
: undefined,
User: { connect: { id: this.request.user.id } }
},
where: {
id_userId: {
id,
userId: this.request.user.id
}
}
},
this.request.user.id
);
}
}
}

View File

@ -1,30 +0,0 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration.service';
import { DataProviderService } from '@ghostfolio/api/services/data-provider.service';
import { AlphaVantageService } from '@ghostfolio/api/services/data-provider/alpha-vantage/alpha-vantage.service';
import { GhostfolioScraperApiService } from '@ghostfolio/api/services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service';
import { RakutenRapidApiService } from '@ghostfolio/api/services/data-provider/rakuten-rapid-api/rakuten-rapid-api.service';
import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation.service';
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { Module } from '@nestjs/common';
import { RedisCacheModule } from '../redis-cache/redis-cache.module';
import { AccountController } from './account.controller';
import { AccountService } from './account.service';
@Module({
imports: [RedisCacheModule],
controllers: [AccountController],
providers: [
AccountService,
AlphaVantageService,
ConfigurationService,
DataProviderService,
GhostfolioScraperApiService,
ImpersonationService,
PrismaService,
RakutenRapidApiService,
YahooFinanceService
]
})
export class AccountModule {}

View File

@ -1,89 +0,0 @@
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { Injectable } from '@nestjs/common';
import { Account, Order, Prisma } from '@prisma/client';
import { RedisCacheService } from '../redis-cache/redis-cache.service';
@Injectable()
export class AccountService {
public constructor(
private readonly redisCacheService: RedisCacheService,
private prisma: PrismaService
) {}
public async account(
accountWhereUniqueInput: Prisma.AccountWhereUniqueInput
): Promise<Account | null> {
return this.prisma.account.findUnique({
where: accountWhereUniqueInput
});
}
public async accountWithOrders(
accountWhereUniqueInput: Prisma.AccountWhereUniqueInput,
accountInclude: Prisma.AccountInclude
): Promise<
Account & {
Order?: Order[];
}
> {
return this.prisma.account.findUnique({
include: accountInclude,
where: accountWhereUniqueInput
});
}
public async accounts(params: {
include?: Prisma.AccountInclude;
skip?: number;
take?: number;
cursor?: Prisma.AccountWhereUniqueInput;
where?: Prisma.AccountWhereInput;
orderBy?: Prisma.AccountOrderByInput;
}): Promise<Account[]> {
const { include, skip, take, cursor, where, orderBy } = params;
return this.prisma.account.findMany({
cursor,
include,
orderBy,
skip,
take,
where
});
}
public async createAccount(
data: Prisma.AccountCreateInput,
aUserId: string
): Promise<Account> {
return this.prisma.account.create({
data
});
}
public async deleteAccount(
where: Prisma.AccountWhereUniqueInput,
aUserId: string
): Promise<Account> {
this.redisCacheService.remove(`${aUserId}.portfolio`);
return this.prisma.account.delete({
where
});
}
public async updateAccount(
params: {
where: Prisma.AccountWhereUniqueInput;
data: Prisma.AccountUpdateInput;
},
aUserId: string
): Promise<Account> {
const { data, where } = params;
return this.prisma.account.update({
data,
where
});
}
}

View File

@ -1,14 +0,0 @@
import { AccountType } from '@prisma/client';
import { IsString, ValidateIf } from 'class-validator';
export class CreateAccountDto {
@IsString()
accountType: AccountType;
@IsString()
name: string;
@IsString()
@ValidateIf((object, value) => value !== null)
platformId: string | null;
}

View File

@ -1,17 +0,0 @@
import { AccountType } from '@prisma/client';
import { IsString, ValidateIf } from 'class-validator';
export class UpdateAccountDto {
@IsString()
accountType: AccountType;
@IsString()
id: string;
@IsString()
name: string;
@IsString()
@ValidateIf((object, value) => value !== null)
platformId: string | null;
}

View File

@ -1,11 +1,6 @@
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import { DataGatheringService } from '@ghostfolio/api/services/data-gathering.service';
import { AdminData } from '@ghostfolio/common/interfaces';
import {
getPermissions,
hasPermission,
permissions
} from '@ghostfolio/common/permissions';
import { RequestWithUser } from '@ghostfolio/common/types';
import { getPermissions, hasPermission, permissions } from '@ghostfolio/helper';
import {
Controller,
Get,
@ -19,6 +14,7 @@ import { AuthGuard } from '@nestjs/passport';
import { StatusCodes, getReasonPhrase } from 'http-status-codes';
import { AdminService } from './admin.service';
import { AdminData } from './interfaces/admin-data.interface';
@Controller('admin')
export class AdminController {

View File

@ -1,9 +1,10 @@
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { AdminData } from '@ghostfolio/common/interfaces';
import { Injectable } from '@nestjs/common';
import { Currency } from '@prisma/client';
import { AdminData } from './interfaces/admin-data.interface';
@Injectable()
export class AdminService {
public constructor(
@ -108,7 +109,7 @@ export class AdminService {
createdAt: true,
id: true
},
take: 30,
take: 20,
where: {
NOT: {
Analytics: null

View File

@ -16,7 +16,6 @@ import { YahooFinanceService } from '../services/data-provider/yahoo-finance/yah
import { ExchangeRateDataService } from '../services/exchange-rate-data.service';
import { PrismaService } from '../services/prisma.service';
import { AccessModule } from './access/access.module';
import { AccountModule } from './account/account.module';
import { AdminModule } from './admin/admin.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
@ -33,7 +32,6 @@ import { UserModule } from './user/user.module';
imports: [
AdminModule,
AccessModule,
AccountModule,
AuthModule,
CacheModule,
ConfigModule.forRoot(),

View File

@ -1,5 +1,5 @@
import { RequestWithUser } from '@ghostfolio/common/types';
import { Controller, Inject, Post, UseGuards } from '@nestjs/common';
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import { Controller, Inject, Param, Post, UseGuards } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';

View File

@ -1,6 +1,9 @@
import { baseCurrency, benchmarks } from '@ghostfolio/common/config';
import { isApiTokenAuthorized } from '@ghostfolio/common/permissions';
import { RequestWithUser } from '@ghostfolio/common/types';
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import {
baseCurrency,
benchmarks,
isApiTokenAuthorized
} from '@ghostfolio/helper';
import {
Body,
Controller,

View File

@ -3,11 +3,11 @@ import { DataProviderService } from '@ghostfolio/api/services/data-provider.serv
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { RulesService } from '@ghostfolio/api/services/rules.service';
import { OrderWithAccount } from '@ghostfolio/common/types';
import { Injectable } from '@nestjs/common';
import { Currency, Type } from '@prisma/client';
import { parseISO } from 'date-fns';
import { OrderWithPlatform } from '../order/interfaces/order-with-platform.type';
import { CreateOrderDto } from './create-order.dto';
import { Data } from './interfaces/data.interface';
@ -33,13 +33,12 @@ export class ExperimentalService {
aDate: Date,
aBaseCurrency: Currency
): Promise<Data> {
const ordersWithPlatform: OrderWithAccount[] = aOrders.map((order) => {
const ordersWithPlatform: OrderWithPlatform[] = aOrders.map((order) => {
return {
...order,
accountId: undefined,
accountUserId: undefined,
createdAt: new Date(),
dataSource: undefined,
date: parseISO(order.date),
fee: 0,
id: undefined,

View File

@ -1,7 +1,7 @@
import { InfoItem } from '@ghostfolio/common/interfaces';
import { Controller, Get } from '@nestjs/common';
import { InfoService } from './info.service';
import { InfoItem } from './interfaces/info-item.interface';
@Controller('info')
export class InfoController {

View File

@ -1,11 +1,12 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration.service';
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { InfoItem } from '@ghostfolio/common/interfaces';
import { permissions } from '@ghostfolio/common/permissions';
import { permissions } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Currency } from '@prisma/client';
import { InfoItem } from './interfaces/info-item.interface';
@Injectable()
export class InfoService {
private static DEMO_USER_ID = '9b112b4d-3b7d-4bad-9bdd-3b0f7b4dac2f';

View File

@ -1,3 +1,3 @@
import { UserWithSettings } from '@ghostfolio/common/interfaces';
import { UserWithSettings } from './user-with-settings';
export type RequestWithUser = Request & { user: UserWithSettings };

View File

@ -1,4 +1,4 @@
import { Currency, DataSource, Type } from '@prisma/client';
import { Currency, Type } from '@prisma/client';
import { IsISO8601, IsNumber, IsString, ValidateIf } from 'class-validator';
export class CreateOrderDto {
@ -8,15 +8,16 @@ export class CreateOrderDto {
@IsString()
currency: Currency;
@IsString()
dataSource: DataSource;
@IsISO8601()
date: string;
@IsNumber()
fee: number;
@IsString()
@ValidateIf((object, value) => value !== null)
platformId: string | null;
@IsNumber()
quantity: number;

View File

@ -0,0 +1,3 @@
import { Order, Platform } from '@prisma/client';
export type OrderWithPlatform = Order & { Platform?: Platform };

View File

@ -1,11 +1,7 @@
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import { nullifyValuesInObjects } from '@ghostfolio/api/helper/object.helper';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation.service';
import {
getPermissions,
hasPermission,
permissions
} from '@ghostfolio/common/permissions';
import { RequestWithUser } from '@ghostfolio/common/types';
import { getPermissions, hasPermission, permissions } from '@ghostfolio/helper';
import {
Body,
Controller,
@ -74,12 +70,8 @@ export class OrderController {
);
let orders = await this.orderService.orders({
include: {
Account: {
include: {
Platform: true
}
}
},
orderBy: { date: 'desc' },
where: { userId: impersonationUserId || this.request.user.id }
@ -129,6 +121,27 @@ export class OrderController {
const accountId = data.accountId;
delete data.accountId;
if (data.platformId) {
const platformId = data.platformId;
delete data.platformId;
return this.orderService.createOrder(
{
...data,
date,
Account: {
connect: {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
Platform: { connect: { id: platformId } },
User: { connect: { id: this.request.user.id } }
},
this.request.user.id
);
} else {
delete data.platformId;
return this.orderService.createOrder(
{
...data,
@ -143,6 +156,7 @@ export class OrderController {
this.request.user.id
);
}
}
@Put(':id')
@UseGuards(AuthGuard('jwt'))
@ -166,18 +180,15 @@ export class OrderController {
}
});
if (!originalOrder) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
const date = parseISO(data.date);
const accountId = data.accountId;
delete data.accountId;
if (data.platformId) {
const platformId = data.platformId;
delete data.platformId;
return this.orderService.updateOrder(
{
data: {
@ -188,6 +199,35 @@ export class OrderController {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
Platform: { connect: { id: platformId } },
User: { connect: { id: this.request.user.id } }
},
where: {
id_userId: {
id,
userId: this.request.user.id
}
}
},
this.request.user.id
);
} else {
// platformId is null, remove it
delete data.platformId;
return this.orderService.updateOrder(
{
data: {
...data,
date,
Account: {
connect: {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
Platform: originalOrder.platformId
? { disconnect: true }
: undefined,
User: { connect: { id: this.request.user.id } }
},
where: {
@ -201,3 +241,4 @@ export class OrderController {
);
}
}
}

View File

@ -1,11 +1,11 @@
import { DataGatheringService } from '@ghostfolio/api/services/data-gathering.service';
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { OrderWithAccount } from '@ghostfolio/common/types';
import { Injectable } from '@nestjs/common';
import { Order, Prisma } from '@prisma/client';
import { CacheService } from '../cache/cache.service';
import { RedisCacheService } from '../redis-cache/redis-cache.service';
import { OrderWithPlatform } from './interfaces/order-with-platform.type';
@Injectable()
export class OrderService {
@ -31,7 +31,7 @@ export class OrderService {
cursor?: Prisma.OrderWhereUniqueInput;
where?: Prisma.OrderWhereInput;
orderBy?: Prisma.OrderOrderByInput;
}): Promise<OrderWithAccount[]> {
}): Promise<OrderWithPlatform[]> {
const { include, skip, take, cursor, where, orderBy } = params;
return this.prisma.order.findMany({

View File

@ -1,4 +1,4 @@
import { Currency, DataSource, Type } from '@prisma/client';
import { Currency, Type } from '@prisma/client';
import { IsISO8601, IsNumber, IsString, ValidateIf } from 'class-validator';
export class UpdateOrderDto {
@ -8,15 +8,16 @@ export class UpdateOrderDto {
@IsString()
currency: Currency;
@IsString()
dataSource: DataSource;
@IsISO8601()
date: string;
@IsNumber()
fee: number;
@IsString()
@ValidateIf((object, value) => value !== null)
platformId: string | null;
@IsString()
id: string;

View File

@ -1,5 +1,13 @@
import { Currency } from '@prisma/client';
export interface PortfolioItem {
date: string;
grossPerformancePercent: number;
investment: number;
positions: { [symbol: string]: Position };
value: number;
}
export interface Position {
averagePrice: number;
currency: Currency;
@ -8,5 +16,4 @@ export interface Position {
investmentInOriginalCurrency?: number;
marketPrice?: number;
quantity: number;
transactionCount: number;
}

View File

@ -1,8 +1,6 @@
import { Currency } from '@prisma/client';
export interface PortfolioPositionDetail {
averagePrice: number;
currency: Currency;
currency: string;
firstBuyDate: string;
grossPerformance: number;
grossPerformancePercent: number;
@ -13,7 +11,6 @@ export interface PortfolioPositionDetail {
minPrice: number;
quantity: number;
symbol: string;
transactionCount: number;
}
export interface HistoricalDataItem {

View File

@ -2,11 +2,6 @@ import { MarketState } from '@ghostfolio/api/services/interfaces/interfaces';
import { Currency } from '@prisma/client';
export interface PortfolioPosition {
accounts: {
[name: string]: { current: number; original: number };
};
allocationCurrent: number;
allocationInvestment: number;
currency: Currency;
exchange?: string;
grossPerformance: number;
@ -18,9 +13,13 @@ export interface PortfolioPosition {
marketPrice: number;
marketState: MarketState;
name: string;
platforms: {
[name: string]: { current: number; original: number };
};
quantity: number;
sector?: string;
transactionCount: number;
shareCurrent: number;
shareInvestment: number;
symbol: string;
type?: string;
url?: string;

View File

@ -1,3 +1,7 @@
export interface PortfolioReport {
rules: { [group: string]: PortfolioReportRule[] };
}
export interface PortfolioReportRule {
evaluation: string;
name: string;

View File

@ -4,19 +4,7 @@ import {
} from '@ghostfolio/api/helper/object.helper';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation.service';
import {
PortfolioItem,
PortfolioOverview,
PortfolioPerformance,
PortfolioPosition,
PortfolioReport
} from '@ghostfolio/common/interfaces';
import {
getPermissions,
hasPermission,
permissions
} from '@ghostfolio/common/permissions';
import { RequestWithUser } from '@ghostfolio/common/types';
import { getPermissions, hasPermission, permissions } from '@ghostfolio/helper';
import {
Controller,
Get,
@ -33,10 +21,16 @@ import { AuthGuard } from '@nestjs/passport';
import { Response } from 'express';
import { StatusCodes, getReasonPhrase } from 'http-status-codes';
import { RequestWithUser } from '../interfaces/request-with-user.type';
import { PortfolioItem } from './interfaces/portfolio-item.interface';
import { PortfolioOverview } from './interfaces/portfolio-overview.interface';
import { PortfolioPerformance } from './interfaces/portfolio-performance.interface';
import {
HistoricalDataItem,
PortfolioPositionDetail
} from './interfaces/portfolio-position-detail.interface';
import { PortfolioPosition } from './interfaces/portfolio-position.interface';
import { PortfolioReport } from './interfaces/portfolio-report.interface';
import { PortfolioService } from './portfolio.service';
@Controller('portfolio')
@ -191,11 +185,11 @@ export class PortfolioController {
portfolioPosition.investment =
portfolioPosition.investment / totalInvestment;
for (const [account, { current, original }] of Object.entries(
portfolioPosition.accounts
for (const [platform, { current, original }] of Object.entries(
portfolioPosition.platforms
)) {
portfolioPosition.accounts[account].current = current / totalValue;
portfolioPosition.accounts[account].original =
portfolioPosition.platforms[platform].current = current / totalValue;
portfolioPosition.platforms[platform].original =
original / totalInvestment;
}

View File

@ -1,14 +1,10 @@
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import { Portfolio } from '@ghostfolio/api/models/portfolio';
import { DataProviderService } from '@ghostfolio/api/services/data-provider.service';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { ImpersonationService } from '@ghostfolio/api/services/impersonation.service';
import { IOrder } from '@ghostfolio/api/services/interfaces/interfaces';
import { RulesService } from '@ghostfolio/api/services/rules.service';
import {
PortfolioItem,
PortfolioOverview
} from '@ghostfolio/common/interfaces';
import { DateRange, RequestWithUser } from '@ghostfolio/common/types';
import { Inject, Injectable } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import {
@ -30,6 +26,9 @@ import * as roundTo from 'round-to';
import { OrderService } from '../order/order.service';
import { RedisCacheService } from '../redis-cache/redis-cache.service';
import { UserService } from '../user/user.service';
import { DateRange } from './interfaces/date-range.type';
import { PortfolioItem } from './interfaces/portfolio-item.interface';
import { PortfolioOverview } from './interfaces/portfolio-overview.interface';
import {
HistoricalDataItem,
PortfolioPositionDetail
@ -74,7 +73,7 @@ export class PortfolioService {
// Get portfolio from database
const orders = await this.orderService.orders({
include: {
Account: true
Platform: true
},
orderBy: { date: 'asc' },
where: { userId: aUserId }
@ -210,8 +209,7 @@ export class PortfolioService {
firstBuyDate,
investment,
marketPrice,
quantity,
transactionCount
quantity
} = portfolio.getPositions(new Date())[aSymbol];
const historicalData = await this.dataProviderService.getHistorical(
@ -264,7 +262,6 @@ export class PortfolioService {
maxPrice,
minPrice,
quantity,
transactionCount,
grossPerformance: this.exchangeRateDataService.toCurrency(
marketPrice - averagePrice,
currency,
@ -318,8 +315,7 @@ export class PortfolioService {
maxPrice: undefined,
minPrice: undefined,
quantity: undefined,
symbol: aSymbol,
transactionCount: undefined
symbol: aSymbol
};
}
@ -335,8 +331,7 @@ export class PortfolioService {
maxPrice: undefined,
minPrice: undefined,
quantity: undefined,
symbol: aSymbol,
transactionCount: undefined
symbol: aSymbol
};
}

View File

@ -1,7 +1,4 @@
import { DataSource } from '@prisma/client';
export interface LookupItem {
dataSource: DataSource;
name: string;
symbol: string;
}

View File

@ -1,7 +1,6 @@
import { Currency, DataSource } from '@prisma/client';
import { Currency } from '@prisma/client';
export interface SymbolItem {
currency: Currency;
dataSource: DataSource;
marketPrice: number;
}

View File

@ -1,4 +1,4 @@
import { RequestWithUser } from '@ghostfolio/common/types';
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import {
Controller,
Get,
@ -28,12 +28,9 @@ export class SymbolController {
*/
@Get('lookup')
@UseGuards(AuthGuard('jwt'))
public async lookupSymbol(
@Query() { query = '' }
): Promise<{ items: LookupItem[] }> {
public async lookupSymbol(@Query() { query }): Promise<LookupItem[]> {
try {
const encodedQuery = encodeURIComponent(query.toLowerCase());
return this.symbolService.lookup(encodedQuery);
return this.symbolService.lookup(query);
} catch {
throw new HttpException(
getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR),

View File

@ -1,8 +1,8 @@
import { DataProviderService } from '@ghostfolio/api/services/data-provider.service';
import { GhostfolioScraperApiService } from '@ghostfolio/api/services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service';
import { convertFromYahooSymbol } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service';
import { Injectable } from '@nestjs/common';
import { Currency, DataSource } from '@prisma/client';
import { Currency } from '@prisma/client';
import * as bent from 'bent';
import { LookupItem } from './interfaces/lookup-item.interface';
import { SymbolItem } from './interfaces/symbol-item.interface';
@ -10,45 +10,55 @@ import { SymbolItem } from './interfaces/symbol-item.interface';
@Injectable()
export class SymbolService {
public constructor(
private readonly dataProviderService: DataProviderService,
private readonly ghostfolioScraperApiService: GhostfolioScraperApiService
private readonly dataProviderService: DataProviderService
) {}
public async get(aSymbol: string): Promise<SymbolItem> {
const response = await this.dataProviderService.get([aSymbol]);
const { currency, dataSource, marketPrice } = response[aSymbol];
const { currency, marketPrice } = response[aSymbol];
return {
dataSource,
marketPrice,
currency: <Currency>(<unknown>currency)
};
}
public async lookup(aQuery: string): Promise<{ items: LookupItem[] }> {
const results: { items: LookupItem[] } = { items: [] };
if (!aQuery) {
return results;
}
public async lookup(aQuery: string): Promise<LookupItem[]> {
const get = bent(
`https://query1.finance.yahoo.com/v1/finance/search?q=${aQuery}&lang=en-US&region=US&quotesCount=8&newsCount=0&enableFuzzyQuery=false&quotesQueryId=tss_match_phrase_query&multiQuoteQueryId=multi_quote_single_token_query&newsQueryId=news_cie_vespa&enableCb=true&enableNavLinks=false&enableEnhancedTrivialQuery=true`,
'GET',
'json',
200
);
try {
const { items } = await this.dataProviderService.search(aQuery);
results.items = items;
const { quotes } = await get();
// Add custom symbols
const scraperConfigurations = await this.ghostfolioScraperApiService.getScraperConfigurations();
scraperConfigurations.forEach((scraperConfiguration) => {
if (scraperConfiguration.name.toLowerCase().startsWith(aQuery)) {
results.items.push({
dataSource: DataSource.GHOSTFOLIO,
name: scraperConfiguration.name,
symbol: scraperConfiguration.symbol
});
return quotes
.filter(({ isYahooFinance }) => {
return isYahooFinance;
})
.filter(({ quoteType }) => {
return (
quoteType === 'CRYPTOCURRENCY' ||
quoteType === 'EQUITY' ||
quoteType === 'ETF'
);
})
.filter(({ quoteType, symbol }) => {
if (quoteType === 'CRYPTOCURRENCY') {
// Only allow cryptocurrencies in USD
return symbol.includes('USD');
}
});
return results;
return true;
})
.map(({ longname, shortname, symbol }) => {
return {
name: longname || shortname,
symbol: convertFromYahooSymbol(symbol)
};
});
} catch (error) {
console.error(error);

View File

@ -1,7 +1,6 @@
import { Access } from '@ghostfolio/api/app/user/interfaces/access.interface';
import { Account } from '@prisma/client';
import { Account, Currency } from '@prisma/client';
import { UserSettings } from './user-settings.interface';
import { Access } from './access.interface';
export interface User {
access: Access[];
@ -15,3 +14,8 @@ export interface User {
type: 'Trial';
};
}
export interface UserSettings {
baseCurrency: Currency;
locale: string;
}

View File

@ -1,10 +1,7 @@
import { Currency, ViewMode } from '@prisma/client';
import { Currency } from '@prisma/client';
import { IsString } from 'class-validator';
export class UpdateUserSettingsDto {
@IsString()
baseCurrency: Currency;
@IsString()
viewMode: ViewMode;
currency: Currency;
}

View File

@ -1,14 +1,8 @@
import { User } from '@ghostfolio/common/interfaces';
import {
getPermissions,
hasPermission,
permissions
} from '@ghostfolio/common/permissions';
import { RequestWithUser } from '@ghostfolio/common/types';
import { RequestWithUser } from '@ghostfolio/api/app/interfaces/request-with-user.type';
import { getPermissions, hasPermission, permissions } from '@ghostfolio/helper';
import {
Body,
Controller,
Delete,
Get,
HttpException,
Inject,
@ -21,10 +15,10 @@ import { REQUEST } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';
import { Provider } from '@prisma/client';
import { User as UserModel } from '@prisma/client';
import { StatusCodes, getReasonPhrase } from 'http-status-codes';
import { UserItem } from './interfaces/user-item.interface';
import { User } from './interfaces/user.interface';
import { UpdateUserSettingsDto } from './update-user-settings.dto';
import { UserService } from './user.service';
@ -36,27 +30,6 @@ export class UserController {
private readonly userService: UserService
) {}
@Delete(':id')
@UseGuards(AuthGuard('jwt'))
public async deleteUser(@Param('id') id: string): Promise<UserModel> {
if (
!hasPermission(
getPermissions(this.request.user.role),
permissions.deleteUser
) ||
id === this.request.user.id
) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
return this.userService.deleteUser({
id
});
}
@Get()
@UseGuards(AuthGuard('jwt'))
public async getUser(@Param('id') id: string): Promise<User> {
@ -93,9 +66,8 @@ export class UserController {
}
return await this.userService.updateUserSettings({
currency: data.baseCurrency,
userId: this.request.user.id,
viewMode: data.viewMode
currency: data.currency,
userId: this.request.user.id
});
}
}

View File

@ -1,13 +1,18 @@
import { ConfigurationService } from '@ghostfolio/api/services/configuration.service';
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
import { locale } from '@ghostfolio/common/config';
import { resetHours } from '@ghostfolio/common/helper';
import { User as IUser, UserWithSettings } from '@ghostfolio/common/interfaces';
import { getPermissions, permissions } from '@ghostfolio/common/permissions';
import {
getPermissions,
locale,
permissions,
resetHours
} from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { Currency, Prisma, Provider, User, ViewMode } from '@prisma/client';
import { Currency, Prisma, Provider, User } from '@prisma/client';
import { add } from 'date-fns';
import { UserWithSettings } from '../interfaces/user-with-settings';
import { User as IUser } from './interfaces/user.interface';
const crypto = require('crypto');
@Injectable()
@ -52,9 +57,8 @@ export class UserService {
accounts: Account,
permissions: currentPermissions,
settings: {
locale,
baseCurrency: Settings?.currency ?? UserService.DEFAULT_CURRENCY,
viewMode: Settings.viewMode ?? ViewMode.DEFAULT
baseCurrency: Settings?.currency || UserService.DEFAULT_CURRENCY,
locale
},
subscription: {
expiresAt: resetHours(add(new Date(), { days: 7 })),
@ -81,8 +85,7 @@ export class UserService {
user.Settings = {
currency: UserService.DEFAULT_CURRENCY,
updatedAt: new Date(),
userId: user?.id,
viewMode: ViewMode.DEFAULT
userId: user?.id
};
}
@ -160,28 +163,6 @@ export class UserService {
}
public async deleteUser(where: Prisma.UserWhereUniqueInput): Promise<User> {
await this.prisma.access.deleteMany({
where: { OR: [{ granteeUserId: where.id }, { userId: where.id }] }
});
await this.prisma.account.deleteMany({
where: { userId: where.id }
});
await this.prisma.analytics.delete({
where: { userId: where.id }
});
await this.prisma.order.deleteMany({
where: { userId: where.id }
});
try {
await this.prisma.settings.delete({
where: { userId: where.id }
});
} catch {}
return this.prisma.user.delete({
where
});
@ -189,12 +170,10 @@ export class UserService {
public async updateUserSettings({
currency,
userId,
viewMode
userId
}: {
currency?: Currency;
currency: Currency;
userId: string;
viewMode?: ViewMode;
}) {
await this.prisma.settings.upsert({
create: {
@ -203,12 +182,10 @@ export class UserService {
connect: {
id: userId
}
},
viewMode
}
},
update: {
currency,
viewMode
currency
},
where: {
userId: userId

View File

@ -1,4 +1,7 @@
import { PortfolioItem, Position } from '@ghostfolio/common/interfaces';
import {
PortfolioItem,
Position
} from '@ghostfolio/api/app/portfolio/interfaces/portfolio-item.interface';
import { Order } from '../order';

View File

@ -1,4 +1,4 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { EvaluationResult } from './evaluation-result.interface';

View File

@ -1,27 +1,27 @@
import { Account, Currency, Platform } from '@prisma/client';
import { Currency, Platform } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';
import { IOrder } from '../services/interfaces/interfaces';
import { OrderType } from './order-type';
export class Order {
private account: Account;
private currency: Currency;
private fee: number;
private date: string;
private id: string;
private quantity: number;
private platform: Platform;
private symbol: string;
private total: number;
private type: OrderType;
private unitPrice: number;
public constructor(data: IOrder) {
this.account = data.account;
this.currency = data.currency;
this.fee = data.fee;
this.date = data.date;
this.id = data.id || uuidv4();
this.platform = data.platform;
this.quantity = data.quantity;
this.symbol = data.symbol;
this.type = data.type;
@ -30,10 +30,6 @@ export class Order {
this.total = this.quantity * data.unitPrice;
}
public getAccount() {
return this.account;
}
public getCurrency() {
return this.currency;
}
@ -50,6 +46,10 @@ export class Order {
return this.id;
}
public getPlatform() {
return this.platform;
}
public getQuantity() {
return this.quantity;
}

View File

@ -1,102 +1,65 @@
import { UNKNOWN_KEY, baseCurrency } from '@ghostfolio/common/config';
import { getUtc, getYesterday } from '@ghostfolio/common/helper';
import {
AccountType,
Currency,
DataSource,
Role,
Type,
ViewMode
} from '@prisma/client';
import { format } from 'date-fns';
import { baseCurrency, getUtc, getYesterday } from '@ghostfolio/helper';
import { Test } from '@nestjs/testing';
import { Currency, Role, Type } from '@prisma/client';
import { ConfigurationService } from '../services/configuration.service';
import { DataProviderService } from '../services/data-provider.service';
import { AlphaVantageService } from '../services/data-provider/alpha-vantage/alpha-vantage.service';
import { GhostfolioScraperApiService } from '../services/data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service';
import { RakutenRapidApiService } from '../services/data-provider/rakuten-rapid-api/rakuten-rapid-api.service';
import { YahooFinanceService } from '../services/data-provider/yahoo-finance/yahoo-finance.service';
import { ExchangeRateDataService } from '../services/exchange-rate-data.service';
import { MarketState } from '../services/interfaces/interfaces';
import { PrismaService } from '../services/prisma.service';
import { RulesService } from '../services/rules.service';
import { Portfolio } from './portfolio';
jest.mock('../services/data-provider.service', () => {
return {
DataProviderService: jest.fn().mockImplementation(() => {
const today = format(new Date(), 'yyyy-MM-dd');
const yesterday = format(getYesterday(), 'yyyy-MM-dd');
return {
get: () => {
return Promise.resolve({
BTCUSD: {
currency: Currency.USD,
dataSource: DataSource.YAHOO,
exchange: UNKNOWN_KEY,
marketPrice: 57973.008,
marketState: MarketState.open,
name: 'Bitcoin USD',
type: 'Cryptocurrency'
},
ETHUSD: {
currency: Currency.USD,
dataSource: DataSource.YAHOO,
exchange: UNKNOWN_KEY,
marketPrice: 3915.337,
marketState: MarketState.open,
name: 'Ethereum USD',
type: 'Cryptocurrency'
}
});
},
getHistorical: () => {
return Promise.resolve({
BTCUSD: {
[yesterday]: 56710.122,
[today]: 57973.008
},
ETHUSD: {
[yesterday]: 3641.984,
[today]: 3915.337
}
});
}
};
})
};
});
jest.mock('../services/exchange-rate-data.service', () => {
return {
ExchangeRateDataService: jest.fn().mockImplementation(() => {
return {
initialize: () => Promise.resolve(),
toCurrency: (value: number) => value
};
})
};
});
jest.mock('../services/data-provider.service');
jest.mock('../services/exchange-rate-data.service');
jest.mock('../services/rules.service');
const DEFAULT_ACCOUNT_ID = '693a834b-eb89-42c9-ae47-35196c25d269';
const USER_ID = 'ca6ce867-5d31-495a-bce9-5942bbca9237';
describe('Portfolio', () => {
let alphaVantageService: AlphaVantageService;
let configurationService: ConfigurationService;
let dataProviderService: DataProviderService;
let exchangeRateDataService: ExchangeRateDataService;
let ghostfolioScraperApiService: GhostfolioScraperApiService;
let portfolio: Portfolio;
let prismaService: PrismaService;
let rakutenRapidApiService: RakutenRapidApiService;
let rulesService: RulesService;
let yahooFinanceService: YahooFinanceService;
beforeAll(async () => {
dataProviderService = new DataProviderService(
null,
null,
null,
null,
null,
null
const app = await Test.createTestingModule({
imports: [],
providers: [
AlphaVantageService,
ConfigurationService,
DataProviderService,
ExchangeRateDataService,
GhostfolioScraperApiService,
PrismaService,
RakutenRapidApiService,
RulesService,
YahooFinanceService
]
}).compile();
alphaVantageService = app.get<AlphaVantageService>(AlphaVantageService);
configurationService = app.get<ConfigurationService>(ConfigurationService);
dataProviderService = app.get<DataProviderService>(DataProviderService);
exchangeRateDataService = app.get<ExchangeRateDataService>(
ExchangeRateDataService
);
exchangeRateDataService = new ExchangeRateDataService(null);
rulesService = new RulesService();
ghostfolioScraperApiService = app.get<GhostfolioScraperApiService>(
GhostfolioScraperApiService
);
prismaService = app.get<PrismaService>(PrismaService);
rakutenRapidApiService = app.get<RakutenRapidApiService>(
RakutenRapidApiService
);
rulesService = app.get<RulesService>(RulesService);
yahooFinanceService = app.get<YahooFinanceService>(YahooFinanceService);
await exchangeRateDataService.initialize();
@ -107,18 +70,6 @@ describe('Portfolio', () => {
);
portfolio.setUser({
accessToken: null,
Account: [
{
accountType: AccountType.SECURITIES,
createdAt: new Date(),
id: DEFAULT_ACCOUNT_ID,
isDefault: true,
name: 'Default Account',
platformId: null,
updatedAt: new Date(),
userId: USER_ID
}
],
alias: 'Test',
createdAt: new Date(),
id: USER_ID,
@ -127,8 +78,7 @@ describe('Portfolio', () => {
Settings: {
currency: Currency.CHF,
updatedAt: new Date(),
userId: USER_ID,
viewMode: ViewMode.DEFAULT
userId: USER_ID
},
thirdPartyId: null,
updatedAt: new Date()
@ -183,10 +133,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 0,
date: new Date(),
id: '8d999347-dee2-46ee-88e1-26b344e71fcc',
platformId: null,
quantity: 1,
symbol: 'BTCUSD',
type: Type.BUY,
@ -207,8 +157,20 @@ describe('Portfolio', () => {
const details = await portfolio.getDetails('1d');
expect(details).toMatchObject({
BTCUSD: {
accounts: {
[UNKNOWN_KEY]: {
currency: Currency.USD,
exchange: 'Other',
grossPerformance: 0,
grossPerformancePercent: 0,
investment: exchangeRateDataService.toCurrency(
1 * 49631.24,
Currency.USD,
baseCurrency
),
// marketPrice: 57973.008,
marketState: MarketState.open,
name: 'Bitcoin USD',
platforms: {
Other: {
/*current: exchangeRateDataService.toCurrency(
1 * 49631.24,
Currency.USD,
@ -221,23 +183,10 @@ describe('Portfolio', () => {
)
}
},
allocationCurrent: 1,
allocationInvestment: 1,
currency: Currency.USD,
exchange: UNKNOWN_KEY,
grossPerformance: 0,
grossPerformancePercent: 0,
investment: exchangeRateDataService.toCurrency(
1 * 49631.24,
Currency.USD,
baseCurrency
),
marketPrice: 57973.008,
marketState: MarketState.open,
name: 'Bitcoin USD',
quantity: 1,
// shareCurrent: 0.9999999559148652,
shareInvestment: 1,
symbol: 'BTCUSD',
transactionCount: 1,
type: 'Cryptocurrency'
}
});
@ -284,10 +233,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 0,
date: new Date(getUtc('2018-01-05')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fb',
platformId: null,
quantity: 0.2,
symbol: 'ETHUSD',
type: Type.BUY,
@ -308,8 +257,19 @@ describe('Portfolio', () => {
const details = await portfolio.getDetails('1d');
expect(details).toMatchObject({
ETHUSD: {
accounts: {
[UNKNOWN_KEY]: {
currency: Currency.USD,
exchange: 'Other',
// grossPerformance: 0,
// grossPerformancePercent: 0,
investment: exchangeRateDataService.toCurrency(
0.2 * 991.49,
Currency.USD,
baseCurrency
),
// marketPrice: 57973.008,
name: 'Ethereum USD',
platforms: {
Other: {
/*current: exchangeRateDataService.toCurrency(
0.2 * 991.49,
Currency.USD,
@ -322,21 +282,9 @@ describe('Portfolio', () => {
)
}
},
// allocationCurrent: 1,
allocationInvestment: 1,
currency: Currency.USD,
exchange: UNKNOWN_KEY,
// grossPerformance: 0,
// grossPerformancePercent: 0,
investment: exchangeRateDataService.toCurrency(
0.2 * 991.49,
Currency.USD,
baseCurrency
),
marketPrice: 3915.337,
name: 'Ethereum USD',
quantity: 0.2,
transactionCount: 1,
// shareCurrent: 1,
shareInvestment: 1,
symbol: 'ETHUSD',
type: 'Cryptocurrency'
}
@ -364,7 +312,7 @@ describe('Portfolio', () => {
baseCurrency
),
investmentInOriginalCurrency: 0.2 * 991.49,
// marketPrice: 3915.337,
// marketPrice: 0,
quantity: 0.2
}
});
@ -379,10 +327,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 0,
date: new Date(getUtc('2018-01-05')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fb',
platformId: null,
quantity: 0.2,
symbol: 'ETHUSD',
type: Type.BUY,
@ -395,10 +343,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 0,
date: new Date(getUtc('2018-01-28')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fc',
platformId: null,
quantity: 0.3,
symbol: 'ETHUSD',
type: Type.BUY,
@ -440,7 +388,7 @@ describe('Portfolio', () => {
baseCurrency
),
investmentInOriginalCurrency: 0.2 * 991.49 + 0.3 * 1050,
// marketPrice: 3641.984,
// marketPrice: 0,
quantity: 0.5
}
});
@ -455,10 +403,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.EUR,
dataSource: DataSource.YAHOO,
date: new Date(getUtc('2017-08-16')),
fee: 2.99,
id: 'd96795b2-6ae6-420e-aa21-fabe5e45d475',
platformId: null,
quantity: 0.05614682,
symbol: 'BTCUSD',
type: Type.BUY,
@ -471,10 +419,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 2.99,
date: new Date(getUtc('2018-01-05')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fb',
platformId: null,
quantity: 0.2,
symbol: 'ETHUSD',
type: Type.BUY,
@ -544,10 +492,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 1.0,
date: new Date(getUtc('2018-01-05')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fb',
platformId: null,
quantity: 0.2,
symbol: 'ETHUSD',
type: Type.BUY,
@ -560,10 +508,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 1.0,
date: new Date(getUtc('2018-01-28')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fc',
platformId: null,
quantity: 0.1,
symbol: 'ETHUSD',
type: Type.SELL,
@ -576,10 +524,10 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 1.0,
date: new Date(getUtc('2018-01-31')),
id: '4a5a5c6e-659d-45cc-9fd4-fd6c873b50fc',
platformId: null,
quantity: 0.2,
symbol: 'ETHUSD',
type: Type.BUY,
@ -589,7 +537,8 @@ describe('Portfolio', () => {
}
]);
expect(portfolio.getCommittedFunds()).toEqual(
// TODO: Fix
/*expect(portfolio.getCommittedFunds()).toEqual(
exchangeRateDataService.toCurrency(
0.2 * 991.49,
Currency.USD,
@ -605,7 +554,7 @@ describe('Portfolio', () => {
Currency.USD,
baseCurrency
)
);
);*/
expect(portfolio.getFees()).toEqual(
exchangeRateDataService.toCurrency(3, Currency.USD, baseCurrency)
@ -617,11 +566,12 @@ describe('Portfolio', () => {
(0.2 * 991.49 - 0.1 * 1050 + 0.2 * 1050) / (0.2 - 0.1 + 0.2),
currency: Currency.USD,
firstBuyDate: '2018-01-05T00:00:00.000Z',
investment: exchangeRateDataService.toCurrency(
// TODO: Fix
/*investment: exchangeRateDataService.toCurrency(
0.2 * 991.49 - 0.1 * 1050 + 0.2 * 1050,
Currency.USD,
baseCurrency
),
),*/
investmentInOriginalCurrency: 0.2 * 991.49 - 0.1 * 1050 + 0.2 * 1050,
// marketPrice: 0,
quantity: 0.2 - 0.1 + 0.2
@ -631,4 +581,8 @@ describe('Portfolio', () => {
expect(portfolio.getSymbols(getYesterday())).toEqual(['ETHUSD']);
});
});
afterAll(async () => {
prismaService.$disconnect();
});
});

View File

@ -1,14 +1,8 @@
import { UNKNOWN_KEY } from '@ghostfolio/common/config';
import { getToday, getYesterday, resetHours } from '@ghostfolio/common/helper';
import {
PortfolioItem,
PortfolioPerformance,
PortfolioPosition,
PortfolioReport,
Position,
UserWithSettings
} from '@ghostfolio/common/interfaces';
import { DateRange, OrderWithAccount } from '@ghostfolio/common/types';
Position
} from '@ghostfolio/api/app/portfolio/interfaces/portfolio-item.interface';
import { getToday, getYesterday, resetHours } from '@ghostfolio/helper';
import {
add,
format,
@ -28,21 +22,26 @@ import {
import { cloneDeep, isEmpty } from 'lodash';
import * as roundTo from 'round-to';
import { UserWithSettings } from '../app/interfaces/user-with-settings';
import { OrderWithPlatform } from '../app/order/interfaces/order-with-platform.type';
import { DateRange } from '../app/portfolio/interfaces/date-range.type';
import { PortfolioPerformance } from '../app/portfolio/interfaces/portfolio-performance.interface';
import { PortfolioPosition } from '../app/portfolio/interfaces/portfolio-position.interface';
import { PortfolioReport } from '../app/portfolio/interfaces/portfolio-report.interface';
import { DataProviderService } from '../services/data-provider.service';
import { ExchangeRateDataService } from '../services/exchange-rate-data.service';
import { IOrder } from '../services/interfaces/interfaces';
import { RulesService } from '../services/rules.service';
import { PortfolioInterface } from './interfaces/portfolio.interface';
import { Order } from './order';
import { OrderType } from './order-type';
import { AccountClusterRiskCurrentInvestment } from './rules/account-cluster-risk/current-investment';
import { AccountClusterRiskInitialInvestment } from './rules/account-cluster-risk/initial-investment';
import { AccountClusterRiskSingleAccount } from './rules/account-cluster-risk/single-account';
import { CurrencyClusterRiskBaseCurrencyCurrentInvestment } from './rules/currency-cluster-risk/base-currency-current-investment';
import { CurrencyClusterRiskBaseCurrencyInitialInvestment } from './rules/currency-cluster-risk/base-currency-initial-investment';
import { CurrencyClusterRiskCurrentInvestment } from './rules/currency-cluster-risk/current-investment';
import { CurrencyClusterRiskInitialInvestment } from './rules/currency-cluster-risk/initial-investment';
import { FeeRatioInitialInvestment } from './rules/fees/fee-ratio-initial-investment';
import { PlatformClusterRiskCurrentInvestment } from './rules/platform-cluster-risk/current-investment';
import { PlatformClusterRiskInitialInvestment } from './rules/platform-cluster-risk/initial-investment';
import { PlatformClusterRiskSinglePlatform } from './rules/platform-cluster-risk/single-platform';
export class Portfolio implements PortfolioInterface {
private orders: Order[] = [];
@ -58,7 +57,7 @@ export class Portfolio implements PortfolioInterface {
public async addCurrentPortfolioItems() {
const currentData = await this.dataProviderService.get(this.getSymbols());
const currentDate = new Date();
let currentDate = new Date();
const year = getYear(currentDate);
const month = getMonth(currentDate);
@ -83,9 +82,7 @@ export class Portfolio implements PortfolioInterface {
marketPrice:
currentData[symbol]?.marketPrice ??
portfolioItemsYesterday.positions[symbol]?.marketPrice,
quantity: portfolioItemsYesterday?.positions[symbol]?.quantity,
transactionCount:
portfolioItemsYesterday?.positions[symbol]?.transactionCount
quantity: portfolioItemsYesterday?.positions[symbol]?.quantity
};
});
@ -120,11 +117,11 @@ export class Portfolio implements PortfolioInterface {
}): Portfolio {
orders.forEach(
({
account,
currency,
fee,
date,
id,
platform,
quantity,
symbol,
type,
@ -132,11 +129,11 @@ export class Portfolio implements PortfolioInterface {
}) => {
this.orders.push(
new Order({
account,
currency,
fee,
date,
id,
platform,
quantity,
symbol,
type,
@ -203,7 +200,7 @@ export class Portfolio implements PortfolioInterface {
const data = await this.dataProviderService.get(symbols);
symbols.forEach((symbol) => {
const accounts: PortfolioPosition['accounts'] = {};
const platforms: PortfolioPosition['platforms'] = {};
const [portfolioItem] = portfolioItems;
const ordersBySymbol = this.getOrders().filter((order) => {
@ -228,17 +225,15 @@ export class Portfolio implements PortfolioInterface {
originalValueOfSymbol *= -1;
}
if (
accounts[orderOfSymbol.getAccount()?.name || UNKNOWN_KEY]?.current
) {
accounts[
orderOfSymbol.getAccount()?.name || UNKNOWN_KEY
if (platforms[orderOfSymbol.getPlatform()?.name || 'Other']?.current) {
platforms[
orderOfSymbol.getPlatform()?.name || 'Other'
].current += currentValueOfSymbol;
accounts[
orderOfSymbol.getAccount()?.name || UNKNOWN_KEY
platforms[
orderOfSymbol.getPlatform()?.name || 'Other'
].original += originalValueOfSymbol;
} else {
accounts[orderOfSymbol.getAccount()?.name || UNKNOWN_KEY] = {
platforms[orderOfSymbol.getPlatform()?.name || 'Other'] = {
current: currentValueOfSymbol,
original: originalValueOfSymbol
};
@ -279,16 +274,8 @@ export class Portfolio implements PortfolioInterface {
details[symbol] = {
...data[symbol],
accounts,
platforms,
symbol,
allocationCurrent:
this.exchangeRateDataService.toCurrency(
portfolioItem.positions[symbol].quantity * now,
data[symbol]?.currency,
this.user.Settings.currency
) / value,
allocationInvestment:
portfolioItem.positions[symbol].investment / investment,
grossPerformance: roundTo(
portfolioItemsNow.positions[symbol].quantity * (now - before),
2
@ -296,7 +283,13 @@ export class Portfolio implements PortfolioInterface {
grossPerformancePercent: roundTo((now - before) / before, 4),
investment: portfolioItem.positions[symbol].investment,
quantity: portfolioItem.positions[symbol].quantity,
transactionCount: portfolioItem.positions[symbol].transactionCount
shareCurrent:
this.exchangeRateDataService.toCurrency(
portfolioItem.positions[symbol].quantity * now,
data[symbol]?.currency,
this.user.Settings.currency
) / value,
shareInvestment: portfolioItem.positions[symbol].investment / investment
};
});
@ -399,19 +392,6 @@ export class Portfolio implements PortfolioInterface {
return {
rules: {
accountClusterRisk: await this.rulesService.evaluate(
this,
[
new AccountClusterRiskCurrentInvestment(
this.exchangeRateDataService
),
new AccountClusterRiskInitialInvestment(
this.exchangeRateDataService
),
new AccountClusterRiskSingleAccount(this.exchangeRateDataService)
],
{ baseCurrency: this.user.Settings.currency }
),
currencyClusterRisk: await this.rulesService.evaluate(
this,
[
@ -430,6 +410,19 @@ export class Portfolio implements PortfolioInterface {
],
{ baseCurrency: this.user.Settings.currency }
),
platformClusterRisk: await this.rulesService.evaluate(
this,
[
new PlatformClusterRiskSinglePlatform(this.exchangeRateDataService),
new PlatformClusterRiskInitialInvestment(
this.exchangeRateDataService
),
new PlatformClusterRiskCurrentInvestment(
this.exchangeRateDataService
)
],
{ baseCurrency: this.user.Settings.currency }
),
fees: await this.rulesService.evaluate(
this,
[new FeeRatioInitialInvestment(this.exchangeRateDataService)],
@ -525,20 +518,20 @@ export class Portfolio implements PortfolioInterface {
return isFinite(value) ? value : null;
}
public async setOrders(aOrders: OrderWithAccount[]) {
public async setOrders(aOrders: OrderWithPlatform[]) {
this.orders = [];
// Map data
aOrders.forEach((order) => {
this.orders.push(
new Order({
account: order.Account,
currency: order.currency,
currency: <any>order.currency,
date: order.date.toISOString(),
fee: order.fee,
platform: order.Platform,
quantity: order.quantity,
symbol: order.symbol,
type: <OrderType>order.type,
type: <any>order.type,
unitPrice: order.unitPrice
})
);
@ -589,8 +582,7 @@ export class Portfolio implements PortfolioInterface {
marketPrice:
historicalData[symbol]?.[format(currentDate, 'yyyy-MM-dd')]
?.marketPrice || 0,
quantity: 0,
transactionCount: 0
quantity: 0
};
});
@ -631,8 +623,7 @@ export class Portfolio implements PortfolioInterface {
marketPrice:
historicalData[symbol]?.[format(yesterday, 'yyyy-MM-dd')]
?.marketPrice || 0,
quantity: 0,
transactionCount: 0
quantity: 0
};
});
@ -739,10 +730,6 @@ export class Portfolio implements PortfolioInterface {
order.getSymbol()
].currency = order.getCurrency();
this.portfolioItems[i].positions[
order.getSymbol()
].transactionCount += 1;
if (order.getType() === 'BUY') {
if (
!this.portfolioItems[i].positions[order.getSymbol()].firstBuyDate

View File

@ -1,7 +1,7 @@
import { groupBy } from '@ghostfolio/common/helper';
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { groupBy } from '@ghostfolio/helper';
import { Currency } from '@prisma/client';
import { PortfolioPosition } from '../app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from '../services/exchange-rate-data.service';
import { EvaluationResult } from './interfaces/evaluation-result.interface';
import { RuleInterface } from './interfaces/rule.interface';

View File

@ -1,5 +1,5 @@
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { Rule } from '../../rule';

View File

@ -1,4 +1,4 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from 'apps/api/src/services/exchange-rate-data.service';
import { Rule } from '../../rule';

View File

@ -1,4 +1,4 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from 'apps/api/src/services/exchange-rate-data.service';
import { Rule } from '../../rule';

View File

@ -1,4 +1,4 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from 'apps/api/src/services/exchange-rate-data.service';
import { Rule } from '../../rule';

View File

@ -1,4 +1,4 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from 'apps/api/src/services/exchange-rate-data.service';
import { Rule } from '../../rule';

View File

@ -1,9 +1,9 @@
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data.service';
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { Rule } from '../../rule';
export class AccountClusterRiskCurrentInvestment extends Rule {
export class PlatformClusterRiskCurrentInvestment extends Rule {
public constructor(public exchangeRateDataService: ExchangeRateDataService) {
super(exchangeRateDataService, {
name: 'Current Investment'
@ -18,22 +18,24 @@ export class AccountClusterRiskCurrentInvestment extends Rule {
}
) {
const ruleSettings =
aRuleSettingsMap[AccountClusterRiskCurrentInvestment.name];
aRuleSettingsMap[PlatformClusterRiskCurrentInvestment.name];
const accounts: {
const platforms: {
[symbol: string]: Pick<PortfolioPosition, 'name'> & {
investment: number;
};
} = {};
Object.values(aPositions).forEach((position) => {
for (const [account, { current }] of Object.entries(position.accounts)) {
if (accounts[account]?.investment) {
accounts[account].investment += current;
for (const [platform, { current }] of Object.entries(
position.platforms
)) {
if (platforms[platform]?.investment) {
platforms[platform].investment += current;
} else {
accounts[account] = {
platforms[platform] = {
investment: current,
name: account
name: platform
};
}
}
@ -42,17 +44,17 @@ export class AccountClusterRiskCurrentInvestment extends Rule {
let maxItem;
let totalInvestment = 0;
Object.values(accounts).forEach((account) => {
Object.values(platforms).forEach((platform) => {
if (!maxItem) {
maxItem = account;
maxItem = platform;
}
// Calculate total investment
totalInvestment += account.investment;
totalInvestment += platform.investment;
// Find maximum
if (account.investment > maxItem?.investment) {
maxItem = account;
if (platform.investment > maxItem?.investment) {
maxItem = platform;
}
});

View File

@ -1,9 +1,9 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from 'apps/api/src/services/exchange-rate-data.service';
import { Rule } from '../../rule';
export class AccountClusterRiskInitialInvestment extends Rule {
export class PlatformClusterRiskInitialInvestment extends Rule {
public constructor(public exchangeRateDataService: ExchangeRateDataService) {
super(exchangeRateDataService, {
name: 'Initial Investment'
@ -18,7 +18,7 @@ export class AccountClusterRiskInitialInvestment extends Rule {
}
) {
const ruleSettings =
aRuleSettingsMap[AccountClusterRiskInitialInvestment.name];
aRuleSettingsMap[PlatformClusterRiskInitialInvestment.name];
const platforms: {
[symbol: string]: Pick<PortfolioPosition, 'name'> & {
@ -27,13 +27,15 @@ export class AccountClusterRiskInitialInvestment extends Rule {
} = {};
Object.values(aPositions).forEach((position) => {
for (const [account, { original }] of Object.entries(position.accounts)) {
if (platforms[account]?.investment) {
platforms[account].investment += original;
for (const [platform, { original }] of Object.entries(
position.platforms
)) {
if (platforms[platform]?.investment) {
platforms[platform].investment += original;
} else {
platforms[account] = {
platforms[platform] = {
investment: original,
name: account
name: platform
};
}
}

View File

@ -1,35 +1,35 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { ExchangeRateDataService } from 'apps/api/src/services/exchange-rate-data.service';
import { Rule } from '../../rule';
export class AccountClusterRiskSingleAccount extends Rule {
export class PlatformClusterRiskSinglePlatform extends Rule {
public constructor(public exchangeRateDataService: ExchangeRateDataService) {
super(exchangeRateDataService, {
name: 'Single Account'
name: 'Single Platform'
});
}
public evaluate(positions: { [symbol: string]: PortfolioPosition }) {
const accounts: string[] = [];
const platforms: string[] = [];
Object.values(positions).forEach((position) => {
for (const [account] of Object.entries(position.accounts)) {
if (!accounts.includes(account)) {
accounts.push(account);
for (const [platform] of Object.entries(position.platforms)) {
if (!platforms.includes(platform)) {
platforms.push(platform);
}
}
});
if (accounts.length === 1) {
if (platforms.length === 1) {
return {
evaluation: `All your investment is managed by a single account`,
evaluation: `All your investment is managed by a single platform`,
value: false
};
}
return {
evaluation: `Your investment is managed by ${accounts.length} accounts`,
evaluation: `Your investment is managed by ${platforms.length} platforms`,
value: true
};
}

View File

@ -1,6 +1,5 @@
import { Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
import { bool, cleanEnv, json, num, port, str } from 'envalid';
import { bool, cleanEnv, num, port, str } from 'envalid';
import { Environment } from './interfaces/environment.interface';
@ -13,7 +12,6 @@ export class ConfigurationService {
ACCESS_TOKEN_SALT: str(),
ALPHA_VANTAGE_API_KEY: str({ default: '' }),
CACHE_TTL: num({ default: 1 }),
DATA_SOURCES: json({ default: JSON.stringify([DataSource.YAHOO]) }),
ENABLE_FEATURE_CUSTOM_SYMBOLS: bool({ default: false }),
ENABLE_FEATURE_FEAR_AND_GREED_INDEX: bool({ default: false }),
ENABLE_FEATURE_SOCIAL_LOGIN: bool({ default: false }),

View File

@ -1,9 +1,10 @@
import { benchmarks, currencyPairs } from '@ghostfolio/common/config';
import {
benchmarks,
currencyPairs,
getUtc,
isGhostfolioScraperApiSymbol,
resetHours
} from '@ghostfolio/common/helper';
} from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import {
differenceInHours,
@ -17,7 +18,6 @@ import {
import { ConfigurationService } from './configuration.service';
import { DataProviderService } from './data-provider.service';
import { GhostfolioScraperApiService } from './data-provider/ghostfolio-scraper-api/ghostfolio-scraper-api.service';
import { PrismaService } from './prisma.service';
@Injectable()
@ -25,7 +25,6 @@ export class DataGatheringService {
public constructor(
private readonly configurationService: ConfigurationService,
private readonly dataProviderService: DataProviderService,
private readonly ghostfolioScraperApi: GhostfolioScraperApiService,
private prisma: PrismaService
) {}
@ -184,17 +183,6 @@ export class DataGatheringService {
}
}
public async getCustomSymbolsToGather(startDate?: Date) {
const scraperConfigurations = await this.ghostfolioScraperApi.getScraperConfigurations();
return scraperConfigurations.map((scraperConfiguration) => {
return {
date: startDate,
symbol: scraperConfiguration.symbol
};
});
}
private getBenchmarksToGather(startDate: Date) {
const benchmarksToGather = benchmarks.map((symbol) => {
return {
@ -213,6 +201,32 @@ export class DataGatheringService {
return benchmarksToGather;
}
private async getCustomSymbolsToGather(startDate: Date) {
const customSymbolsToGather = [];
if (this.configurationService.get('ENABLE_FEATURE_CUSTOM_SYMBOLS')) {
try {
const {
value: scraperConfigString
} = await this.prisma.property.findFirst({
select: {
value: true
},
where: { key: 'SCRAPER_CONFIG' }
});
JSON.parse(scraperConfigString).forEach((item) => {
customSymbolsToGather.push({
date: startDate,
symbol: item.symbol
});
});
} catch {}
}
return customSymbolsToGather;
}
private async getSymbols7D(): Promise<{ date: Date; symbol: string }[]> {
const startDate = subDays(resetHours(new Date()), 7);

View File

@ -1,12 +1,10 @@
import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface';
import {
isCrypto,
isGhostfolioScraperApiSymbol,
isRakutenRapidApiSymbol
} from '@ghostfolio/common/helper';
import { Granularity } from '@ghostfolio/common/types';
} from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { DataSource, MarketData } from '@prisma/client';
import { MarketData } from '@prisma/client';
import { format } from 'date-fns';
import { ConfigurationService } from './configuration.service';
@ -15,6 +13,7 @@ import { GhostfolioScraperApiService } from './data-provider/ghostfolio-scraper-
import { RakutenRapidApiService } from './data-provider/rakuten-rapid-api/rakuten-rapid-api.service';
import { YahooFinanceService } from './data-provider/yahoo-finance/yahoo-finance.service';
import { DataProviderInterface } from './interfaces/data-provider.interface';
import { Granularity } from './interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse
@ -185,19 +184,4 @@ export class DataProviderService implements DataProviderInterface {
return dataOfYahoo;
}
public async search(aSymbol: string) {
return this.getDataProvider().search(aSymbol);
}
private getDataProvider() {
switch (this.configurationService.get('DATA_SOURCES')[0]) {
case DataSource.ALPHA_VANTAGE:
return this.alphaVantageService;
case DataSource.YAHOO:
return this.yahooFinanceService;
default:
throw new Error('No data provider has been found.');
}
}
}

View File

@ -1,11 +1,9 @@
import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface';
import { Granularity } from '@ghostfolio/common/types';
import { Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
import { isAfter, isBefore, parse } from 'date-fns';
import { ConfigurationService } from '../../configuration.service';
import { DataProviderInterface } from '../../interfaces/data-provider.interface';
import { Granularity } from '../../interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse
@ -79,17 +77,7 @@ export class AlphaVantageService implements DataProviderInterface {
}
}
public async search(aSymbol: string): Promise<{ items: LookupItem[] }> {
const result = await this.alphaVantage.data.search(aSymbol);
return {
items: result?.bestMatches?.map((bestMatch) => {
return {
dataSource: DataSource.ALPHA_VANTAGE,
name: bestMatch['2. name'],
symbol: bestMatch['1. symbol']
};
})
};
public search(aSymbol: string) {
return this.alphaVantage.data.search(aSymbol);
}
}

View File

@ -1,19 +1,17 @@
import { getYesterday } from '@ghostfolio/common/helper';
import { Granularity } from '@ghostfolio/common/types';
import { getYesterday } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
import * as bent from 'bent';
import * as cheerio from 'cheerio';
import { format } from 'date-fns';
import { DataProviderInterface } from '../../interfaces/data-provider.interface';
import { Granularity } from '../../interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse,
MarketState
} from '../../interfaces/interfaces';
import { PrismaService } from '../../prisma.service';
import { ScraperConfig } from './interfaces/scraper-config.interface';
@Injectable()
export class GhostfolioScraperApiService implements DataProviderInterface {
@ -31,7 +29,7 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
try {
const symbol = aSymbols[0];
const scraperConfig = await this.getScraperConfigurationBySymbol(symbol);
const scraperConfig = await this.getScraperConfig(symbol);
const { marketPrice } = await this.prisma.marketData.findFirst({
orderBy: {
@ -46,7 +44,6 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
[symbol]: {
marketPrice,
currency: scraperConfig?.currency,
dataSource: DataSource.GHOSTFOLIO,
marketState: MarketState.delayed,
name: scraperConfig?.name
}
@ -73,17 +70,15 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
try {
const symbol = aSymbols[0];
const scraperConfiguration = await this.getScraperConfigurationBySymbol(
symbol
);
const scraperConfig = await this.getScraperConfig(symbol);
const get = bent(scraperConfiguration?.url, 'GET', 'string', 200, {});
const get = bent(scraperConfig?.url, 'GET', 'string', 200, {});
const html = await get();
const $ = cheerio.load(html);
const value = this.extractNumberFromString(
$(scraperConfiguration?.selector).text()
$(scraperConfig?.selector).text()
);
return {
@ -100,27 +95,6 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
return {};
}
public async getScraperConfigurations(): Promise<ScraperConfig[]> {
try {
const {
value: scraperConfigString
} = await this.prisma.property.findFirst({
select: {
value: true
},
where: { key: 'SCRAPER_CONFIG' }
});
return JSON.parse(scraperConfigString);
} catch {}
return [];
}
public async search(aSymbol: string) {
return { items: [] };
}
private extractNumberFromString(aString: string): number {
try {
const [numberString] = aString.match(
@ -132,10 +106,22 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
}
}
private async getScraperConfigurationBySymbol(aSymbol: string) {
const scraperConfigurations = await this.getScraperConfigurations();
return scraperConfigurations.find((scraperConfiguration) => {
return scraperConfiguration.symbol === aSymbol;
private async getScraperConfig(aSymbol: string) {
try {
const {
value: scraperConfigString
} = await this.prisma.property.findFirst({
select: {
value: true
},
where: { key: 'SCRAPER_CONFIG' }
});
return JSON.parse(scraperConfigString).find((item) => {
return item.symbol === aSymbol;
});
} catch {}
return {};
}
}

View File

@ -1,9 +0,0 @@
import { Currency } from '@prisma/client';
export interface ScraperConfig {
currency: Currency;
name: string;
selector: string;
symbol: string;
url: string;
}

View File

@ -1,12 +1,11 @@
import { getToday, getYesterday } from '@ghostfolio/common/helper';
import { Granularity } from '@ghostfolio/common/types';
import { getToday, getYesterday } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
import * as bent from 'bent';
import { format, subMonths, subWeeks, subYears } from 'date-fns';
import { ConfigurationService } from '../../configuration.service';
import { DataProviderInterface } from '../../interfaces/data-provider.interface';
import { Granularity } from '../../interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse,
@ -40,7 +39,6 @@ export class RakutenRapidApiService implements DataProviderInterface {
return {
'GF.FEAR_AND_GREED_INDEX': {
currency: undefined,
dataSource: DataSource.RAKUTEN,
marketPrice: fgi.now.value,
marketState: MarketState.open,
name: RakutenRapidApiService.FEAR_AND_GREED_INDEX_NAME
@ -117,14 +115,6 @@ export class RakutenRapidApiService implements DataProviderInterface {
return {};
}
public async search(aSymbol: string) {
return { items: [] };
}
public setPrisma(aPrismaService: PrismaService) {
this.prisma = aPrismaService;
}
private async getFearAndGreedIndex(): Promise<{
now: { value: number; valueText: string };
previousClose: { value: number; valueText: string };
@ -155,4 +145,8 @@ export class RakutenRapidApiService implements DataProviderInterface {
return undefined;
}
}
public setPrisma(aPrismaService: PrismaService) {
this.prisma = aPrismaService;
}
}

View File

@ -0,0 +1,24 @@
/*
import { Test } from '@nestjs/testing';
import { YahooFinanceService } from './yahoo-finance.service';
describe('AppService', () => {
let service: YahooFinanceService;
beforeAll(async () => {
const app = await Test.createTestingModule({
imports: [],
providers: [YahooFinanceService]
}).compile();
service = app.get<YahooFinanceService>(YahooFinanceService);
});
describe('get', () => {
it('should return data for USDCHF', () => {
expect(service.get(['USDCHF'])).toEqual('{}');
});
});
});
*/

View File

@ -1,14 +1,10 @@
import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface';
import { UNKNOWN_KEY } from '@ghostfolio/common/config';
import { isCrypto, isCurrency, parseCurrency } from '@ghostfolio/common/helper';
import { Granularity } from '@ghostfolio/common/types';
import { isCrypto, isCurrency, parseCurrency } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
import * as bent from 'bent';
import { format } from 'date-fns';
import * as yahooFinance from 'yahoo-finance';
import { DataProviderInterface } from '../../interfaces/data-provider.interface';
import { Granularity } from '../../interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse,
@ -24,8 +20,6 @@ import {
@Injectable()
export class YahooFinanceService implements DataProviderInterface {
private yahooFinanceHostname = 'https://query1.finance.yahoo.com';
public constructor() {}
public async get(
@ -55,7 +49,6 @@ export class YahooFinanceService implements DataProviderInterface {
response[symbol] = {
currency: parseCurrency(value.price?.currency),
dataSource: DataSource.YAHOO,
exchange: this.parseExchange(value.price?.exchangeName),
marketState:
value.price?.marketState === 'REGULAR' || isCrypto(symbol)
@ -140,49 +133,6 @@ export class YahooFinanceService implements DataProviderInterface {
}
}
public async search(aSymbol: string): Promise<{ items: LookupItem[] }> {
let items = [];
try {
const get = bent(
`${this.yahooFinanceHostname}/v1/finance/search?q=${aSymbol}&lang=en-US&region=US&quotesCount=8&newsCount=0&enableFuzzyQuery=false&quotesQueryId=tss_match_phrase_query&multiQuoteQueryId=multi_quote_single_token_query&newsQueryId=news_cie_vespa&enableCb=true&enableNavLinks=false&enableEnhancedTrivialQuery=true`,
'GET',
'json',
200
);
const result = await get();
items = result.quotes
.filter((quote) => {
return quote.isYahooFinance;
})
.filter(({ quoteType }) => {
return (
quoteType === 'CRYPTOCURRENCY' ||
quoteType === 'EQUITY' ||
quoteType === 'ETF'
);
})
.filter(({ quoteType, symbol }) => {
if (quoteType === 'CRYPTOCURRENCY') {
// Only allow cryptocurrencies in USD
return symbol.includes('USD');
}
return true;
})
.map(({ longname, shortname, symbol }) => {
return {
dataSource: DataSource.YAHOO,
name: longname || shortname,
symbol: convertFromYahooSymbol(symbol)
};
});
} catch {}
return { items };
}
/**
* Converts a symbol to a Yahoo symbol
*
@ -218,7 +168,7 @@ export class YahooFinanceService implements DataProviderInterface {
private parseExchange(aString: string): string {
if (aString?.toLowerCase() === 'ccc') {
return UNKNOWN_KEY;
return 'Other';
}
return aString;
@ -248,7 +198,7 @@ export class YahooFinanceService implements DataProviderInterface {
return Industry.Software;
}
return Industry.Unknown;
return Industry.Other;
}
private parseSector(aString: string): Sector {
@ -270,7 +220,7 @@ export class YahooFinanceService implements DataProviderInterface {
return Sector.Technology;
}
return Sector.Unknown;
return Sector.Other;
}
private parseType(aString: string): Type {
@ -282,7 +232,7 @@ export class YahooFinanceService implements DataProviderInterface {
return Type.Stock;
}
return Type.Unknown;
return Type.Other;
}
}

View File

@ -1,4 +1,4 @@
import { getYesterday } from '@ghostfolio/common/helper';
import { getYesterday } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { Currency } from '@prisma/client';
import { format } from 'date-fns';

View File

@ -1,6 +1,4 @@
import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface';
import { Granularity } from '@ghostfolio/common/types';
import { Granularity } from './granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse
@ -17,6 +15,4 @@ export interface DataProviderInterface {
): Promise<{
[symbol: string]: { [date: string]: IDataProviderHistoricalResponse };
}>;
search(aSymbol: string): Promise<{ items: LookupItem[] }>;
}

View File

@ -4,7 +4,6 @@ export interface Environment extends CleanedEnvAccessors {
ACCESS_TOKEN_SALT: string;
ALPHA_VANTAGE_API_KEY: string;
CACHE_TTL: number;
DATA_SOURCES: string | string[]; // string is not correct, error in envalid?
ENABLE_FEATURE_CUSTOM_SYMBOLS: boolean;
ENABLE_FEATURE_FEAR_AND_GREED_INDEX: boolean;
ENABLE_FEATURE_SOCIAL_LOGIN: boolean;

View File

@ -1,5 +1,4 @@
import { UNKNOWN_KEY } from '@ghostfolio/common/config';
import { Account, Currency, DataSource } from '@prisma/client';
import { Currency, Platform } from '@prisma/client';
import { OrderType } from '../../models/order-type';
@ -8,9 +7,9 @@ export const Industry = {
Biotechnology: 'Biotechnology',
Food: 'Food',
Internet: 'Internet',
Other: 'Other',
Pharmaceutical: 'Pharmaceutical',
Software: 'Software',
Unknown: UNKNOWN_KEY
Software: 'Software'
};
export const MarketState = {
@ -22,23 +21,23 @@ export const MarketState = {
export const Sector = {
Consumer: 'Consumer',
Healthcare: 'Healthcare',
Technology: 'Technology',
Unknown: UNKNOWN_KEY
Other: 'Other',
Technology: 'Technology'
};
export const Type = {
Cryptocurrency: 'Cryptocurrency',
ETF: 'ETF',
Stock: 'Stock',
Unknown: UNKNOWN_KEY
Other: 'Other',
Stock: 'Stock'
};
export interface IOrder {
account: Account;
currency: Currency;
date: string;
fee: number;
id?: string;
platform: Platform;
quantity: number;
symbol: string;
type: OrderType;
@ -52,7 +51,6 @@ export interface IDataProviderHistoricalResponse {
export interface IDataProviderResponse {
currency: Currency;
dataSource: DataSource;
exchange?: string;
industry?: Industry;
marketChange?: number;

View File

@ -2,14 +2,14 @@ import { Injectable } from '@nestjs/common';
import { Portfolio } from '../models/portfolio';
import { Rule } from '../models/rule';
import { AccountClusterRiskCurrentInvestment } from '../models/rules/account-cluster-risk/current-investment';
import { AccountClusterRiskInitialInvestment } from '../models/rules/account-cluster-risk/initial-investment';
import { AccountClusterRiskSingleAccount } from '../models/rules/account-cluster-risk/single-account';
import { CurrencyClusterRiskBaseCurrencyCurrentInvestment } from '../models/rules/currency-cluster-risk/base-currency-current-investment';
import { CurrencyClusterRiskBaseCurrencyInitialInvestment } from '../models/rules/currency-cluster-risk/base-currency-initial-investment';
import { CurrencyClusterRiskCurrentInvestment } from '../models/rules/currency-cluster-risk/current-investment';
import { CurrencyClusterRiskInitialInvestment } from '../models/rules/currency-cluster-risk/initial-investment';
import { FeeRatioInitialInvestment } from '../models/rules/fees/fee-ratio-initial-investment';
import { PlatformClusterRiskCurrentInvestment } from '../models/rules/platform-cluster-risk/current-investment';
import { PlatformClusterRiskInitialInvestment } from '../models/rules/platform-cluster-risk/initial-investment';
import { PlatformClusterRiskSinglePlatform } from '../models/rules/platform-cluster-risk/single-platform';
@Injectable()
export class RulesService {
@ -39,17 +39,6 @@ export class RulesService {
private getDefaultRuleSettings(aUserSettings: { baseCurrency: string }) {
return {
[AccountClusterRiskCurrentInvestment.name]: {
baseCurrency: aUserSettings.baseCurrency,
isActive: true,
threshold: 0.5
},
[AccountClusterRiskInitialInvestment.name]: {
baseCurrency: aUserSettings.baseCurrency,
isActive: true,
threshold: 0.5
},
[AccountClusterRiskSingleAccount.name]: { isActive: true },
[CurrencyClusterRiskBaseCurrencyInitialInvestment.name]: {
baseCurrency: aUserSettings.baseCurrency,
isActive: true
@ -72,7 +61,18 @@ export class RulesService {
baseCurrency: aUserSettings.baseCurrency,
isActive: true,
threshold: 0.01
}
},
[PlatformClusterRiskCurrentInvestment.name]: {
baseCurrency: aUserSettings.baseCurrency,
isActive: true,
threshold: 0.5
},
[PlatformClusterRiskInitialInvestment.name]: {
baseCurrency: aUserSettings.baseCurrency,
isActive: true,
threshold: 0.5
},
[PlatformClusterRiskSinglePlatform.name]: { isActive: true }
};
}
}

View File

@ -1,7 +1,7 @@
import {
DEFAULT_DATE_FORMAT,
DEFAULT_DATE_FORMAT_MONTH_YEAR
} from '@ghostfolio/common/config';
} from '@ghostfolio/helper';
export const DateFormats = {
display: {

View File

@ -9,6 +9,11 @@ const routes: Routes = [
loadChildren: () =>
import('./pages/about/about-page.module').then((m) => m.AboutPageModule)
},
{
path: 'admin',
loadChildren: () =>
import('./pages/admin/admin-page.module').then((m) => m.AdminPageModule)
},
{
path: 'account',
loadChildren: () =>
@ -17,16 +22,9 @@ const routes: Routes = [
)
},
{
path: 'accounts',
path: 'auth',
loadChildren: () =>
import('./pages/accounts/accounts-page.module').then(
(m) => m.AccountsPageModule
)
},
{
path: 'admin',
loadChildren: () =>
import('./pages/admin/admin-page.module').then((m) => m.AdminPageModule)
import('./pages/auth/auth-page.module').then((m) => m.AuthPageModule)
},
{
path: 'analysis',
@ -35,23 +33,11 @@ const routes: Routes = [
(m) => m.AnalysisPageModule
)
},
{
path: 'auth',
loadChildren: () =>
import('./pages/auth/auth-page.module').then((m) => m.AuthPageModule)
},
{
path: 'home',
loadChildren: () =>
import('./pages/home/home-page.module').then((m) => m.HomePageModule)
},
{
path: 'pricing',
loadChildren: () =>
import('./pages/pricing/pricing-page.module').then(
(m) => m.PricingPageModule
)
},
{
path: 'report',
loadChildren: () =>
@ -78,16 +64,11 @@ const routes: Routes = [
(m) => m.TransactionsPageModule
)
},
{
path: 'zen',
loadChildren: () =>
import('./pages/zen/zen-page.module').then((m) => m.ZenPageModule)
},
{
// wildcard, if requested url doesn't match any paths for routes defined
// earlier
path: '**',
redirectTo: 'home',
redirectTo: '/home',
pathMatch: 'full'
}
];

View File

@ -25,10 +25,7 @@
<router-outlet></router-outlet>
</main>
<footer
*ngIf="currentRoute === 'start' || deviceType !== 'mobile'"
class="footer d-flex justify-content-center position-absolute w-100"
>
<footer class="footer d-flex justify-content-center position-absolute w-100">
<div class="container text-center">
<div>
© {{ currentYear }} <a href="https://ghostfol.io">Ghostfolio</a>

View File

@ -5,12 +5,16 @@ import {
OnDestroy,
OnInit
} from '@angular/core';
import { NavigationEnd, PRIMARY_OUTLET, Router } from '@angular/router';
import { primaryColorHex, secondaryColorHex } from '@ghostfolio/common/config';
import { InfoItem, User } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { NavigationEnd, Router } from '@angular/router';
import { InfoItem } from '@ghostfolio/api/app/info/interfaces/info-item.interface';
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
import {
hasPermission,
permissions,
primaryColorHex,
secondaryColorHex
} from '@ghostfolio/helper';
import { MaterialCssVarsService } from 'angular-material-css-vars';
import { DeviceDetectorService } from 'ngx-device-detector';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
@ -28,7 +32,6 @@ export class AppComponent implements OnDestroy, OnInit {
public canCreateAccount: boolean;
public currentRoute: string;
public currentYear = new Date().getFullYear();
public deviceType: string;
public info: InfoItem;
public isLoggedIn = false;
public user: User;
@ -39,7 +42,6 @@ export class AppComponent implements OnDestroy, OnInit {
public constructor(
private cd: ChangeDetectorRef,
private dataService: DataService,
private deviceService: DeviceDetectorService,
private materialCssVarsService: MaterialCssVarsService,
private router: Router,
private tokenStorageService: TokenStorageService
@ -49,19 +51,15 @@ export class AppComponent implements OnDestroy, OnInit {
}
public ngOnInit() {
this.deviceType = this.deviceService.getDeviceInfo().deviceType;
this.dataService.fetchInfo().subscribe((info) => {
this.info = info;
});
this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.subscribe(() => {
const urlTree = this.router.parseUrl(this.router.url);
const urlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET];
const urlSegments = urlSegmentGroup.segments;
this.currentRoute = urlSegments[0].path;
.subscribe((test) => {
this.currentRoute = this.router.url.toString().substring(1);
// this.initializeTheme();
});
this.tokenStorageService
@ -76,7 +74,7 @@ export class AppComponent implements OnDestroy, OnInit {
this.canCreateAccount = hasPermission(
this.user.permissions,
permissions.createUserAccount
permissions.createAccount
);
this.cd.markForCheck();
@ -87,16 +85,6 @@ export class AppComponent implements OnDestroy, OnInit {
});
}
public onCreateAccount() {
this.tokenStorageService.signOut();
window.location.reload();
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
private initializeTheme() {
this.materialCssVarsService.setDarkTheme(
window.matchMedia('(prefers-color-scheme: dark)').matches
@ -109,4 +97,14 @@ export class AppComponent implements OnDestroy, OnInit {
this.materialCssVarsService.setPrimaryColor(primaryColorHex);
this.materialCssVarsService.setAccentColor(secondaryColorHex);
}
public onCreateAccount() {
this.tokenStorageService.signOut();
window.location.reload();
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
}

View File

@ -22,7 +22,7 @@ import { AppComponent } from './app.component';
import { GfHeaderModule } from './components/header/header.module';
import { authInterceptorProviders } from './core/auth.interceptor';
import { httpResponseInterceptorProviders } from './core/http-response.interceptor';
import { LanguageService } from './core/language.service';
import { LanguageManager } from './core/language-manager.service';
@NgModule({
declarations: [AppComponent],
@ -46,11 +46,11 @@ import { LanguageService } from './core/language.service';
providers: [
authInterceptorProviders,
httpResponseInterceptorProviders,
LanguageService,
LanguageManager,
{
provide: DateAdapter,
useClass: CustomDateAdapter,
deps: [LanguageService, MAT_DATE_LOCALE, Platform]
deps: [LanguageManager, MAT_DATE_LOCALE, Platform]
},
{ provide: MAT_DATE_FORMATS, useValue: DateFormats }
],

View File

@ -1,14 +1,14 @@
<table class="gf-table w-100" mat-table [dataSource]="dataSource">
<table mat-table [dataSource]="dataSource" class="w-100">
<ng-container matColumnDef="granteeAlias">
<th *matHeaderCellDef class="px-1" i18n mat-header-cell>User</th>
<td *matCellDef="let element" class="px-1" mat-cell>
<th mat-header-cell *matHeaderCellDef i18n>User</th>
<td mat-cell *matCellDef="let element">
{{ element.granteeAlias }}
</td></ng-container
>
<ng-container matColumnDef="type">
<th *matHeaderCellDef class="px-1" i18n mat-header-cell>Type</th>
<td *matCellDef="let element" class="px-1" mat-cell>
<th mat-header-cell *matHeaderCellDef i18n>Type</th>
<td mat-cell *matCellDef="let element">
<ion-icon class="mr-1" name="lock-closed-outline"></ion-icon>
Restricted Access
</td></ng-container

View File

@ -1,5 +1,3 @@
@import '~apps/client/src/styles/ghostfolio-style';
:host {
display: block;
}

View File

@ -6,7 +6,7 @@ import {
OnInit
} from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Access } from '@ghostfolio/common/interfaces';
import { Access } from '@ghostfolio/api/app/access/interfaces/access.interface';
@Component({
selector: 'gf-access-table',

View File

@ -1,81 +0,0 @@
<table
class="gf-table w-100"
matSort
matSortActive="account"
matSortDirection="desc"
mat-table
[dataSource]="dataSource"
>
<ng-container matColumnDef="account">
<th *matHeaderCellDef class="px-1" i18n mat-header-cell mat-sort-header>
Name
</th>
<td *matCellDef="let element" class="px-1" mat-cell>
{{ element.name }}
</td>
</ng-container>
<ng-container matColumnDef="platform">
<th *matHeaderCellDef class="px-1" i18n mat-header-cell mat-sort-header>
Platform
</th>
<td *matCellDef="let element" class="px-1" mat-cell>
<div class="d-flex">
<gf-symbol-icon
*ngIf="element.Platform?.url"
class="mr-1"
[tooltip]=""
[url]="element.Platform?.url"
></gf-symbol-icon>
<span>{{ element.Platform?.name }}</span>
</div>
</td>
</ng-container>
<ng-container matColumnDef="actions">
<th *matHeaderCellDef class="px-1 text-center" i18n mat-header-cell></th>
<td *matCellDef="let element" class="px-1 text-center" mat-cell>
<button
class="mx-1 no-min-width px-2"
mat-button
[matMenuTriggerFor]="accountMenu"
(click)="$event.stopPropagation()"
>
<ion-icon name="ellipsis-vertical"></ion-icon>
</button>
<mat-menu #accountMenu="matMenu" xPosition="before">
<button i18n mat-menu-item (click)="onUpdateAccount(element)">
Edit
</button>
<button
i18n
mat-menu-item
[disabled]="element.isDefault || element.Order?.length > 0"
(click)="onDeleteAccount(element.id)"
>
Delete
</button>
</mat-menu>
</td>
</ng-container>
<ng-container matColumnDef="transactions">
<th *matHeaderCellDef i18n mat-header-cell mat-sort-header>Transactions</th>
<td *matCellDef="let element" mat-cell>
{{ element.Order?.length }}
</td>
</ng-container>
<tr *matHeaderRowDef="displayedColumns" mat-header-row></tr>
<tr *matRowDef="let row; columns: displayedColumns" mat-row></tr>
</table>
<ngx-skeleton-loader
*ngIf="isLoading"
animation="pulse"
class="px-4 py-3"
[theme]="{
height: '1.5rem',
width: '100%'
}"
></ngx-skeleton-loader>

View File

@ -1,27 +0,0 @@
@import '~apps/client/src/styles/ghostfolio-style';
:host {
display: block;
::ng-deep {
.mat-form-field-infix {
border-top: 0 solid transparent !important;
}
}
.mat-table {
th {
::ng-deep {
.mat-sort-header-container {
justify-content: inherit;
}
}
}
}
}
:host-context(.is-dark-theme) {
.mat-form-field {
color: rgba(var(--light-primary-text));
}
}

View File

@ -1,85 +0,0 @@
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
ViewChild
} from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { Account as AccountModel } from '@prisma/client';
import { Subject, Subscription } from 'rxjs';
@Component({
selector: 'gf-accounts-table',
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './accounts-table.component.html',
styleUrls: ['./accounts-table.component.scss']
})
export class AccountsTableComponent implements OnChanges, OnDestroy, OnInit {
@Input() accounts: AccountModel[];
@Input() baseCurrency: string;
@Input() deviceType: string;
@Input() locale: string;
@Input() showActions: boolean;
@Output() accountDeleted = new EventEmitter<string>();
@Output() accountToUpdate = new EventEmitter<AccountModel>();
@ViewChild(MatSort) sort: MatSort;
public dataSource: MatTableDataSource<AccountModel> = new MatTableDataSource();
public displayedColumns = [];
public isLoading = true;
public routeQueryParams: Subscription;
private unsubscribeSubject = new Subject<void>();
public constructor(
private dialog: MatDialog,
private route: ActivatedRoute,
private router: Router
) {}
public ngOnInit() {}
public ngOnChanges() {
this.displayedColumns = ['account', 'platform', 'transactions'];
if (this.showActions) {
this.displayedColumns.push('actions');
}
this.isLoading = true;
if (this.accounts) {
this.dataSource = new MatTableDataSource(this.accounts);
this.dataSource.sort = this.sort;
this.isLoading = false;
}
}
public onDeleteAccount(aId: string) {
const confirmation = confirm('Do you really want to delete this account?');
if (confirmation) {
this.accountDeleted.emit(aId);
}
}
public onUpdateAccount(aAccount: AccountModel) {
this.accountToUpdate.emit(aAccount);
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
}

View File

@ -1,33 +0,0 @@
import { CommonModule } from '@angular/common';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatMenuModule } from '@angular/material/menu';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { RouterModule } from '@angular/router';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { GfSymbolIconModule } from '../symbol-icon/symbol-icon.module';
import { GfValueModule } from '../value/value.module';
import { AccountsTableComponent } from './accounts-table.component';
@NgModule({
declarations: [AccountsTableComponent],
exports: [AccountsTableComponent],
imports: [
CommonModule,
GfSymbolIconModule,
GfValueModule,
MatButtonModule,
MatInputModule,
MatMenuModule,
MatSortModule,
MatTableModule,
NgxSkeletonLoaderModule,
RouterModule
],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class GfAccountsTableModule {}

View File

@ -5,7 +5,7 @@ import {
OnChanges,
OnInit
} from '@angular/core';
import { resolveFearAndGreedIndex } from '@ghostfolio/common/helper';
import { resolveFearAndGreedIndex } from '@ghostfolio/helper';
@Component({
selector: 'gf-fear-and-greed-index',

View File

@ -6,80 +6,59 @@
<span class="spacer"></span>
<a
class="d-none d-sm-block"
[routerLink]="['/']"
i18n
mat-flat-button
[color]="
currentRoute === 'home' || currentRoute === 'zen' ? 'primary' : null
"
[routerLink]="['/']"
[color]="currentRoute === 'home' ? 'primary' : null"
>Overview</a
>
<a
*ngIf="user?.settings?.viewMode === 'DEFAULT'"
class="d-none d-sm-block mx-1"
[routerLink]="['/analysis']"
i18n
mat-flat-button
[color]="currentRoute === 'analysis' ? 'primary' : null"
[routerLink]="['/analysis']"
>Analysis</a
>
<a
*ngIf="user?.settings?.viewMode === 'DEFAULT'"
class="d-none d-sm-block mx-1"
[routerLink]="['/report']"
i18n
mat-flat-button
[color]="currentRoute === 'report' ? 'primary' : null"
[routerLink]="['/report']"
>X-ray</a
>
<a
class="d-none d-sm-block mx-1"
[routerLink]="['/transactions']"
i18n
mat-flat-button
[color]="currentRoute === 'transactions' ? 'primary' : null"
[routerLink]="['/transactions']"
>Transactions</a
>
<a
class="d-none d-sm-block mx-1"
i18n
mat-flat-button
[color]="currentRoute === 'accounts' ? 'primary' : null"
[routerLink]="['/accounts']"
>Accounts</a
>
<a
*ngIf="hasPermissionToAccessAdminControl"
class="d-none d-sm-block mx-1"
[routerLink]="['/admin']"
i18n
mat-flat-button
[color]="currentRoute === 'admin' ? 'primary' : null"
[routerLink]="['/admin']"
>Admin Control</a
>
<a
class="d-none d-sm-block mx-1"
[routerLink]="['/resources']"
i18n
mat-flat-button
[color]="currentRoute === 'resources' ? 'primary' : null"
[routerLink]="['/resources']"
>Resources</a
>
<a
*ngIf="hasPermissionForSubscription"
class="d-none d-sm-block mx-1"
i18n
mat-flat-button
[color]="currentRoute === 'pricing' ? 'primary' : null"
[routerLink]="['/pricing']"
>Pricing</a
>
<a
class="d-none d-sm-block mx-1"
[routerLink]="['/about']"
i18n
mat-flat-button
[color]="currentRoute === 'about' ? 'primary' : null"
[routerLink]="['/about']"
>About</a
>
<button
@ -140,81 +119,60 @@
</ng-container>
<a
class="d-block d-sm-none"
[routerLink]="['/analysis']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'analysis' }"
[routerLink]="['/analysis']"
>Analysis</a
>
<a
class="d-block d-sm-none"
[routerLink]="['/report']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'report' }"
[routerLink]="['/report']"
>X-ray</a
>
<a
class="d-block d-sm-none"
[routerLink]="['/transactions']"
i18n
mat-menu-item
[ngClass]="{
'font-weight-bold': currentRoute === 'transactions'
}"
[routerLink]="['/transactions']"
[ngClass]="{ 'font-weight-bold': currentRoute === 'transactions' }"
>Transactions</a
>
<a
class="d-block d-sm-none"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'accounts' }"
[routerLink]="['/accounts']"
>Accounts</a
>
<a
class="align-items-center d-flex"
[routerLink]="['/account']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'account' }"
[routerLink]="['/account']"
>My Ghostfolio</a
>Account</a
>
<a
*ngIf="hasPermissionToAccessAdminControl"
class="d-block d-sm-none"
[routerLink]="['/admin']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'admin' }"
[routerLink]="['/admin']"
>Admin Control</a
>
<hr class="m-0" />
<a
class="d-block d-sm-none"
[routerLink]="['/resources']"
i18n
mat-menu-item
[ngClass]="{
'font-weight-bold': currentRoute === 'resources'
}"
[routerLink]="['/resources']"
[ngClass]="{ 'font-weight-bold': currentRoute === 'resources' }"
>Resources</a
>
<a
*ngIf="hasPermissionForSubscription"
class="d-block d-sm-none"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'pricing' }"
[routerLink]="['/pricing']"
>Pricing</a
>
<a
class="d-block d-sm-none"
[routerLink]="['/about']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'about' }"
[routerLink]="['/about']"
>About Ghostfolio</a
>
<hr class="d-block d-sm-none m-0" />
@ -224,27 +182,19 @@
<ng-container *ngIf="user === null">
<a
*ngIf="currentRoute && currentRoute !== 'start'"
[routerLink]="['/']"
class="mx-2 no-min-width px-2"
mat-button
[routerLink]="['/']"
>
<gf-logo></gf-logo>
</a>
<span class="spacer"></span>
<a
*ngIf="hasPermissionForSubscription"
i18n
mat-flat-button
[color]="currentRoute === 'pricing' ? 'primary' : null"
[routerLink]="['/pricing']"
>Pricing</a
>
<a
class="d-none d-sm-block mx-1"
[routerLink]="['/about']"
i18n
mat-flat-button
[color]="currentRoute === 'about' ? 'primary' : null"
[routerLink]="['/about']"
>About</a
>
<a

View File

@ -6,12 +6,13 @@ import {
} from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { InfoItem } from '@ghostfolio/api/app/info/interfaces/info-item.interface';
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
import { LoginWithAccessTokenDialog } from '@ghostfolio/client/pages/login/login-with-access-token-dialog/login-with-access-token-dialog.component';
import { DataService } from '@ghostfolio/client/services/data.service';
import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service';
import { TokenStorageService } from '@ghostfolio/client/services/token-storage.service';
import { InfoItem, User } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { hasPermission, permissions } from '@ghostfolio/helper';
import { EMPTY, Subject } from 'rxjs';
import { catchError, takeUntil } from 'rxjs/operators';
@ -26,9 +27,8 @@ export class HeaderComponent implements OnChanges {
@Input() info: InfoItem;
@Input() user: User;
public hasPermissionForSocialLogin: boolean;
public hasPermissionForSubscription: boolean;
public hasPermissionToAccessAdminControl: boolean;
public hasPermissionForSocialLogin: boolean;
public impersonationId: string;
private unsubscribeSubject = new Subject<void>();
@ -48,20 +48,17 @@ export class HeaderComponent implements OnChanges {
}
public ngOnChanges() {
if (this.user) {
this.hasPermissionToAccessAdminControl = hasPermission(
this.user.permissions,
permissions.accessAdminControl
);
}
this.hasPermissionForSocialLogin = hasPermission(
this.info?.globalPermissions,
permissions.enableSocialLogin
);
this.hasPermissionForSubscription = hasPermission(
this.info?.globalPermissions,
permissions.enableSubscription
);
this.hasPermissionToAccessAdminControl = hasPermission(
this.user?.permissions,
permissions.accessAdminControl
);
}
public impersonateAccount(aId: string) {

View File

@ -9,8 +9,8 @@ import {
OnInit,
ViewChild
} from '@angular/core';
import { primaryColorRgb } from '@ghostfolio/common/config';
import { PortfolioItem } from '@ghostfolio/common/interfaces';
import { PortfolioItem } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-item.interface';
import { primaryColorRgb } from '@ghostfolio/helper';
import {
LineController,
LineElement,

View File

@ -9,8 +9,7 @@ import {
OnInit,
ViewChild
} from '@angular/core';
import { primaryColorRgb, secondaryColorRgb } from '@ghostfolio/common/config';
import { getBackgroundColor } from '@ghostfolio/common/helper';
import { primaryColorRgb, secondaryColorRgb } from '@ghostfolio/helper';
import {
Chart,
Filler,
@ -63,10 +62,6 @@ export class LineChartComponent implements OnChanges, OnDestroy, OnInit {
}
}
public ngOnDestroy() {
this.chart?.destroy();
}
private initialize() {
this.isLoading = true;
const benchmarkPrices = [];
@ -81,7 +76,7 @@ export class LineChartComponent implements OnChanges, OnDestroy, OnInit {
const canvas = document.getElementById('chartCanvas');
const gradient = this.chartCanvas?.nativeElement
var gradient = this.chartCanvas?.nativeElement
?.getContext('2d')
.createLinearGradient(
0,
@ -93,7 +88,14 @@ export class LineChartComponent implements OnChanges, OnDestroy, OnInit {
0,
`rgba(${primaryColorRgb.r}, ${primaryColorRgb.g}, ${primaryColorRgb.b}, 0.01)`
);
gradient.addColorStop(1, getBackgroundColor());
gradient.addColorStop(
1,
getComputedStyle(document.documentElement).getPropertyValue(
window.matchMedia('(prefers-color-scheme: dark)').matches
? '--dark-background'
: '--light-background'
)
);
const data = {
labels,
@ -179,4 +181,8 @@ export class LineChartComponent implements OnChanges, OnDestroy, OnInit {
this.isLoading = false;
}
public ngOnDestroy() {
this.chart?.destroy();
}
}

View File

@ -46,7 +46,7 @@ export class PerformanceChartDialog {
this.historicalDataItems = this.data.historicalDataItems;
this.historicalDataItems?.forEach((historicalDataItem) => {
this.historicalDataItems.forEach((historicalDataItem) => {
const benchmarkItem = historicalData.find((item) => {
return item.date === historicalDataItem.date;
});

View File

@ -5,7 +5,7 @@ import {
OnChanges,
OnInit
} from '@angular/core';
import { PortfolioOverview } from '@ghostfolio/common/interfaces';
import { PortfolioOverview } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-overview.interface';
import { Currency } from '@prisma/client';
@Component({

View File

@ -7,7 +7,7 @@ import {
OnInit,
ViewChild
} from '@angular/core';
import { PortfolioPerformance } from '@ghostfolio/common/interfaces';
import { PortfolioPerformance } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-performance.interface';
import { Currency } from '@prisma/client';
import { CountUp } from 'countup.js';
import { isNumber } from 'lodash';

View File

@ -4,7 +4,7 @@ import {
Input,
OnInit
} from '@angular/core';
import { PortfolioPerformance } from '@ghostfolio/common/interfaces';
import { PortfolioPerformance } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-performance.interface';
import { Currency } from '@prisma/client';
@Component({

View File

@ -7,7 +7,7 @@ import {
OnChanges,
OnInit
} from '@angular/core';
import { PortfolioItem } from '@ghostfolio/common/interfaces';
import { PortfolioItem } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-item.interface';
import { endOfDay, parseISO, startOfDay } from 'date-fns';
@Component({

View File

@ -7,9 +7,7 @@ import {
OnInit,
ViewChild
} from '@angular/core';
import { UNKNOWN_KEY } from '@ghostfolio/common/config';
import { getCssVariable, getTextColor } from '@ghostfolio/common/helper';
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { Currency } from '@prisma/client';
import { Tooltip } from 'chart.js';
import { LinearScale } from 'chart.js';
@ -38,14 +36,6 @@ export class PortfolioProportionChartComponent
public chart: Chart;
public isLoading = true;
private colorMap: {
[symbol: string]: string;
} = {
[UNKNOWN_KEY]: `rgba(${getTextColor()}, ${getCssVariable(
'--palette-foreground-divider-alpha'
)})`
};
public constructor() {
Chart.register(ArcElement, DoughnutController, LinearScale, Tooltip);
}
@ -58,67 +48,37 @@ export class PortfolioProportionChartComponent
}
}
public ngOnDestroy() {
this.chart?.destroy();
}
private initialize() {
this.isLoading = true;
const chartData: {
[symbol: string]: { color?: string; value: number };
} = {};
const chartData: { [symbol: string]: number } = {};
Object.keys(this.positions).forEach((symbol) => {
if (this.positions[symbol][this.key]) {
if (chartData[this.positions[symbol][this.key]]) {
chartData[this.positions[symbol][this.key]].value += this.positions[
chartData[this.positions[symbol][this.key]] += this.positions[
symbol
].value;
} else {
chartData[this.positions[symbol][this.key]] = {
value: this.positions[symbol].value
};
}
} else {
if (chartData[UNKNOWN_KEY]) {
chartData[UNKNOWN_KEY].value += this.positions[symbol].value;
} else {
chartData[UNKNOWN_KEY] = {
value: this.positions[symbol].value
};
chartData[this.positions[symbol][this.key]] = this.positions[
symbol
].value;
}
}
});
const chartDataSorted = Object.entries(chartData)
.sort((a, b) => {
return a[1].value - b[1].value;
return a[1] - b[1];
})
.reverse();
chartDataSorted.forEach(([symbol, item], index) => {
if (this.colorMap[symbol]) {
// Reuse color
item.color = this.colorMap[symbol];
} else {
const color = this.getColorPalette()[index];
// Store color for reuse
this.colorMap[symbol] = color;
item.color = color;
}
});
const data = {
datasets: [
{
backgroundColor: chartDataSorted.map(([, item]) => {
return item.color;
}),
backgroundColor: this.getColorPalette(),
borderWidth: 0,
data: chartDataSorted.map(([, item]) => {
return item.value;
data: chartDataSorted.map(([, value]) => {
return value;
})
}
],
@ -140,14 +100,21 @@ export class PortfolioProportionChartComponent
tooltip: {
callbacks: {
label: (context) => {
const label =
context.label === UNKNOWN_KEY ? 'Other' : context.label;
const label = data.labels[context.dataIndex];
if (this.isInPercent) {
const value = 100 * <number>context.raw;
const value =
100 *
data.datasets[context.datasetIndex].data[
context.dataIndex
];
return `${label} (${value.toFixed(2)}%)`;
} else {
const value = <number>context.raw;
const value =
data.datasets[context.datasetIndex].data[
context.dataIndex
];
return `${label} (${value.toLocaleString(this.locale, {
maximumFractionDigits: 2,
minimumFractionDigits: 2
@ -186,4 +153,8 @@ export class PortfolioProportionChartComponent
'#cc5de8' // grape 5
];
}
public ngOnDestroy() {
this.chart?.destroy();
}
}

Some files were not shown because too many files have changed in this diff Show More