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) {