Compare commits

...

5 Commits

Author SHA1 Message Date
e248c9cedd Release 0.98.0 (#61) 2021-05-02 21:22:30 +02:00
90a2fea7d6 Feature/create and update accounts (#60)
* Allow to create and update accounts

* Activate account selector in transaction dialog

* Refactor analytics and report from platforms to accounts
2021-05-02 21:18:52 +02:00
d17b02092e Release 0.97.0 (#59) 2021-05-01 12:33:35 +02:00
c70eb7793e Feature/migration to accounts (#58)
* Migrate transaction table
* Add accounts page
* Add account page logic
2021-05-01 12:30:52 +02:00
e3a1d2b9cf Fix tests (#57) 2021-05-01 12:28:48 +02:00
58 changed files with 1342 additions and 185 deletions

View File

@ -5,6 +5,18 @@ 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).
## 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

View File

@ -0,0 +1,237 @@
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/helper';
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, Order } 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

@ -0,0 +1,30 @@
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

@ -0,0 +1,89 @@
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

@ -0,0 +1,14 @@
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

@ -0,0 +1,17 @@
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

@ -16,6 +16,7 @@ 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';
@ -32,6 +33,7 @@ import { UserModule } from './user/user.module';
imports: [
AdminModule,
AccessModule,
AccountModule,
AuthModule,
CacheModule,
ConfigModule.forRoot(),

View File

@ -7,7 +7,7 @@ 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 { OrderWithAccount } from '../order/interfaces/order-with-account.type';
import { CreateOrderDto } from './create-order.dto';
import { Data } from './interfaces/data.interface';
@ -33,7 +33,7 @@ export class ExperimentalService {
aDate: Date,
aBaseCurrency: Currency
): Promise<Data> {
const ordersWithPlatform: OrderWithPlatform[] = aOrders.map((order) => {
const ordersWithPlatform: OrderWithAccount[] = aOrders.map((order) => {
return {
...order,
accountId: undefined,

View File

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

View File

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

View File

@ -71,7 +71,11 @@ export class OrderController {
let orders = await this.orderService.orders({
include: {
Platform: true
Account: {
include: {
Platform: true
}
}
},
orderBy: { date: 'desc' },
where: { userId: impersonationUserId || this.request.user.id }
@ -180,6 +184,13 @@ export class OrderController {
}
});
if (!originalOrder) {
throw new HttpException(
getReasonPhrase(StatusCodes.FORBIDDEN),
StatusCodes.FORBIDDEN
);
}
const date = parseISO(data.date);
const accountId = data.accountId;

View File

@ -5,7 +5,7 @@ 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';
import { OrderWithAccount } from './interfaces/order-with-account.type';
@Injectable()
export class OrderService {
@ -31,7 +31,7 @@ export class OrderService {
cursor?: Prisma.OrderWhereUniqueInput;
where?: Prisma.OrderWhereInput;
orderBy?: Prisma.OrderOrderByInput;
}): Promise<OrderWithPlatform[]> {
}): Promise<OrderWithAccount[]> {
const { include, skip, take, cursor, where, orderBy } = params;
return this.prisma.order.findMany({

View File

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

View File

@ -185,11 +185,11 @@ export class PortfolioController {
portfolioPosition.investment =
portfolioPosition.investment / totalInvestment;
for (const [platform, { current, original }] of Object.entries(
portfolioPosition.platforms
for (const [account, { current, original }] of Object.entries(
portfolioPosition.accounts
)) {
portfolioPosition.platforms[platform].current = current / totalValue;
portfolioPosition.platforms[platform].original =
portfolioPosition.accounts[account].current = current / totalValue;
portfolioPosition.accounts[account].original =
original / totalInvestment;
}

View File

@ -73,7 +73,7 @@ export class PortfolioService {
// Get portfolio from database
const orders = await this.orderService.orders({
include: {
Platform: true
Account: true
},
orderBy: { date: 'asc' },
where: { userId: aUserId }

View File

@ -1,27 +1,27 @@
import { Currency, Platform } from '@prisma/client';
import { Account, 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,6 +30,10 @@ export class Order {
this.total = this.quantity * data.unitPrice;
}
public getAccount() {
return this.account;
}
public getCurrency() {
return this.currency;
}
@ -46,10 +50,6 @@ export class Order {
return this.id;
}
public getPlatform() {
return this.platform;
}
public getQuantity() {
return this.quantity;
}

View File

@ -1,6 +1,6 @@
import { baseCurrency, getUtc, getYesterday } from '@ghostfolio/helper';
import { Test } from '@nestjs/testing';
import { Currency, Role, Type } from '@prisma/client';
import { AccountType, Currency, DataSource, Role, Type } from '@prisma/client';
import { ConfigurationService } from '../services/configuration.service';
import { DataProviderService } from '../services/data-provider.service';
@ -70,6 +70,18 @@ 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,
@ -133,6 +145,7 @@ describe('Portfolio', () => {
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
dataSource: DataSource.YAHOO,
fee: 0,
date: new Date(),
id: '8d999347-dee2-46ee-88e1-26b344e71fcc',
@ -187,6 +200,7 @@ describe('Portfolio', () => {
// shareCurrent: 0.9999999559148652,
shareInvestment: 1,
symbol: 'BTCUSD',
transactionCount: 0,
type: 'Cryptocurrency'
}
});
@ -233,6 +247,7 @@ 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',
@ -285,6 +300,7 @@ describe('Portfolio', () => {
quantity: 0.2,
// shareCurrent: 1,
shareInvestment: 1,
transactionCount: 1,
symbol: 'ETHUSD',
type: 'Cryptocurrency'
}
@ -327,6 +343,7 @@ 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',
@ -343,6 +360,7 @@ 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',
@ -403,6 +421,7 @@ 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',
@ -419,6 +438,7 @@ 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',
@ -492,6 +512,7 @@ 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',
@ -508,6 +529,7 @@ 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',
@ -524,6 +546,7 @@ 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',

View File

@ -23,7 +23,7 @@ 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 { OrderWithAccount } from '../app/order/interfaces/order-with-account.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';
@ -34,14 +34,14 @@ import { IOrder } from '../services/interfaces/interfaces';
import { RulesService } from '../services/rules.service';
import { PortfolioInterface } from './interfaces/portfolio.interface';
import { Order } from './order';
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[] = [];
@ -119,11 +119,11 @@ export class Portfolio implements PortfolioInterface {
}): Portfolio {
orders.forEach(
({
account,
currency,
fee,
date,
id,
platform,
quantity,
symbol,
type,
@ -131,11 +131,11 @@ export class Portfolio implements PortfolioInterface {
}) => {
this.orders.push(
new Order({
account,
currency,
fee,
date,
id,
platform,
quantity,
symbol,
type,
@ -202,7 +202,7 @@ export class Portfolio implements PortfolioInterface {
const data = await this.dataProviderService.get(symbols);
symbols.forEach((symbol) => {
const platforms: PortfolioPosition['platforms'] = {};
const accounts: PortfolioPosition['accounts'] = {};
const [portfolioItem] = portfolioItems;
const ordersBySymbol = this.getOrders().filter((order) => {
@ -227,15 +227,15 @@ export class Portfolio implements PortfolioInterface {
originalValueOfSymbol *= -1;
}
if (platforms[orderOfSymbol.getPlatform()?.name || 'Other']?.current) {
platforms[
orderOfSymbol.getPlatform()?.name || 'Other'
if (accounts[orderOfSymbol.getAccount()?.name || 'Other']?.current) {
accounts[
orderOfSymbol.getAccount()?.name || 'Other'
].current += currentValueOfSymbol;
platforms[
orderOfSymbol.getPlatform()?.name || 'Other'
accounts[
orderOfSymbol.getAccount()?.name || 'Other'
].original += originalValueOfSymbol;
} else {
platforms[orderOfSymbol.getPlatform()?.name || 'Other'] = {
accounts[orderOfSymbol.getAccount()?.name || 'Other'] = {
current: currentValueOfSymbol,
original: originalValueOfSymbol
};
@ -276,7 +276,7 @@ export class Portfolio implements PortfolioInterface {
details[symbol] = {
...data[symbol],
platforms,
accounts,
symbol,
grossPerformance: roundTo(
portfolioItemsNow.positions[symbol].quantity * (now - before),
@ -396,6 +396,19 @@ 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,
[
@ -414,19 +427,6 @@ 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)],
@ -522,17 +522,17 @@ export class Portfolio implements PortfolioInterface {
return isFinite(value) ? value : null;
}
public async setOrders(aOrders: OrderWithPlatform[]) {
public async setOrders(aOrders: OrderWithAccount[]) {
this.orders = [];
// Map data
aOrders.forEach((order) => {
this.orders.push(
new Order({
account: order.Account,
currency: <any>order.currency,
date: order.date.toISOString(),
fee: order.fee,
platform: order.Platform,
quantity: order.quantity,
symbol: order.symbol,
type: <any>order.type,

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
import { DataSource } from '.prisma/client';
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';

View File

@ -1,4 +1,4 @@
import { Currency } from '.prisma/client';
import { Currency } from '@prisma/client';
export interface ScraperConfig {
currency: Currency;

View File

@ -1,6 +1,6 @@
import { DataSource } from '.prisma/client';
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';

View File

@ -1,6 +1,6 @@
import { DataSource } from '.prisma/client';
import { isCrypto, isCurrency, parseCurrency } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { DataSource } from '@prisma/client';
import { format } from 'date-fns';
import * as yahooFinance from 'yahoo-finance';

View File

@ -1,4 +1,4 @@
import { Currency, DataSource, Platform } from '@prisma/client';
import { Account, Currency, DataSource, Platform } from '@prisma/client';
import { OrderType } from '../../models/order-type';
@ -33,11 +33,11 @@ export const Type = {
};
export interface IOrder {
account: Account;
currency: Currency;
date: string;
fee: number;
id?: string;
platform: Platform;
quantity: number;
symbol: string;
type: OrderType;

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,6 +39,17 @@ 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
@ -61,18 +72,7 @@ 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

@ -9,11 +9,6 @@ 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: () =>
@ -21,6 +16,18 @@ const routes: Routes = [
(m) => m.AccountPageModule
)
},
{
path: 'accounts',
loadChildren: () =>
import('./pages/accounts/accounts-page.module').then(
(m) => m.AccountsPageModule
)
},
{
path: 'admin',
loadChildren: () =>
import('./pages/admin/admin-page.module').then((m) => m.AdminPageModule)
},
{
path: 'auth',
loadChildren: () =>

View File

@ -74,7 +74,7 @@ export class AppComponent implements OnDestroy, OnInit {
this.canCreateAccount = hasPermission(
this.user.permissions,
permissions.createAccount
permissions.createUserAccount
);
this.cd.markForCheck();

View File

@ -0,0 +1,98 @@
<table
class="w-100"
matSort
matSortActive="account"
matSortDirection="desc"
mat-table
[dataSource]="dataSource"
>
<ng-container matColumnDef="account">
<th *matHeaderCellDef i18n mat-header-cell mat-sort-header>Name</th>
<td *matCellDef="let element" mat-cell>
{{ element.name }}
</td>
</ng-container>
<ng-container matColumnDef="type">
<th
*matHeaderCellDef
class="d-none d-lg-table-cell justify-content-center"
i18n
mat-header-cell
mat-sort-header
>
Type
</th>
<td
mat-cell
*matCellDef="let element"
class="d-none d-lg-table-cell text-center"
>
<div class="d-inline-flex justify-content-center px-2 py-1 type-badge">
<span>{{ element.accountType }}</span>
</div>
</td>
</ng-container>
<ng-container matColumnDef="platform">
<th *matHeaderCellDef i18n mat-header-cell mat-sort-header>Platform</th>
<td mat-cell *matCellDef="let element">
<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-0 text-center" i18n mat-header-cell></th>
<td *matCellDef="let element" class="px-0 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

@ -0,0 +1,59 @@
:host {
display: block;
::ng-deep {
.mat-form-field-infix {
border-top: 0 solid transparent !important;
}
}
.mat-table {
td {
border: 0;
}
th {
::ng-deep {
.mat-sort-header-container {
justify-content: inherit;
}
}
}
.mat-row {
&:nth-child(even) {
background-color: rgba(
var(--dark-primary-text),
var(--palette-background-hover-alpha)
);
}
.type-badge {
background-color: rgba(var(--dark-primary-text), 0.05);
border-radius: 1rem;
line-height: 1em;
}
}
}
}
:host-context(.is-dark-theme) {
.mat-form-field {
color: rgba(var(--light-primary-text));
}
.mat-table {
.mat-row {
&:nth-child(even) {
background-color: rgba(
var(--light-primary-text),
var(--palette-background-hover-alpha)
);
}
.type-badge {
background-color: rgba(var(--light-primary-text), 0.1);
}
}
}
}

View File

@ -0,0 +1,85 @@
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', 'type', '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

@ -0,0 +1,33 @@
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

@ -36,6 +36,14 @@
[color]="currentRoute === 'transactions' ? 'primary' : null"
>Transactions</a
>
<a
class="d-none d-sm-block mx-1"
[routerLink]="['/accounts']"
i18n
mat-flat-button
[color]="currentRoute === 'accounts' ? 'primary' : null"
>Accounts</a
>
<a
*ngIf="hasPermissionToAccessAdminControl"
class="d-none d-sm-block mx-1"
@ -141,13 +149,21 @@
[ngClass]="{ 'font-weight-bold': currentRoute === 'transactions' }"
>Transactions</a
>
<a
class="d-block d-sm-none"
[routerLink]="['/accounts']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'accounts' }"
>Accounts</a
>
<a
class="align-items-center d-flex"
[routerLink]="['/account']"
i18n
mat-menu-item
[ngClass]="{ 'font-weight-bold': currentRoute === 'account' }"
>Account</a
>Ghostfolio Account</a
>
<a
*ngIf="hasPermissionToAccessAdminControl"

View File

@ -17,25 +17,21 @@
mat-table
[dataSource]="dataSource"
>
<ng-container matColumnDef="platform">
<th
*matHeaderCellDef
class="d-none d-lg-table-cell text-center px-0"
i18n
mat-header-cell
>
Platform
</th>
<td *matCellDef="let element" class="d-none d-lg-table-cell px-0" mat-cell>
<div class="d-flex justify-content-center">
<ng-container matColumnDef="account">
<th *matHeaderCellDef i18n mat-header-cell mat-sort-header>Account</th>
<td *matCellDef="let element" mat-cell>
<div class="d-flex">
<gf-symbol-icon
*ngIf="element.Platform?.url"
[tooltip]="element.Platform?.name"
[url]="element.Platform?.url"
*ngIf="element.Account?.Platform?.url"
class="mr-1"
[tooltip]="element.Account?.Platform?.name"
[url]="element.Account?.Platform?.url"
></gf-symbol-icon>
<span class="d-none d-lg-block">{{ element.Account?.name }}</span>
</div>
</td>
</ng-container>
<ng-container matColumnDef="date">
<th
*matHeaderCellDef

View File

@ -68,7 +68,7 @@ export class TransactionsTableComponent
public ngOnChanges() {
this.displayedColumns = [
'platform',
'account',
'date',
'type',
'symbol',
@ -78,12 +78,12 @@ export class TransactionsTableComponent
'fee'
];
this.isLoading = true;
if (this.showActions) {
this.displayedColumns.push('actions');
}
this.isLoading = true;
if (this.transactions) {
this.dataSource = new MatTableDataSource(this.transactions);
this.dataSource.sort = this.sort;

View File

@ -8,11 +8,10 @@ import {
hasPermission,
permissions
} from '@ghostfolio/helper';
import { Currency } from '@prisma/client';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Currency } from '.prisma/client';
@Component({
selector: 'gf-account-page',
templateUrl: './account-page.html',

View File

@ -0,0 +1,15 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '@ghostfolio/client/core/auth.guard';
import { AccountsPageComponent } from './accounts-page.component';
const routes: Routes = [
{ path: '', component: AccountsPageComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AccountsPageRoutingModule {}

View File

@ -0,0 +1,192 @@
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { CreateAccountDto } from '@ghostfolio/api/app/account/create-account.dto';
import { UpdateAccountDto } from '@ghostfolio/api/app/account/update-account.dto';
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
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 { hasPermission, permissions } from '@ghostfolio/helper';
import { Account as AccountModel, AccountType } from '@prisma/client';
import { DeviceDetectorService } from 'ngx-device-detector';
import { Subject, Subscription } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { CreateOrUpdateAccountDialog } from './create-or-update-account-dialog/create-or-update-account-dialog.component';
@Component({
selector: 'gf-accounts-page',
templateUrl: './accounts-page.html',
styleUrls: ['./accounts-page.scss']
})
export class AccountsPageComponent implements OnInit {
public accounts: AccountModel[];
public deviceType: string;
public hasImpersonationId: boolean;
public hasPermissionToCreateAccount: boolean;
public hasPermissionToDeleteAccount: boolean;
public routeQueryParams: Subscription;
public user: User;
private unsubscribeSubject = new Subject<void>();
/**
* @constructor
*/
public constructor(
private cd: ChangeDetectorRef,
private dataService: DataService,
private deviceService: DeviceDetectorService,
private dialog: MatDialog,
private impersonationStorageService: ImpersonationStorageService,
private route: ActivatedRoute,
private router: Router,
private tokenStorageService: TokenStorageService
) {
this.routeQueryParams = route.queryParams
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe((params) => {
if (params['createDialog']) {
this.openCreateAccountDialog();
} else if (params['editDialog']) {
if (this.accounts) {
const account = this.accounts.find((account) => {
return account.id === params['transactionId'];
});
this.openUpdateAccountDialog(account);
} else {
this.router.navigate(['.'], { relativeTo: this.route });
}
}
});
}
/**
* Initializes the controller
*/
public ngOnInit() {
this.deviceType = this.deviceService.getDeviceInfo().deviceType;
this.impersonationStorageService
.onChangeHasImpersonation()
.subscribe((aId) => {
this.hasImpersonationId = !!aId;
});
this.tokenStorageService
.onChangeHasToken()
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe(() => {
this.dataService.fetchUser().subscribe((user) => {
this.user = user;
this.hasPermissionToCreateAccount = hasPermission(
user.permissions,
permissions.createAccount
);
this.hasPermissionToDeleteAccount = hasPermission(
user.permissions,
permissions.deleteAccount
);
this.cd.markForCheck();
});
});
this.fetchAccounts();
}
public fetchAccounts() {
this.dataService.fetchAccounts().subscribe((response) => {
this.accounts = response;
if (this.accounts?.length <= 0) {
this.router.navigate([], { queryParams: { createDialog: true } });
}
this.cd.markForCheck();
});
}
public onDeleteAccount(aId: string) {
this.dataService.deleteAccount(aId).subscribe({
next: () => {
this.fetchAccounts();
}
});
}
public onUpdateAccount(aAccount: AccountModel) {
this.router.navigate([], {
queryParams: { editDialog: true, transactionId: aAccount.id }
});
}
public openUpdateAccountDialog({
accountType,
id,
name,
platformId
}: AccountModel): void {
const dialogRef = this.dialog.open(CreateOrUpdateAccountDialog, {
data: {
account: {
accountType,
id,
name,
platformId
}
},
height: this.deviceType === 'mobile' ? '97.5vh' : '80vh',
width: this.deviceType === 'mobile' ? '100vw' : '50rem'
});
dialogRef.afterClosed().subscribe((data: any) => {
const account: UpdateAccountDto = data?.account;
if (account) {
this.dataService.putAccount(account).subscribe({
next: () => {
this.fetchAccounts();
}
});
}
this.router.navigate(['.'], { relativeTo: this.route });
});
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
private openCreateAccountDialog(): void {
const dialogRef = this.dialog.open(CreateOrUpdateAccountDialog, {
data: {
account: {
accountType: AccountType.SECURITIES,
name: null,
platformId: null
}
},
height: this.deviceType === 'mobile' ? '97.5vh' : '80vh',
width: this.deviceType === 'mobile' ? '100vw' : '50rem'
});
dialogRef.afterClosed().subscribe((data: any) => {
const account: CreateAccountDto = data?.account;
if (account) {
this.dataService.postAccount(account).subscribe({
next: () => {
this.fetchAccounts();
}
});
}
this.router.navigate(['.'], { relativeTo: this.route });
});
}
}

View File

@ -0,0 +1,31 @@
<div class="container">
<div class="row mb-3">
<div class="col">
<h3 class="d-flex justify-content-center mb-3" i18n>Accounts</h3>
<gf-accounts-table
[accounts]="accounts"
[baseCurrency]="user?.settings?.baseCurrency"
[deviceType]="deviceType"
[locale]="user?.settings?.locale"
[showActions]="!hasImpersonationId && hasPermissionToDeleteAccount"
(accountDeleted)="onDeleteAccount($event)"
(accountToUpdate)="onUpdateAccount($event)"
></gf-accounts-table>
</div>
</div>
<div
*ngIf="!hasImpersonationId && hasPermissionToCreateAccount"
class="fab-container"
>
<a
class="align-items-center d-flex justify-content-center"
color="primary"
mat-fab
[routerLink]="[]"
[queryParams]="{ createDialog: true }"
>
<ion-icon name="add-outline" size="large"></ion-icon>
</a>
</div>
</div>

View File

@ -0,0 +1,25 @@
import { CommonModule } from '@angular/common';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { RouterModule } from '@angular/router';
import { GfAccountsTableModule } from '@ghostfolio/client/components/accounts-table/accounts-table.module';
import { AccountsPageRoutingModule } from './accounts-page-routing.module';
import { AccountsPageComponent } from './accounts-page.component';
import { CreateOrUpdateAccountDialogModule } from './create-or-update-account-dialog/create-or-update-account-dialog.module';
@NgModule({
declarations: [AccountsPageComponent],
exports: [],
imports: [
AccountsPageRoutingModule,
CommonModule,
CreateOrUpdateAccountDialogModule,
GfAccountsTableModule,
MatButtonModule,
RouterModule
],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AccountsPageModule {}

View File

@ -0,0 +1,8 @@
:host {
.fab-container {
position: fixed;
right: 2rem;
bottom: 2rem;
z-index: 999;
}
}

View File

@ -0,0 +1,43 @@
import { ChangeDetectionStrategy, Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Currency } from '@prisma/client';
import { Subject } from 'rxjs';
import { DataService } from '../../../services/data.service';
import { CreateOrUpdateAccountDialogParams } from './interfaces/interfaces';
@Component({
host: { class: 'h-100' },
selector: 'gf-create-or-update-account-dialog',
changeDetection: ChangeDetectionStrategy.OnPush,
styleUrls: ['./create-or-update-account-dialog.scss'],
templateUrl: 'create-or-update-account-dialog.html'
})
export class CreateOrUpdateAccountDialog {
public currencies: Currency[] = [];
public platforms: { id: string; name: string }[];
private unsubscribeSubject = new Subject<void>();
public constructor(
private dataService: DataService,
public dialogRef: MatDialogRef<CreateOrUpdateAccountDialog>,
@Inject(MAT_DIALOG_DATA) public data: CreateOrUpdateAccountDialogParams
) {}
ngOnInit() {
this.dataService.fetchInfo().subscribe(({ currencies, platforms }) => {
this.currencies = currencies;
this.platforms = platforms;
});
}
public onCancel(): void {
this.dialogRef.close();
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
}

View File

@ -0,0 +1,43 @@
<form #addAccountForm="ngForm" class="d-flex flex-column h-100">
<h1 *ngIf="data.account.id" mat-dialog-title i18n>Update account</h1>
<h1 *ngIf="!data.account.id" mat-dialog-title i18n>Add account</h1>
<div class="flex-grow-1" mat-dialog-content>
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Name</mat-label>
<input matInput name="name" required [(ngModel)]="data.account.name" />
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Type</mat-label>
<mat-select name="type" required [(value)]="data.account.accountType">
<mat-option value="SECURITIES" i18n> SECURITIES </mat-option>
</mat-select>
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Platform</mat-label>
<mat-select name="platformId" [(value)]="data.account.platformId">
<mat-option [value]="null"></mat-option>
<mat-option *ngFor="let platform of platforms" [value]="platform.id"
>{{ platform.name }}</mat-option
>
</mat-select>
</mat-form-field>
</div>
</div>
<div class="justify-content-end" mat-dialog-actions>
<button i18n mat-button (click)="onCancel()">Cancel</button>
<button
color="primary"
i18n
mat-flat-button
[disabled]="!addAccountForm.form.valid"
[mat-dialog-close]="data"
>
Save
</button>
</div>
</form>

View File

@ -0,0 +1,27 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { CreateOrUpdateAccountDialog } from './create-or-update-account-dialog.component';
@NgModule({
declarations: [CreateOrUpdateAccountDialog],
exports: [],
imports: [
CommonModule,
FormsModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
ReactiveFormsModule
],
providers: []
})
export class CreateOrUpdateAccountDialogModule {}

View File

@ -0,0 +1,43 @@
:host {
display: block;
.mat-dialog-content {
max-height: unset;
.autocomplete {
font-size: 90%;
height: 2.5rem;
.symbol {
display: inline-block;
min-width: 4rem;
}
}
.mat-select {
&.no-arrow {
::ng-deep {
.mat-select-arrow {
opacity: 0;
}
}
}
}
.mat-datepicker-input {
&.mat-input-element:disabled {
color: var(--dark-primary-text);
}
}
}
}
:host-context(.is-dark-theme) {
.mat-dialog-content {
.mat-datepicker-input {
&.mat-input-element:disabled {
color: var(--light-primary-text);
}
}
}
}

View File

@ -0,0 +1,5 @@
import { Account } from '@prisma/client';
export interface CreateOrUpdateAccountDialogParams {
account: Account;
}

View File

@ -16,6 +16,9 @@ import { takeUntil } from 'rxjs/operators';
styleUrls: ['./analysis-page.scss']
})
export class AnalysisPageComponent implements OnDestroy, OnInit {
public accounts: {
[symbol: string]: Pick<PortfolioPosition, 'name'> & { value: number };
};
public deviceType: string;
public period = 'current';
public periodOptions: ToggleOption[] = [
@ -23,9 +26,6 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
{ label: 'Current', value: 'current' }
];
public hasImpersonationId: boolean;
public platforms: {
[symbol: string]: Pick<PortfolioPosition, 'name'> & { value: number };
};
public portfolioItems: PortfolioItem[];
public portfolioPositions: { [symbol: string]: PortfolioPosition };
public positions: { [symbol: string]: any };
@ -95,7 +95,7 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
},
aPeriod: string
) {
this.platforms = {};
this.accounts = {};
this.positions = {};
this.positionsArray = [];
@ -113,16 +113,16 @@ export class AnalysisPageComponent implements OnDestroy, OnInit {
};
this.positionsArray.push(position);
for (const [platform, { current, original }] of Object.entries(
position.platforms
for (const [account, { current, original }] of Object.entries(
position.accounts
)) {
if (this.platforms[platform]?.value) {
this.platforms[platform].value +=
if (this.accounts[account]?.value) {
this.accounts[account].value +=
aPeriod === 'original' ? original : current;
} else {
this.platforms[platform] = {
this.accounts[account] = {
value: aPeriod === 'original' ? original : current,
name: platform
name: account
};
}
}

View File

@ -36,7 +36,7 @@
<div class="col-md-6">
<mat-card class="mb-3">
<mat-card-header class="w-100">
<mat-card-title i18n>By Platform</mat-card-title>
<mat-card-title i18n>By Account</mat-card-title>
<gf-toggle
[defaultValue]="period"
[isLoading]="false"
@ -50,7 +50,7 @@
[baseCurrency]="user?.settings?.baseCurrency"
[isInPercent]="hasImpersonationId"
[locale]="user?.settings?.locale"
[positions]="platforms"
[positions]="accounts"
></gf-portfolio-proportion-chart>
</mat-card-content>
</mat-card>

View File

@ -10,9 +10,9 @@ import { takeUntil } from 'rxjs/operators';
styleUrls: ['./report-page.scss']
})
export class ReportPageComponent implements OnInit {
public accountClusterRiskRules: PortfolioReportRule[];
public currencyClusterRiskRules: PortfolioReportRule[];
public feeRules: PortfolioReportRule[];
public platformClusterRiskRules: PortfolioReportRule[];
private unsubscribeSubject = new Subject<void>();
@ -32,11 +32,11 @@ export class ReportPageComponent implements OnInit {
.fetchPortfolioReport()
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe((portfolioReport) => {
this.accountClusterRiskRules =
portfolioReport.rules['accountClusterRisk'] || null;
this.currencyClusterRiskRules =
portfolioReport.rules['currencyClusterRisk'] || null;
this.feeRules = portfolioReport.rules['fees'] || null;
this.platformClusterRiskRules =
portfolioReport.rules['platformClusterRisk'] || null;
this.cd.markForCheck();
});

View File

@ -18,8 +18,8 @@
<gf-rules [rules]="currencyClusterRiskRules"></gf-rules>
</div>
<div class="mb-4">
<h4 class="m-0" i18n>Platform Cluster Risks</h4>
<gf-rules [rules]="platformClusterRiskRules"></gf-rules>
<h4 class="m-0" i18n>Account Cluster Risks</h4>
<gf-rules [rules]="accountClusterRiskRules"></gf-rules>
</div>
<div>
<h4 class="m-0" i18n>Fees</h4>

View File

@ -121,11 +121,10 @@
/>
</mat-form-field>
</div>
<div class="d-none">
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Account</mat-label>
<mat-select
disabled
name="accountId"
required
[(value)]="data.transaction.accountId"
@ -136,17 +135,6 @@
</mat-select>
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Platform</mat-label>
<mat-select name="platformId" [(value)]="data.transaction.platformId">
<mat-option [value]="null"></mat-option>
<mat-option *ngFor="let platform of platforms" [value]="platform.id"
>{{ platform.name }}</mat-option
>
</mat-select>
</mat-form-field>
</div>
</div>
<div class="justify-content-end" mat-dialog-actions>
<button i18n mat-button (click)="onCancel()">Cancel</button>

View File

@ -1,6 +1,4 @@
import { Account } from '@prisma/client';
import { Order } from '../../interfaces/order.interface';
import { Account, Order } from '@prisma/client';
export interface CreateOrUpdateTransactionDialogParams {
accountId: string;

View File

@ -1,15 +0,0 @@
import { Currency, DataSource } from '.prisma/client';
export interface Order {
accountId: string;
currency: Currency;
dataSource: DataSource;
date: Date;
fee: number;
id: string;
quantity: number;
platformId: string;
symbol: string;
type: string;
unitPrice: number;
}

View File

@ -1,6 +1,7 @@
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { CreateOrderDto } from '@ghostfolio/api/app/order/create-order.dto';
import { UpdateOrderDto } from '@ghostfolio/api/app/order/update-order.dto';
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
import { DataService } from '@ghostfolio/client/services/data.service';
@ -199,7 +200,7 @@ export class TransactionsPageComponent implements OnInit {
});
dialogRef.afterClosed().subscribe((data: any) => {
const transaction: UpdateOrderDto = data?.transaction;
const transaction: CreateOrderDto = data?.transaction;
if (transaction) {
this.dataService.postOrder(transaction).subscribe({

View File

@ -1,8 +1,11 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Access } from '@ghostfolio/api/app/access/interfaces/access.interface';
import { CreateAccountDto } from '@ghostfolio/api/app/account/create-account.dto';
import { UpdateAccountDto } from '@ghostfolio/api/app/account/update-account.dto';
import { AdminData } from '@ghostfolio/api/app/admin/interfaces/admin-data.interface';
import { InfoItem } from '@ghostfolio/api/app/info/interfaces/info-item.interface';
import { CreateOrderDto } from '@ghostfolio/api/app/order/create-order.dto';
import { UpdateOrderDto } from '@ghostfolio/api/app/order/update-order.dto';
import { PortfolioItem } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-item.interface';
import { PortfolioOverview } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-overview.interface';
@ -19,6 +22,7 @@ import { UserItem } from '@ghostfolio/api/app/user/interfaces/user-item.interfac
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
import { UpdateUserSettingsDto } from '@ghostfolio/api/app/user/update-user-settings.dto';
import { Order as OrderModel } from '@prisma/client';
import { Account as AccountModel } from '@prisma/client';
@Injectable({
providedIn: 'root'
@ -28,10 +32,18 @@ export class DataService {
public constructor(private http: HttpClient) {}
public fetchAccounts() {
return this.http.get<AccountModel[]>('/api/account');
}
public fetchAdminData() {
return this.http.get<AdminData>('/api/admin');
}
public deleteAccount(aId: string) {
return this.http.delete<any>(`/api/account/${aId}`);
}
public deleteOrder(aId: string) {
return this.http.delete<any>(`/api/order/${aId}`);
}
@ -108,7 +120,11 @@ export class DataService {
return this.http.get<any>(`/api/auth/anonymous/${accessToken}`);
}
public postOrder(aOrder: UpdateOrderDto) {
public postAccount(aAccount: CreateAccountDto) {
return this.http.post<OrderModel>(`/api/account`, aAccount);
}
public postOrder(aOrder: CreateOrderDto) {
return this.http.post<OrderModel>(`/api/order`, aOrder);
}
@ -116,6 +132,10 @@ export class DataService {
return this.http.post<UserItem>(`/api/user`, {});
}
public putAccount(aAccount: UpdateAccountDto) {
return this.http.put<UserItem>(`/api/account/${aAccount.id}`, aAccount);
}
public putOrder(aOrder: UpdateOrderDto) {
return this.http.put<UserItem>(`/api/order/${aOrder.id}`, aOrder);
}

View File

@ -9,10 +9,13 @@ export const permissions = {
accessFearAndGreedIndex: 'accessFearAndGreedIndex',
createAccount: 'createAccount',
createOrder: 'createOrder',
createUserAccount: 'createUserAccount',
deleteAccount: 'deleteAcccount',
deleteOrder: 'deleteOrder',
enableSocialLogin: 'enableSocialLogin',
enableSubscription: 'enableSubscription',
readForeignPortfolio: 'readForeignPortfolio',
updateAccount: 'updateAccount',
updateOrder: 'updateOrder',
updateUserSettings: 'updateUserSettings'
};
@ -29,20 +32,26 @@ export function getPermissions(aRole: Role): string[] {
case 'ADMIN':
return [
permissions.accessAdminControl,
permissions.createAccount,
permissions.createOrder,
permissions.deleteAccount,
permissions.deleteOrder,
permissions.readForeignPortfolio,
permissions.updateAccount,
permissions.updateOrder,
permissions.updateUserSettings
];
case 'DEMO':
return [permissions.createAccount];
return [permissions.createUserAccount];
case 'USER':
return [
permissions.createAccount,
permissions.createOrder,
permissions.deleteAccount,
permissions.deleteOrder,
permissions.updateAccount,
permissions.updateOrder,
permissions.updateUserSettings
];

View File

@ -1,6 +1,6 @@
{
"name": "ghostfolio",
"version": "0.96.0",
"version": "0.98.0",
"homepage": "https://ghostfol.io",
"license": "AGPL-3.0",
"scripts": {