Browse Source

Merge branch 'main' into fix/sell-activity-fee-cash-balance

pull/6862/head
Thomas Kaul 1 week ago
committed by GitHub
parent
commit
b361ae03f4
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 3
      CHANGELOG.md
  2. 4
      apps/api/src/app/endpoints/public/public.controller.ts
  3. 21
      apps/api/src/app/portfolio/current-rate.service.ts
  4. 34
      apps/api/src/app/portfolio/portfolio.service.ts
  5. 8
      apps/api/src/models/rule.ts
  6. 3
      apps/api/src/models/rules/asset-class-cluster-risk/equity.ts
  7. 3
      apps/api/src/models/rules/asset-class-cluster-risk/fixed-income.ts
  8. 2
      apps/api/src/models/rules/currency-cluster-risk/base-currency-current-investment.ts
  9. 2
      apps/api/src/models/rules/currency-cluster-risk/current-investment.ts
  10. 4
      apps/api/src/services/data-provider/data-provider.service.ts
  11. 52
      apps/client/src/app/components/investment-chart/investment-chart.component.ts
  12. 14
      libs/common/src/lib/helper.ts
  13. 16
      libs/ui/src/lib/treemap-chart/treemap-chart.component.ts

3
CHANGELOG.md

@ -9,7 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- Fixed the cash balance computation for `SELL` activities to subtract the fee instead of adding it (the previous logic inflated the account's cash balance by twice the fee)
- Resolved an issue with the cash balance calculation of an account for `SELL` activities to ensure fees are correctly subtracted
- Resolved an exception in the portfolio details endpoint when an asset profile is unmatched
## 3.3.0 - 2026-05-14

4
apps/api/src/app/endpoints/public/public.controller.ts

@ -151,11 +151,11 @@ export class PublicController {
};
const totalValue = getSum(
Object.values(holdings).map(({ currency, marketPrice, quantity }) => {
Object.values(holdings).map(({ assetProfile, marketPrice, quantity }) => {
return new Big(
this.exchangeRateDataService.toCurrency(
quantity * marketPrice,
currency,
assetProfile.currency,
this.request.user?.settings?.settings.baseCurrency ??
DEFAULT_CURRENCY
)

21
apps/api/src/app/portfolio/current-rate.service.ts

@ -2,7 +2,10 @@ import { ActivitiesService } from '@ghostfolio/api/app/activities/activities.ser
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
import { MarketDataService } from '@ghostfolio/api/services/market-data/market-data.service';
import { resetHours } from '@ghostfolio/common/helper';
import {
getAssetProfileIdentifier,
resetHours
} from '@ghostfolio/common/helper';
import {
AssetProfileIdentifier,
DataProviderInfo,
@ -114,8 +117,8 @@ export class CurrentRateService {
errors: quoteErrors.map(({ dataSource, symbol }) => {
return { dataSource, symbol };
}),
values: uniqBy(values, ({ date, symbol }) => {
return `${date}-${symbol}`;
values: uniqBy(values, ({ dataSource, date, symbol }) => {
return `${date}-${getAssetProfileIdentifier({ dataSource, symbol })}`;
})
};
@ -124,7 +127,11 @@ export class CurrentRateService {
try {
// If missing quote, fallback to the latest available historical market price
let value: GetValueObject = response.values.find((currentValue) => {
return currentValue.symbol === symbol && isToday(currentValue.date);
return (
currentValue.dataSource === dataSource &&
currentValue.symbol === symbol &&
isToday(currentValue.date)
);
});
if (!value) {
@ -147,7 +154,11 @@ export class CurrentRateService {
const [latestValue] = response.values
.filter((currentValue) => {
return currentValue.symbol === symbol && currentValue.marketPrice;
return (
currentValue.dataSource === dataSource &&
currentValue.marketPrice &&
currentValue.symbol === symbol
);
})
.sort((a, b) => {
if (a.date < b.date) {

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

@ -36,7 +36,12 @@ import {
TAG_ID_EXCLUDE_FROM_ANALYSIS,
UNKNOWN_KEY
} from '@ghostfolio/common/config';
import { DATE_FORMAT, getSum, parseDate } from '@ghostfolio/common/helper';
import {
DATE_FORMAT,
getAssetProfileIdentifier,
getSum,
parseDate
} from '@ghostfolio/common/helper';
import {
AccountsResponse,
Activity,
@ -64,7 +69,7 @@ import {
} from '@ghostfolio/common/types';
import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type';
import { Inject, Injectable } from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import {
Account,
@ -558,9 +563,17 @@ export class PortfolioService {
const cashSymbolProfiles = this.getCashSymbolProfiles(cashDetails);
symbolProfiles.push(...cashSymbolProfiles);
const symbolProfileMap: { [symbol: string]: EnhancedSymbolProfile } = {};
const symbolProfileMap: {
[assetProfileIdentifier: string]: EnhancedSymbolProfile;
} = {};
for (const symbolProfile of symbolProfiles) {
symbolProfileMap[symbolProfile.symbol] = symbolProfile;
symbolProfileMap[
getAssetProfileIdentifier({
dataSource: symbolProfile.dataSource,
symbol: symbolProfile.symbol
})
] = symbolProfile;
}
const portfolioItemsNow: { [symbol: string]: TimelinePosition } = {};
@ -571,6 +584,7 @@ export class PortfolioService {
for (const {
activitiesCount,
currency,
dataSource,
dateOfFirstActivity,
dividend,
grossPerformance,
@ -600,7 +614,17 @@ export class PortfolioService {
}
}
const assetProfile = symbolProfileMap[symbol];
const assetProfile =
symbolProfileMap[getAssetProfileIdentifier({ dataSource, symbol })];
if (!assetProfile) {
Logger.warn(
`Asset profile not found for ${symbol} (${dataSource})`,
'PortfolioService'
);
continue;
}
let markets: PortfolioPosition['markets'];
let marketsAdvanced: PortfolioPosition['marketsAdvanced'];

8
apps/api/src/models/rule.ts

@ -1,6 +1,5 @@
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { DEFAULT_LANGUAGE_CODE } from '@ghostfolio/common/config';
import { groupBy } from '@ghostfolio/common/helper';
import {
PortfolioPosition,
PortfolioReportRule,
@ -9,6 +8,7 @@ import {
} from '@ghostfolio/common/interfaces';
import { Big } from 'big.js';
import { groupBy } from 'lodash';
import { EvaluationResult } from './interfaces/evaluation-result.interface';
import { RuleInterface } from './interfaces/rule.interface';
@ -41,10 +41,10 @@ export abstract class Rule<T extends RuleSettings> implements RuleInterface<T> {
public groupCurrentHoldingsByAttribute(
holdings: PortfolioPosition[],
attribute: keyof PortfolioPosition,
attribute: `assetProfile.${Extract<keyof PortfolioPosition['assetProfile'], string>}`,
baseCurrency: string
) {
return Array.from(groupBy(attribute, holdings).entries()).map(
return Object.entries(groupBy(holdings, attribute)).map(
([attributeValue, objs]) => ({
groupKey: attributeValue,
investment: objs.reduce(
@ -59,7 +59,7 @@ export abstract class Rule<T extends RuleSettings> implements RuleInterface<T> {
new Big(currentValue.quantity)
.mul(currentValue.marketPrice ?? 0)
.toNumber(),
currentValue.currency,
currentValue.assetProfile.currency,
baseCurrency
),
0

3
apps/api/src/models/rules/asset-class-cluster-risk/equity.ts

@ -27,9 +27,10 @@ export class AssetClassClusterRiskEquity extends Rule<Settings> {
public evaluate(ruleSettings: Settings) {
const holdingsGroupedByAssetClass = this.groupCurrentHoldingsByAttribute(
this.holdings,
'assetClass',
'assetProfile.assetClass',
ruleSettings.baseCurrency
);
let totalValue = 0;
const equityValueInBaseCurrency =

3
apps/api/src/models/rules/asset-class-cluster-risk/fixed-income.ts

@ -27,9 +27,10 @@ export class AssetClassClusterRiskFixedIncome extends Rule<Settings> {
public evaluate(ruleSettings: Settings) {
const holdingsGroupedByAssetClass = this.groupCurrentHoldingsByAttribute(
this.holdings,
'assetClass',
'assetProfile.assetClass',
ruleSettings.baseCurrency
);
let totalValue = 0;
const fixedIncomeValueInBaseCurrency =

2
apps/api/src/models/rules/currency-cluster-risk/base-currency-current-investment.ts

@ -27,7 +27,7 @@ export class CurrencyClusterRiskBaseCurrencyCurrentInvestment extends Rule<Setti
public evaluate(ruleSettings: Settings) {
const holdingsGroupedByCurrency = this.groupCurrentHoldingsByAttribute(
this.holdings,
'currency',
'assetProfile.currency',
ruleSettings.baseCurrency
);

2
apps/api/src/models/rules/currency-cluster-risk/current-investment.ts

@ -27,7 +27,7 @@ export class CurrencyClusterRiskCurrentInvestment extends Rule<Settings> {
public evaluate(ruleSettings: Settings) {
const holdingsGroupedByCurrency = this.groupCurrentHoldingsByAttribute(
this.holdings,
'currency',
'assetProfile.currency',
ruleSettings.baseCurrency
);

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

@ -82,6 +82,7 @@ export class DataProviderService implements OnModuleInit {
return false;
}
// TODO: Change symbol in response to assetProfileIdentifier
public async getAssetProfiles(items: AssetProfileIdentifier[]): Promise<{
[symbol: string]: Partial<SymbolProfile>;
}> {
@ -330,6 +331,7 @@ export class DataProviderService implements OnModuleInit {
});
}
// TODO: Change symbol in response to assetProfileIdentifier
public async getHistorical(
aItems: AssetProfileIdentifier[],
aGranularity: Granularity = 'month',
@ -395,6 +397,7 @@ export class DataProviderService implements OnModuleInit {
}
}
// TODO: Change symbol in response to assetProfileIdentifier
public async getHistoricalRaw({
assetProfileIdentifiers,
from,
@ -508,6 +511,7 @@ export class DataProviderService implements OnModuleInit {
return result;
}
// TODO: Change symbol in response to assetProfileIdentifier
public async getQuotes({
items,
requestTimeout,

52
apps/client/src/app/components/investment-chart/investment-chart.component.ts

@ -24,7 +24,7 @@ import {
Input,
OnChanges,
OnDestroy,
ViewChild
viewChild
} from '@angular/core';
import {
BarController,
@ -55,20 +55,21 @@ import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
templateUrl: './investment-chart.component.html'
})
export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
@Input() benchmarkDataItems: InvestmentItem[] = [];
@Input() benchmarkDataLabel = '';
@Input() colorScheme: ColorScheme;
@Input() currency: string;
@Input() groupBy: GroupBy;
@Input() historicalDataItems: LineChartItem[] = [];
@Input() isInPercentage = false;
@Input() isLoading = false;
@Input() locale = getLocale();
@Input() savingsRate = 0;
@Input() public readonly benchmarkDataItems: InvestmentItem[] = [];
@Input() public readonly benchmarkDataLabel = '';
@Input() public readonly colorScheme: ColorScheme;
@Input() public readonly currency: string;
@Input() public readonly groupBy: GroupBy;
@Input() public readonly historicalDataItems: LineChartItem[] = [];
@Input() public readonly isInPercentage = false;
@Input() public readonly isLoading = false;
@Input() public readonly locale = getLocale();
@Input() public readonly savingsRate = 0;
@ViewChild('chartCanvas') chartCanvas: ElementRef<HTMLCanvasElement>;
private readonly chartCanvas =
viewChild.required<ElementRef<HTMLCanvasElement>>('chartCanvas');
public chart: Chart<'bar' | 'line'>;
private chart: Chart<'bar' | 'line'>;
private investments: InvestmentItem[];
private values: LineChartItem[];
@ -118,7 +119,7 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
borderWidth: this.groupBy ? 0 : 1,
data: this.investments.map(({ date, investment }) => {
return {
x: parseDate(date).getTime(),
x: parseDate(date)?.getTime() ?? null,
y: this.isInPercentage ? investment * 100 : investment
};
}),
@ -138,7 +139,7 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
borderWidth: 2,
data: this.values.map(({ date, value }) => {
return {
x: parseDate(date).getTime(),
x: parseDate(date)?.getTime() ?? null,
y: this.isInPercentage ? value * 100 : value
};
}),
@ -165,14 +166,16 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
this.getTooltipPluginConfiguration();
const annotations = this.chart.options.plugins.annotation
.annotations as Record<string, AnnotationOptions<'line'>>;
?.annotations as Record<string, AnnotationOptions<'line'>>;
if (this.savingsRate && annotations.savingsRate) {
annotations.savingsRate.value = this.savingsRate;
}
this.chart.update();
} else {
this.chart = new Chart(this.chartCanvas.nativeElement, {
this.chart = new Chart<'bar' | 'line'>(
this.chartCanvas().nativeElement,
{
data: chartData,
options: {
animation: false,
@ -278,10 +281,11 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
}
},
plugins: [
getVerticalHoverLinePlugin(this.chartCanvas, this.colorScheme)
getVerticalHoverLinePlugin(this.chartCanvas(), this.colorScheme)
],
type: this.groupBy ? 'bar' : 'line'
});
}
);
}
}
}
@ -305,8 +309,12 @@ export class GfInvestmentChartComponent implements OnChanges, OnDestroy {
}
private isInFuture<T>(aContext: ScriptableLineSegmentContext, aValue: T) {
return isAfter(new Date(aContext?.p1?.parsed?.x), new Date())
? aValue
: undefined;
const xValue = aContext?.p1?.parsed?.x;
if (xValue == null) {
return undefined;
}
return isAfter(new Date(xValue), new Date()) ? aValue : undefined;
}
}

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

@ -342,20 +342,6 @@ export function getYesterday() {
return subDays(new Date(Date.UTC(year, month, day)), 1);
}
export function groupBy<T, K extends keyof T>(
key: K,
arr: T[]
): Map<T[K], T[]> {
const map = new Map<T[K], T[]>();
arr.forEach((t) => {
if (!map.has(t[key])) {
map.set(t[key], []);
}
map.get(t[key])!.push(t);
});
return map;
}
export function interpolate(template: string, context: any) {
return template?.replace(/[$]{([^}]+)}/g, (_, objectPath) => {
const properties = objectPath.split('.');

16
libs/ui/src/lib/treemap-chart/treemap-chart.component.ts

@ -280,8 +280,8 @@ export class GfTreemapChartComponent
);
}
const name = raw._data.name;
const symbol = raw._data.symbol;
const name = raw._data.assetProfile.name;
const symbol = raw._data.assetProfile.symbol;
return [
isUUID(symbol) ? (name ?? symbol) : symbol,
@ -322,8 +322,10 @@ export class GfTreemapChartComponent
['desc']
) as PortfolioPosition[];
const dataSource: DataSource = dataset[dataIndex].dataSource;
const symbol: string = dataset[dataIndex].symbol;
const dataSource: DataSource =
dataset[dataIndex].assetProfile.dataSource;
const symbol: string = dataset[dataIndex].assetProfile.symbol;
this.treemapChartClicked.emit({ dataSource, symbol });
} catch {}
@ -357,10 +359,12 @@ export class GfTreemapChartComponent
callbacks: {
label: ({ raw }: GfTreemapTooltipItem) => {
const allocationInPercentage = `${(raw._data.allocationInPercentage * 100).toFixed(2)}%`;
const name = raw._data.name;
const name = raw._data.assetProfile.name;
const sign =
raw._data.netPerformancePercentWithCurrencyEffect > 0 ? '+' : '';
const symbol = raw._data.symbol;
const symbol = raw._data.assetProfile.symbol;
const netPerformanceInPercentageWithSign = `${sign}${(raw._data.netPerformancePercentWithCurrencyEffect * 100).toFixed(2)}%`;

Loading…
Cancel
Save