From a99bc6bb55ea5424c84ab55304a586631b4be6c8 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:45:12 +0100 Subject: [PATCH 01/32] feat(targets): add typed target model and allocation calculator --- .../interfaces/portfolio-targets.interface.ts | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 libs/common/src/lib/interfaces/portfolio-targets.interface.ts diff --git a/libs/common/src/lib/interfaces/portfolio-targets.interface.ts b/libs/common/src/lib/interfaces/portfolio-targets.interface.ts new file mode 100644 index 0000000000..8c06f90737 --- /dev/null +++ b/libs/common/src/lib/interfaces/portfolio-targets.interface.ts @@ -0,0 +1,21 @@ +import { AssetClass } from '@ghostfolio/prisma/enums'; + +/** + * The first release uses a single global profile. The collection supports + * future account-specific profiles without changing the persisted shape. + */ +export interface PortfolioTargetProfile { + id: string; + name: string; + presetId?: string; + /** Fractions in [0, 1]; the complete allocation must sum to 1. */ + allocations: Record; + /** Maximum absolute drift per asset class, as a fraction (0.05 = 5%). */ + tolerance: number; +} + +export interface PortfolioTargetsSettings { + version: 1; + activeProfileId: string; + profiles: PortfolioTargetProfile[]; +} From 5d77c2dee03159e996915f1b738f79bcd96e8703 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:45:15 +0100 Subject: [PATCH 02/32] feat(targets): add typed target model and allocation calculator --- .../portfolio-targets-calculator.ts | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts new file mode 100644 index 0000000000..6ba18e74e6 --- /dev/null +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts @@ -0,0 +1,189 @@ +import { UNKNOWN_KEY } from '@ghostfolio/common/config'; +import { + PortfolioDetails, + PortfolioTargetsSettings +} from '@ghostfolio/common/interfaces'; +import { AssetClass } from '@ghostfolio/prisma/enums'; + +export const TARGET_ASSET_CLASSES = Object.values(AssetClass); + +export type TargetAllocationKey = AssetClass | typeof UNKNOWN_KEY; + +export interface TargetAllocationRow { + assetClass: TargetAllocationKey; + actual: number; + target: number; + /** Signed percentage-point difference, expressed as a fraction. */ + drift: number; + outOfTolerance: boolean; +} + +export interface TargetAllocationResult { + rows: TargetAllocationRow[]; + /** Total asset value, including cash balances. */ + totalValue: number; + /** Estimated cash in account balances (not cash already in holdings). */ + accountCashValue: number; + /** Half of the absolute drifts; excludes unclassified holdings. */ + totalDrift: number; + maxDrift: number; + outOfToleranceCount: number; + unclassifiedValue: number; + status: 'ready' | 'empty' | 'unavailable' | 'inconsistent'; +} + +/** The first release permits only one active target, but uses a versioned shape. */ +export function getActivePortfolioTarget(settings: PortfolioTargetsSettings) { + return settings.profiles.find(({ id }) => id === settings.activeProfileId); +} + +export function isValidPortfolioTarget( + allocations: Partial>, + tolerance: number +): boolean { + if (!Number.isFinite(tolerance) || tolerance < 0 || tolerance > 1) { + return false; + } + + const values = TARGET_ASSET_CLASSES.map((assetClass) => allocations[assetClass] ?? 0); + + return ( + values.every((value) => Number.isFinite(value) && value >= 0 && value <= 1) && + Math.abs(values.reduce((sum, value) => sum + value, 0) - 1) < 1e-8 && + Object.keys(allocations).every((key) => + TARGET_ASSET_CLASSES.includes(key as AssetClass) + ) + ); +} + +/** + * Computes actual allocation from the unfiltered (or account-only filtered) + * portfolio details. Account value includes cash, while ordinary holdings + * generally do not include the accounts' cash balances. + * + * Never use this method on redacted values: combining percentage-only + * holdings with account balances would yield incorrect allocations. + */ +export function calculatePortfolioTargets({ + details, + targets, + tolerance +}: { + details: Pick; + targets: Partial>; + tolerance: number; +}): TargetAllocationResult { + const empty = (status: TargetAllocationResult['status']): TargetAllocationResult => ({ + rows: [], + totalValue: 0, + accountCashValue: 0, + totalDrift: 0, + maxDrift: 0, + outOfToleranceCount: 0, + unclassifiedValue: 0, + status + }); + + if (!isValidPortfolioTarget(targets, tolerance)) { + return empty('inconsistent'); + } + + const values = new Map( + TARGET_ASSET_CLASSES.map((assetClass) => [assetClass, 0]) + ); + + let holdingsValue = 0; + for (const holding of details.holdings) { + const value = holding.valueInBaseCurrency; + if (value === undefined || !Number.isFinite(value)) { + return empty('unavailable'); + } + + if (value < 0) { + return empty('inconsistent'); + } + + holdingsValue += value; + + const assetClass = holding.assetProfile.assetClass; + const key = assetClass && TARGET_ASSET_CLASSES.includes(assetClass) + ? assetClass + : UNKNOWN_KEY; + + values.set(key, (values.get(key) ?? 0) + value); + } + + const accountValues = Object.values(details.accounts); + if (accountValues.some(({ valueInBaseCurrency }) => + !Number.isFinite(valueInBaseCurrency) || valueInBaseCurrency < 0 + )) { + return empty('inconsistent'); + } + + const accountsTotal = accountValues.reduce( + (sum, account) => sum + account.valueInBaseCurrency, + 0 + ); + + // Positions with no account are included in the UNKNOWN account bucket. + // An empty accounts object is tolerated only if there are no holdings. + if (accountValues.length === 0 && holdingsValue > 0) { + return empty('unavailable'); + } + + const accountCashValue = accountsTotal - holdingsValue; + const epsilon = Math.max(accountsTotal, 1) * 1e-8; + + // A negative residual signals that accounts and holdings cannot be + // reconciled (rather than negative cash to silently normalize). + if (accountCashValue < -epsilon) { + return empty('inconsistent'); + } + + const totalValue = accountsTotal; + if (totalValue <= epsilon) { + return empty('empty'); + } + + values.set( + AssetClass.LIQUIDITY, + (values.get(AssetClass.LIQUIDITY) ?? 0) + Math.max(0, accountCashValue) + ); + + const rows: TargetAllocationRow[] = TARGET_ASSET_CLASSES.map((assetClass) => { + const actual = (values.get(assetClass) ?? 0) / totalValue; + const target = targets[assetClass] ?? 0; + const drift = actual - target; + return { + assetClass, + actual, + target, + drift, + outOfTolerance: Math.abs(drift) > tolerance + 1e-10 + }; + }); + + const unclassifiedValue = values.get(UNKNOWN_KEY) ?? 0; + if (unclassifiedValue > 0) { + rows.push({ + assetClass: UNKNOWN_KEY, + actual: unclassifiedValue / totalValue, + target: 0, + drift: unclassifiedValue / totalValue, + outOfTolerance: true + }); + } + + const drifts = rows.map(({ drift }) => Math.abs(drift)); + + return { + rows, + totalValue, + accountCashValue: Math.max(0, accountCashValue), + totalDrift: drifts.reduce((sum, value) => sum + value, 0) / 2, + maxDrift: Math.max(...drifts), + outOfToleranceCount: rows.filter(({ outOfTolerance }) => outOfTolerance).length, + unclassifiedValue, + status: unclassifiedValue > 0 ? 'inconsistent' : 'ready' + }; +} From dff1b2883045b0818b2982abe672518d2ae4839f Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:45:27 +0100 Subject: [PATCH 03/32] test(targets): cover cash reconciliation, drifts, and error states --- .../portfolio-targets-calculator.spec.ts | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.spec.ts diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.spec.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.spec.ts new file mode 100644 index 0000000000..07e3dda77a --- /dev/null +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.spec.ts @@ -0,0 +1,103 @@ +import { PortfolioDetails } from '@ghostfolio/common/interfaces'; +import { AssetClass } from '@ghostfolio/prisma/enums'; + +import { + calculatePortfolioTargets, + isValidPortfolioTarget +} from './portfolio-targets-calculator'; + +const allocations = { + [AssetClass.ALTERNATIVE_INVESTMENT]: 0, + [AssetClass.COMMODITY]: 0, + [AssetClass.EQUITY]: 0.6, + [AssetClass.FIXED_INCOME]: 0.4, + [AssetClass.LIQUIDITY]: 0, + [AssetClass.REAL_ESTATE]: 0 +}; + +function makeDetails({ + cash = 0, + equity = 0, + bonds = 0 +}: { + cash?: number; + equity?: number; + bonds?: number; +}): Pick { + const holdings = [ + ...(equity > 0 + ? [{ assetProfile: { assetClass: AssetClass.EQUITY }, valueInBaseCurrency: equity }] + : []), + ...(bonds > 0 + ? [{ assetProfile: { assetClass: AssetClass.FIXED_INCOME }, valueInBaseCurrency: bonds }] + : []) + ] as PortfolioDetails['holdings']; + + return { + accounts: { + example: { + balance: cash, + currency: 'EUR', + name: 'Example', + valueInBaseCurrency: cash + equity + bonds + } + }, + holdings + }; +} + +describe('Portfolio targets calculator', () => { + it('validates a complete 100% target and the tolerance', () => { + expect(isValidPortfolioTarget(allocations, 0.05)).toBe(true); + expect(isValidPortfolioTarget({ ...allocations, [AssetClass.EQUITY]: 0.5 }, 0.05)).toBe(false); + expect(isValidPortfolioTarget(allocations, -0.01)).toBe(false); + }); + + it('reconciles account cash exactly once', () => { + const result = calculatePortfolioTargets({ + details: makeDetails({ equity: 600, bonds: 300, cash: 100 }), + targets: allocations, + tolerance: 0.05 + }); + + expect(result.status).toBe('ready'); + expect(result.totalValue).toBe(1000); + expect(result.accountCashValue).toBe(100); + expect(result.rows.find(({ assetClass }) => assetClass === AssetClass.LIQUIDITY)?.actual).toBeCloseTo(0.1); + expect(result.rows.find(({ assetClass }) => assetClass === AssetClass.EQUITY)?.actual).toBeCloseTo(0.6); + expect(result.outOfToleranceCount).toBe(2); + expect(result.totalDrift).toBeCloseTo(0.1); + }); + + it('handles a cash-only account', () => { + const result = calculatePortfolioTargets({ + details: makeDetails({ cash: 100 }), + targets: allocations, + tolerance: 0.05 + }); + expect(result.status).toBe('ready'); + expect(result.rows.find(({ assetClass }) => assetClass === AssetClass.LIQUIDITY)?.actual).toBe(1); + }); + + it('does not fabricate allocations if values are redacted', () => { + const details = makeDetails({ equity: 100 }); + details.holdings[0].valueInBaseCurrency = undefined; + expect(calculatePortfolioTargets({ details, targets: allocations, tolerance: 0.05 }).status) + .toBe('unavailable'); + }); + + it('rejects negative account-to-holdings residuals', () => { + const details = makeDetails({ equity: 100 }); + details.accounts.example.valueInBaseCurrency = 50; + expect(calculatePortfolioTargets({ details, targets: allocations, tolerance: 0.05 }).status) + .toBe('inconsistent'); + }); + + it('handles an empty portfolio', () => { + expect(calculatePortfolioTargets({ + details: makeDetails({}), + targets: allocations, + tolerance: 0.05 + }).status).toBe('empty'); + }); +}); From 222dfda6f0502e711e272decc39e9d4a9d8165b7 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:49:20 +0100 Subject: [PATCH 04/32] feat(targets): validate versioned global target settings --- .../portfolio-targets-validation.ts | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-validation.ts diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-validation.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-validation.ts new file mode 100644 index 0000000000..29e46d2ed3 --- /dev/null +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-validation.ts @@ -0,0 +1,70 @@ +import { PortfolioTargetsSettings } from '@ghostfolio/common/interfaces/portfolio-targets.interface'; +import { AssetClass } from '@ghostfolio/prisma/enums'; + +const assetClasses = Object.values(AssetClass); + +export function isValidPortfolioTargetsSettings( + value: unknown +): value is PortfolioTargetsSettings { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false; + } + + const settings = value as Partial; + + if ( + settings.version !== 1 || + typeof settings.activeProfileId !== 'string' || + !Array.isArray(settings.profiles) || + // Only one global target is supported in the first release. + settings.profiles.length !== 1 + ) { + return false; + } + + const profile = settings.profiles[0]; + + if ( + !profile || + typeof profile.id !== 'string' || + profile.id.length === 0 || + profile.id.length > 100 || + profile.id !== settings.activeProfileId || + typeof profile.name !== 'string' || + profile.name.trim().length === 0 || + profile.name.length > 100 || + (profile.presetId !== undefined && + (typeof profile.presetId !== 'string' || + profile.presetId.length > 100)) || + typeof profile.tolerance !== 'number' || + !Number.isFinite(profile.tolerance) || + profile.tolerance < 0 || + profile.tolerance > 1 || + !profile.allocations || + typeof profile.allocations !== 'object' || + Array.isArray(profile.allocations) + ) { + return false; + } + + const keys = Object.keys(profile.allocations); + if ( + keys.length !== assetClasses.length || + keys.some((key) => !assetClasses.includes(key as AssetClass)) + ) { + return false; + } + + const weights = assetClasses.map((assetClass) => profile.allocations[assetClass]); + + return ( + weights.every( + (weight) => + typeof weight === 'number' && + Number.isFinite(weight) && + weight >= 0 && + weight <= 1 + ) && + Math.abs(weights.reduce((sum, weight) => sum + weight, 0) - 1) < 1e-8 + ); +} From 24826142fcc3de0d9e4db2ca9d013683088dd4dc Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:49:38 +0100 Subject: [PATCH 05/32] feat(targets): integrate validated settings into user preferences --- libs/common/src/lib/interfaces/user-settings.interface.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libs/common/src/lib/interfaces/user-settings.interface.ts b/libs/common/src/lib/interfaces/user-settings.interface.ts index b093314d79..af0cda9ef8 100644 --- a/libs/common/src/lib/interfaces/user-settings.interface.ts +++ b/libs/common/src/lib/interfaces/user-settings.interface.ts @@ -1,3 +1,4 @@ +import { PortfolioTargetsSettings } from './portfolio-targets.interface'; import { XRayRulesSettings } from '@ghostfolio/common/interfaces/x-ray-rules-settings.interface'; import { ColorScheme, @@ -27,6 +28,7 @@ export interface UserSettings { language?: string; locale?: string; performanceCalculationType?: PerformanceCalculationType; + portfolioTargets?: PortfolioTargetsSettings; projectedTotalAmount?: number; retirementDate?: string; safeWithdrawalRate?: number; From 0d2db72afbb08a297e4f8307f098f8217fb41d9b Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:49:41 +0100 Subject: [PATCH 06/32] feat(targets): integrate validated settings into user preferences --- libs/common/src/lib/interfaces/index.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libs/common/src/lib/interfaces/index.ts b/libs/common/src/lib/interfaces/index.ts index dfd20f118f..d6d1287ce2 100644 --- a/libs/common/src/lib/interfaces/index.ts +++ b/libs/common/src/lib/interfaces/index.ts @@ -35,6 +35,7 @@ import type { PortfolioDetails } from './portfolio-details.interface'; import type { PortfolioPerformance } from './portfolio-performance.interface'; import type { PortfolioPosition } from './portfolio-position.interface'; import type { PortfolioReportRule } from './portfolio-report-rule.interface'; +import type { PortfolioTargetProfile, PortfolioTargetsSettings } from './portfolio-targets.interface'; import type { PortfolioSummary } from './portfolio-summary.interface'; import type { Product } from './product.interface'; import type { ReferralPartner } from './referral-partner.interface'; @@ -197,6 +198,8 @@ export { PortfolioReportResponse, PortfolioReportRule, PortfolioSummary, + PortfolioTargetProfile, + PortfolioTargetsSettings, Product, PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON, From 976d03ead4bea8a08db716e995b05d9869e280e0 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:49:43 +0100 Subject: [PATCH 07/32] feat(targets): integrate validated settings into user preferences --- .../src/lib/dtos/update-user-setting.dto.ts | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/libs/common/src/lib/dtos/update-user-setting.dto.ts b/libs/common/src/lib/dtos/update-user-setting.dto.ts index b51d8bb61b..237df65a8e 100644 --- a/libs/common/src/lib/dtos/update-user-setting.dto.ts +++ b/libs/common/src/lib/dtos/update-user-setting.dto.ts @@ -1,4 +1,4 @@ -import { XRayRulesSettings } from '@ghostfolio/common/interfaces'; +import { PortfolioTargetsSettings, XRayRulesSettings } from '@ghostfolio/common/interfaces'; import type { ColorScheme, DateRange, @@ -6,6 +6,7 @@ import type { ViewMode } from '@ghostfolio/common/types'; import { PerformanceCalculationType } from '@ghostfolio/common/types/performance-calculation-type.type'; +import { isValidPortfolioTargetsSettings } from '@ghostfolio/common/portfolio-targets/portfolio-targets-validation'; import { IsCurrencyCode } from '@ghostfolio/common/validators/is-currency-code'; import { @@ -15,7 +16,8 @@ import { IsIn, IsNumber, IsOptional, - IsString + IsString, + ValidateBy } from 'class-validator'; import { eachYearOfInterval, format } from 'date-fns'; @@ -109,6 +111,16 @@ export class UpdateUserSettingDto { * The target financial amount the user aims to reach before retiring. * Can be explicitly set to null to clear the value and calculate it dynamically. */ + @IsOptional() + @ValidateBy({ + name: 'isValidPortfolioTargetsSettings', + validator: { + validate: isValidPortfolioTargetsSettings, + defaultMessage: () => 'portfolioTargets must contain one valid global target allocation' + } + }) + portfolioTargets?: PortfolioTargetsSettings; + @IsNumber() @IsOptional() projectedTotalAmount?: number | null; From 714408eeaa78b74b06bd8007f9353c8c94f77940 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:50:04 +0100 Subject: [PATCH 08/32] test(targets): validate global target persistence payload --- .../portfolio-targets-validation.spec.ts | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-validation.spec.ts diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-validation.spec.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-validation.spec.ts new file mode 100644 index 0000000000..c07d37df12 --- /dev/null +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-validation.spec.ts @@ -0,0 +1,72 @@ +import { AssetClass } from '@ghostfolio/prisma/enums'; + +import { isValidPortfolioTargetsSettings } from './portfolio-targets-validation'; + +const allocations = { + [AssetClass.ALTERNATIVE_INVESTMENT]: 0, + [AssetClass.COMMODITY]: 0.2, + [AssetClass.EQUITY]: 0.4, + [AssetClass.FIXED_INCOME]: 0.4, + [AssetClass.LIQUIDITY]: 0, + [AssetClass.REAL_ESTATE]: 0 +}; + +const validSettings = { + version: 1, + activeProfileId: 'global', + profiles: [ + { + id: 'global', + name: 'Golden Butterfly (simplified)', + allocations, + tolerance: 0.05 + } + ] +}; + +describe('Portfolio targets settings validation', () => { + it('accepts a single complete allocation', () => { + expect(isValidPortfolioTargetsSettings(validSettings)).toBe(true); + }); + + it('rejects multiple profiles in v1', () => { + expect(isValidPortfolioTargetsSettings({ + ...validSettings, + profiles: [...validSettings.profiles, ...validSettings.profiles] + })).toBe(false); + }); + + it('rejects non-100-percent allocations', () => { + expect(isValidPortfolioTargetsSettings({ + ...validSettings, + profiles: [{ + ...validSettings.profiles[0], + allocations: { ...allocations, [AssetClass.EQUITY]: 0.3 } + }] + })).toBe(false); + }); + + it('rejects invalid tolerances', () => { + expect(isValidPortfolioTargetsSettings({ + ...validSettings, + profiles: [{ ...validSettings.profiles[0], tolerance: -0.1 }] + })).toBe(false); + }); + + it('rejects a mismatched active profile', () => { + expect(isValidPortfolioTargetsSettings({ + ...validSettings, + activeProfileId: 'other' + })).toBe(false); + }); + + it('rejects unknown allocation keys', () => { + expect(isValidPortfolioTargetsSettings({ + ...validSettings, + profiles: [{ + ...validSettings.profiles[0], + allocations: { ...allocations, UNKNOWN: 0 } + }] + })).toBe(false); + }); +}); From 364c96795717941797cf9ed8ce4dec4210939dd1 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 20:50:23 +0100 Subject: [PATCH 09/32] docs(targets): position settings field documentation correctly --- libs/common/src/lib/dtos/update-user-setting.dto.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/libs/common/src/lib/dtos/update-user-setting.dto.ts b/libs/common/src/lib/dtos/update-user-setting.dto.ts index 237df65a8e..733642437a 100644 --- a/libs/common/src/lib/dtos/update-user-setting.dto.ts +++ b/libs/common/src/lib/dtos/update-user-setting.dto.ts @@ -107,10 +107,7 @@ export class UpdateUserSettingDto { @IsOptional() performanceCalculationType?: PerformanceCalculationType; - /** - * The target financial amount the user aims to reach before retiring. - * Can be explicitly set to null to clear the value and calculate it dynamically. - */ + /** Desired asset-class allocation and tolerance for the global portfolio. */ @IsOptional() @ValidateBy({ name: 'isValidPortfolioTargetsSettings', @@ -121,6 +118,10 @@ export class UpdateUserSettingDto { }) portfolioTargets?: PortfolioTargetsSettings; + /** + * The target financial amount the user aims to reach before retiring. + * Can be explicitly set to null to clear the value and calculate it dynamically. + */ @IsNumber() @IsOptional() projectedTotalAmount?: number | null; From 8d35259ce6533965bcfca68fac3f847019de24a2 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:06:55 +0100 Subject: [PATCH 10/32] feat(targets): provide five editable allocation presets --- .../portfolio-targets-presets.ts | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts new file mode 100644 index 0000000000..747970c0d2 --- /dev/null +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts @@ -0,0 +1,50 @@ +import { PortfolioTargetProfile } from '@ghostfolio/common/interfaces'; +import { AssetClass } from '@ghostfolio/prisma/enums'; + +export interface PortfolioTargetPreset { + id: string; + name: string; + allocations: Record; +} + +function makePreset( + id: string, + name: string, + equity: number, + fixedIncome: number, + commodity = 0 +): PortfolioTargetPreset { + return { + id, + name, + allocations: { + [AssetClass.ALTERNATIVE_INVESTMENT]: 0, + [AssetClass.COMMODITY]: commodity, + [AssetClass.EQUITY]: equity, + [AssetClass.FIXED_INCOME]: fixedIncome, + [AssetClass.LIQUIDITY]: 0, + [AssetClass.REAL_ESTATE]: 0 + } + }; +} + +/** Editable starting points, not investment recommendations. */ +export const PORTFOLIO_TARGET_PRESETS: PortfolioTargetPreset[] = [ + makePreset('conservative-20-80', $localize`Conservative (20/80)`, 0.2, 0.8), + makePreset('cautious-40-60', $localize`Cautious (40/60)`, 0.4, 0.6), + makePreset('moderate-60-40', $localize`Moderate (60/40)`, 0.6, 0.4), + makePreset('aggressive-80-20', $localize`Aggressive (80/20)`, 0.8, 0.2), + makePreset('golden-butterfly', 'Golden Butterfly', 0.4, 0.4, 0.2) +]; + +export function createDefaultPortfolioTarget(): PortfolioTargetProfile { + const preset = PORTFOLIO_TARGET_PRESETS[2]; + + return { + id: 'global', + name: preset.name, + presetId: preset.id, + allocations: { ...preset.allocations }, + tolerance: 0.05 + }; +} From c520dd7bed573774200dfa34d9d16bed5c836691 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:07:20 +0100 Subject: [PATCH 11/32] feat(targets): define editable allocation presets --- .../pages/portfolio/targets/target-presets.ts | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/target-presets.ts diff --git a/apps/client/src/app/pages/portfolio/targets/target-presets.ts b/apps/client/src/app/pages/portfolio/targets/target-presets.ts new file mode 100644 index 0000000000..39a73e4e04 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-presets.ts @@ -0,0 +1,29 @@ +import { PortfolioTargetProfile } from '@ghostfolio/common/interfaces'; +import { AssetClass } from '@ghostfolio/prisma/enums'; + +export const TARGET_PRESETS = [ + { id: 'cautious', label: $localize`Cautious (20/80)`, equity: 20, bonds: 80, commodities: 0 }, + { id: 'conservative', label: $localize`Conservative (40/60)`, equity: 40, bonds: 60, commodities: 0 }, + { id: 'moderate', label: $localize`Moderate (60/40)`, equity: 60, bonds: 40, commodities: 0 }, + { id: 'aggressive', label: $localize`Aggressive (80/20)`, equity: 80, bonds: 20, commodities: 0 }, + { id: 'golden-butterfly', label: $localize`Golden Butterfly (simplified)`, equity: 40, bonds: 40, commodities: 20 } +] as const; + +export function createTargetFromPreset(presetId: string): PortfolioTargetProfile { + const preset = TARGET_PRESETS.find(({ id }) => id === presetId) ?? TARGET_PRESETS[2]; + + return { + id: 'global', + name: preset.label, + presetId: preset.id, + tolerance: 0.05, + allocations: { + [AssetClass.ALTERNATIVE_INVESTMENT]: 0, + [AssetClass.COMMODITY]: preset.commodities / 100, + [AssetClass.EQUITY]: preset.equity / 100, + [AssetClass.FIXED_INCOME]: preset.bonds / 100, + [AssetClass.LIQUIDITY]: 0, + [AssetClass.REAL_ESTATE]: 0 + } + }; +} From 1a98569dd13bfa702c89963a38a03a9a9b4e0524 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:07:42 +0100 Subject: [PATCH 12/32] feat(targets): add editable allocation dialog and doughnut chart --- .../target-configuration-dialog.component.ts | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts new file mode 100644 index 0000000000..d96444d5b7 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts @@ -0,0 +1,119 @@ +import { PortfolioTargetProfile, User } from '@ghostfolio/common/interfaces'; +import { TARGET_ASSET_CLASSES } from '@ghostfolio/common/portfolio-targets/portfolio-targets-calculator'; +import { isValidPortfolioTargetsSettings } from '@ghostfolio/common/portfolio-targets/portfolio-targets-validation'; +import { AssetClass } from '@ghostfolio/prisma/enums'; +import { translate } from '@ghostfolio/ui/i18n'; +import { GfPortfolioProportionChartComponent } from '@ghostfolio/ui/portfolio-proportion-chart'; + +import { DecimalPipe } from '@angular/common'; +import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { MatButtonModule } from '@angular/material/button'; +import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatInputModule } from '@angular/material/input'; +import { MatSelectModule } from '@angular/material/select'; + +import { createTargetFromPreset, TARGET_PRESETS } from './target-presets'; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + DecimalPipe, + FormsModule, + GfPortfolioProportionChartComponent, + MatButtonModule, + MatDialogModule, + MatFormFieldModule, + MatInputModule, + MatSelectModule + ], + selector: 'gf-target-configuration-dialog', + styleUrls: ['./target-configuration-dialog.component.scss'], + templateUrl: './target-configuration-dialog.component.html' +}) +export class GfTargetConfigurationDialogComponent { + protected readonly classes = TARGET_ASSET_CLASSES; + protected readonly presets = TARGET_PRESETS; + protected profile: PortfolioTargetProfile; + + private readonly data = inject<{ + profile?: PortfolioTargetProfile; + user: User; + }>(MAT_DIALOG_DATA); + private readonly dialogRef = + inject>(MatDialogRef); + + protected readonly labels = Object.fromEntries( + TARGET_ASSET_CLASSES.map((assetClass) => [assetClass, translate(assetClass)]) + ) as Record; + + public constructor() { + const defaultProfile = createTargetFromPreset('moderate'); + this.profile = { + ...(this.data.profile ?? defaultProfile), + allocations: { ...(this.data.profile?.allocations ?? defaultProfile.allocations) } + }; + } + + protected get chartData() { + return Object.fromEntries(this.classes.map((assetClass) => [ + assetClass, + { + name: this.labels[assetClass], + value: Math.max(0, this.profile.allocations[assetClass] ?? 0) + } + ])); + } + + protected get total() { + return this.classes.reduce( + (sum, assetClass) => sum + (this.profile.allocations[assetClass] ?? 0), + 0 + ); + } + + protected get isValid() { + return isValidPortfolioTargetsSettings({ + version: 1, + activeProfileId: 'global', + profiles: [{ ...this.profile, id: 'global' }] + }); + } + + protected applyPreset(presetId: string) { + const next = createTargetFromPreset(presetId); + this.profile = { + ...next, + tolerance: this.profile.tolerance + }; + } + + protected updateAllocation(assetClass: AssetClass, percent: number) { + this.profile = { + ...this.profile, + presetId: undefined, + allocations: { + ...this.profile.allocations, + [assetClass]: Number(percent) / 100 + } + }; + } + + protected updateTolerance(percent: number) { + this.profile = { + ...this.profile, + tolerance: Number(percent) / 100 + }; + } + + protected save() { + if (this.isValid) { + this.dialogRef.close(this.profile); + } + } + + protected cancel() { + this.dialogRef.close(); + } +} From e6d2afd747a654b55b230f1c84060c5745fedf0e Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:07:44 +0100 Subject: [PATCH 13/32] feat(targets): add editable allocation dialog and doughnut chart --- ...target-configuration-dialog.component.html | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html new file mode 100644 index 0000000000..a921785992 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html @@ -0,0 +1,76 @@ +

Configure target

+ +
+ + Starting allocation + + @for (preset of presets; track preset.id) { + {{ preset.label }} + } + Custom + + +

+ Presets are starting points. Edit any percentage to customize your target. +

+
+
+
+ +
+ Total: {{ total * 100 | number: '1.0-2' }}% +
+
+
+ @for (assetClass of classes; track assetClass) { +
+ +
+ + % +
+
+ } +
+
+ +
+ + % +
+
+ @if (!isValid) { +

+ Each percentage must be between 0 and 100, and the total must equal 100%. +

+ } +
+
+
+ + + + From bd2bcf970f2067460944a1e75da9ad8c939a2fa3 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:07:47 +0100 Subject: [PATCH 14/32] feat(targets): add editable allocation dialog and doughnut chart --- .../target-configuration-dialog.component.scss | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.scss diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.scss b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.scss new file mode 100644 index 0000000000..14cfd49a11 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.scss @@ -0,0 +1,16 @@ +:host { display: block; } +.configuration-content { min-width: min(760px, 80vw); } +.allocation-input { + display: flex; + gap: 1rem; + align-items: center; + justify-content: space-between; + margin-bottom: 0.65rem; + label { flex: 1; } + .input-group { width: 9rem; } +} +gf-portfolio-proportion-chart { display: block; min-height: 250px; } +@media (max-width: 600px) { + .configuration-content { min-width: 0; } + .allocation-input { gap: 0.5rem; } +} From d61822d05acf833cd736e2ef892332a11e79177e Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:24 +0100 Subject: [PATCH 15/32] feat(targets): implement target overview and account-only scope --- .../targets/targets-page.component.ts | 205 ++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/targets-page.component.ts diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts new file mode 100644 index 0000000000..419275bb46 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts @@ -0,0 +1,205 @@ +import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service'; +import { UserService } from '@ghostfolio/client/services/user/user.service'; +import { UNKNOWN_KEY } from '@ghostfolio/common/config'; +import { Filter, PortfolioTargetProfile, User } from '@ghostfolio/common/interfaces'; +import { hasPermission, permissions } from '@ghostfolio/common/permissions'; +import { + calculatePortfolioTargets, + TargetAllocationResult +} from '@ghostfolio/common/portfolio-targets/portfolio-targets-calculator'; +import { hasScope, scopes } from '@ghostfolio/common/scopes'; +import { AssetClass } from '@ghostfolio/prisma/enums'; +import { translate } from '@ghostfolio/ui/i18n'; +import { DataService } from '@ghostfolio/ui/services'; + +import { DecimalPipe } from '@angular/common'; +import { + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + DestroyRef, + inject, + OnInit +} from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { MatButtonModule } from '@angular/material/button'; +import { MatCardModule } from '@angular/material/card'; +import { MatDialog } from '@angular/material/dialog'; +import { MatFormFieldModule } from '@angular/material/form-field'; +import { MatSelectModule } from '@angular/material/select'; +import { finalize, switchMap } from 'rxjs'; + +import { GfTargetConfigurationDialogComponent } from './target-configuration-dialog.component'; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [ + DecimalPipe, + MatButtonModule, + MatCardModule, + MatFormFieldModule, + MatSelectModule + ], + selector: 'gf-targets-page', + styleUrls: ['./targets-page.component.scss'], + templateUrl: './targets-page.component.html' +}) +export class GfTargetsPageComponent implements OnInit { + protected user: User; + protected profile?: PortfolioTargetProfile; + protected result?: TargetAllocationResult; + protected selectedAccountId = ''; + protected isLoading = true; + protected isSaving = false; + protected hasError = false; + protected canEdit = false; + protected readonly UNKNOWN_KEY = UNKNOWN_KEY; + protected readonly classes = Object.values(AssetClass); + protected readonly labels: Record = Object.fromEntries( + Object.values(AssetClass).map((assetClass) => [assetClass, translate(assetClass)]) + ); + private readonly changeDetectorRef = inject(ChangeDetectorRef); + private readonly dataService = inject(DataService); + private readonly destroyRef = inject(DestroyRef); + private readonly dialog = inject(MatDialog); + private readonly impersonationService = inject(ImpersonationStorageService); + private readonly userService = inject(UserService); + private isImpersonating = false; + + public ngOnInit() { + this.impersonationService.onChangeHasImpersonation() + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((id) => { + this.isImpersonating = !!id; + this.updateEditingPermission(); + }); + + this.userService.stateChanged + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((state) => { + if (!state?.user) { + return; + } + this.user = state.user; + this.profile = this.user.settings.portfolioTargets?.profiles.find( + ({ id }) => id === this.user.settings.portfolioTargets?.activeProfileId + ); + this.updateEditingPermission(); + this.fetchAllocations(); + }); + } + + protected get accounts() { + return (this.user?.accounts ?? []).filter((account) => !account.isExcluded); + } + + protected get usableResult() { + return this.result?.status === 'ready'; + } + + protected get hasReadValues() { + return hasScope(this.user?.scopes, scopes.portfolioReadValues) && + !this.user?.settings?.isRestrictedView; + } + + protected get displayedRows() { + return this.result?.rows ?? []; + } + + protected formatClass(assetClass: string) { + return assetClass === UNKNOWN_KEY + ? $localize`Unclassified` + : this.labels[assetClass] ?? assetClass; + } + + protected changeAccount(accountId: string) { + this.selectedAccountId = accountId; + this.fetchAllocations(); + } + + protected openConfiguration() { + if (!this.canEdit || !this.user) { + return; + } + + const ref = this.dialog.open(GfTargetConfigurationDialogComponent, { + autoFocus: false, + maxWidth: '96vw', + width: '820px', + data: { profile: this.profile, user: this.user } + }); + + ref.afterClosed().pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe((profile?: PortfolioTargetProfile) => { + if (!profile) { + return; + } + this.isSaving = true; + this.dataService.putUserSetting({ + portfolioTargets: { + version: 1, + activeProfileId: 'global', + profiles: [{ ...profile, id: 'global' }] + } + }).pipe( + switchMap(() => this.userService.get(true)), + finalize(() => { + this.isSaving = false; + this.changeDetectorRef.markForCheck(); + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe({ + error: () => { + this.hasError = true; + this.changeDetectorRef.markForCheck(); + } + }); + }); + } + + private updateEditingPermission() { + this.canEdit = !!this.user && !this.isImpersonating && + hasPermission(this.user.permissions, permissions.updateUserSettings); + this.changeDetectorRef.markForCheck(); + } + + private fetchAllocations() { + if (!this.user) { + return; + } + + this.isLoading = true; + this.hasError = false; + this.result = undefined; + + const filters: Filter[] = this.selectedAccountId + ? [{ type: 'ACCOUNT', id: this.selectedAccountId }] + : []; + + this.dataService.fetchPortfolioDetails({ filters }) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe({ + next: (details) => { + if (this.profile) { + if (!this.hasReadValues || ('hasError' in details && details.hasError)) { + this.result = undefined; + this.hasError = true; + } else { + this.result = calculatePortfolioTargets({ + details, + targets: this.profile.allocations, + tolerance: this.profile.tolerance + }); + } + } + this.isLoading = false; + this.changeDetectorRef.markForCheck(); + }, + error: () => { + this.hasError = true; + this.isLoading = false; + this.changeDetectorRef.markForCheck(); + } + }); + } +} From 57a3459ee9b0ae838a867914ed8f0fa0237f7639 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:27 +0100 Subject: [PATCH 16/32] feat(targets): implement target overview and account-only scope --- .../pages/portfolio/targets/targets-page.html | 147 ++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/targets-page.html diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.html b/apps/client/src/app/pages/portfolio/targets/targets-page.html new file mode 100644 index 0000000000..1690657b48 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.html @@ -0,0 +1,147 @@ +
+

Targets

+ +
+
+ @if (profile) { +
{{ profile.name }}
+ Allowed deviation: + ±{{ profile.tolerance * 100 | number: '1.0-1' }}% + } @else { + No target configured yet + } +
+ @if (canEdit) { + + } +
+ + @if (accounts.length > 1) { + + @if (selectedAccountId) { +

+ Comparing the selected account with the global portfolio target. +

+ } + } + + @if (!profile) { + + +

+ Create a target to compare the actual asset allocation with your desired allocation. +

+
+
+ } @else if (isLoading) { +

Loading portfolio allocation…

+ } @else if (hasError || !result || result.status === 'unavailable') { + + +

+ The current allocation cannot be calculated with the available data or permissions. +

+
+
+ } @else if (result.status === 'empty') { +

The selected portfolio is empty.

+ } @else if (result.status === 'inconsistent') { + + +

+ The asset classification or account values cannot be reconciled. Check unclassified + holdings, missing market prices, or negative balances before using this comparison. +

+
+
+ } @else { +
+
+ +
Total allocation drift
+
{{ result.totalDrift * 100 | number: '1.0-2' }}%
+
+
+
+ +
Maximum deviation
+
{{ result.maxDrift * 100 | number: '1.0-2' }}%
+
+
+
+ +
Classes outside tolerance
+
{{ result.outOfToleranceCount }} / {{ displayedRows.length }}
+
+
+
+ + + Actual vs target allocation + +
+ Actual + Target +
+ @for (row of displayedRows; track row.assetClass) { +
+
+ {{ formatClass(row.assetClass) }} + + {{ (row.drift >= 0 ? '+' : '') + (row.drift * 100 | number: '1.0-2') }}% + +
+
+
+
+
+
+
+
+ } +
+
+ + + Deviation details + + + + + + + + + + + @for (row of displayedRows; track row.assetClass) { + + + + + + + + } + +
Asset classActualTargetDeviationStatus
{{ formatClass(row.assetClass) }}{{ row.actual * 100 | number: '1.0-2' }}%{{ row.target * 100 | number: '1.0-2' }}%{{ row.drift * 100 | number: '+1.0-2' }}% + @if (row.outOfTolerance) { + Outside tolerance + } @else { + Within tolerance + } +
+
+
+ } +
From 1d8d9c974a87957f0b9dabadfce1d812af66055e Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:29 +0100 Subject: [PATCH 17/32] feat(targets): implement target overview and account-only scope --- .../src/app/pages/portfolio/targets/targets-page.scss | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/targets-page.scss diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.scss b/apps/client/src/app/pages/portfolio/targets/targets-page.scss new file mode 100644 index 0000000000..51dff3d32e --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.scss @@ -0,0 +1,7 @@ +:host { display: block; } +.account-select { width: min(320px, 100%); } +.comparison-track { height: 0.62rem; background: rgba(128,128,128,.11); border-radius: .35rem; margin-bottom: .3rem; overflow: hidden; } +.comparison-bar { height: 100%; border-radius: .35rem; } +.current-bar, .current-marker { background: #36cfcc; } +.target-bar, .target-marker { background: #3686cf; } +.legend-marker { display: inline-block; width: .65rem; height: .65rem; border-radius: .15rem; } From d953dcd8a5f95be84d18582ae2701019da7d5673 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:31 +0100 Subject: [PATCH 18/32] feat(targets): implement target overview and account-only scope --- .../pages/portfolio/targets/targets-page.routes.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 apps/client/src/app/pages/portfolio/targets/targets-page.routes.ts diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.routes.ts b/apps/client/src/app/pages/portfolio/targets/targets-page.routes.ts new file mode 100644 index 0000000000..06e1cb29d7 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.routes.ts @@ -0,0 +1,14 @@ +import { AuthGuard } from '@ghostfolio/client/core/auth.guard'; + +import { Routes } from '@angular/router'; + +import { GfTargetsPageComponent } from './targets-page.component'; + +export const routes: Routes = [ + { + canActivate: [AuthGuard], + component: GfTargetsPageComponent, + path: '', + title: $localize`Targets` + } +]; From aeccb234721339fae7f4bba95d0fc371be014b07 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:43 +0100 Subject: [PATCH 19/32] feat(targets): add Targets between Allocations and FIRE --- libs/common/src/lib/routes/routes.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libs/common/src/lib/routes/routes.ts b/libs/common/src/lib/routes/routes.ts index ca3cdd3663..9402715144 100644 --- a/libs/common/src/lib/routes/routes.ts +++ b/libs/common/src/lib/routes/routes.ts @@ -214,6 +214,11 @@ export const internalRoutes = { routerLink: ['/portfolio'], title: $localize`Analysis` }, + targets: { + path: 'targets', + routerLink: ['/portfolio', 'targets'], + title: $localize`Targets` + }, fire: { path: 'fire', routerLink: ['/portfolio', 'fire'], From a1f9b1bf6460a99b3a5660e80df82e790b0e3bc0 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:46 +0100 Subject: [PATCH 20/32] feat(targets): add Targets between Allocations and FIRE --- apps/client/src/app/pages/portfolio/portfolio-page.routes.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/client/src/app/pages/portfolio/portfolio-page.routes.ts b/apps/client/src/app/pages/portfolio/portfolio-page.routes.ts index aeebf4a6b7..70dd307807 100644 --- a/apps/client/src/app/pages/portfolio/portfolio-page.routes.ts +++ b/apps/client/src/app/pages/portfolio/portfolio-page.routes.ts @@ -24,6 +24,11 @@ export const routes: Routes = [ loadChildren: () => import('./allocations/allocations-page.routes').then((m) => m.routes) }, + { + path: internalRoutes.portfolio.subRoutes.targets.path, + loadChildren: () => + import('./targets/targets-page.routes').then((m) => m.routes) + }, { path: internalRoutes.portfolio.subRoutes.fire.path, loadChildren: () => From d6682304552e0b29a4cf91fe3ef029525f6278af Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:08:49 +0100 Subject: [PATCH 21/32] feat(targets): add Targets between Allocations and FIRE --- .../src/app/pages/portfolio/portfolio-page.component.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/apps/client/src/app/pages/portfolio/portfolio-page.component.ts b/apps/client/src/app/pages/portfolio/portfolio-page.component.ts index f921654878..2539ee686a 100644 --- a/apps/client/src/app/pages/portfolio/portfolio-page.component.ts +++ b/apps/client/src/app/pages/portfolio/portfolio-page.component.ts @@ -18,6 +18,7 @@ import { analyticsOutline, calculatorOutline, pieChartOutline, + flagOutline, scanOutline, swapVerticalOutline } from 'ionicons/icons'; @@ -61,6 +62,11 @@ export class PortfolioPageComponent { routerLink: internalRoutes.portfolio.subRoutes.allocations.routerLink }, + { + iconName: 'flag-outline', + label: internalRoutes.portfolio.subRoutes.targets.title, + routerLink: internalRoutes.portfolio.subRoutes.targets.routerLink + }, { iconName: 'calculator-outline', label: internalRoutes.portfolio.subRoutes.fire.title, @@ -81,6 +87,7 @@ export class PortfolioPageComponent { addIcons({ analyticsOutline, calculatorOutline, + flagOutline, pieChartOutline, scanOutline, swapVerticalOutline From 989302b8d5c3afa6382e82feda43be056affafd6 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:09:19 +0100 Subject: [PATCH 22/32] fix(targets): correct account typing and stable chart inputs --- .../app/pages/portfolio/targets/targets-page.component.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts index 419275bb46..acf2ad900e 100644 --- a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts @@ -53,8 +53,6 @@ export class GfTargetsPageComponent implements OnInit { protected isSaving = false; protected hasError = false; protected canEdit = false; - protected readonly UNKNOWN_KEY = UNKNOWN_KEY; - protected readonly classes = Object.values(AssetClass); protected readonly labels: Record = Object.fromEntries( Object.values(AssetClass).map((assetClass) => [assetClass, translate(assetClass)]) ); @@ -90,11 +88,7 @@ export class GfTargetsPageComponent implements OnInit { } protected get accounts() { - return (this.user?.accounts ?? []).filter((account) => !account.isExcluded); - } - - protected get usableResult() { - return this.result?.status === 'ready'; + return this.user?.accounts ?? []; } protected get hasReadValues() { From 1d842cda70421ef08fe33142c0b5dfa2a4e8eef9 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:09:22 +0100 Subject: [PATCH 23/32] fix(targets): correct account typing and stable chart inputs --- apps/client/src/app/pages/portfolio/targets/targets-page.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.html b/apps/client/src/app/pages/portfolio/targets/targets-page.html index 1690657b48..9cb395e012 100644 --- a/apps/client/src/app/pages/portfolio/targets/targets-page.html +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.html @@ -129,7 +129,7 @@ {{ formatClass(row.assetClass) }} {{ row.actual * 100 | number: '1.0-2' }}% {{ row.target * 100 | number: '1.0-2' }}% - {{ row.drift * 100 | number: '+1.0-2' }}% + {{ row.drift >= 0 ? '+' : '' }}{{ row.drift * 100 | number: '1.0-2' }}% @if (row.outOfTolerance) { Outside tolerance From b1fa3e25ba47d903f1b9a2420b2791ad2ec9c98e Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:09:25 +0100 Subject: [PATCH 24/32] fix(targets): correct account typing and stable chart inputs --- .../targets/target-configuration-dialog.component.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts index d96444d5b7..b12d391493 100644 --- a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts @@ -37,7 +37,7 @@ export class GfTargetConfigurationDialogComponent { protected readonly presets = TARGET_PRESETS; protected profile: PortfolioTargetProfile; - private readonly data = inject<{ + protected readonly data = inject<{ profile?: PortfolioTargetProfile; user: User; }>(MAT_DIALOG_DATA); @@ -54,10 +54,13 @@ export class GfTargetConfigurationDialogComponent { ...(this.data.profile ?? defaultProfile), allocations: { ...(this.data.profile?.allocations ?? defaultProfile.allocations) } }; + this.updateChartData(); } - protected get chartData() { - return Object.fromEntries(this.classes.map((assetClass) => [ + protected chartData: Record = {}; + + private updateChartData() { + this.chartData = Object.fromEntries(this.classes.map((assetClass) => [ assetClass, { name: this.labels[assetClass], @@ -87,6 +90,7 @@ export class GfTargetConfigurationDialogComponent { ...next, tolerance: this.profile.tolerance }; + this.updateChartData(); } protected updateAllocation(assetClass: AssetClass, percent: number) { @@ -98,6 +102,7 @@ export class GfTargetConfigurationDialogComponent { [assetClass]: Number(percent) / 100 } }; + this.updateChartData(); } protected updateTolerance(percent: number) { From a50e9dcbdd5d193958f950d29ac7f68f9eb9b6b8 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:10:08 +0100 Subject: [PATCH 25/32] fix(targets): identify custom presets and flag unclassified holdings --- .../portfolio/targets/target-configuration-dialog.component.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts index b12d391493..30881303c1 100644 --- a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts @@ -97,6 +97,7 @@ export class GfTargetConfigurationDialogComponent { this.profile = { ...this.profile, presetId: undefined, + name: $localize`Custom`, allocations: { ...this.profile.allocations, [assetClass]: Number(percent) / 100 From 0a2c63325ee951cf737564448920eadb5e8119c0 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:10:11 +0100 Subject: [PATCH 26/32] fix(targets): identify custom presets and flag unclassified holdings --- .../app/pages/portfolio/targets/targets-page.component.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts index acf2ad900e..e122d80a5c 100644 --- a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts @@ -1,6 +1,6 @@ import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service'; import { UserService } from '@ghostfolio/client/services/user/user.service'; -import { UNKNOWN_KEY } from '@ghostfolio/common/config'; +import { TAG_ID_EXCLUDE_FROM_ANALYSIS, UNKNOWN_KEY } from '@ghostfolio/common/config'; import { Filter, PortfolioTargetProfile, User } from '@ghostfolio/common/interfaces'; import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { @@ -88,7 +88,9 @@ export class GfTargetsPageComponent implements OnInit { } protected get accounts() { - return this.user?.accounts ?? []; + return (this.user?.accounts ?? []).filter((account) => + !account.tags?.some(({ id }) => id === TAG_ID_EXCLUDE_FROM_ANALYSIS) + ); } protected get hasReadValues() { From 7e422923e2d6a3909c2e6a5e492fe5b256e9bbbd Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:10:13 +0100 Subject: [PATCH 27/32] fix(targets): identify custom presets and flag unclassified holdings --- .../src/lib/portfolio-targets/portfolio-targets-calculator.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts index 6ba18e74e6..23db53a9cf 100644 --- a/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-calculator.ts @@ -184,6 +184,6 @@ export function calculatePortfolioTargets({ maxDrift: Math.max(...drifts), outOfToleranceCount: rows.filter(({ outOfTolerance }) => outOfTolerance).length, unclassifiedValue, - status: unclassifiedValue > 0 ? 'inconsistent' : 'ready' + status: 'ready' }; } From 0f5afc3f4c7d90bc90f38f12bacea210f07d0236 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:10:16 +0100 Subject: [PATCH 28/32] fix(targets): identify custom presets and flag unclassified holdings --- .../client/src/app/pages/portfolio/targets/targets-page.html | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.html b/apps/client/src/app/pages/portfolio/targets/targets-page.html index 9cb395e012..5b829158f7 100644 --- a/apps/client/src/app/pages/portfolio/targets/targets-page.html +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.html @@ -65,6 +65,11 @@ } @else { + @if (result.unclassifiedValue > 0) { +

+ Some holdings have no asset classification. The reported allocation is incomplete. +

+ }
From c0b30298a246177b3a9b483167da18a64387df3c Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:11:02 +0100 Subject: [PATCH 29/32] refactor(targets): share preset definitions with common model --- .../pages/portfolio/targets/target-presets.ts | 29 +++++++------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/apps/client/src/app/pages/portfolio/targets/target-presets.ts b/apps/client/src/app/pages/portfolio/targets/target-presets.ts index 39a73e4e04..7488a64fe9 100644 --- a/apps/client/src/app/pages/portfolio/targets/target-presets.ts +++ b/apps/client/src/app/pages/portfolio/targets/target-presets.ts @@ -1,29 +1,22 @@ import { PortfolioTargetProfile } from '@ghostfolio/common/interfaces'; -import { AssetClass } from '@ghostfolio/prisma/enums'; +import { PORTFOLIO_TARGET_PRESETS } from '@ghostfolio/common/portfolio-targets/portfolio-targets-presets'; -export const TARGET_PRESETS = [ - { id: 'cautious', label: $localize`Cautious (20/80)`, equity: 20, bonds: 80, commodities: 0 }, - { id: 'conservative', label: $localize`Conservative (40/60)`, equity: 40, bonds: 60, commodities: 0 }, - { id: 'moderate', label: $localize`Moderate (60/40)`, equity: 60, bonds: 40, commodities: 0 }, - { id: 'aggressive', label: $localize`Aggressive (80/20)`, equity: 80, bonds: 20, commodities: 0 }, - { id: 'golden-butterfly', label: $localize`Golden Butterfly (simplified)`, equity: 40, bonds: 40, commodities: 20 } -] as const; +/** The user-visible presets share the same source as the default model. */ +export const TARGET_PRESETS = PORTFOLIO_TARGET_PRESETS.map(({ id, name }) => ({ + id, + label: name +})); export function createTargetFromPreset(presetId: string): PortfolioTargetProfile { - const preset = TARGET_PRESETS.find(({ id }) => id === presetId) ?? TARGET_PRESETS[2]; + const preset = + PORTFOLIO_TARGET_PRESETS.find(({ id }) => id === presetId) ?? + PORTFOLIO_TARGET_PRESETS[2]; return { id: 'global', - name: preset.label, + name: preset.name, presetId: preset.id, tolerance: 0.05, - allocations: { - [AssetClass.ALTERNATIVE_INVESTMENT]: 0, - [AssetClass.COMMODITY]: preset.commodities / 100, - [AssetClass.EQUITY]: preset.equity / 100, - [AssetClass.FIXED_INCOME]: preset.bonds / 100, - [AssetClass.LIQUIDITY]: 0, - [AssetClass.REAL_ESTATE]: 0 - } + allocations: { ...preset.allocations } }; } From 8f74eddeac7ab5442c48dd06891c1acedac64d51 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:11:22 +0100 Subject: [PATCH 30/32] refactor(targets): align preset names with planned risk profiles --- .../src/lib/portfolio-targets/portfolio-targets-presets.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts index 747970c0d2..f42a8599a5 100644 --- a/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.ts @@ -30,8 +30,8 @@ function makePreset( /** Editable starting points, not investment recommendations. */ export const PORTFOLIO_TARGET_PRESETS: PortfolioTargetPreset[] = [ - makePreset('conservative-20-80', $localize`Conservative (20/80)`, 0.2, 0.8), - makePreset('cautious-40-60', $localize`Cautious (40/60)`, 0.4, 0.6), + makePreset('cautious-20-80', $localize`Cautious (20/80)`, 0.2, 0.8), + makePreset('conservative-40-60', $localize`Conservative (40/60)`, 0.4, 0.6), makePreset('moderate-60-40', $localize`Moderate (60/40)`, 0.6, 0.4), makePreset('aggressive-80-20', $localize`Aggressive (80/20)`, 0.8, 0.2), makePreset('golden-butterfly', 'Golden Butterfly', 0.4, 0.4, 0.2) From af63e9246b26cd466e01c3d7b54f7106c6ff3067 Mon Sep 17 00:00:00 2001 From: PJ Date: Wed, 18 Nov 2026 21:11:36 +0100 Subject: [PATCH 31/32] test(targets): cover preset totals and editable copies --- .../portfolio-targets-presets.spec.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-presets.spec.ts diff --git a/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.spec.ts b/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.spec.ts new file mode 100644 index 0000000000..c4735879c3 --- /dev/null +++ b/libs/common/src/lib/portfolio-targets/portfolio-targets-presets.spec.ts @@ -0,0 +1,35 @@ +import { AssetClass } from '@ghostfolio/prisma/enums'; + +import { + createDefaultPortfolioTarget, + PORTFOLIO_TARGET_PRESETS +} from './portfolio-targets-presets'; +import { isValidPortfolioTarget } from './portfolio-targets-calculator'; + +describe('Portfolio target presets', () => { + it('provides five valid, editable starting points', () => { + expect(PORTFOLIO_TARGET_PRESETS).toHaveLength(5); + for (const { allocations } of PORTFOLIO_TARGET_PRESETS) { + expect(isValidPortfolioTarget(allocations, 0.05)).toBe(true); + } + }); + + it('keeps the original global default independent from the presets', () => { + const target = createDefaultPortfolioTarget(); + target.allocations[AssetClass.EQUITY] = 0.1; + + expect(PORTFOLIO_TARGET_PRESETS[2].allocations[AssetClass.EQUITY]).toBe(0.6); + expect(target.tolerance).toBe(0.05); + expect(target.id).toBe('global'); + }); + + it('represents Golden Butterfly at macro-class level', () => { + const butterfly = PORTFOLIO_TARGET_PRESETS.find( + ({ id }) => id === 'golden-butterfly' + ); + + expect(butterfly?.allocations[AssetClass.EQUITY]).toBe(0.4); + expect(butterfly?.allocations[AssetClass.FIXED_INCOME]).toBe(0.4); + expect(butterfly?.allocations[AssetClass.COMMODITY]).toBe(0.2); + }); +}); From 1f7e7bc1ab911eb36d8cd47c47ca3de0d4ff9993 Mon Sep 17 00:00:00 2001 From: Piggei Date: Thu, 19 Nov 2026 23:42:07 +0100 Subject: [PATCH 32/32] feat(targets): finalize portfolio targets with independent cash reconciliation --- .../users/user-targets-settings.spec.ts | 133 ++++ .../app/endpoints/users/user.controller.ts | 6 + .../portfolio-targets-details.spec.ts | 216 ++++++ .../src/app/portfolio/portfolio.controller.ts | 14 +- .../app/portfolio/portfolio.service.spec.ts | 136 ++++ .../src/app/portfolio/portfolio.service.ts | 1 + apps/api/src/helper/object.helper.spec.ts | 8 + ...target-configuration-dialog.component.html | 33 +- ...get-configuration-dialog.component.spec.ts | 116 ++++ .../target-configuration-dialog.component.ts | 47 +- .../targets/target-percent.pipe.spec.ts | 33 + .../portfolio/targets/target-percent.pipe.ts | 34 + .../pages/portfolio/targets/target-presets.ts | 29 +- .../targets/targets-page.component.spec.ts | 382 +++++++++++ .../targets/targets-page.component.ts | 247 +++++-- .../pages/portfolio/targets/targets-page.html | 189 ++++-- .../pages/portfolio/targets/targets-page.scss | 126 +++- apps/client/src/locales/messages.ca.xlf | 378 ++++++++++- apps/client/src/locales/messages.de.xlf | 364 ++++++++++ apps/client/src/locales/messages.es.xlf | 364 ++++++++++ apps/client/src/locales/messages.fr.xlf | 376 ++++++++++- apps/client/src/locales/messages.it.xlf | 376 ++++++++++- apps/client/src/locales/messages.ja.xlf | 376 ++++++++++- apps/client/src/locales/messages.ko.xlf | 376 ++++++++++- apps/client/src/locales/messages.nl.xlf | 376 ++++++++++- apps/client/src/locales/messages.pl.xlf | 376 ++++++++++- apps/client/src/locales/messages.pt.xlf | 376 ++++++++++- apps/client/src/locales/messages.tr.xlf | 364 ++++++++++ apps/client/src/locales/messages.uk.xlf | 376 ++++++++++- apps/client/src/locales/messages.xlf | 322 +++++++++ apps/client/src/locales/messages.zh.xlf | 364 ++++++++++ apps/client/src/styles.scss | 12 + libs/common/src/lib/config.ts | 1 + .../src/lib/dtos/update-user-setting.dto.ts | 15 +- .../interfaces/portfolio-summary.interface.ts | 7 + .../portfolio-targets-calculator.spec.ts | 629 +++++++++++++++++- .../portfolio-targets-calculator.ts | 180 ++++- .../portfolio-targets-dto.spec.ts | 50 ++ .../portfolio-targets-presets.spec.ts | 6 +- .../portfolio-targets-presets.ts | 10 +- .../portfolio-targets-validation.spec.ts | 66 +- .../portfolio-targets-validation.ts | 7 +- 42 files changed, 7609 insertions(+), 288 deletions(-) create mode 100644 apps/api/src/app/endpoints/users/user-targets-settings.spec.ts create mode 100644 apps/api/src/app/portfolio/portfolio-targets-details.spec.ts create mode 100644 apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.spec.ts create mode 100644 apps/client/src/app/pages/portfolio/targets/target-percent.pipe.spec.ts create mode 100644 apps/client/src/app/pages/portfolio/targets/target-percent.pipe.ts create mode 100644 apps/client/src/app/pages/portfolio/targets/targets-page.component.spec.ts create mode 100644 libs/common/src/lib/portfolio-targets/portfolio-targets-dto.spec.ts diff --git a/apps/api/src/app/endpoints/users/user-targets-settings.spec.ts b/apps/api/src/app/endpoints/users/user-targets-settings.spec.ts new file mode 100644 index 0000000000..eccef49e00 --- /dev/null +++ b/apps/api/src/app/endpoints/users/user-targets-settings.spec.ts @@ -0,0 +1,133 @@ +import { UserSettings } from '@ghostfolio/common/interfaces'; +import { permissions } from '@ghostfolio/common/permissions'; +import { createDefaultPortfolioTarget } from '@ghostfolio/common/portfolio-targets/portfolio-targets-presets'; +import { + ImpersonationContext, + RequestWithUser +} from '@ghostfolio/common/types'; + +import { UserController } from './user.controller'; + +jest.mock( + '@ghostfolio/api/services/configuration/configuration.service', + () => ({ ConfigurationService: class {} }) +); +jest.mock('@ghostfolio/api/services/property/property.service', () => ({ + PropertyService: class {} +})); +jest.mock('@ghostfolio/api/services/user/user.service', () => ({ + UserService: class {} +})); + +const context = { isActive: false } as ImpersonationContext; + +describe('User controller target settings replacement and authorization', () => { + function setup(allowed = true) { + const oldProfile = { + ...createDefaultPortfolioTarget(), + presetId: 'old-preset' + }; + const previous = { + locale: 'it-IT', + isExperimentalFeatures: true, + portfolioTargets: { + version: 1 as const, + activeProfileId: 'global', + profiles: [oldProfile, { ...oldProfile, id: 'stale' }] + } + }; + const request = { + user: { + id: 'owner', + role: 'USER', + permissions: allowed ? [permissions.updateUserSettings] : [], + settings: { settings: previous } + } + } as unknown as RequestWithUser; + const updateUserSetting = jest.fn(({ userSettings }) => + Promise.resolve(userSettings) + ); + const controller = new UserController( + undefined, + undefined, + undefined, + request, + { updateUserSetting } as never + ); + return { controller, previous, updateUserSetting }; + } + + it('replaces profiles and removed preset metadata while preserving unrelated settings', async () => { + const { controller, previous, updateUserSetting } = setup(); + const profile = createDefaultPortfolioTarget(); + delete profile.presetId; + profile.name = 'Custom'; + const portfolioTargets = { + version: 1 as const, + activeProfileId: 'global', + profiles: [profile] + }; + const saved = (await controller.updateUserSetting( + { portfolioTargets }, + context + )) as UserSettings; + expect(saved).toEqual({ + locale: 'it-IT', + isExperimentalFeatures: true, + portfolioTargets + }); + expect(saved.portfolioTargets.profiles).toHaveLength(1); + expect(saved.portfolioTargets.profiles[0]).not.toHaveProperty('presetId'); + expect(previous.portfolioTargets.profiles).toHaveLength(2); + expect(updateUserSetting).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'owner', + emitPortfolioChangedEvent: false + }) + ); + }); + + it('preserves targets on unrelated updates', async () => { + const { controller, previous } = setup(); + const saved = (await controller.updateUserSetting( + { locale: 'en-US' }, + context + )) as UserSettings; + expect(saved.portfolioTargets).toEqual(previous.portfolioTargets); + expect(saved.locale).toBe('en-US'); + }); + + it('rejects users without settings permission', async () => { + const { controller, updateUserSetting } = setup(false); + await expect( + controller.updateUserSetting( + { + portfolioTargets: { + version: 1, + activeProfileId: 'global', + profiles: [createDefaultPortfolioTarget()] + } + }, + context + ) + ).rejects.toMatchObject({ status: 403 }); + expect(updateUserSetting).not.toHaveBeenCalled(); + }); + + it('rejects target writes during impersonation', async () => { + const { controller, updateUserSetting } = setup(); + await expect( + controller.updateUserSetting( + { + portfolioTargets: { + version: 1, + activeProfileId: 'global', + profiles: [createDefaultPortfolioTarget()] + } + }, + { isActive: true } as ImpersonationContext + ) + ).rejects.toMatchObject({ status: 403 }); + expect(updateUserSetting).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/app/endpoints/users/user.controller.ts b/apps/api/src/app/endpoints/users/user.controller.ts index 326e38bb41..5613251f57 100644 --- a/apps/api/src/app/endpoints/users/user.controller.ts +++ b/apps/api/src/app/endpoints/users/user.controller.ts @@ -227,6 +227,12 @@ export class UserController { data ); + // Targets are a versioned document: arrays and optional preset metadata + // must be replaced rather than merged with the previous profile. + if (data.portfolioTargets !== undefined) { + userSettings.portfolioTargets = data.portfolioTargets; + } + if (userSettings['filters.dataSource']) { userSettings['filters.dataSource'] = decodeDataSource( userSettings['filters.dataSource'] diff --git a/apps/api/src/app/portfolio/portfolio-targets-details.spec.ts b/apps/api/src/app/portfolio/portfolio-targets-details.spec.ts new file mode 100644 index 0000000000..e1f61a7aa9 --- /dev/null +++ b/apps/api/src/app/portfolio/portfolio-targets-details.spec.ts @@ -0,0 +1,216 @@ +import { RedactValuesInResponseInterceptor } from '@ghostfolio/api/interceptors/redact-values-in-response/redact-values-in-response.interceptor'; +import { SubscriptionType } from '@ghostfolio/common/enums'; +import { PortfolioDetails } from '@ghostfolio/common/interfaces'; +import { scopes } from '@ghostfolio/common/scopes'; +import { + ImpersonationContext, + RequestWithUser +} from '@ghostfolio/common/types'; + +import { lastValueFrom, of } from 'rxjs'; + +import { GetDetailsDto } from './get-details.dto'; +import { PortfolioController } from './portfolio.controller'; + +jest.mock('@ghostfolio/api/services/activities/activities.service', () => ({ + ActivitiesService: class {} +})); +jest.mock('@ghostfolio/api/services/api/api.service', () => ({ + ApiService: class {} +})); +jest.mock( + '@ghostfolio/api/services/configuration/configuration.service', + () => ({ ConfigurationService: class {} }) +); +jest.mock('./portfolio.service', () => ({ PortfolioService: class {} })); + +function holding() { + return { + investment: 600, + marketPrice: 100, + quantity: 6, + valueInBaseCurrency: 600, + assetProfile: { + assetClass: 'EQUITY', + assetSubClass: null, + name: 'Synthetic equity' + }, + markets: undefined, + marketsAdvanced: undefined + } as unknown as PortfolioDetails['holdings'][number]; +} + +async function details( + holdings = [holding()], + hasErrors = false, + readValues = true, + options: { + restricted?: boolean; + subscription?: SubscriptionType; + enableSubscription?: boolean; + } = {} +) { + const controller = new PortfolioController( + undefined, + { buildFiltersFromQueryParams: () => [] } as never, + { get: () => !!options.enableSubscription } as never, + { + getDetails: async () => ({ + holdings, + hasErrors, + accounts: {}, + platforms: {}, + summary: { + accountCashInBaseCurrency: 100, + cash: 100, + emergencyFund: { cash: 0 }, + filteredValueInBaseCurrency: 600 + } + }) + } as never, + { + user: { + subscription: { type: options.subscription }, + settings: { settings: { isRestrictedView: !!options.restricted } } + } + } as unknown as RequestWithUser + ); + return controller.getDetails( + { + userId: 'synthetic', + scopes: readValues ? [scopes.portfolioReadValues] : [] + } as ImpersonationContext, + {} as GetDetailsDto + ); +} + +describe('Portfolio details financial error flag for Targets', () => { + it('allows valid values with missing optional market/profile metadata', async () => { + expect((await details()).hasError).toBe(false); + }); + + it('allows unknown asset classification without inventing one', async () => { + const value = holding(); + value.assetProfile.assetClass = null; + const result = await details([value]); + expect(result.hasError).toBe(false); + expect(result.holdings[0].assetProfile.assetClass).toBeNull(); + }); + + it.each([undefined, null, NaN, Infinity])( + 'flags invalid financial value %s in a later holding', + async (value) => { + const bad = { ...holding(), valueInBaseCurrency: value }; + expect((await details([holding(), bad])).hasError).toBe(true); + } + ); + + it.each(['investment', 'marketPrice', 'quantity'])( + 'flags a missing %s', + async (field) => { + const bad = { ...holding(), [field]: undefined }; + expect((await details([bad])).hasError).toBe(true); + } + ); + + it('preserves genuine calculator errors', async () => { + expect((await details([holding()], true)).hasError).toBe(true); + }); + + it('does not label finite negative positions as a data error', async () => { + expect( + ( + await details([ + { ...holding(), quantity: -1, valueInBaseCurrency: -100 } + ]) + ).hasError + ).toBe(false); + }); + + it('keeps restricted monetary summary fields redacted', async () => { + expect((await details([holding()], false, false)).summary.cash).toBeNull(); + }); + + it.each([ + { + readValues: true, + restricted: false, + enableSubscription: false, + subscription: undefined, + masked: false + }, + { + readValues: false, + restricted: false, + enableSubscription: false, + subscription: undefined, + masked: true + }, + { + readValues: true, + restricted: true, + enableSubscription: false, + subscription: undefined, + masked: true + }, + { + readValues: true, + restricted: false, + enableSubscription: true, + subscription: SubscriptionType.Basic, + masked: true + }, + { + readValues: true, + restricted: false, + enableSubscription: true, + subscription: SubscriptionType.Premium, + masked: false + } + ])( + 'protects independent cash under controller permissions: %j', + async ({ readValues, masked, ...options }) => { + const result = await details([holding()], false, readValues, options); + expect(result.summary.accountCashInBaseCurrency).toBe( + masked ? null : 100 + ); + expect(result.summary.cash).toBe(masked ? null : 100); + } + ); + + it.each([ + { + readValues: true, + restricted: false, + missingContext: false, + masked: false + }, + { + readValues: false, + restricted: false, + missingContext: false, + masked: true + }, + { readValues: true, restricted: true, missingContext: false, masked: true }, + { readValues: true, restricted: false, missingContext: true, masked: true } + ])( + 'protects independent cash through the response interceptor: %j', + async ({ readValues, restricted, missingContext, masked }) => { + const request = { + impersonation: missingContext + ? undefined + : { scopes: readValues ? [scopes.portfolioReadValues] : [] }, + user: { settings: { settings: { isRestrictedView: restricted } } } + }; + const result = await lastValueFrom( + new RedactValuesInResponseInterceptor().intercept( + { switchToHttp: () => ({ getRequest: () => request }) } as never, + { handle: () => of({ summary: { accountCashInBaseCurrency: 100 } }) } + ) + ); + expect(result.summary.accountCashInBaseCurrency).toBe( + masked ? null : 100 + ); + } + ); +}); diff --git a/apps/api/src/app/portfolio/portfolio.controller.ts b/apps/api/src/app/portfolio/portfolio.controller.ts index 8d4e081d7f..ba176728d5 100644 --- a/apps/api/src/app/portfolio/portfolio.controller.ts +++ b/apps/api/src/app/portfolio/portfolio.controller.ts @@ -2,7 +2,6 @@ import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorat import { Impersonation } from '@ghostfolio/api/decorators/impersonation.decorator'; import { RequiresScope } from '@ghostfolio/api/decorators/requires-scope.decorator'; import { - hasNotDefinedValuesInObject, nullifyValuesInObject, nullifyValuesInObjects } from '@ghostfolio/api/helper/object.helper'; @@ -121,7 +120,17 @@ export class PortfolioController { withSummary: true }); - if (hasErrors || hasNotDefinedValuesInObject(holdings)) { + // Optional profile/market metadata may be absent on a valid holding. + // Check the financial values of every holding instead of recursively + // treating missing metadata as a valuation error. + const hasInvalidHoldingValues = holdings.some( + ({ investment, marketPrice, quantity, valueInBaseCurrency }) => + [investment, marketPrice, quantity, valueInBaseCurrency].some( + (value) => !Number.isFinite(value) + ) + ); + + if (hasErrors || hasInvalidHoldingValues) { hasError = true; } @@ -147,6 +156,7 @@ export class PortfolioController { }); portfolioSummary = nullifyValuesInObject(summary, [ + 'accountCashInBaseCurrency', 'cash', 'currentNetWorth', 'currentValueInBaseCurrency', diff --git a/apps/api/src/app/portfolio/portfolio.service.spec.ts b/apps/api/src/app/portfolio/portfolio.service.spec.ts index 3994dc7c93..cc879ece55 100644 --- a/apps/api/src/app/portfolio/portfolio.service.spec.ts +++ b/apps/api/src/app/portfolio/portfolio.service.spec.ts @@ -2,6 +2,7 @@ import { PortfolioCalculator } from '@ghostfolio/api/app/portfolio/calculator/po import { userDummyData } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator-test-utils'; import { PortfolioCalculatorFactory } from '@ghostfolio/api/app/portfolio/calculator/portfolio-calculator.factory'; import { CurrentRateService } from '@ghostfolio/api/app/portfolio/current-rate.service'; +import { WHERE_ACCOUNT_NOT_EXCLUDED } from '@ghostfolio/api/helper/account.helper'; import { AccountBalanceService } from '@ghostfolio/api/services/account-balance/account-balance.service'; import { AccountService } from '@ghostfolio/api/services/account/account.service'; import { CashDetails } from '@ghostfolio/api/services/account/interfaces/cash-details.interface'; @@ -430,6 +431,45 @@ describe('PortfolioService', () => { }); }); + describe('independent account cash selection', () => { + it.each([false, true])( + 'preserves exclusion and account-selection constraints (selected: %s)', + async (selected) => { + const filters: Filter[] = selected + ? [{ type: 'ACCOUNT', id: 'euro' }] + : []; + const euro = { id: 'euro', balance: 20, currency: 'EUR' }; + const dollar = { id: 'dollar', balance: 60, currency: 'USD' }; + const accounts = ( + selected ? [euro] : [euro, dollar] + ) as AccountWithBalance[]; + const accountsSpy = jest + .spyOn(accountService, 'accounts') + .mockResolvedValue(accounts); + const conversion = jest + .spyOn(exchangeRateDataService, 'toCurrency') + .mockImplementation((value, currency) => + currency === 'EUR' ? value * 2 : value + ); + const result = await accountService.getCashDetails({ + userId: userDummyData.id, + currency: 'USD', + filters + }); + expect(accountsSpy).toHaveBeenCalledWith({ + where: { + userId: userDummyData.id, + AND: [WHERE_ACCOUNT_NOT_EXCLUDED], + ...(selected ? { id: { in: ['euro'] } } : {}) + } + }); + expect(result.balanceInBaseCurrency).toBe(selected ? 40 : 100); + expect(result.accounts).toEqual(accounts); + expect(conversion).toHaveBeenCalledTimes(accounts.length); + } + ); + }); + describe('getDetails', () => { const setUpCashOnlyPortfolio = ({ baseCurrency = 'CHF', @@ -546,6 +586,46 @@ describe('PortfolioService', () => { .mockResolvedValue({ accounts: {}, platforms: {} }); }; + it.each([ + { filters: [] as Filter[] }, + { filters: [{ type: 'ACCOUNT', id: 'selected-account' }] as Filter[] } + ])( + 'passes the existing filtered cash result to the summary: %j', + async ({ filters }) => { + setUpCashOnlyPortfolio(); + const summarySpy = jest + .spyOn( + portfolioService as unknown as { + getSummary: (args: { + balanceInBaseCurrency: number; + }) => Promise; + }, + 'getSummary' + ) + .mockImplementation( + async ({ balanceInBaseCurrency }) => + ({ + accountCashInBaseCurrency: balanceInBaseCurrency + }) as PortfolioSummary + ); + const result = await portfolioService.getDetails({ + filters, + userId: userDummyData.id, + withSummary: true + }); + expect(accountService.getCashDetails).toHaveBeenCalledTimes(1); + expect(accountService.getCashDetails).toHaveBeenCalledWith({ + filters, + userId: userDummyData.id, + currency: 'CHF' + }); + expect(summarySpy).toHaveBeenCalledWith( + expect.objectContaining({ balanceInBaseCurrency: 1820 }) + ); + expect(result.summary.accountCashInBaseCurrency).toBe(1820); + } + ); + it('should return cash holdings when the calculator emits cash positions with the exchange-rate data source', async () => { setUpCashOnlyPortfolio(); @@ -1356,6 +1436,38 @@ describe('PortfolioService', () => { } as unknown as Awaited>); }); + it.each([ + { balance: 0.01, fund: 10000 }, + { balance: 100, fund: 3e15 }, + { balance: 100, fund: 1e16 } + ])( + 'exposes account cash unchanged by fund adjustments: %j', + async ({ balance, fund }) => { + jest + .spyOn(accountService, 'getCashDetails') + .mockResolvedValue({ accounts: [], balanceInBaseCurrency: balance }); + jest.spyOn(userService, 'user').mockResolvedValue({ + id: userDummyData.id, + settings: { settings: { baseCurrency: 'CHF', emergencyFund: fund } } + } as unknown as Awaited>); + const summary = await getSummary({ + portfolioCalculator: createPortfolioCalculator(), + balanceInBaseCurrency: balance, + emergencyFundHoldingsValueInBaseCurrency: 0, + filteredValueInBaseCurrency: new Big(3000), + userCurrency: 'CHF', + userId: userDummyData.id + }); + expect(summary.accountCashInBaseCurrency).toBe(balance); + expect(summary.cash).toBe(new Big(balance).minus(fund).toNumber()); + expect(summary.emergencyFund.cash).toBe(fund); + expect(summary.totalCashInBaseCurrency).toBe(1000); + // Only the pre-existing excluded-account lookup occurs in getSummary. + expect(accountService.getCashDetails).toHaveBeenCalledTimes(1); + expect(exchangeRateDataService.toCurrency).not.toHaveBeenCalled(); + } + ); + it('should derive the cash and net worth from the account balance when there are no excluded accounts, no emergency fund and no liabilities', async () => { jest.spyOn(accountService, 'getCashDetails').mockResolvedValue({ accounts: [], @@ -1877,6 +1989,30 @@ describe('PortfolioService', () => { expect(platforms[account.platformId].valueInBaseCurrency).toBe(110); }); + it('keeps permanently excluded accounts out of account totals', async () => { + const excluded = { + ...account, + id: 'excluded', + balance: 5000, + tags: [{ id: TAG_ID_EXCLUDE_FROM_ANALYSIS }] + }; + jest + .spyOn(accountService, 'getAccounts') + .mockResolvedValue([ + account, + excluded + ] as unknown as AccountWithBalance[]); + const { accounts } = await getValueOfAccountsAndPlatforms({ + activities: [], + filters: [], + portfolioItemsNow: {}, + userCurrency: 'USD', + userId: userDummyData.id + }); + expect(Object.keys(accounts)).toEqual([account.id]); + expect(accounts[account.id].valueInBaseCurrency).toBe(100); + }); + it('should not accumulate rounding errors of the balances of accounts sharing a platform', async () => { const platformId = randomUUID(); diff --git a/apps/api/src/app/portfolio/portfolio.service.ts b/apps/api/src/app/portfolio/portfolio.service.ts index 8cb3ce9f1f..00f9ad31e0 100644 --- a/apps/api/src/app/portfolio/portfolio.service.ts +++ b/apps/api/src/app/portfolio/portfolio.service.ts @@ -2289,6 +2289,7 @@ export class PortfolioService { })?.toNumber(); return { + accountCashInBaseCurrency: balanceInBaseCurrency, annualizedPerformancePercent, annualizedPerformancePercentWithCurrencyEffect, cash, diff --git a/apps/api/src/helper/object.helper.spec.ts b/apps/api/src/helper/object.helper.spec.ts index e74fd2db47..994197da18 100644 --- a/apps/api/src/helper/object.helper.spec.ts +++ b/apps/api/src/helper/object.helper.spec.ts @@ -27,6 +27,14 @@ describe('query', () => { }); describe('redactAttributes', () => { + it('redacts independent summary cash with the centralized paths', () => { + expect( + redactPaths({ + object: { summary: { accountCashInBaseCurrency: 0.01 } }, + paths: DEFAULT_REDACTED_PATHS + }) + ).toEqual({ summary: { accountCashInBaseCurrency: null } }); + }); it('should redact provided attributes', () => { expect(redactPaths({ object: {}, paths: [] })).toStrictEqual({}); diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html index a921785992..9932949d02 100644 --- a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.html @@ -1,13 +1,16 @@ -

Configure target

+

Configure target

Starting allocation - + @for (preset of presets; track preset.id) { {{ preset.label }} } - Custom + Custom

@@ -17,13 +20,14 @@

- Total: {{ total * 100 | number: '1.0-2' }}% + Total: + {{ total | targetPercent: data.user.settings.locale }}
@@ -33,10 +37,10 @@
Allowed deviation
@@ -64,13 +68,16 @@
@if (!isValid) {

- Each percentage must be between 0 and 100, and the total must equal 100%. + Each percentage must be between 0 and 100, and the total must equal + 100%.

}
- - + + diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.spec.ts b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.spec.ts new file mode 100644 index 0000000000..a61ab520a7 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.spec.ts @@ -0,0 +1,116 @@ +import { PortfolioTargetProfile, User } from '@ghostfolio/common/interfaces'; +import { createDefaultPortfolioTarget } from '@ghostfolio/common/portfolio-targets/portfolio-targets-presets'; +import { AssetClass } from '@ghostfolio/prisma/enums'; + +import { TestBed } from '@angular/core/testing'; +import '@angular/localize/init'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; + +import { GfTargetConfigurationDialogComponent } from './target-configuration-dialog.component'; +import { + createTargetFromPreset, + getTargetProfileName, + TARGET_PRESETS +} from './target-presets'; + +jest.mock('@ghostfolio/ui/i18n', () => ({ + translate: (value: string) => value +})); +jest.mock('@ghostfolio/ui/portfolio-proportion-chart', () => ({ + GfPortfolioProportionChartComponent: class {} +})); + +describe('Portfolio target configuration dialog', () => { + const close = jest.fn(); + function create(profile?: PortfolioTargetProfile) { + TestBed.configureTestingModule({ + providers: [ + { + provide: MAT_DIALOG_DATA, + useValue: { profile, user: { settings: {} } as User } + }, + { provide: MatDialogRef, useValue: { close } } + ] + }); + return TestBed.runInInjectionContext( + () => new GfTargetConfigurationDialogComponent() + ); + } + afterEach(() => { + TestBed.resetTestingModule(); + close.mockClear(); + }); + + it('starts with a valid moderate target for existing users without settings', () => { + const component = create(); + expect(component['profile'].presetId).toBe('moderate-60-40'); + expect(component['isValid']).toBe(true); + }); + + it('edits a copy and cancels without modifying persisted targets', () => { + const profile = createDefaultPortfolioTarget(); + const component = create(profile); + component['updateAllocation'](AssetClass.EQUITY, 50); + component['cancel'](); + expect(profile.allocations.EQUITY).toBe(0.6); + expect(close).toHaveBeenCalledWith(); + }); + + it('does not convert blank fields into valid zero allocations or tolerances', () => { + const component = create(); + component['updateTolerance'](null); + expect(component['isValid']).toBe(false); + component['updateTolerance'](5); + component['updateAllocation'](AssetClass.COMMODITY, null); + expect(component['isValid']).toBe(false); + component['save'](); + expect(close).not.toHaveBeenCalled(); + }); + + it('keeps tolerance when selecting a preset and invalidates the preset label on editing', () => { + const component = create(); + component['updateTolerance'](7); + component['applyPreset']('golden-butterfly'); + expect(component['profile'].tolerance).toBe(0.07); + expect(component['profile'].name).toBe('Golden Butterfly (simplified)'); + component['updateAllocation'](AssetClass.EQUITY, 35); + expect(component['profile'].presetId).toBeUndefined(); + expect(component['profile'].name).toBe('Custom'); + expect(component['chartData'][AssetClass.EQUITY].value).toBe(0.35); + expect(component['isValid']).toBe(false); + }); + + it('saves a valid profile and uses the same client label for each preset', () => { + const component = create(); + component['save'](); + expect(close).toHaveBeenCalledWith(component['profile']); + for (const { id, label } of TARGET_PRESETS) { + expect(getTargetProfileName(createTargetFromPreset(id))).toBe(label); + const modified = createTargetFromPreset(id); + modified.allocations.EQUITY = 0; + expect(createTargetFromPreset(id).allocations.EQUITY).toBeGreaterThan(0); + } + }); + it('resolves a stored preset in the active UI language without rewriting its name', () => { + const stored = createTargetFromPreset('moderate-60-40'); + const label = TARGET_PRESETS[2]; + const originalLabel = label.label; + try { + label.label = 'Moderato (60/40)'; + expect(getTargetProfileName(stored)).toBe('Moderato (60/40)'); + expect(stored.name).toBe('Moderate (60/40)'); + } finally { + label.label = originalLabel; + } + }); + + it('preserves a personal profile name while localizing generated labels', () => { + const stored = { + ...createDefaultPortfolioTarget(), + presetId: undefined, + name: 'Piano famiglia' + }; + expect(getTargetProfileName(stored)).toBe('Piano famiglia'); + expect(getTargetProfileName({ ...stored, name: 'Custom' })).toBe('Custom'); + }); +}); diff --git a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts index 30881303c1..cc352cb526 100644 --- a/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts +++ b/apps/client/src/app/pages/portfolio/targets/target-configuration-dialog.component.ts @@ -5,21 +5,25 @@ import { AssetClass } from '@ghostfolio/prisma/enums'; import { translate } from '@ghostfolio/ui/i18n'; import { GfPortfolioProportionChartComponent } from '@ghostfolio/ui/portfolio-proportion-chart'; -import { DecimalPipe } from '@angular/common'; import { ChangeDetectionStrategy, Component, inject } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; -import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; +import { + MAT_DIALOG_DATA, + MatDialogModule, + MatDialogRef +} from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatSelectModule } from '@angular/material/select'; +import { GfTargetPercentPipe } from './target-percent.pipe'; import { createTargetFromPreset, TARGET_PRESETS } from './target-presets'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, imports: [ - DecimalPipe, + GfTargetPercentPipe, FormsModule, GfPortfolioProportionChartComponent, MatButtonModule, @@ -42,17 +46,24 @@ export class GfTargetConfigurationDialogComponent { user: User; }>(MAT_DIALOG_DATA); private readonly dialogRef = - inject>(MatDialogRef); + inject< + MatDialogRef + >(MatDialogRef); protected readonly labels = Object.fromEntries( - TARGET_ASSET_CLASSES.map((assetClass) => [assetClass, translate(assetClass)]) + TARGET_ASSET_CLASSES.map((assetClass) => [ + assetClass, + translate(assetClass) + ]) ) as Record; public constructor() { - const defaultProfile = createTargetFromPreset('moderate'); + const defaultProfile = createTargetFromPreset('moderate-60-40'); this.profile = { ...(this.data.profile ?? defaultProfile), - allocations: { ...(this.data.profile?.allocations ?? defaultProfile.allocations) } + allocations: { + ...(this.data.profile?.allocations ?? defaultProfile.allocations) + } }; this.updateChartData(); } @@ -60,13 +71,15 @@ export class GfTargetConfigurationDialogComponent { protected chartData: Record = {}; private updateChartData() { - this.chartData = Object.fromEntries(this.classes.map((assetClass) => [ - assetClass, - { - name: this.labels[assetClass], - value: Math.max(0, this.profile.allocations[assetClass] ?? 0) - } - ])); + this.chartData = Object.fromEntries( + this.classes.map((assetClass) => [ + assetClass, + { + name: this.labels[assetClass], + value: Math.max(0, this.profile.allocations[assetClass] ?? 0) + } + ]) + ); } protected get total() { @@ -97,10 +110,10 @@ export class GfTargetConfigurationDialogComponent { this.profile = { ...this.profile, presetId: undefined, - name: $localize`Custom`, + name: 'Custom', allocations: { ...this.profile.allocations, - [assetClass]: Number(percent) / 100 + [assetClass]: percent == null ? NaN : Number(percent) / 100 } }; this.updateChartData(); @@ -109,7 +122,7 @@ export class GfTargetConfigurationDialogComponent { protected updateTolerance(percent: number) { this.profile = { ...this.profile, - tolerance: Number(percent) / 100 + tolerance: percent == null ? NaN : Number(percent) / 100 }; } diff --git a/apps/client/src/app/pages/portfolio/targets/target-percent.pipe.spec.ts b/apps/client/src/app/pages/portfolio/targets/target-percent.pipe.spec.ts new file mode 100644 index 0000000000..4c51356439 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-percent.pipe.spec.ts @@ -0,0 +1,33 @@ +import { LOCALE_ID } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; + +import { GfTargetPercentPipe } from './target-percent.pipe'; + +describe('Target percentage locale', () => { + let pipe: GfTargetPercentPipe; + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [{ provide: LOCALE_ID, useValue: 'en' }] + }); + pipe = TestBed.runInInjectionContext(() => new GfTargetPercentPipe()); + }); + afterEach(() => TestBed.resetTestingModule()); + + it('honors an Italian number locale on an English interface', () => { + expect(pipe.transform(0.1234, 'it-IT')).toBe('12,34%'); + expect(pipe.transform(0.1234, 'en-US')).toBe('12.34%'); + }); + + it('uses the interface locale when no number preference exists', () => { + expect(pipe.transform(0.1234)).toBe('12.34%'); + }); + + it('formats signed drift and tolerance without changing their values', () => { + expect(pipe.transform(-0.105, 'it-IT', 2, true)).toBe('-10,5%'); + expect(pipe.transform(0, 'it-IT', 2, true)).toBe('+0%'); + expect(pipe.transform(0.055, 'it-IT', 1)).toBe('5,5%'); + }); + it('falls back to the interface locale for a malformed stored preference', () => { + expect(pipe.transform(0.1234, 'not_a_locale')).toBe('12.34%'); + }); +}); diff --git a/apps/client/src/app/pages/portfolio/targets/target-percent.pipe.ts b/apps/client/src/app/pages/portfolio/targets/target-percent.pipe.ts new file mode 100644 index 0000000000..ab54b62173 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/target-percent.pipe.ts @@ -0,0 +1,34 @@ +import { LOCALE_ID, Pipe, PipeTransform, inject } from '@angular/core'; + +export function getTargetNumberLocale( + locale: string | undefined, + fallback: string +) { + try { + return Intl.getCanonicalLocales(locale ?? fallback)[0] ?? fallback; + } catch { + return fallback; + } +} + +/** Use the user's number locale independently from the interface language. */ +@Pipe({ name: 'targetPercent' }) +export class GfTargetPercentPipe implements PipeTransform { + private readonly defaultLocale = inject(LOCALE_ID); + + public transform( + value: number, + locale?: string, + maximumFractionDigits = 2, + signed = false + ) { + return new Intl.NumberFormat( + getTargetNumberLocale(locale, this.defaultLocale), + { + style: 'percent', + maximumFractionDigits, + signDisplay: signed ? 'always' : 'auto' + } + ).format(value); + } +} diff --git a/apps/client/src/app/pages/portfolio/targets/target-presets.ts b/apps/client/src/app/pages/portfolio/targets/target-presets.ts index 7488a64fe9..53b83b90ae 100644 --- a/apps/client/src/app/pages/portfolio/targets/target-presets.ts +++ b/apps/client/src/app/pages/portfolio/targets/target-presets.ts @@ -2,12 +2,23 @@ import { PortfolioTargetProfile } from '@ghostfolio/common/interfaces'; import { PORTFOLIO_TARGET_PRESETS } from '@ghostfolio/common/portfolio-targets/portfolio-targets-presets'; /** The user-visible presets share the same source as the default model. */ -export const TARGET_PRESETS = PORTFOLIO_TARGET_PRESETS.map(({ id, name }) => ({ +export const TARGET_PRESETS = PORTFOLIO_TARGET_PRESETS.map(({ id }) => ({ id, - label: name + label: + id === 'cautious-20-80' + ? $localize`Cautious (20/80)` + : id === 'conservative-40-60' + ? $localize`Conservative (40/60)` + : id === 'moderate-60-40' + ? $localize`Moderate (60/40)` + : id === 'aggressive-80-20' + ? $localize`Aggressive (80/20)` + : $localize`Golden Butterfly (simplified)` })); -export function createTargetFromPreset(presetId: string): PortfolioTargetProfile { +export function createTargetFromPreset( + presetId: string +): PortfolioTargetProfile { const preset = PORTFOLIO_TARGET_PRESETS.find(({ id }) => id === presetId) ?? PORTFOLIO_TARGET_PRESETS[2]; @@ -20,3 +31,15 @@ export function createTargetFromPreset(presetId: string): PortfolioTargetProfile allocations: { ...preset.allocations } }; } + +/** Preset and generated labels follow the UI language; personal names stay intact. */ +export function getTargetProfileName(profile: PortfolioTargetProfile): string { + const preset = TARGET_PRESETS.find(({ id }) => id === profile.presetId); + if (preset) { + return preset.label; + } + + return !profile.presetId && profile.name === 'Custom' + ? $localize`Custom` + : profile.name; +} diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.component.spec.ts b/apps/client/src/app/pages/portfolio/targets/targets-page.component.spec.ts new file mode 100644 index 0000000000..e374cd4e70 --- /dev/null +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.component.spec.ts @@ -0,0 +1,382 @@ +import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service'; +import { UserService } from '@ghostfolio/client/services/user/user.service'; +import { TAG_ID_EXCLUDE_FROM_ANALYSIS } from '@ghostfolio/common/config'; +import { + AccountsResponse, + PortfolioDetails, + User +} from '@ghostfolio/common/interfaces'; +import { permissions } from '@ghostfolio/common/permissions'; +import { createDefaultPortfolioTarget } from '@ghostfolio/common/portfolio-targets/portfolio-targets-presets'; +import { scopes } from '@ghostfolio/common/scopes'; +import { DataService } from '@ghostfolio/ui/services'; + +import { ChangeDetectorRef } from '@angular/core'; +import { TestBed } from '@angular/core/testing'; +import '@angular/localize/init'; +import { MatDialog } from '@angular/material/dialog'; +import { provideNoopAnimations } from '@angular/platform-browser/animations'; +import { BehaviorSubject, Subject, of, throwError } from 'rxjs'; + +import { GfTargetsPageComponent } from './targets-page.component'; + +jest.mock('@ghostfolio/ui/services', () => ({ DataService: class {} })); +// Keep the real monetary formatter; the icon renderer is irrelevant here and +// its browser-only dependency graph is not transformed by the Jest preset. +jest.mock('@ionic/angular/standalone', () => { + const { Component } = + jest.requireActual('@angular/core'); + class IonIconStub {} + Component({ + selector: 'ion-icon', + standalone: true, + template: '', + inputs: ['name'] + })(IonIconStub); + return { IonIcon: IonIconStub }; +}); +jest.mock('@ghostfolio/ui/i18n', () => ({ + translate: (value: string) => value +})); +jest.mock('@ghostfolio/client/services/user/user.service', () => ({ + UserService: class {} +})); +jest.mock('./target-configuration-dialog.component', () => ({ + GfTargetConfigurationDialogComponent: class {} +})); + +function makeUser(): User { + return { + id: 'owner', + permissions: [permissions.updateUserSettings], + scopes: [scopes.accountRead, scopes.portfolioReadValues], + settings: { + portfolioTargets: { + version: 1, + activeProfileId: 'global', + profiles: [createDefaultPortfolioTarget()] + } + } + } as User; +} + +function makeDetails(): PortfolioDetails { + return { + accounts: { + one: { + balance: 100, + currency: 'EUR', + name: 'One', + valueInBaseCurrency: 100 + } + }, + holdings: [], + summary: { + accountCashInBaseCurrency: 100, + cash: 100, + emergencyFund: { cash: 0 }, + filteredValueInBaseCurrency: 0, + liabilitiesInBaseCurrency: 0 + } + } as PortfolioDetails; +} + +describe('Portfolio Targets page requests and persistence', () => { + let component: GfTargetsPageComponent; + let dialog: { open: jest.Mock }; + let state: BehaviorSubject<{ user: User }>; + let impersonation: BehaviorSubject; + let afterClosed: Subject>; + let dataService: { + fetchAccounts: jest.Mock; + fetchPortfolioDetails: jest.Mock; + putUserSetting: jest.Mock; + }; + + beforeEach(() => { + state = new BehaviorSubject({ user: makeUser() }); + impersonation = new BehaviorSubject(null); + afterClosed = new Subject(); + dialog = { open: jest.fn(() => ({ afterClosed: () => afterClosed })) }; + dataService = { + fetchAccounts: jest.fn(() => + of({ + accounts: [ + { id: 'one', name: 'One', tags: [] }, + { + id: 'excluded', + name: 'Excluded', + tags: [{ id: TAG_ID_EXCLUDE_FROM_ANALYSIS }] + } + ] + } as AccountsResponse) + ), + fetchPortfolioDetails: jest.fn(() => of(makeDetails())), + putUserSetting: jest.fn(() => of({})) + }; + TestBed.configureTestingModule({ + providers: [ + provideNoopAnimations(), + { provide: ChangeDetectorRef, useValue: { markForCheck: jest.fn() } }, + { provide: DataService, useValue: dataService }, + { + provide: UserService, + useValue: { + stateChanged: state, + get: jest.fn(() => of(state.value.user)) + } + }, + { + provide: ImpersonationStorageService, + useValue: { onChangeHasImpersonation: () => impersonation } + }, + { + provide: MatDialog, + useValue: dialog + } + ] + }); + component = TestBed.runInInjectionContext( + () => new GfTargetsPageComponent() + ); + component.ngOnInit(); + }); + + afterEach(() => TestBed.resetTestingModule()); + + it.each([ + { locale: 'en-US', currency: 'USD', amount: '100.00' }, + { locale: 'it-IT', currency: 'EUR', amount: '100,00' } + ])( + 'renders portfolio value before the unchanged drift cards ($locale)', + ({ locale, currency, amount }) => { + const user = makeUser(); + user.settings.locale = locale; + user.settings.baseCurrency = currency; + state.next({ user }); + const fixture = TestBed.createComponent(GfTargetsPageComponent); + fixture.detectChanges(); + const element = fixture.nativeElement as HTMLElement; + const cards = element.querySelectorAll('.row.mb-3 > .col-md-4'); + expect(cards).toHaveLength(3); + const text = Array.from(cards, (card) => + card.textContent.replace(/\s+/g, ' ').trim() + ); + expect(text[0]).toContain('Portfolio value'); + expect(text[0]).toContain(amount); + expect(text[0]).toContain(currency); + expect(text[1]).toContain('Total allocation drift'); + expect(text[1]).toContain('100%'); + expect(text[2]).toContain('Maximum deviation'); + expect(text[2]).toContain('100%'); + expect(element.textContent).not.toContain('Classes outside tolerance'); + } + ); + + it.each([ + 'loading', + 'unavailable', + 'inconsistent', + 'unsupported', + 'restricted' + ])('does not render monetary summary cards in state %s', (status) => { + const details = makeDetails(); + if (status === 'restricted') { + const user = makeUser(); + user.settings.isRestrictedView = true; + state.next({ user }); + } else if (status === 'loading') { + dataService.fetchPortfolioDetails.mockReturnValue( + new Subject() + ); + } else { + if (status === 'unavailable') + delete details.summary.accountCashInBaseCurrency; + if (status === 'inconsistent') + details.accounts.one.valueInBaseCurrency = 50; + if (status === 'unsupported') details.accounts.one.balance = -10; + dataService.fetchPortfolioDetails.mockReturnValue(of(details)); + } + const fixture = TestBed.createComponent(GfTargetsPageComponent); + fixture.detectChanges(); + expect( + (fixture.nativeElement as HTMLElement).querySelectorAll( + '.row.mb-3 > .col-md-4' + ) + ).toHaveLength(0); + }); + + it('renders the calculated value for the selected account', () => { + const user = makeUser(); + user.settings.baseCurrency = 'USD'; + user.settings.locale = 'en-US'; + state.next({ user }); + const fixture = TestBed.createComponent(GfTargetsPageComponent); + fixture.detectChanges(); + const details = makeDetails(); + details.accounts.one.balance = 250; + details.accounts.one.valueInBaseCurrency = 250; + details.summary.accountCashInBaseCurrency = 250; + dataService.fetchPortfolioDetails.mockReturnValue(of(details)); + fixture.componentInstance['changeAccount']('one'); + fixture.componentRef.changeDetectorRef.detectChanges(); + expect(dataService.fetchPortfolioDetails).toHaveBeenLastCalledWith({ + filters: [{ type: 'ACCOUNT', id: 'one' }] + }); + expect( + (fixture.nativeElement as HTMLElement).querySelector( + '.row.mb-3 > .col-md-4' + ).textContent + ).toContain('250.00'); + expect((fixture.nativeElement as HTMLElement).textContent).not.toContain( + 'Excluded' + ); + }); + + it('uses tagged account data, preserves the global option and sends account-only filters', () => { + expect(component['accounts'].map(({ id }) => id)).toEqual(['one']); + expect(dataService.fetchAccounts).toHaveBeenCalledWith({ filters: [] }); + expect(dataService.fetchPortfolioDetails).toHaveBeenLastCalledWith({ + filters: [] + }); + component['changeAccount']('one'); + expect(dataService.fetchPortfolioDetails).toHaveBeenLastCalledWith({ + filters: [{ type: 'ACCOUNT', id: 'one' }] + }); + expect(component['profile'].id).toBe('global'); + }); + + it('falls back to the global portfolio when an account disappears or is excluded', () => { + component['changeAccount']('one'); + dataService.fetchAccounts.mockReturnValue(of({ accounts: [] })); + state.next({ user: makeUser() }); + expect(component['selectedAccountId']).toBe(''); + expect(dataService.fetchPortfolioDetails).toHaveBeenLastCalledWith({ + filters: [] + }); + }); + + it('cancels stale account-switch responses', () => { + const stale = new Subject(); + dataService.fetchPortfolioDetails.mockReturnValueOnce(stale); + component['changeAccount']('one'); + component['changeAccount'](''); + stale.next({ ...makeDetails(), holdings: [], accounts: {} }); + expect(component['result'].status).toBe('ready'); + }); + + it('clears financial data and cancels pending requests on impersonation', () => { + impersonation.next('another-user'); + expect(component['result']).toBeUndefined(); + expect(component['accounts']).toEqual([]); + expect(component['canEdit']).toBe(false); + }); + + it('does not request monetary data after values permission is removed', () => { + dataService.fetchPortfolioDetails.mockClear(); + const user = makeUser(); + user.scopes = []; + state.next({ user }); + expect(dataService.fetchPortfolioDetails).not.toHaveBeenCalled(); + expect(component['result']).toBeUndefined(); + }); + + it('does not request account data without account-read scope', () => { + dataService.fetchAccounts.mockClear(); + const user = makeUser(); + user.scopes = [scopes.portfolioReadValues]; + state.next({ user }); + expect(dataService.fetchAccounts).not.toHaveBeenCalled(); + expect(dataService.fetchPortfolioDetails).toHaveBeenLastCalledWith({ + filters: [] + }); + }); + + it('checks editing permission again when a dialog is submitted', () => { + component['openConfiguration'](); + impersonation.next('another-user'); + afterClosed.next(createDefaultPortfolioTarget()); + expect(dataService.putUserSetting).not.toHaveBeenCalled(); + }); + + it('always saves a global versioned configuration when viewing a single account', () => { + component['changeAccount']('one'); + component['openConfiguration'](); + afterClosed.next(createDefaultPortfolioTarget()); + expect(dataService.putUserSetting).toHaveBeenCalledWith({ + portfolioTargets: { + version: 1, + activeProfileId: 'global', + profiles: [createDefaultPortfolioTarget()] + } + }); + }); + + it('preserves the allocation display on save failure and permits retry', () => { + dataService.putUserSetting.mockReturnValue( + throwError(() => new Error('failed')) + ); + component['openConfiguration'](); + afterClosed.next(createDefaultPortfolioTarget()); + expect(component['hasSaveError']).toBe(true); + expect(component['hasError']).toBe(false); + expect(component['isSaving']).toBe(false); + expect(component['result'].status).toBe('ready'); + component['openConfiguration'](); + expect(dialog.open).toHaveBeenLastCalledWith( + expect.anything(), + expect.objectContaining({ + data: expect.objectContaining({ + profile: createDefaultPortfolioTarget() + }) + }) + ); + }); + + it('clears the allocation when the user state becomes unavailable', () => { + state.next({ user: undefined }); + expect(component['result']).toBeUndefined(); + expect(component['accounts']).toEqual([]); + expect(component['canEdit']).toBe(false); + }); + it('does not bypass the backend error signal even if amounts look plausible', () => { + dataService.fetchPortfolioDetails.mockReturnValue( + of({ ...makeDetails(), hasError: true }) + ); + component['changeAccount'](''); + expect(component['hasError']).toBe(true); + expect(component['result']).toBeUndefined(); + }); + + it('clears monetary results when restricted view is enabled', () => { + dataService.fetchPortfolioDetails.mockClear(); + const user = makeUser(); + user.settings.isRestrictedView = true; + state.next({ user }); + expect(dataService.fetchPortfolioDetails).not.toHaveBeenCalled(); + expect(component['result']).toBeUndefined(); + }); + it('identifies negative balances as unsupported even with a backend error', () => { + const details = makeDetails(); + details.accounts.one.balance = -10; + details.accounts.one.valueInBaseCurrency = -10; + details.summary.accountCashInBaseCurrency = -10; + details.summary.cash = -10; + dataService.fetchPortfolioDetails.mockReturnValue( + of({ ...details, hasError: true }) + ); + component['changeAccount'](''); + expect(component['hasError']).toBe(false); + expect(component['result'].status).toBe('unsupported'); + expect(component['result'].rows).toEqual([]); + }); + + it('shows no allocation when an older backend omits independent cash', () => { + const details = makeDetails(); + delete details.summary.accountCashInBaseCurrency; + dataService.fetchPortfolioDetails.mockReturnValue(of(details)); + component['changeAccount'](''); + expect(component['result'].status).toBe('unavailable'); + expect(component['result'].rows).toEqual([]); + }); +}); diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts index e122d80a5c..50b8145844 100644 --- a/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.component.ts @@ -1,24 +1,34 @@ import { ImpersonationStorageService } from '@ghostfolio/client/services/impersonation-storage.service'; import { UserService } from '@ghostfolio/client/services/user/user.service'; -import { TAG_ID_EXCLUDE_FROM_ANALYSIS, UNKNOWN_KEY } from '@ghostfolio/common/config'; -import { Filter, PortfolioTargetProfile, User } from '@ghostfolio/common/interfaces'; +import { + TAG_ID_EXCLUDE_FROM_ANALYSIS, + UNKNOWN_KEY +} from '@ghostfolio/common/config'; +import { + AccountsResponse, + Filter, + PortfolioTargetProfile, + User +} from '@ghostfolio/common/interfaces'; import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { calculatePortfolioTargets, - TargetAllocationResult + TargetAllocationResult, + TargetAllocationRow } from '@ghostfolio/common/portfolio-targets/portfolio-targets-calculator'; import { hasScope, scopes } from '@ghostfolio/common/scopes'; import { AssetClass } from '@ghostfolio/prisma/enums'; import { translate } from '@ghostfolio/ui/i18n'; import { DataService } from '@ghostfolio/ui/services'; +import { GfValueComponent } from '@ghostfolio/ui/value'; -import { DecimalPipe } from '@angular/common'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, DestroyRef, inject, + LOCALE_ID, OnInit } from '@angular/core'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @@ -27,25 +37,35 @@ import { MatCardModule } from '@angular/material/card'; import { MatDialog } from '@angular/material/dialog'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatSelectModule } from '@angular/material/select'; -import { finalize, switchMap } from 'rxjs'; +import { MatTooltipModule } from '@angular/material/tooltip'; +import { of, Subscription, finalize, switchMap } from 'rxjs'; import { GfTargetConfigurationDialogComponent } from './target-configuration-dialog.component'; +import { + GfTargetPercentPipe, + getTargetNumberLocale +} from './target-percent.pipe'; +import { getTargetProfileName } from './target-presets'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, imports: [ - DecimalPipe, + GfTargetPercentPipe, + GfValueComponent, MatButtonModule, MatCardModule, MatFormFieldModule, - MatSelectModule + MatSelectModule, + MatTooltipModule ], selector: 'gf-targets-page', - styleUrls: ['./targets-page.component.scss'], - templateUrl: './targets-page.component.html' + styleUrls: ['./targets-page.scss'], + templateUrl: './targets-page.html' }) export class GfTargetsPageComponent implements OnInit { - protected user: User; + protected user?: User; + protected accounts: AccountsResponse['accounts'] = []; + protected hasSaveError = false; protected profile?: PortfolioTargetProfile; protected result?: TargetAllocationResult; protected selectedAccountId = ''; @@ -54,8 +74,12 @@ export class GfTargetsPageComponent implements OnInit { protected hasError = false; protected canEdit = false; protected readonly labels: Record = Object.fromEntries( - Object.values(AssetClass).map((assetClass) => [assetClass, translate(assetClass)]) + Object.values(AssetClass).map((assetClass) => [ + assetClass, + translate(assetClass) + ]) ); + private readonly defaultLocale = inject(LOCALE_ID); private readonly changeDetectorRef = inject(ChangeDetectorRef); private readonly dataService = inject(DataService); private readonly destroyRef = inject(DestroyRef); @@ -63,12 +87,22 @@ export class GfTargetsPageComponent implements OnInit { private readonly impersonationService = inject(ImpersonationStorageService); private readonly userService = inject(UserService); private isImpersonating = false; + private allocationRequest?: Subscription; + private draftProfile?: PortfolioTargetProfile; + private contextVersion = 0; public ngOnInit() { - this.impersonationService.onChangeHasImpersonation() + this.impersonationService + .onChangeHasImpersonation() .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((id) => { + this.contextVersion++; + this.draftProfile = undefined; this.isImpersonating = !!id; + this.allocationRequest?.unsubscribe(); + this.result = undefined; + this.accounts = []; + this.selectedAccountId = ''; this.updateEditingPermission(); }); @@ -76,26 +110,41 @@ export class GfTargetsPageComponent implements OnInit { .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((state) => { if (!state?.user) { + this.contextVersion++; + this.allocationRequest?.unsubscribe(); + this.user = undefined; + this.profile = undefined; + this.result = undefined; + this.accounts = []; + this.draftProfile = undefined; + this.isLoading = false; + this.updateEditingPermission(); return; } + if (this.user?.id !== state.user.id) { + this.contextVersion++; + this.draftProfile = undefined; + this.selectedAccountId = ''; + } this.user = state.user; this.profile = this.user.settings.portfolioTargets?.profiles.find( - ({ id }) => id === this.user.settings.portfolioTargets?.activeProfileId + ({ id }) => + id === state.user.settings.portfolioTargets?.activeProfileId ); this.updateEditingPermission(); this.fetchAllocations(); }); } - protected get accounts() { - return (this.user?.accounts ?? []).filter((account) => - !account.tags?.some(({ id }) => id === TAG_ID_EXCLUDE_FROM_ANALYSIS) - ); + protected get profileName() { + return this.profile ? getTargetProfileName(this.profile) : undefined; } protected get hasReadValues() { - return hasScope(this.user?.scopes, scopes.portfolioReadValues) && - !this.user?.settings?.isRestrictedView; + return ( + hasScope(this.user?.scopes, scopes.portfolioReadValues) && + !this.user?.settings?.isRestrictedView + ); } protected get displayedRows() { @@ -105,7 +154,48 @@ export class GfTargetsPageComponent implements OnInit { protected formatClass(assetClass: string) { return assetClass === UNKNOWN_KEY ? $localize`Unclassified` - : this.labels[assetClass] ?? assetClass; + : (this.labels[assetClass] ?? assetClass); + } + + protected allocationTooltip(row: TargetAllocationRow) { + if (!this.hasReadValues || this.result?.status !== 'ready') { + return ''; + } + + const locale = getTargetNumberLocale( + this.user?.settings.locale, + this.defaultLocale + ); + const percent = new Intl.NumberFormat(locale, { + style: 'percent', + maximumFractionDigits: 2 + }); + const actual = percent.format(row.actual); + const target = percent.format(row.target); + const deviation = new Intl.NumberFormat(locale, { + maximumFractionDigits: 2, + signDisplay: 'exceptZero' + }).format(row.drift * 100); + const currency = this.user?.settings.baseCurrency; + const value = currency + ? new Intl.NumberFormat(locale, { + style: 'currency', + currency, + maximumFractionDigits: 2 + }).format(row.actual * this.result.totalValue) + : undefined; + + return [ + this.formatClass(row.assetClass), + value + ? $localize`Actual: ${actual} (${value})` + : $localize`Actual: ${actual}`, + $localize`Target: ${target}`, + $localize`Deviation: ${deviation} percentage points`, + row.outOfTolerance + ? $localize`Outside tolerance` + : $localize`Within tolerance` + ].join('\n'); } protected changeAccount(accountId: string) { @@ -114,47 +204,64 @@ export class GfTargetsPageComponent implements OnInit { } protected openConfiguration() { - if (!this.canEdit || !this.user) { + if (!this.canEdit || !this.user || this.isSaving) { return; } + const contextVersion = this.contextVersion; const ref = this.dialog.open(GfTargetConfigurationDialogComponent, { - autoFocus: false, maxWidth: '96vw', width: '820px', - data: { profile: this.profile, user: this.user } + data: { profile: this.draftProfile ?? this.profile, user: this.user } }); - ref.afterClosed().pipe(takeUntilDestroyed(this.destroyRef)) + ref + .afterClosed() + .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((profile?: PortfolioTargetProfile) => { - if (!profile) { + if ( + !profile || + !this.canEdit || + this.isSaving || + contextVersion !== this.contextVersion + ) { return; } + this.draftProfile = profile; this.isSaving = true; - this.dataService.putUserSetting({ - portfolioTargets: { - version: 1, - activeProfileId: 'global', - profiles: [{ ...profile, id: 'global' }] - } - }).pipe( - switchMap(() => this.userService.get(true)), - finalize(() => { - this.isSaving = false; - this.changeDetectorRef.markForCheck(); - }), - takeUntilDestroyed(this.destroyRef) - ).subscribe({ - error: () => { - this.hasError = true; - this.changeDetectorRef.markForCheck(); - } - }); + this.hasSaveError = false; + this.dataService + .putUserSetting({ + portfolioTargets: { + version: 1, + activeProfileId: 'global', + profiles: [{ ...profile, id: 'global' }] + } + }) + .pipe( + switchMap(() => this.userService.get(true)), + finalize(() => { + this.isSaving = false; + this.changeDetectorRef.markForCheck(); + }), + takeUntilDestroyed(this.destroyRef) + ) + .subscribe({ + next: () => { + this.draftProfile = undefined; + }, + error: () => { + this.hasSaveError = true; + this.changeDetectorRef.markForCheck(); + } + }); }); } private updateEditingPermission() { - this.canEdit = !!this.user && !this.isImpersonating && + this.canEdit = + !!this.user && + !this.isImpersonating && hasPermission(this.user.permissions, permissions.updateUserSettings); this.changeDetectorRef.markForCheck(); } @@ -164,21 +271,45 @@ export class GfTargetsPageComponent implements OnInit { return; } + this.allocationRequest?.unsubscribe(); this.isLoading = true; this.hasError = false; this.result = undefined; + this.changeDetectorRef.markForCheck(); - const filters: Filter[] = this.selectedAccountId - ? [{ type: 'ACCOUNT', id: this.selectedAccountId }] - : []; + if (!this.hasReadValues) { + this.accounts = []; + this.isLoading = false; + return; + } - this.dataService.fetchPortfolioDetails({ filters }) - .pipe(takeUntilDestroyed(this.destroyRef)) + this.allocationRequest = ( + hasScope(this.user.scopes, scopes.accountRead) + ? this.dataService.fetchAccounts({ filters: [] }) + : of({ accounts: [] as AccountsResponse['accounts'] }) + ) + .pipe( + switchMap(({ accounts }) => { + this.accounts = accounts.filter( + (account) => + !account.tags?.some( + ({ id }) => id === TAG_ID_EXCLUDE_FROM_ANALYSIS + ) + ); + if (!this.accounts.some(({ id }) => id === this.selectedAccountId)) { + this.selectedAccountId = ''; + } + const filters: Filter[] = this.selectedAccountId + ? [{ type: 'ACCOUNT', id: this.selectedAccountId }] + : []; + return this.dataService.fetchPortfolioDetails({ filters }); + }), + takeUntilDestroyed(this.destroyRef) + ) .subscribe({ next: (details) => { if (this.profile) { - if (!this.hasReadValues || ('hasError' in details && details.hasError)) { - this.result = undefined; + if (!this.hasReadValues) { this.hasError = true; } else { this.result = calculatePortfolioTargets({ @@ -186,12 +317,24 @@ export class GfTargetsPageComponent implements OnInit { targets: this.profile.allocations, tolerance: this.profile.tolerance }); + // Known negative exposures remain an unsupported financial case, + // even when the backend also reports valuation errors. No + // percentages are shown for either state. + if ( + 'hasError' in details && + details.hasError && + this.result.status !== 'unsupported' + ) { + this.result = undefined; + this.hasError = true; + } } } this.isLoading = false; this.changeDetectorRef.markForCheck(); }, error: () => { + this.accounts = []; this.hasError = true; this.isLoading = false; this.changeDetectorRef.markForCheck(); diff --git a/apps/client/src/app/pages/portfolio/targets/targets-page.html b/apps/client/src/app/pages/portfolio/targets/targets-page.html index 5b829158f7..56eaf5d36e 100644 --- a/apps/client/src/app/pages/portfolio/targets/targets-page.html +++ b/apps/client/src/app/pages/portfolio/targets/targets-page.html @@ -1,28 +1,40 @@

Targets

-
+
@if (profile) { -
{{ profile.name }}
+
{{ profileName }}
Allowed deviation: - ±{{ profile.tolerance * 100 | number: '1.0-1' }}% + + ±{{ profile.tolerance | targetPercent: user?.settings.locale : 1 }} + } @else { No target configured yet }
@if (canEdit) { - }
- @if (accounts.length > 1) { + @if (accounts.length > 0) {