Compare commits

...

25 Commits

Author SHA1 Message Date
e68ebdf76d Release 0.96.0 2021-04-30 21:18:42 +02:00
949cf58eef Release 0.96.0 (#56) 2021-04-30 21:14:28 +02:00
0816defb95 Feature/update slogan (#55)
* Harmonize slogan
2021-04-30 21:11:48 +02:00
a076a1c933 Feature/extend position detail dialog (#54)
* Extend position detail dialog

* Absolute change
* Number of transactions
2021-04-30 21:08:43 +02:00
40c95a541d Add data source to transaction model (#53) 2021-04-28 21:30:49 +02:00
2d04d7b8d5 Release 0.94.0 (#52) 2021-04-27 21:04:51 +02:00
94e0feac68 Add scraper symbols to symbol lookup results (#51) 2021-04-27 21:03:22 +02:00
cd9e974c40 Release 0.93.0 (#50) 2021-04-26 22:09:20 +02:00
11700f75d9 Improve colors in dark mode, improve user table (#49) 2021-04-26 21:54:19 +02:00
0439a7beaa Release 0.92.0 (#48) 2021-04-25 21:27:13 +02:00
608b195ba9 Extend user table (#47)
* Column: accounts
* Horizontal scrollbar
2021-04-25 21:25:23 +02:00
8cb5fd64dd Prepare for multi accounts support: store account for new transactions (#46) 2021-04-25 21:22:35 +02:00
ef317a86ed Setup angular compiler options (#45) 2021-04-25 17:41:53 +02:00
19ada83d0b Fix header and about page (#44) 2021-04-25 17:29:04 +02:00
6ecf66ea2a Fix types 2021-04-25 12:34:34 +02:00
65ba16c07c Fix tests 2021-04-25 12:30:28 +02:00
aee7c12c44 Release 0.91.0 (#43) 2021-04-25 12:15:40 +02:00
125956eb3e Refactor number extraction from string (#41) 2021-04-25 12:11:52 +02:00
954224401d Prepare for multi accounts support (#42) 2021-04-25 12:07:32 +02:00
d268de3e12 Feature/improve styling of x ray rules (#40) 2021-04-24 22:22:41 +02:00
39cfb4603b Extend support for feature flags (#39) 2021-04-24 22:01:38 +02:00
15a70abf67 Release 0.90.0 2021-04-22 22:02:52 +02:00
5cb69291f5 Introduce market states (#38)
* closed
* delayed (no live data)
* open
2021-04-22 22:00:46 +02:00
cf582b2e98 Add symbol icon to position detail dialog (#37) 2021-04-22 21:21:52 +02:00
82e159a083 Filter inactive users (#36) 2021-04-22 20:55:05 +02:00
71 changed files with 873 additions and 381 deletions

View File

@ -5,6 +5,70 @@ 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.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
- Improved the user table styling of the admin control panel
- Improved the background colors in the dark mode
## 0.92.0 - 25.04.2021
### Added
- Prepared further for multi accounts support: store account for new transactions
- Added a horizontal scrollbar to the user table of the admin control panel
### Fixed
- Fixed an issue in the header with outdated data
- Fixed an issue on the about page with outdated data
## 0.91.0 - 25.04.2021
### Added
- Extended the support for feature flags to simplify the initial project setup
- Prepared for multi accounts support
### Changed
- Improved the styling of the rules in the _X-ray_ section
## 0.90.0 - 22.04.2021
### Added
- Added the symbol logo to the position detail dialog
- Introduced a third option for the market state: `delayed` (besides `open` and `closed`)
### Changed
- Improved the user table of the admin control panel
## 0.89.0 - 21.04.2021
### Added
@ -84,7 +148,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Fixed an issue in the portfolio update on deleting a transaction
- Fixed an issue in the _X-Ray_ section (missing redirection on logout)
- Fixed an issue in the _X-ray_ section (missing redirection on logout)
## 0.82.0 - 10.04.2021
@ -157,7 +221,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Grouped the _X-Ray_ section visually in _Currency Cluster Risk_ and _Platform Cluster Risk_
- Grouped the _X-ray_ section visually in _Currency Cluster Risk_ and _Platform Cluster Risk_
## 0.76.0 - 02.04.2021
@ -169,7 +233,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Fixed an issue in the _X-Ray_ section (empty portfolio)
- Fixed an issue in the _X-ray_ section (empty portfolio)
## 0.75.0 - 01.04.2021
@ -182,7 +246,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added a _Create Account_ message in the _Live Demo_
- Added skeleton loaders to the _X-Ray_ section
- Added skeleton loaders to the _X-ray_ section
### Changed
@ -198,7 +262,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Improved the intro text in the _X-Ray_ section
- Improved the intro text in the _X-ray_ section
### Fixed
@ -214,7 +278,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added an intro text to the _X-Ray_ section
- Added an intro text to the _X-ray_ section
### Changed
@ -233,7 +297,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Changed
- Improved the styling in the _X-Ray_ section
- Improved the styling in the _X-ray_ section
## 0.70.0 - 27.03.2021
@ -241,7 +305,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added the current _Fear & Greed Index_ as text
- Extended the landing page text: _Ghostfolio_ empowers busy folks...
- Added the first static portfolio analysis rule in the brand new _X-Ray_ section
- Added the first static portfolio analysis rule in the brand new _X-ray_ section
### Changed

View File

@ -97,7 +97,7 @@ export class AdminService {
},
select: {
_count: {
select: { Order: true }
select: { Account: true, Order: true }
},
alias: true,
Analytics: {
@ -109,7 +109,12 @@ export class AdminService {
createdAt: true,
id: true
},
take: 20
take: 20,
where: {
NOT: {
Analytics: null
}
}
});
}
}

View File

@ -36,7 +36,10 @@ export class ExperimentalService {
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

@ -26,7 +26,11 @@ export class InfoService {
const globalPermissions: string[] = [];
if (this.configurationService.get('ENABLE_FEATURE_SOCIAL_LOGIN')) {
globalPermissions.push(permissions.useSocialLogin);
globalPermissions.push(permissions.enableSocialLogin);
}
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) {
globalPermissions.push(permissions.enableSubscription);
}
return {

View File

@ -1,3 +1,6 @@
import { Settings, User } from '@prisma/client';
import { Account, Settings, User } from '@prisma/client';
export type UserWithSettings = User & { Settings: Settings };
export type UserWithSettings = User & {
Account: Account[];
Settings: Settings;
};

View File

@ -1,10 +1,16 @@
import { Currency, Type } from '@prisma/client';
import { Currency, DataSource, Type } from '@prisma/client';
import { IsISO8601, IsNumber, IsString, ValidateIf } from 'class-validator';
export class CreateOrderDto {
@IsString()
accountId: string;
@IsString()
currency: Currency;
@IsString()
dataSource: DataSource;
@IsISO8601()
date: string;

View File

@ -118,6 +118,9 @@ export class OrderController {
const date = parseISO(data.date);
const accountId = data.accountId;
delete data.accountId;
if (data.platformId) {
const platformId = data.platformId;
delete data.platformId;
@ -126,6 +129,11 @@ export class OrderController {
{
...data,
date,
Account: {
connect: {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
Platform: { connect: { id: platformId } },
User: { connect: { id: this.request.user.id } }
},
@ -138,6 +146,11 @@ export class OrderController {
{
...data,
date,
Account: {
connect: {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
User: { connect: { id: this.request.user.id } }
},
this.request.user.id
@ -169,6 +182,9 @@ export class OrderController {
const date = parseISO(data.date);
const accountId = data.accountId;
delete data.accountId;
if (data.platformId) {
const platformId = data.platformId;
delete data.platformId;
@ -178,6 +194,11 @@ export class OrderController {
data: {
...data,
date,
Account: {
connect: {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
Platform: { connect: { id: platformId } },
User: { connect: { id: this.request.user.id } }
},
@ -199,6 +220,11 @@ export class OrderController {
data: {
...data,
date,
Account: {
connect: {
id_userId: { id: accountId, userId: this.request.user.id }
}
},
Platform: originalOrder.platformId
? { disconnect: true }
: undefined,

View File

@ -1,10 +1,16 @@
import { Currency, Type } from '@prisma/client';
import { Currency, DataSource, Type } from '@prisma/client';
import { IsISO8601, IsNumber, IsString, ValidateIf } from 'class-validator';
export class UpdateOrderDto {
@IsString()
accountId: string;
@IsString()
currency: Currency;
@IsString()
dataSource: DataSource;
@IsISO8601()
date: string;

View File

@ -16,4 +16,5 @@ export interface Position {
investmentInOriginalCurrency?: number;
marketPrice?: number;
quantity: number;
transactionCount: number;
}

View File

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

View File

@ -1,3 +1,4 @@
import { MarketState } from '@ghostfolio/api/services/interfaces/interfaces';
import { Currency } from '@prisma/client';
export interface PortfolioPosition {
@ -7,10 +8,10 @@ export interface PortfolioPosition {
grossPerformancePercent: number;
industry?: string;
investment: number;
isMarketOpen: boolean;
marketChange?: number;
marketChangePercent?: number;
marketPrice: number;
marketState: MarketState;
name: string;
platforms: {
[name: string]: { current: number; original: number };
@ -19,6 +20,7 @@ export interface PortfolioPosition {
sector?: string;
shareCurrent: number;
shareInvestment: number;
transactionCount: number;
symbol: string;
type?: string;
url?: string;

View File

@ -209,7 +209,8 @@ export class PortfolioService {
firstBuyDate,
investment,
marketPrice,
quantity
quantity,
transactionCount
} = portfolio.getPositions(new Date())[aSymbol];
const historicalData = await this.dataProviderService.getHistorical(
@ -262,6 +263,7 @@ export class PortfolioService {
maxPrice,
minPrice,
quantity,
transactionCount,
grossPerformance: this.exchangeRateDataService.toCurrency(
marketPrice - averagePrice,
currency,
@ -315,7 +317,8 @@ export class PortfolioService {
maxPrice: undefined,
minPrice: undefined,
quantity: undefined,
symbol: aSymbol
symbol: aSymbol,
transactionCount: undefined
};
}
@ -331,7 +334,8 @@ export class PortfolioService {
maxPrice: undefined,
minPrice: undefined,
quantity: undefined,
symbol: aSymbol
symbol: aSymbol,
transactionCount: undefined
};
}

View File

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

View File

@ -1,4 +1,6 @@
import { DataGatheringService } from '@ghostfolio/api/services/data-gathering.service';
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 } from '@prisma/client';
@ -10,31 +12,51 @@ import { SymbolItem } from './interfaces/symbol-item.interface';
@Injectable()
export class SymbolService {
public constructor(
private readonly dataProviderService: DataProviderService
private readonly dataProviderService: DataProviderService,
private readonly ghostfolioScraperApiService: GhostfolioScraperApiService
) {}
public async get(aSymbol: string): Promise<SymbolItem> {
const response = await this.dataProviderService.get([aSymbol]);
const { currency, marketPrice } = response[aSymbol];
const { currency, dataSource, marketPrice } = response[aSymbol];
return {
dataSource,
marketPrice,
currency: <Currency>(<unknown>currency)
};
}
public async lookup(aQuery: string): Promise<LookupItem[]> {
public async lookup(aQuery = ''): Promise<LookupItem[]> {
const query = aQuery.toLowerCase();
const results: LookupItem[] = [];
if (!query) {
return results;
}
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`,
`https://query1.finance.yahoo.com/v1/finance/search?q=${query}&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
);
// Add custom symbols
const scraperConfigurations = await this.ghostfolioScraperApiService.getScraperConfigurations();
scraperConfigurations.forEach((scraperConfiguration) => {
if (scraperConfiguration.name.toLowerCase().startsWith(query)) {
results.push({
name: scraperConfiguration.name,
symbol: scraperConfiguration.symbol
});
}
});
try {
const { quotes } = await get();
return quotes
const searchResult = quotes
.filter(({ isYahooFinance }) => {
return isYahooFinance;
})
@ -59,6 +81,8 @@ export class SymbolService {
symbol: convertFromYahooSymbol(symbol)
};
});
return results.concat(searchResult);
} catch (error) {
console.error(error);

View File

@ -1,9 +1,10 @@
import { Currency } from '@prisma/client';
import { Account, Currency } from '@prisma/client';
import { Access } from './access.interface';
export interface User {
access: Access[];
accounts: Account[];
alias?: string;
id: string;
permissions: string[];

View File

@ -25,6 +25,7 @@ export class UserService {
) {}
public async getUser({
Account,
alias,
id,
role,
@ -53,6 +54,7 @@ export class UserService {
id: accessItem.id
};
}),
accounts: Account,
permissions: currentPermissions,
settings: {
baseCurrency: Settings?.currency || UserService.DEFAULT_CURRENCY,
@ -69,7 +71,7 @@ export class UserService {
userWhereUniqueInput: Prisma.UserWhereUniqueInput
): Promise<UserWithSettings | null> {
const user = await this.prisma.user.findUnique({
include: { Settings: true },
include: { Account: true, Settings: true },
where: userWhereUniqueInput
});
@ -116,7 +118,15 @@ export class UserService {
public async createUser(data?: Prisma.UserCreateInput): Promise<User> {
let user = await this.prisma.user.create({
data
data: {
...data,
Account: {
create: {
isDefault: true,
name: 'Default Account'
}
}
}
});
if (data.provider === Provider.ANONYMOUS) {

View File

@ -5,18 +5,24 @@ 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';
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;
@ -31,6 +37,7 @@ describe('Portfolio', () => {
ConfigurationService,
DataProviderService,
ExchangeRateDataService,
GhostfolioScraperApiService,
PrismaService,
RakutenRapidApiService,
RulesService,
@ -44,6 +51,9 @@ describe('Portfolio', () => {
exchangeRateDataService = app.get<ExchangeRateDataService>(
ExchangeRateDataService
);
ghostfolioScraperApiService = app.get<GhostfolioScraperApiService>(
GhostfolioScraperApiService
);
prismaService = app.get<PrismaService>(PrismaService);
rakutenRapidApiService = app.get<RakutenRapidApiService>(
RakutenRapidApiService
@ -62,13 +72,13 @@ describe('Portfolio', () => {
accessToken: null,
alias: 'Test',
createdAt: new Date(),
id: '',
id: USER_ID,
provider: null,
role: Role.USER,
Settings: {
currency: Currency.CHF,
updatedAt: new Date(),
userId: ''
userId: USER_ID
},
thirdPartyId: null,
updatedAt: new Date()
@ -119,6 +129,8 @@ describe('Portfolio', () => {
it('should return ["BTC"]', async () => {
await portfolio.setOrders([
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 0,
@ -130,7 +142,7 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 49631.24,
updatedAt: null,
userId: null
userId: USER_ID
}
]);
@ -154,8 +166,8 @@ describe('Portfolio', () => {
Currency.USD,
baseCurrency
),
isMarketOpen: true,
// marketPrice: 57973.008,
marketState: MarketState.open,
name: 'Bitcoin USD',
platforms: {
Other: {
@ -217,6 +229,8 @@ describe('Portfolio', () => {
it('should return ["ETHUSD"]', async () => {
await portfolio.setOrders([
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 0,
@ -228,7 +242,7 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 991.49,
updatedAt: null,
userId: null
userId: USER_ID
}
]);
@ -269,7 +283,7 @@ describe('Portfolio', () => {
}
},
quantity: 0.2,
shareCurrent: 1,
// shareCurrent: 1,
shareInvestment: 1,
symbol: 'ETHUSD',
type: 'Cryptocurrency'
@ -309,6 +323,8 @@ describe('Portfolio', () => {
it('should return ["ETHUSD"]', async () => {
await portfolio.setOrders([
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 0,
@ -320,9 +336,11 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 991.49,
updatedAt: null,
userId: null
userId: USER_ID
},
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 0,
@ -334,7 +352,7 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 1050,
updatedAt: null,
userId: null
userId: USER_ID
}
]);
@ -381,6 +399,8 @@ describe('Portfolio', () => {
it('should return ["BTCUSD", "ETHUSD"]', async () => {
await portfolio.setOrders([
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.EUR,
date: new Date(getUtc('2017-08-16')),
@ -392,9 +412,11 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 3562.089535970158,
updatedAt: null,
userId: null
userId: USER_ID
},
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 2.99,
@ -406,7 +428,7 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 991.49,
updatedAt: null,
userId: null
userId: USER_ID
}
]);
@ -466,6 +488,8 @@ describe('Portfolio', () => {
it('should work with buy and sell', async () => {
await portfolio.setOrders([
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 1.0,
@ -477,9 +501,11 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 991.49,
updatedAt: null,
userId: null
userId: USER_ID
},
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 1.0,
@ -491,9 +517,11 @@ describe('Portfolio', () => {
type: Type.SELL,
unitPrice: 1050,
updatedAt: null,
userId: null
userId: USER_ID
},
{
accountId: DEFAULT_ACCOUNT_ID,
accountUserId: USER_ID,
createdAt: null,
currency: Currency.USD,
fee: 1.0,
@ -505,7 +533,7 @@ describe('Portfolio', () => {
type: Type.BUY,
unitPrice: 1050,
updatedAt: null,
userId: null
userId: USER_ID
}
]);

View File

@ -57,7 +57,7 @@ export class Portfolio implements PortfolioInterface {
public async addCurrentPortfolioItems() {
const currentData = await this.dataProviderService.get(this.getSymbols());
let currentDate = new Date();
const currentDate = new Date();
const year = getYear(currentDate);
const month = getMonth(currentDate);
@ -82,7 +82,9 @@ export class Portfolio implements PortfolioInterface {
marketPrice:
currentData[symbol]?.marketPrice ??
portfolioItemsYesterday.positions[symbol]?.marketPrice,
quantity: portfolioItemsYesterday?.positions[symbol]?.quantity
quantity: portfolioItemsYesterday?.positions[symbol]?.quantity,
transactionCount:
portfolioItemsYesterday?.positions[symbol]?.transactionCount
};
});
@ -289,7 +291,9 @@ export class Portfolio implements PortfolioInterface {
data[symbol]?.currency,
this.user.Settings.currency
) / value,
shareInvestment: portfolioItem.positions[symbol].investment / investment
shareInvestment:
portfolioItem.positions[symbol].investment / investment,
transactionCount: portfolioItem.positions[symbol].transactionCount
};
});
@ -582,7 +586,8 @@ export class Portfolio implements PortfolioInterface {
marketPrice:
historicalData[symbol]?.[format(currentDate, 'yyyy-MM-dd')]
?.marketPrice || 0,
quantity: 0
quantity: 0,
transactionCount: 0
};
});
@ -623,7 +628,8 @@ export class Portfolio implements PortfolioInterface {
marketPrice:
historicalData[symbol]?.[format(yesterday, 'yyyy-MM-dd')]
?.marketPrice || 0,
quantity: 0
quantity: 0,
transactionCount: 0
};
});
@ -730,6 +736,10 @@ 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

@ -15,6 +15,7 @@ export class ConfigurationService {
ENABLE_FEATURE_CUSTOM_SYMBOLS: bool({ default: false }),
ENABLE_FEATURE_FEAR_AND_GREED_INDEX: bool({ default: false }),
ENABLE_FEATURE_SOCIAL_LOGIN: bool({ default: false }),
ENABLE_FEATURE_SUBSCRIPTION: bool({ default: false }),
GOOGLE_CLIENT_ID: str({ default: 'dummyClientId' }),
GOOGLE_SECRET: str({ default: 'dummySecret' }),
JWT_SECRET_KEY: str({}),

View File

@ -18,6 +18,7 @@ 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,6 +26,7 @@ export class DataGatheringService {
public constructor(
private readonly configurationService: ConfigurationService,
private readonly dataProviderService: DataProviderService,
private readonly ghostfolioScraperApi: GhostfolioScraperApiService,
private prisma: PrismaService
) {}
@ -183,6 +185,17 @@ 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 {
@ -201,32 +214,6 @@ 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,3 +1,4 @@
import { DataSource } from '.prisma/client';
import { getYesterday } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import * as bent from 'bent';
@ -8,12 +9,16 @@ import { DataProviderInterface } from '../../interfaces/data-provider.interface'
import { Granularity } from '../../interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse
IDataProviderResponse,
MarketState
} from '../../interfaces/interfaces';
import { PrismaService } from '../../prisma.service';
import { ScraperConfig } from './interfaces/scraper-config.interface';
@Injectable()
export class GhostfolioScraperApiService implements DataProviderInterface {
private static NUMERIC_REGEXP = /[-]{0,1}[\d]*[.,]{0,1}[\d]+/g;
public constructor(private prisma: PrismaService) {}
public async get(
@ -26,7 +31,7 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
try {
const symbol = aSymbols[0];
const scraperConfig = await this.getScraperConfig(symbol);
const scraperConfig = await this.getScraperConfigurationBySymbol(symbol);
const { marketPrice } = await this.prisma.marketData.findFirst({
orderBy: {
@ -41,7 +46,8 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
[symbol]: {
marketPrice,
currency: scraperConfig?.currency,
isMarketOpen: false,
dataSource: DataSource.GHOSTFOLIO,
marketState: MarketState.delayed,
name: scraperConfig?.name
}
};
@ -67,19 +73,18 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
try {
const symbol = aSymbols[0];
const scraperConfig = await this.getScraperConfig(symbol);
const scraperConfiguration = await this.getScraperConfigurationBySymbol(
symbol
);
const get = bent(scraperConfig?.url, 'GET', 'string', 200, {});
const get = bent(scraperConfiguration?.url, 'GET', 'string', 200, {});
const html = await get();
const $ = cheerio.load(html);
const string = $(scraperConfig?.selector)
.text()
.replace('CHF', '')
.trim();
const value = parseFloat(string);
const value = this.extractNumberFromString(
$(scraperConfiguration?.selector).text()
);
return {
[symbol]: {
@ -95,7 +100,7 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
return {};
}
private async getScraperConfig(aSymbol: string) {
public async getScraperConfigurations(): Promise<ScraperConfig[]> {
try {
const {
value: scraperConfigString
@ -106,11 +111,27 @@ export class GhostfolioScraperApiService implements DataProviderInterface {
where: { key: 'SCRAPER_CONFIG' }
});
return JSON.parse(scraperConfigString).find((item) => {
return item.symbol === aSymbol;
});
return JSON.parse(scraperConfigString);
} catch {}
return {};
return [];
}
private extractNumberFromString(aString: string): number {
try {
const [numberString] = aString.match(
GhostfolioScraperApiService.NUMERIC_REGEXP
);
return parseFloat(numberString.trim());
} catch {
return undefined;
}
}
private async getScraperConfigurationBySymbol(aSymbol: string) {
const scraperConfigurations = await this.getScraperConfigurations();
return scraperConfigurations.find((scraperConfiguration) => {
return scraperConfiguration.symbol === aSymbol;
});
}
}

View File

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

View File

@ -1,3 +1,4 @@
import { DataSource } from '.prisma/client';
import { getToday, getYesterday } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import * as bent from 'bent';
@ -8,7 +9,8 @@ import { DataProviderInterface } from '../../interfaces/data-provider.interface'
import { Granularity } from '../../interfaces/granularity.type';
import {
IDataProviderHistoricalResponse,
IDataProviderResponse
IDataProviderResponse,
MarketState
} from '../../interfaces/interfaces';
import { PrismaService } from '../../prisma.service';
@ -38,8 +40,9 @@ export class RakutenRapidApiService implements DataProviderInterface {
return {
'GF.FEAR_AND_GREED_INDEX': {
currency: undefined,
isMarketOpen: true,
dataSource: DataSource.RAKUTEN,
marketPrice: fgi.now.value,
marketState: MarketState.open,
name: RakutenRapidApiService.FEAR_AND_GREED_INDEX_NAME
}
};

View File

@ -1,3 +1,4 @@
import { DataSource } from '.prisma/client';
import { isCrypto, isCurrency, parseCurrency } from '@ghostfolio/helper';
import { Injectable } from '@nestjs/common';
import { format } from 'date-fns';
@ -9,6 +10,7 @@ import {
IDataProviderHistoricalResponse,
IDataProviderResponse,
Industry,
MarketState,
Sector,
Type
} from '../../interfaces/interfaces';
@ -48,9 +50,12 @@ export class YahooFinanceService implements DataProviderInterface {
response[symbol] = {
currency: parseCurrency(value.price?.currency),
dataSource: DataSource.YAHOO,
exchange: this.parseExchange(value.price?.exchangeName),
isMarketOpen:
value.price?.marketState === 'REGULAR' || isCrypto(symbol),
marketState:
value.price?.marketState === 'REGULAR' || isCrypto(symbol)
? MarketState.open
: MarketState.closed,
marketPrice: value.price?.regularMarketPrice || 0,
name: value.price?.longName || value.price?.shortName || symbol,
type: this.parseType(this.getType(symbol, value))

View File

@ -7,6 +7,7 @@ export interface Environment extends CleanedEnvAccessors {
ENABLE_FEATURE_CUSTOM_SYMBOLS: boolean;
ENABLE_FEATURE_FEAR_AND_GREED_INDEX: boolean;
ENABLE_FEATURE_SOCIAL_LOGIN: boolean;
ENABLE_FEATURE_SUBSCRIPTION: boolean;
GOOGLE_CLIENT_ID: string;
GOOGLE_SECRET: string;
JWT_SECRET_KEY: string;

View File

@ -1,4 +1,4 @@
import { Currency, Platform } from '@prisma/client';
import { Currency, DataSource, Platform } from '@prisma/client';
import { OrderType } from '../../models/order-type';
@ -12,6 +12,12 @@ export const Industry = {
Software: 'Software'
};
export const MarketState = {
closed: 'closed',
delayed: 'delayed',
open: 'open'
};
export const Sector = {
Consumer: 'Consumer',
Healthcare: 'Healthcare',
@ -45,12 +51,13 @@ export interface IDataProviderHistoricalResponse {
export interface IDataProviderResponse {
currency: Currency;
dataSource: DataSource;
exchange?: string;
industry?: Industry;
isMarketOpen: boolean;
marketChange?: number;
marketChangePercent?: number;
marketPrice: number;
marketState: MarketState;
name: string;
sector?: Sector;
type?: Type;
@ -59,6 +66,8 @@ export interface IDataProviderResponse {
export type Industry = typeof Industry[keyof typeof Industry];
export type MarketState = typeof MarketState[keyof typeof MarketState];
export type Sector = typeof Sector[keyof typeof Sector];
export type Type = typeof Type[keyof typeof Type];

View File

@ -2,7 +2,8 @@ import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy {
async onModuleInit() {
await this.$connect();

View File

@ -1,3 +1,9 @@
<gf-symbol-icon
*ngIf="symbolUrl"
class="mr-1"
size="large"
[url]="symbolUrl"
></gf-symbol-icon>
<span class="flex-grow-1 text-truncate">{{ title }}</span>
<button
*ngIf="deviceType !== 'mobile'"

View File

@ -1,3 +1,4 @@
:host {
align-items: center;
display: flex;
}

View File

@ -16,6 +16,7 @@ import {
})
export class DialogHeaderComponent implements OnInit {
@Input() deviceType: string;
@Input() symbolUrl: string;
@Input() title: string;
@Output() closeButtonClicked = new EventEmitter<void>();

View File

@ -1,13 +1,14 @@
import { CommonModule } from '@angular/common';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { GfSymbolIconModule } from '@ghostfolio/client/components/symbol-icon/symbol-icon.module';
import { DialogHeaderComponent } from './dialog-header.component';
@NgModule({
declarations: [DialogHeaderComponent],
exports: [DialogHeaderComponent],
imports: [CommonModule, MatButtonModule],
imports: [CommonModule, GfSymbolIconModule, MatButtonModule],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

View File

@ -37,7 +37,7 @@
>Transactions</a
>
<a
*ngIf="canAccessAdminAccessControl"
*ngIf="hasPermissionToAccessAdminControl"
class="d-none d-sm-block mx-1"
[routerLink]="['/admin']"
i18n
@ -150,7 +150,7 @@
>Account</a
>
<a
*ngIf="canAccessAdminAccessControl"
*ngIf="hasPermissionToAccessAdminControl"
class="d-block d-sm-none"
[routerLink]="['/admin']"
i18n

View File

@ -27,8 +27,8 @@ export class HeaderComponent implements OnChanges {
@Input() info: InfoItem;
@Input() user: User;
public canAccessAdminAccessControl: boolean;
public hasPermissionToUseSocialLogin: boolean;
public hasPermissionToAccessAdminControl: boolean;
public hasPermissionForSocialLogin: boolean;
public impersonationId: string;
private unsubscribeSubject = new Subject<void>();
@ -49,15 +49,15 @@ export class HeaderComponent implements OnChanges {
public ngOnChanges() {
if (this.user) {
this.canAccessAdminAccessControl = hasPermission(
this.hasPermissionToAccessAdminControl = hasPermission(
this.user.permissions,
permissions.accessAdminControl
);
}
this.hasPermissionToUseSocialLogin = hasPermission(
this.hasPermissionForSocialLogin = hasPermission(
this.info?.globalPermissions,
permissions.useSocialLogin
permissions.enableSocialLogin
);
}
@ -81,7 +81,7 @@ export class HeaderComponent implements OnChanges {
autoFocus: false,
data: {
accessToken: '',
hasPermissionToUseSocialLogin: this.hasPermissionToUseSocialLogin
hasPermissionToUseSocialLogin: this.hasPermissionForSocialLogin
},
width: '30rem'
});

View File

@ -34,16 +34,16 @@
<div *ngIf="showDetails" class="row">
<div class="d-flex col justify-content-end">
<gf-value
colorizeSign="true"
isCurrency="true"
[colorizeSign]="true"
[isCurrency]="true"
[locale]="locale"
[value]="isLoading ? undefined : performance?.currentNetPerformance"
></gf-value>
</div>
<div class="col">
<gf-value
colorizeSign="true"
isPercent="true"
[colorizeSign]="true"
[isPercent]="true"
[locale]="locale"
[value]="
isLoading ? undefined : performance?.currentNetPerformancePercent

View File

@ -16,17 +16,17 @@
<div class="d-flex flex-column flex-wrap justify-content-end">
<gf-value
class="justify-content-end mb-2"
colorizeSign="true"
position="end"
[colorizeSign]="true"
[currency]="baseCurrency"
[locale]="locale"
[value]="isLoading ? undefined : performance?.currentGrossPerformance"
></gf-value>
<gf-value
class="justify-content-end"
colorizeSign="true"
isPercent="true"
position="end"
[colorizeSign]="true"
[isPercent]="true"
[locale]="locale"
[value]="
isLoading ? undefined : performance?.currentGrossPerformancePercent
@ -39,17 +39,17 @@
<div class="d-flex flex-column flex-wrap justify-content-end">
<gf-value
class="justify-content-end mb-2"
colorizeSign="true"
position="end"
[colorizeSign]="true"
[currency]="baseCurrency"
[locale]="locale"
[value]="isLoading ? undefined : performance?.currentNetPerformance"
></gf-value>
<gf-value
class="justify-content-end"
colorizeSign="true"
isPercent="true"
position="end"
[colorizeSign]="true"
[isPercent]="true"
[locale]="locale"
[value]="
isLoading ? undefined : performance?.currentNetPerformancePercent

View File

@ -3,5 +3,6 @@ export interface PositionDetailDialogParams {
deviceType: string;
locale: string;
symbol: string;
symbolUrl: string;
title: string;
}

View File

@ -23,6 +23,7 @@ export class PositionDetailDialog {
public benchmarkDataItems: LineChartItem[];
public currency: string;
public firstBuyDate: string;
public grossPerformance: number;
public grossPerformancePercent: number;
public historicalDataItems: LineChartItem[];
public investment: number;
@ -30,6 +31,7 @@ export class PositionDetailDialog {
public maxPrice: number;
public minPrice: number;
public quantity: number;
public transactionCount: number;
public constructor(
private cd: ChangeDetectorRef,
@ -44,18 +46,21 @@ export class PositionDetailDialog {
averagePrice,
currency,
firstBuyDate,
grossPerformance,
grossPerformancePercent,
historicalData,
investment,
marketPrice,
maxPrice,
minPrice,
quantity
quantity,
transactionCount
}) => {
this.averagePrice = averagePrice;
this.benchmarkDataItems = [];
this.currency = currency;
this.firstBuyDate = firstBuyDate;
this.grossPerformance = quantity * grossPerformance;
this.grossPerformancePercent = grossPerformancePercent;
this.historicalDataItems = historicalData.map(
(historicalDataItem) => {
@ -75,6 +80,7 @@ export class PositionDetailDialog {
this.maxPrice = maxPrice;
this.minPrice = minPrice;
this.quantity = quantity;
this.transactionCount = transactionCount;
if (isToday(parseISO(this.firstBuyDate))) {
// Add average price

View File

@ -1,6 +1,7 @@
<gf-dialog-header
mat-dialog-title
[deviceType]="data.deviceType"
[symbolUrl]="data.symbolUrl"
[title]="data.title"
(closeButtonClicked)="onClose()"
></gf-dialog-header>
@ -20,19 +21,22 @@
<div class="row">
<div class="col-6 mb-3">
<gf-value
colorizeSign="true"
isPercent="true"
label="Performance"
label="Change"
size="medium"
[colorizeSign]="true"
[currency]="data.baseCurrency"
[locale]="data.locale"
[value]="grossPerformancePercent"
[value]="grossPerformance"
></gf-value>
</div>
<div class="col-6 mb-3">
<gf-value
label="First Buy Date"
label="Performance"
size="medium"
[value]="firstBuyDate"
[colorizeSign]="true"
[isPercent]="true"
[locale]="data.locale"
[value]="grossPerformancePercent"
></gf-value>
</div>
<div class="col-6 mb-3">
@ -75,9 +79,9 @@
</div>
<div class="col-6 mb-3">
<gf-value
isCurrency="true"
label="Quantity"
size="medium"
[isCurrency]="true"
[value]="quantity"
></gf-value>
</div>
@ -90,6 +94,22 @@
[value]="investment"
></gf-value>
</div>
<div class="col-6 mb-3">
<gf-value
label="First Buy Date"
size="medium"
[value]="firstBuyDate"
></gf-value>
</div>
<div class="col-6 mb-3">
<gf-value
label="Transactions"
size="medium"
[isCurrency]="true"
[locale]="data.locale"
[value]="transactionCount"
></gf-value>
</div>
</div>
</div>
</div>

View File

@ -9,7 +9,7 @@
<gf-trend-indicator
class="d-flex"
[isLoading]="isLoading"
[isPaused]="!position?.isMarketOpen"
[marketState]="position?.marketState"
[range]="range"
[value]="position?.grossPerformancePercent"
></gf-trend-indicator>
@ -35,11 +35,6 @@
<div class="h6 m-0 text-truncate">{{ position?.name }}</div>
<div class="d-flex">
<span>{{ position?.symbol | gfSymbol }}</span>
<gf-symbol-icon
*ngIf="position?.url"
class="ml-1"
[url]="position?.url"
></gf-symbol-icon>
<span *ngIf="position?.exchange" class="ml-2 text-muted"
>({{ position.exchange }})</span
>
@ -47,14 +42,14 @@
<div class="d-flex mt-1">
<gf-value
class="mr-3"
colorizeSign="true"
[colorizeSign]="true"
[currency]="position?.currency"
[locale]="locale"
[value]="position?.grossPerformance"
></gf-value>
<gf-value
colorizeSign="true"
isPercent="true"
[colorizeSign]="true"
[isPercent]="true"
[locale]="locale"
[value]="position?.grossPerformancePercent"
></gf-value>

View File

@ -51,6 +51,11 @@ export class PositionComponent implements OnDestroy, OnInit {
public ngOnInit() {}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
private openDialog(): void {
const dialogRef = this.dialog.open(PositionDetailDialog, {
autoFocus: false,
@ -59,6 +64,7 @@ export class PositionComponent implements OnDestroy, OnInit {
deviceType: this.deviceType,
locale: this.locale,
symbol: this.position?.symbol,
symbolUrl: this.position?.url,
title: this.position?.name
},
height: this.deviceType === 'mobile' ? '97.5vh' : '80vh',
@ -69,9 +75,4 @@ export class PositionComponent implements OnDestroy, OnInit {
this.router.navigate(['.'], { relativeTo: this.route });
});
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
}

View File

@ -5,7 +5,6 @@ import { RouterModule } from '@angular/router';
import { GfSymbolModule } from '@ghostfolio/client/pipes/symbol/symbol.module';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { GfSymbolIconModule } from '../symbol-icon/symbol-icon.module';
import { GfTrendIndicatorModule } from '../trend-indicator/trend-indicator.module';
import { GfValueModule } from '../value/value.module';
import { GfPositionDetailDialogModule } from './position-detail-dialog/position-detail-dialog.module';
@ -17,7 +16,6 @@ import { PositionComponent } from './position.component';
imports: [
CommonModule,
GfPositionDetailDialogModule,
GfSymbolIconModule,
GfSymbolModule,
GfTrendIndicatorModule,
GfValueModule,

View File

@ -28,8 +28,8 @@
<td class="d-none d-lg-table-cell" mat-cell *matCellDef="let element">
<div class="d-flex justify-content-end">
<gf-value
colorizeSign="true"
isPercent="true"
[colorizeSign]="true"
[isPercent]="true"
[locale]="locale"
[value]="isLoading ? undefined : element.grossPerformancePercent"
></gf-value>
@ -50,7 +50,7 @@
<td mat-cell *matCellDef="let element">
<div class="d-flex justify-content-end">
<gf-value
isPercent="true"
[isPercent]="true"
[locale]="locale"
[value]="isLoading ? undefined : element.shareInvestment"
></gf-value>
@ -71,7 +71,7 @@
<td mat-cell *matCellDef="let element">
<div class="d-flex justify-content-end">
<gf-value
isPercent="true"
[isPercent]="true"
[locale]="locale"
[value]="isLoading ? undefined : element.shareCurrent"
></gf-value>

View File

@ -6,6 +6,7 @@ import {
OnInit
} from '@angular/core';
import { PortfolioPosition } from '@ghostfolio/api/app/portfolio/interfaces/portfolio-position.interface';
import { MarketState } from '@ghostfolio/api/services/interfaces/interfaces';
@Component({
selector: 'gf-positions',
@ -40,7 +41,10 @@ export class PositionsComponent implements OnChanges, OnInit {
this.positionsWithPriority = [];
for (const [, portfolioPosition] of Object.entries(this.positions)) {
if (portfolioPosition.isMarketOpen || this.range !== '1d') {
if (
portfolioPosition.marketState === MarketState.open ||
this.range !== '1d'
) {
// Only show positions where the market is open in today's view
this.positionsWithPriority.push(portfolioPosition);
} else {

View File

@ -1,18 +1,18 @@
<div class="py-3">
<div class="flex-nowrap no-gutters row">
<div class="align-items-center flex-nowrap no-gutters row">
<div *ngIf="isLoading">
<ngx-skeleton-loader
animation="pulse"
class="mr-3"
class="mr-2"
[theme]="{
height: '3rem',
width: '3rem'
height: '2rem',
width: '2rem'
}"
></ngx-skeleton-loader>
</div>
<div
*ngIf="!isLoading"
class="align-items-center d-flex icon-container mr-3 px-3"
class="align-items-center d-flex icon-container mr-2 px-2"
[ngClass]="{ okay: rule?.value === true, warn: rule?.value === false }"
>
<ion-icon

View File

@ -2,15 +2,16 @@
display: block;
.icon-container {
background-color: rgba(var(--dark-primary-text), 0.05);
border-radius: 0.25rem;
height: 3rem;
height: 2rem;
&.okay {
background-color: var(--success);
color: var(--success);
}
&.warn {
background-color: var(--warning);
color: var(--danger);
}
}
@ -21,6 +22,6 @@
:host-context(.is-dark-theme) {
.icon-container {
color: rgba(var(--dark-primary-text));
background-color: rgba(var(--light-primary-text), 0.05);
}
}

View File

@ -1,5 +1,6 @@
<img
*ngIf="url"
src="https://www.google.com/s2/favicons?domain={{ url }}&sz=64"
[ngClass]="{ large: size === 'large' }"
[title]="tooltip ? tooltip : ''"
/>

View File

@ -5,5 +5,10 @@
border-radius: 0.2rem;
height: 0.8rem;
width: 0.8rem;
&.large {
height: 1.4rem;
width: 1.4rem;
}
}
}

View File

@ -12,6 +12,7 @@ import {
styleUrls: ['./symbol-icon.component.scss']
})
export class SymbolIconComponent implements OnInit {
@Input() size: 'large';
@Input() tooltip: string;
@Input() url: string;

View File

@ -116,7 +116,7 @@
<td *matCellDef="let element" class="d-none d-lg-table-cell" mat-cell>
<div class="d-flex justify-content-end">
<gf-value
isCurrency="true"
[isCurrency]="true"
[locale]="locale"
[value]="isLoading ? undefined : element.quantity"
></gf-value>
@ -137,7 +137,7 @@
<td *matCellDef="let element" class="d-none d-lg-table-cell" mat-cell>
<div class="d-flex justify-content-end">
<gf-value
isCurrency="true"
[isCurrency]="true"
[locale]="locale"
[value]="isLoading ? undefined : element.unitPrice"
></gf-value>
@ -158,7 +158,7 @@
<td class="d-none d-lg-table-cell" mat-cell *matCellDef="let element">
<div class="d-flex justify-content-end">
<gf-value
isCurrency="true"
[isCurrency]="true"
[locale]="locale"
[value]="isLoading ? undefined : element.fee"
></gf-value>

View File

@ -10,12 +10,21 @@
<ng-template #other>
<ion-icon
*ngIf="isPaused && range === '1d'; else trend"
*ngIf="marketState === 'closed' && range === '1d'; else delayed"
class="text-muted"
name="pause-circle-outline"
size="large"
>
</ion-icon>
<ng-template #delayed>
<ion-icon
*ngIf="marketState === 'delayed' && range === '1d'; else trend"
class="text-muted"
name="time-outline"
size="large"
>
</ion-icon>
</ng-template>
<ng-template #trend>
<ng-container>
<ion-icon

View File

@ -4,6 +4,7 @@ import {
Input,
OnInit
} from '@angular/core';
import { MarketState } from '@ghostfolio/api/services/interfaces/interfaces';
@Component({
selector: 'gf-trend-indicator',
@ -13,7 +14,7 @@ import {
})
export class TrendIndicatorComponent implements OnInit {
@Input() isLoading: boolean;
@Input() isPaused: boolean;
@Input() marketState: MarketState;
@Input() range: string;
@Input() value: number;

View File

@ -1,8 +1,9 @@
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { InfoItem } from '@ghostfolio/api/app/info/interfaces/info-item.interface';
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
import { DataService } from '@ghostfolio/client/services/data.service';
import { TokenStorageService } from '@ghostfolio/client/services/token-storage.service';
import { baseCurrency } from '@ghostfolio/helper';
import { baseCurrency, hasPermission, permissions } from '@ghostfolio/helper';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@ -15,6 +16,7 @@ import { environment } from '../../../environments/environment';
})
export class AboutPageComponent implements OnInit {
public baseCurrency = baseCurrency;
public hasPermissionForSubscription: boolean;
public isLoggedIn: boolean;
public lastPublish = environment.lastPublish;
public user: User;
@ -35,6 +37,15 @@ export class AboutPageComponent implements OnInit {
* Initializes the controller
*/
public ngOnInit() {
this.dataService.fetchInfo().subscribe((info) => {
this.hasPermissionForSubscription = hasPermission(
info.globalPermissions,
permissions.enableSubscription
);
this.cd.markForCheck();
});
this.isLoggedIn = !!this.tokenStorageService.getToken();
if (this.isLoggedIn)

View File

@ -61,7 +61,7 @@
</div>
</div>
<div class="mb-5 row">
<div *ngIf="hasPermissionForSubscription" class="mb-5 row">
<div class="col">
<h3 class="mb-3 text-center" i18n>Pricing Plans</h3>
<div class="row">

View File

@ -3,7 +3,11 @@ import { Access } from '@ghostfolio/api/app/access/interfaces/access.interface';
import { User } from '@ghostfolio/api/app/user/interfaces/user.interface';
import { DataService } from '@ghostfolio/client/services/data.service';
import { TokenStorageService } from '@ghostfolio/client/services/token-storage.service';
import { DEFAULT_DATE_FORMAT } from '@ghostfolio/helper';
import {
DEFAULT_DATE_FORMAT,
hasPermission,
permissions
} from '@ghostfolio/helper';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@ -19,6 +23,7 @@ export class AccountPageComponent implements OnDestroy, OnInit {
public baseCurrency: Currency;
public currencies: Currency[] = [];
public defaultDateFormat = DEFAULT_DATE_FORMAT;
public hasPermissionForSubscription: boolean;
public user: User;
private unsubscribeSubject = new Subject<void>();
@ -34,8 +39,13 @@ export class AccountPageComponent implements OnDestroy, OnInit {
this.dataService
.fetchInfo()
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe(({ currencies }) => {
.subscribe(({ currencies, globalPermissions }) => {
this.currencies = currencies;
this.hasPermissionForSubscription = hasPermission(
globalPermissions,
permissions.enableSubscription
);
});
this.tokenStorageService
@ -70,6 +80,11 @@ export class AccountPageComponent implements OnDestroy, OnInit {
});
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
private update() {
this.dataService
.fetchAccesses()
@ -80,9 +95,4 @@ export class AccountPageComponent implements OnDestroy, OnInit {
this.cd.markForCheck();
});
}
public ngOnDestroy() {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
}

View File

@ -15,7 +15,7 @@
<div class="w-50" i18n>Alias</div>
<div class="w-50">{{ user.alias }}</div>
</div>
<div class="d-flex py-1">
<div *ngIf="hasPermissionForSubscription" class="d-flex py-1">
<div class="w-50" i18n>Membership</div>
<div class="w-50">
<div class="align-items-center d-flex mb-1">

View File

@ -70,42 +70,36 @@
<div class="col">
<h3 class="mb-3 text-center" i18n>Users</h3>
<mat-card class="px-0">
<mat-card-content>
<table class="users w-100">
<mat-card-content class="users">
<table>
<thead>
<tr class="mat-header-row">
<th class="mat-header-cell pl-2 py-2 text-truncate" i18n>
User
</th>
<th class="mat-header-cell pr-2 py-2 text-truncate" i18n>
<th class="mat-header-cell pl-3 py-2" i18n>User</th>
<th class="mat-header-cell pr-2 py-2" i18n>
Registration Date
</th>
<th class="mat-header-cell pr-2 py-2 text-truncate" i18n>
Transactions
</th>
<th class="mat-header-cell pr-2 py-2 text-truncate" i18n>
Engagement
</th>
<th class="mat-header-cell pr-2 py-2 text-truncate" i18n>
Last Activitiy
</th>
<th class="mat-header-cell pr-2 py-2" i18n>Accounts</th>
<th class="mat-header-cell pr-2 py-2" i18n>Transactions</th>
<th class="mat-header-cell pr-2 py-2" i18n>Engagement</th>
<th class="mat-header-cell pr-3 py-2" i18n>Last Activitiy</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let userItem of users" class="mat-row">
<td class="mat-cell pl-2 py-2 text-truncate">
<td class="mat-cell pl-3 py-2">
{{ userItem.alias || userItem.id }}
</td>
<td class="mat-cell pr-2 py-2 text-truncate">
<td class="mat-cell pr-2 py-2">
{{ userItem.createdAt | date: defaultDateFormat }}
</td>
<td class="mat-cell pr-2 py-2 text-truncate">
{{ userItem._count?.Order }}
<td class="mat-cell pr-2 py-2">
{{ userItem._count?.Account }}
</td>
<td class="mat-cell pr-2 py-2 text-truncate">
<td class="mat-cell pr-2 py-2">{{ userItem._count?.Order }}</td>
<td class="mat-cell pr-2 py-2">
{{ userItem.Analytics?.activityCount }}
</td>
<td class="mat-cell pr-2 py-2 text-truncate">
<td class="mat-cell pr-3 py-2">
{{ formatDistanceToNow(userItem.Analytics?.updatedAt) }}
</td>
</tr>

View File

@ -2,16 +2,25 @@
color: rgb(var(--dark-primary-text));
display: block;
table {
.mat-card-content {
&.users {
table-layout: fixed;
overflow-x: auto;
tr {
&:nth-child(even) {
background-color: rgba(
var(--dark-primary-text),
var(--palette-background-hover-alpha)
);
table {
min-width: 100%;
tr {
&:nth-child(even) {
background-color: rgba(
var(--dark-primary-text),
var(--palette-background-hover-alpha)
);
}
}
.mat-row,
.mat-header-row {
width: 100%;
}
}
}

View File

@ -8,7 +8,7 @@ import { FormControl, Validators } from '@angular/forms';
import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { LookupItem } from '@ghostfolio/api/app/symbol/interfaces/lookup-item.interface';
import { Currency, Order as OrderModel } from '@prisma/client';
import { Currency } from '@prisma/client';
import { Observable, Subject } from 'rxjs';
import {
debounceTime,
@ -19,6 +19,7 @@ import {
} from 'rxjs/operators';
import { DataService } from '../../../services/data.service';
import { CreateOrUpdateTransactionDialogParams } from './interfaces/interfaces';
@Component({
host: { class: 'h-100' },
@ -33,7 +34,7 @@ export class CreateOrUpdateTransactionDialog {
public isLoading = false;
public platforms: { id: string; name: string }[];
public searchSymbolCtrl = new FormControl(
this.data.symbol,
this.data.transaction.symbol,
Validators.required
);
@ -43,7 +44,7 @@ export class CreateOrUpdateTransactionDialog {
private cd: ChangeDetectorRef,
private dataService: DataService,
public dialogRef: MatDialogRef<CreateOrUpdateTransactionDialog>,
@Inject(MAT_DIALOG_DATA) public data: OrderModel
@Inject(MAT_DIALOG_DATA) public data: CreateOrUpdateTransactionDialogParams
) {}
ngOnInit() {
@ -72,14 +73,15 @@ export class CreateOrUpdateTransactionDialog {
public onUpdateSymbol(event: MatAutocompleteSelectedEvent) {
this.isLoading = true;
this.data.symbol = event.option.value;
this.data.transaction.symbol = event.option.value;
this.dataService
.fetchSymbolItem(this.data.symbol)
.fetchSymbolItem(this.data.transaction.symbol)
.pipe(takeUntil(this.unsubscribeSubject))
.subscribe(({ currency, marketPrice }) => {
this.data.currency = currency;
this.data.unitPrice = marketPrice;
.subscribe(({ currency, dataSource, marketPrice }) => {
this.data.transaction.currency = currency;
this.data.transaction.dataSource = dataSource;
this.data.transaction.unitPrice = marketPrice;
this.isLoading = false;
@ -88,10 +90,11 @@ export class CreateOrUpdateTransactionDialog {
}
public onUpdateSymbolByTyping(value: string) {
this.data.currency = null;
this.data.unitPrice = null;
this.data.transaction.currency = null;
this.data.transaction.dataSource = null;
this.data.transaction.unitPrice = null;
this.data.symbol = value;
this.data.transaction.symbol = value;
}
public ngOnDestroy() {

View File

@ -1,6 +1,6 @@
<form #addTransactionForm="ngForm" class="d-flex flex-column h-100">
<h1 *ngIf="data.id" mat-dialog-title i18n>Update transaction</h1>
<h1 *ngIf="!data.id" mat-dialog-title i18n>Add transaction</h1>
<h1 *ngIf="data.transaction.id" mat-dialog-title i18n>Update transaction</h1>
<h1 *ngIf="!data.transaction.id" mat-dialog-title i18n>Add transaction</h1>
<div class="flex-grow-1" mat-dialog-content>
<div>
<mat-form-field appearance="outline" class="w-100">
@ -25,7 +25,7 @@
class="autocomplete"
[value]="lookupItem.symbol"
>
<span class="mr-2 symbol">{{ lookupItem.symbol }}</span
<span class="mr-2 symbol">{{ lookupItem.symbol | gfSymbol }}</span
><span><b>{{ lookupItem.name }}</b></span>
</mat-option>
</ng-container>
@ -36,7 +36,7 @@
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Type</mat-label>
<mat-select name="type" required [(value)]="data.type">
<mat-select name="type" required [(value)]="data.transaction.type">
<mat-option value="BUY" i18n> BUY </mat-option>
<mat-option value="SELL" i18n> SELL </mat-option>
</mat-select>
@ -50,7 +50,7 @@
disabled
name="currency"
required
[(value)]="data.currency"
[(value)]="data.transaction.currency"
>
<mat-option *ngFor="let currency of currencies" [value]="currency"
>{{ currency }}</mat-option
@ -58,6 +58,18 @@
</mat-select>
</mat-form-field>
</div>
<div class="d-none">
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Data Source</mat-label>
<input
disabled
matInput
name="dataSource"
required
[(ngModel)]="data.transaction.dataSource"
/>
</mat-form-field>
</div>
<div>
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Date</mat-label>
@ -67,7 +79,7 @@
name="date"
required
[matDatepicker]="date"
[(ngModel)]="data.date"
[(ngModel)]="data.transaction.date"
/>
<mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
<mat-datepicker #date disabled="false"></mat-datepicker>
@ -81,7 +93,7 @@
name="fee"
required
type="number"
[(ngModel)]="data.fee"
[(ngModel)]="data.transaction.fee"
/>
</mat-form-field>
</div>
@ -93,7 +105,7 @@
name="quantity"
required
type="number"
[(ngModel)]="data.quantity"
[(ngModel)]="data.transaction.quantity"
/>
</mat-form-field>
</div>
@ -105,14 +117,29 @@
name="unitPrice"
required
type="number"
[(ngModel)]="data.unitPrice"
[(ngModel)]="data.transaction.unitPrice"
/>
</mat-form-field>
</div>
<div class="d-none">
<mat-form-field appearance="outline" class="w-100">
<mat-label i18n>Account</mat-label>
<mat-select
disabled
name="accountId"
required
[(value)]="data.transaction.accountId"
>
<mat-option *ngFor="let account of data.accounts" [value]="account.id"
>{{ account.name }}</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.platformId">
<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
@ -127,7 +154,7 @@
color="primary"
i18n
mat-flat-button
[disabled]="!(addTransactionForm.form.valid && data.symbol)"
[disabled]="!(addTransactionForm.form.valid && data.transaction.symbol)"
[mat-dialog-close]="data"
>
Save

View File

@ -9,6 +9,7 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { GfSymbolModule } from '@ghostfolio/client/pipes/symbol/symbol.module';
import { CreateOrUpdateTransactionDialog } from './create-or-update-transaction-dialog.component';
@ -17,6 +18,7 @@ import { CreateOrUpdateTransactionDialog } from './create-or-update-transaction-
exports: [],
imports: [
CommonModule,
GfSymbolModule,
FormsModule,
MatAutocompleteModule,
MatButtonModule,

View File

@ -0,0 +1,9 @@
import { Account } from '@prisma/client';
import { Order } from '../../interfaces/order.interface';
export interface CreateOrUpdateTransactionDialogParams {
accountId: string;
accounts: Account[];
transaction: Order;
}

View File

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

View File

@ -122,37 +122,10 @@ export class TransactionsPageComponent implements OnInit {
});
}
private openCreateTransactionDialog(): void {
const dialogRef = this.dialog.open(CreateOrUpdateTransactionDialog, {
data: {
currency: null,
date: new Date(),
fee: 0,
platformId: null,
quantity: null,
symbol: null,
type: 'BUY',
unitPrice: null
},
height: this.deviceType === 'mobile' ? '97.5vh' : '80vh',
width: this.deviceType === 'mobile' ? '100vw' : '50rem'
});
dialogRef.afterClosed().subscribe((order: UpdateOrderDto) => {
if (order) {
this.dataService.postOrder(order).subscribe({
next: () => {
this.fetchOrders();
}
});
}
this.router.navigate(['.'], { relativeTo: this.route });
});
}
public openUpdateTransactionDialog({
accountId,
currency,
dataSource,
date,
fee,
id,
@ -164,23 +137,30 @@ export class TransactionsPageComponent implements OnInit {
}: OrderModel): void {
const dialogRef = this.dialog.open(CreateOrUpdateTransactionDialog, {
data: {
currency,
date,
fee,
id,
platformId,
quantity,
symbol,
type,
unitPrice
accounts: this.user.accounts,
transaction: {
accountId,
currency,
dataSource,
date,
fee,
id,
platformId,
quantity,
symbol,
type,
unitPrice
}
},
height: this.deviceType === 'mobile' ? '97.5vh' : '80vh',
width: this.deviceType === 'mobile' ? '100vw' : '50rem'
});
dialogRef.afterClosed().subscribe((order: UpdateOrderDto) => {
if (order) {
this.dataService.putOrder(order).subscribe({
dialogRef.afterClosed().subscribe((data: any) => {
const transaction: UpdateOrderDto = data?.transaction;
if (transaction) {
this.dataService.putOrder(transaction).subscribe({
next: () => {
this.fetchOrders();
}
@ -195,4 +175,41 @@ export class TransactionsPageComponent implements OnInit {
this.unsubscribeSubject.next();
this.unsubscribeSubject.complete();
}
private openCreateTransactionDialog(): void {
const dialogRef = this.dialog.open(CreateOrUpdateTransactionDialog, {
data: {
accounts: this.user?.accounts,
transaction: {
accountId: this.user?.accounts.find((account) => {
return account.isDefault;
})?.id,
currency: null,
date: new Date(),
fee: 0,
platformId: null,
quantity: null,
symbol: null,
type: 'BUY',
unitPrice: null
}
},
height: this.deviceType === 'mobile' ? '97.5vh' : '80vh',
width: this.deviceType === 'mobile' ? '100vw' : '50rem'
});
dialogRef.afterClosed().subscribe((data: any) => {
const transaction: UpdateOrderDto = data?.transaction;
if (transaction) {
this.dataService.postOrder(transaction).subscribe({
next: () => {
this.fetchOrders();
}
});
}
this.router.navigate(['.'], { relativeTo: this.route });
});
}
}

View File

@ -1,7 +1,7 @@
{
"background_color": "transparent",
"categories": ["finance", "utilities"],
"description": "Privacy-first Portfolio Tracker",
"description": "Open Source Portfolio Tracker",
"display": "standalone",
"icons": [
{

View File

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ghostfolio Privacy-first Portfolio Tracker</title>
<title>Ghostfolio Open Source Portfolio Tracker</title>
<base href="/" />
<meta charset="utf-8" />
<meta content="yes" name="apple-mobile-web-app-capable" />
@ -25,13 +25,13 @@
/>
<meta
name="twitter:title"
content="Ghostfolio Privacy-first Portfolio Tracker"
content="Ghostfolio Open Source Portfolio Tracker"
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta property="og:description" content="" />
<meta
property="og:title"
content="Ghostfolio Privacy-first Portfolio Tracker"
content="Ghostfolio Open Source Portfolio Tracker"
/>
<meta property="og:type" content="website" />
<meta property="og:url" content="https://www.ghostfol.io" />
@ -42,7 +42,7 @@
<meta property="og:updated_time" content="2021-03-20T00:00:00+00:00" />
<meta
property="og:site_name"
content="Ghostfolio Privacy-first Portfolio Tracker"
content="Ghostfolio Open Source Portfolio Tracker"
/>
<link

View File

@ -57,11 +57,20 @@ body {
}
}
.mat-card:not([class*='mat-elevation-z']) {
border-color: rgba(
var(--light-primary-text),
var(--palette-foreground-divider-alpha)
);
.mat-card {
background: var(--dark-background);
&:not([class*='mat-elevation-z']) {
border-color: rgba(
var(--light-primary-text),
var(--palette-foreground-divider-alpha)
);
box-shadow: none;
}
}
.mat-dialog-container {
background: var(--dark-background);
}
.mat-fab,

View File

@ -12,5 +12,9 @@
{
"path": "./tsconfig.editor.json"
}
]
],
"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictTemplates": false
}
}

View File

@ -10,10 +10,11 @@ export const permissions = {
createAccount: 'createAccount',
createOrder: 'createOrder',
deleteOrder: 'deleteOrder',
enableSocialLogin: 'enableSocialLogin',
enableSubscription: 'enableSubscription',
readForeignPortfolio: 'readForeignPortfolio',
updateOrder: 'updateOrder',
updateUserSettings: 'updateUserSettings',
useSocialLogin: 'useSocialLogin'
updateUserSettings: 'updateUserSettings'
};
export function hasPermission(

View File

@ -1,6 +1,6 @@
{
"name": "ghostfolio",
"version": "0.89.0",
"version": "0.96.0",
"homepage": "https://ghostfol.io",
"license": "AGPL-3.0",
"scripts": {
@ -15,6 +15,9 @@
"angular": "node --max_old_space_size=32768 ./node_modules/@angular/cli/bin/ng",
"build:all": "ng build --prod api && ng build --prod client && yarn replace-placeholders-in-build",
"clean": "rimraf dist",
"database:format-schema": "prisma format",
"database:generate-typings": "prisma generate",
"database:gui": "prisma studio",
"database:push": "prisma db push --preview-feature",
"database:seed": "prisma db seed --preview-feature",
"dep-graph": "nx dep-graph",

View File

@ -24,6 +24,22 @@ model Access {
@@id([id, userId])
}
model Account {
accountType AccountType @default(SECURITIES)
createdAt DateTime @default(now())
id String @default(uuid())
isDefault Boolean @default(false)
name String?
Order Order[]
Platform Platform? @relation(fields: [platformId], references: [id])
platformId String?
updatedAt DateTime @updatedAt
User User @relation(fields: [userId], references: [id])
userId String
@@id([id, userId])
}
model Analytics {
activityCount Int @default(0)
updatedAt DateTime @updatedAt
@ -43,29 +59,34 @@ model MarketData {
}
model Order {
createdAt DateTime @default(now())
currency Currency
date DateTime
fee Float
id String @default(uuid())
Platform Platform? @relation(fields: [platformId], references: [id])
platformId String?
quantity Float
symbol String
type Type
unitPrice Float
updatedAt DateTime @updatedAt
User User @relation(fields: [userId], references: [id])
userId String
Account Account? @relation(fields: [accountId, accountUserId], references: [id, userId])
accountId String?
accountUserId String?
createdAt DateTime @default(now())
currency Currency
dataSource DataSource @default(YAHOO)
date DateTime
fee Float
id String @default(uuid())
Platform Platform? @relation(fields: [platformId], references: [id])
platformId String?
quantity Float
symbol String
type Type
unitPrice Float
updatedAt DateTime @updatedAt
User User @relation(fields: [userId], references: [id])
userId String
@@id([id, userId])
}
model Platform {
id String @id @default(uuid())
name String?
url String @unique
Order Order[]
Account Account[]
id String @id @default(uuid())
name String?
Order Order[]
url String @unique
}
model Property {
@ -84,6 +105,7 @@ model User {
Access Access[] @relation("accessGet")
AccessGive Access[] @relation(name: "accessGive")
accessToken String?
Account Account[]
alias String?
Analytics Analytics?
createdAt DateTime @default(now())
@ -96,6 +118,10 @@ model User {
updatedAt DateTime @updatedAt
}
enum AccountType {
SECURITIES
}
enum Currency {
CHF
EUR
@ -103,6 +129,12 @@ enum Currency {
USD
}
enum DataSource {
GHOSTFOLIO
RAKUTEN
YAHOO
}
enum Provider {
ANONYMOUS
GOOGLE

View File

@ -1,4 +1,10 @@
import { Currency, PrismaClient, Role, Type } from '@prisma/client';
import {
AccountType,
Currency,
PrismaClient,
Role,
Type
} from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
@ -76,6 +82,16 @@ async function main() {
create: {
accessToken:
'c689bcc894e4a420cb609ee34271f3e07f200594f7d199c50d75add7102889eb60061a04cd2792ebc853c54e37308271271e7bf588657c9e0c37faacbc28c3c6',
Account: {
create: [
{
accountType: AccountType.SECURITIES,
id: 'f4425b66-9ba9-4ac4-93d7-fdf9a145e8cb',
isDefault: true,
name: 'Default Account'
}
]
},
alias: 'Admin',
id: '4e1af723-95f6-44f8-92a7-464df17f6ec3',
role: Role.ADMIN
@ -88,106 +104,155 @@ async function main() {
create: {
accessToken:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjliMTEyYjRkLTNiN2QtNGJhZC05YmRkLTNiMGY3YjRkYWMyZiIsImlhdCI6MTYxODUxMjAxNCwiZXhwIjoxNjIxMTA0MDE0fQ.l3WUxpI0hxuQtdPrD0kd7sem6S2kx_7CrdNvkmlKuWw',
alias: 'Demo',
id: '9b112b4d-3b7d-4bad-9bdd-3b0f7b4dac2f',
role: Role.DEMO,
Order: {
Account: {
create: [
{
currency: Currency.USD,
date: new Date(Date.UTC(2017, 0, 3, 0, 0, 0)),
fee: 30,
id: 'cf7c0418-8535-4089-ae3d-5dbfa0aec2e1',
platformId: platformDegiro.id,
quantity: 50,
symbol: 'TSLA',
type: Type.BUY,
unitPrice: 42.97
accountType: AccountType.SECURITIES,
id: 'd804de69-0429-42dc-b6ca-b308fd7dd926',
name: 'Coinbase Account',
platformId: platformCoinbase.id
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2017, 7, 16, 0, 0, 0)),
fee: 29.9,
id: 'a1c5d73a-8631-44e5-ac44-356827a5212c',
platformId: platformCoinbase.id,
quantity: 0.5614682,
symbol: 'BTCUSD',
type: Type.BUY,
unitPrice: 3562.089535970158
accountType: AccountType.SECURITIES,
id: '65cfb79d-b6c7-4591-9d46-73426bc62094',
name: 'DEGIRO Account',
platformId: platformDegiro.id
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2018, 9, 1, 0, 0, 0)),
fee: 80.79,
id: '71c08e2a-4a86-44ae-a890-c337de5d5f9b',
platformId: platformInteractiveBrokers.id,
quantity: 5,
symbol: 'AMZN',
type: Type.BUY,
unitPrice: 2021.99
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2019, 2, 1, 0, 0, 0)),
fee: 19.9,
id: '385f2c2c-d53e-4937-b0e5-e92ef6020d4e',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 144.38
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2019, 8, 3, 0, 0, 0)),
fee: 19.9,
id: '185f2c2c-d53e-4937-b0e5-a93ef6020d4e',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 147.99
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2020, 2, 2, 0, 0, 0)),
fee: 19.9,
id: '347b0430-a84f-4031-a0f9-390399066ad6',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 151.41
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2020, 8, 1, 0, 0, 0)),
fee: 19.9,
id: '67ec3f47-3189-4b63-ba05-60d3a06b302f',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 177.69
},
{
currency: Currency.USD,
date: new Date(Date.UTC(2020, 2, 1, 0, 0, 0)),
fee: 19.9,
id: 'd01c6fbc-fa8d-47e6-8e80-66f882d2bfd2',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 203.15
accountType: AccountType.SECURITIES,
id: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
isDefault: true,
name: 'Interactive Brokers Account',
platformId: platformInteractiveBrokers.id
}
]
}
},
alias: 'Demo',
id: '9b112b4d-3b7d-4bad-9bdd-3b0f7b4dac2f',
role: Role.DEMO
},
update: {},
where: { id: '9b112b4d-3b7d-4bad-9bdd-3b0f7b4dac2f' }
});
await prisma.order.createMany({
data: [
{
accountId: '65cfb79d-b6c7-4591-9d46-73426bc62094',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2017, 0, 3, 0, 0, 0)),
fee: 30,
id: 'cf7c0418-8535-4089-ae3d-5dbfa0aec2e1',
platformId: platformDegiro.id,
quantity: 50,
symbol: 'TSLA',
type: Type.BUY,
unitPrice: 42.97,
userId: userDemo.id
},
{
accountId: 'd804de69-0429-42dc-b6ca-b308fd7dd926',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2017, 7, 16, 0, 0, 0)),
fee: 29.9,
id: 'a1c5d73a-8631-44e5-ac44-356827a5212c',
platformId: platformCoinbase.id,
quantity: 0.5614682,
symbol: 'BTCUSD',
type: Type.BUY,
unitPrice: 3562.089535970158,
userId: userDemo.id
},
{
accountId: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2018, 9, 1, 0, 0, 0)),
fee: 80.79,
id: '71c08e2a-4a86-44ae-a890-c337de5d5f9b',
platformId: platformInteractiveBrokers.id,
quantity: 5,
symbol: 'AMZN',
type: Type.BUY,
unitPrice: 2021.99,
userId: userDemo.id
},
{
accountId: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2019, 2, 1, 0, 0, 0)),
fee: 19.9,
id: '385f2c2c-d53e-4937-b0e5-e92ef6020d4e',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 144.38,
userId: userDemo.id
},
{
accountId: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2019, 8, 3, 0, 0, 0)),
fee: 19.9,
id: '185f2c2c-d53e-4937-b0e5-a93ef6020d4e',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 147.99,
userId: userDemo.id
},
{
accountId: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2020, 2, 2, 0, 0, 0)),
fee: 19.9,
id: '347b0430-a84f-4031-a0f9-390399066ad6',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 151.41,
userId: userDemo.id
},
{
accountId: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2020, 8, 1, 0, 0, 0)),
fee: 19.9,
id: '67ec3f47-3189-4b63-ba05-60d3a06b302f',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 177.69,
userId: userDemo.id
},
{
accountId: '480269ce-e12a-4fd1-ac88-c4b0ff3f899c',
accountUserId: userDemo.id,
currency: Currency.USD,
date: new Date(Date.UTC(2020, 2, 1, 0, 0, 0)),
fee: 19.9,
id: 'd01c6fbc-fa8d-47e6-8e80-66f882d2bfd2',
platformId: platformInteractiveBrokers.id,
quantity: 10,
symbol: 'VTI',
type: Type.BUY,
unitPrice: 203.15,
userId: userDemo.id
}
],
skipDuplicates: true
});
console.log({
platformBitcoinSuisse,
platformBitpanda,