mirror of https://github.com/ghostfolio/ghostfolio
committed by
GitHub
50 changed files with 8568 additions and 59 deletions
@ -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(); |
||||
|
}); |
||||
|
}); |
||||
@ -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 |
||||
|
); |
||||
|
} |
||||
|
); |
||||
|
}); |
||||
@ -0,0 +1,83 @@ |
|||||
|
<h2 i18n mat-dialog-title>Configure target</h2> |
||||
|
<mat-dialog-content class="configuration-content"> |
||||
|
<div class="mb-3"> |
||||
|
<mat-form-field appearance="outline" class="w-100"> |
||||
|
<mat-label i18n>Starting allocation</mat-label> |
||||
|
<mat-select |
||||
|
[value]="profile.presetId ?? 'custom'" |
||||
|
(selectionChange)="applyPreset($event.value)" |
||||
|
> |
||||
|
@for (preset of presets; track preset.id) { |
||||
|
<mat-option [value]="preset.id">{{ preset.label }}</mat-option> |
||||
|
} |
||||
|
<mat-option i18n value="custom" [disabled]="true">Custom</mat-option> |
||||
|
</mat-select> |
||||
|
</mat-form-field> |
||||
|
<p class="text-body-secondary small" i18n> |
||||
|
Presets are starting points. Edit any percentage to customize your target. |
||||
|
</p> |
||||
|
</div> |
||||
|
<div class="row"> |
||||
|
<div class="col-md-5 mb-3"> |
||||
|
<gf-portfolio-proportion-chart |
||||
|
[colorScheme]="data.user.settings.colorScheme" |
||||
|
[data]="chartData" |
||||
|
[isInPercentage]="true" |
||||
|
[locale]="data.user.settings.locale" |
||||
|
/> |
||||
|
<div class="text-center fw-bold mt-2"> |
||||
|
<span i18n>Total</span>: |
||||
|
{{ total | targetPercent: data.user.settings.locale }} |
||||
|
</div> |
||||
|
</div> |
||||
|
<div class="col-md-7"> |
||||
|
@for (assetClass of classes; track assetClass) { |
||||
|
<div class="allocation-input"> |
||||
|
<label [for]="'target-' + assetClass">{{ labels[assetClass] }}</label> |
||||
|
<div class="input-group"> |
||||
|
<input |
||||
|
class="form-control" |
||||
|
max="100" |
||||
|
min="0" |
||||
|
step="0.5" |
||||
|
type="number" |
||||
|
[id]="'target-' + assetClass" |
||||
|
[ngModel]="profile.allocations[assetClass] * 100" |
||||
|
(ngModelChange)="updateAllocation(assetClass, $event)" |
||||
|
/> |
||||
|
<span class="input-group-text">%</span> |
||||
|
</div> |
||||
|
</div> |
||||
|
} |
||||
|
<hr /> |
||||
|
<div class="allocation-input"> |
||||
|
<label for="target-tolerance" i18n>Allowed deviation</label> |
||||
|
<div class="input-group"> |
||||
|
<input |
||||
|
class="form-control" |
||||
|
id="target-tolerance" |
||||
|
max="100" |
||||
|
min="0" |
||||
|
step="0.5" |
||||
|
type="number" |
||||
|
[ngModel]="profile.tolerance * 100" |
||||
|
(ngModelChange)="updateTolerance($event)" |
||||
|
/> |
||||
|
<span class="input-group-text">%</span> |
||||
|
</div> |
||||
|
</div> |
||||
|
@if (!isValid) { |
||||
|
<p class="text-danger small" i18n> |
||||
|
Each percentage must be between 0 and 100, and the total must equal |
||||
|
100%. |
||||
|
</p> |
||||
|
} |
||||
|
</div> |
||||
|
</div> |
||||
|
</mat-dialog-content> |
||||
|
<mat-dialog-actions align="end"> |
||||
|
<button i18n mat-button (click)="cancel()">Cancel</button> |
||||
|
<button i18n mat-flat-button [disabled]="!isValid" (click)="save()"> |
||||
|
Save target |
||||
|
</button> |
||||
|
</mat-dialog-actions> |
||||
@ -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; } |
||||
|
} |
||||
@ -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'); |
||||
|
}); |
||||
|
}); |
||||
@ -0,0 +1,138 @@ |
|||||
|
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 { 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 { GfTargetPercentPipe } from './target-percent.pipe'; |
||||
|
import { createTargetFromPreset, TARGET_PRESETS } from './target-presets'; |
||||
|
|
||||
|
@Component({ |
||||
|
changeDetection: ChangeDetectionStrategy.OnPush, |
||||
|
imports: [ |
||||
|
GfTargetPercentPipe, |
||||
|
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; |
||||
|
|
||||
|
protected readonly data = inject<{ |
||||
|
profile?: PortfolioTargetProfile; |
||||
|
user: User; |
||||
|
}>(MAT_DIALOG_DATA); |
||||
|
private readonly dialogRef = |
||||
|
inject< |
||||
|
MatDialogRef<GfTargetConfigurationDialogComponent, PortfolioTargetProfile> |
||||
|
>(MatDialogRef); |
||||
|
|
||||
|
protected readonly labels = Object.fromEntries( |
||||
|
TARGET_ASSET_CLASSES.map((assetClass) => [ |
||||
|
assetClass, |
||||
|
translate(assetClass) |
||||
|
]) |
||||
|
) as Record<AssetClass, string>; |
||||
|
|
||||
|
public constructor() { |
||||
|
const defaultProfile = createTargetFromPreset('moderate-60-40'); |
||||
|
this.profile = { |
||||
|
...(this.data.profile ?? defaultProfile), |
||||
|
allocations: { |
||||
|
...(this.data.profile?.allocations ?? defaultProfile.allocations) |
||||
|
} |
||||
|
}; |
||||
|
this.updateChartData(); |
||||
|
} |
||||
|
|
||||
|
protected chartData: Record<string, { name: string; value: number }> = {}; |
||||
|
|
||||
|
private updateChartData() { |
||||
|
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() { |
||||
|
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 |
||||
|
}; |
||||
|
this.updateChartData(); |
||||
|
} |
||||
|
|
||||
|
protected updateAllocation(assetClass: AssetClass, percent: number) { |
||||
|
this.profile = { |
||||
|
...this.profile, |
||||
|
presetId: undefined, |
||||
|
name: 'Custom', |
||||
|
allocations: { |
||||
|
...this.profile.allocations, |
||||
|
[assetClass]: percent == null ? NaN : Number(percent) / 100 |
||||
|
} |
||||
|
}; |
||||
|
this.updateChartData(); |
||||
|
} |
||||
|
|
||||
|
protected updateTolerance(percent: number) { |
||||
|
this.profile = { |
||||
|
...this.profile, |
||||
|
tolerance: percent == null ? NaN : Number(percent) / 100 |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
protected save() { |
||||
|
if (this.isValid) { |
||||
|
this.dialogRef.close(this.profile); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
protected cancel() { |
||||
|
this.dialogRef.close(); |
||||
|
} |
||||
|
} |
||||
@ -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%'); |
||||
|
}); |
||||
|
}); |
||||
@ -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); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,45 @@ |
|||||
|
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 }) => ({ |
||||
|
id, |
||||
|
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 { |
||||
|
const preset = |
||||
|
PORTFOLIO_TARGET_PRESETS.find(({ id }) => id === presetId) ?? |
||||
|
PORTFOLIO_TARGET_PRESETS[2]; |
||||
|
|
||||
|
return { |
||||
|
id: 'global', |
||||
|
name: preset.name, |
||||
|
presetId: preset.id, |
||||
|
tolerance: 0.05, |
||||
|
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; |
||||
|
} |
||||
@ -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<typeof import('@angular/core')>('@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<string | null>; |
||||
|
let afterClosed: Subject<ReturnType<typeof createDefaultPortfolioTarget>>; |
||||
|
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<PortfolioDetails>() |
||||
|
); |
||||
|
} 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<PortfolioDetails>(); |
||||
|
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([]); |
||||
|
}); |
||||
|
}); |
||||
@ -0,0 +1,344 @@ |
|||||
|
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 { |
||||
|
AccountsResponse, |
||||
|
Filter, |
||||
|
PortfolioTargetProfile, |
||||
|
User |
||||
|
} from '@ghostfolio/common/interfaces'; |
||||
|
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; |
||||
|
import { |
||||
|
calculatePortfolioTargets, |
||||
|
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 { |
||||
|
ChangeDetectionStrategy, |
||||
|
ChangeDetectorRef, |
||||
|
Component, |
||||
|
DestroyRef, |
||||
|
inject, |
||||
|
LOCALE_ID, |
||||
|
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 { 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: [ |
||||
|
GfTargetPercentPipe, |
||||
|
GfValueComponent, |
||||
|
MatButtonModule, |
||||
|
MatCardModule, |
||||
|
MatFormFieldModule, |
||||
|
MatSelectModule, |
||||
|
MatTooltipModule |
||||
|
], |
||||
|
selector: 'gf-targets-page', |
||||
|
styleUrls: ['./targets-page.scss'], |
||||
|
templateUrl: './targets-page.html' |
||||
|
}) |
||||
|
export class GfTargetsPageComponent implements OnInit { |
||||
|
protected user?: User; |
||||
|
protected accounts: AccountsResponse['accounts'] = []; |
||||
|
protected hasSaveError = false; |
||||
|
protected profile?: PortfolioTargetProfile; |
||||
|
protected result?: TargetAllocationResult; |
||||
|
protected selectedAccountId = ''; |
||||
|
protected isLoading = true; |
||||
|
protected isSaving = false; |
||||
|
protected hasError = false; |
||||
|
protected canEdit = false; |
||||
|
protected readonly labels: Record<string, string> = Object.fromEntries( |
||||
|
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); |
||||
|
private readonly dialog = inject(MatDialog); |
||||
|
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() |
||||
|
.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(); |
||||
|
}); |
||||
|
|
||||
|
this.userService.stateChanged |
||||
|
.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 === state.user.settings.portfolioTargets?.activeProfileId |
||||
|
); |
||||
|
this.updateEditingPermission(); |
||||
|
this.fetchAllocations(); |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
protected get profileName() { |
||||
|
return this.profile ? getTargetProfileName(this.profile) : undefined; |
||||
|
} |
||||
|
|
||||
|
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 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) { |
||||
|
this.selectedAccountId = accountId; |
||||
|
this.fetchAllocations(); |
||||
|
} |
||||
|
|
||||
|
protected openConfiguration() { |
||||
|
if (!this.canEdit || !this.user || this.isSaving) { |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
const contextVersion = this.contextVersion; |
||||
|
const ref = this.dialog.open(GfTargetConfigurationDialogComponent, { |
||||
|
maxWidth: '96vw', |
||||
|
width: '820px', |
||||
|
data: { profile: this.draftProfile ?? this.profile, user: this.user } |
||||
|
}); |
||||
|
|
||||
|
ref |
||||
|
.afterClosed() |
||||
|
.pipe(takeUntilDestroyed(this.destroyRef)) |
||||
|
.subscribe((profile?: PortfolioTargetProfile) => { |
||||
|
if ( |
||||
|
!profile || |
||||
|
!this.canEdit || |
||||
|
this.isSaving || |
||||
|
contextVersion !== this.contextVersion |
||||
|
) { |
||||
|
return; |
||||
|
} |
||||
|
this.draftProfile = profile; |
||||
|
this.isSaving = true; |
||||
|
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 && |
||||
|
hasPermission(this.user.permissions, permissions.updateUserSettings); |
||||
|
this.changeDetectorRef.markForCheck(); |
||||
|
} |
||||
|
|
||||
|
private fetchAllocations() { |
||||
|
if (!this.user) { |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
this.allocationRequest?.unsubscribe(); |
||||
|
this.isLoading = true; |
||||
|
this.hasError = false; |
||||
|
this.result = undefined; |
||||
|
this.changeDetectorRef.markForCheck(); |
||||
|
|
||||
|
if (!this.hasReadValues) { |
||||
|
this.accounts = []; |
||||
|
this.isLoading = false; |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
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) { |
||||
|
this.hasError = true; |
||||
|
} else { |
||||
|
this.result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
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(); |
||||
|
} |
||||
|
}); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,247 @@ |
|||||
|
<div class="container"> |
||||
|
<h1 class="d-none d-sm-block h3 mb-3 text-center" i18n>Targets</h1> |
||||
|
|
||||
|
<div |
||||
|
class="d-flex justify-content-between align-items-center flex-wrap gap-3 mb-3" |
||||
|
> |
||||
|
<div> |
||||
|
@if (profile) { |
||||
|
<div class="fw-bold">{{ profileName }}</div> |
||||
|
<span class="text-body-secondary small" i18n>Allowed deviation:</span> |
||||
|
<span class="small"> |
||||
|
±{{ profile.tolerance | targetPercent: user?.settings.locale : 1 }} |
||||
|
</span> |
||||
|
} @else { |
||||
|
<span class="text-body-secondary" i18n>No target configured yet</span> |
||||
|
} |
||||
|
</div> |
||||
|
@if (canEdit) { |
||||
|
<button |
||||
|
i18n |
||||
|
mat-flat-button |
||||
|
[disabled]="isSaving" |
||||
|
(click)="openConfiguration()" |
||||
|
> |
||||
|
Configure target |
||||
|
</button> |
||||
|
} |
||||
|
</div> |
||||
|
|
||||
|
@if (accounts.length > 0) { |
||||
|
<mat-form-field appearance="outline" class="account-select"> |
||||
|
<mat-label i18n>Account</mat-label> |
||||
|
<mat-select |
||||
|
[value]="selectedAccountId" |
||||
|
(selectionChange)="changeAccount($event.value)" |
||||
|
> |
||||
|
<mat-option i18n value="">All accounts</mat-option> |
||||
|
@for (account of accounts; track account.id) { |
||||
|
<mat-option [value]="account.id">{{ account.name }}</mat-option> |
||||
|
} |
||||
|
</mat-select> |
||||
|
</mat-form-field> |
||||
|
@if (selectedAccountId) { |
||||
|
<p class="text-body-secondary small" i18n> |
||||
|
Comparing the selected account with the global portfolio target. |
||||
|
</p> |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@if (hasSaveError) { |
||||
|
<p class="text-danger" i18n role="alert"> |
||||
|
The target could not be saved. Please try again. |
||||
|
</p> |
||||
|
} |
||||
|
|
||||
|
@if (!profile) { |
||||
|
<mat-card appearance="outlined"> |
||||
|
<mat-card-content> |
||||
|
<p class="mb-0" i18n> |
||||
|
Create a target to compare the actual asset allocation with your |
||||
|
desired allocation. |
||||
|
</p> |
||||
|
</mat-card-content> |
||||
|
</mat-card> |
||||
|
} @else if (isLoading) { |
||||
|
<p class="text-body-secondary" i18n>Loading portfolio allocation…</p> |
||||
|
} @else if (hasError || !result || result.status === 'unavailable') { |
||||
|
<mat-card appearance="outlined"> |
||||
|
<mat-card-content> |
||||
|
<p class="mb-0" i18n> |
||||
|
The current allocation cannot be calculated with the available data or |
||||
|
permissions. |
||||
|
</p> |
||||
|
</mat-card-content> |
||||
|
</mat-card> |
||||
|
} @else if (result.status === 'empty') { |
||||
|
<p class="text-body-secondary" i18n>The selected portfolio is empty.</p> |
||||
|
} @else if (result.status === 'unsupported') { |
||||
|
<mat-card appearance="outlined"> |
||||
|
<mat-card-content> |
||||
|
<p class="mb-0" i18n> |
||||
|
Negative cash balances, short positions and liabilities can be valid |
||||
|
financial data, but are not supported by this version of the |
||||
|
allocation comparison. |
||||
|
</p> |
||||
|
</mat-card-content> |
||||
|
</mat-card> |
||||
|
} @else if (result.status === 'inconsistent') { |
||||
|
<mat-card appearance="outlined"> |
||||
|
<mat-card-content> |
||||
|
<p class="mb-0" i18n> |
||||
|
Account values, holdings and cash cannot be reconciled. The allocation |
||||
|
comparison is unavailable. |
||||
|
</p> |
||||
|
</mat-card-content> |
||||
|
</mat-card> |
||||
|
} @else { |
||||
|
@if (result.unclassifiedValue > 0) { |
||||
|
<p class="text-warning" i18n> |
||||
|
Some holdings have no asset classification. The reported allocation is |
||||
|
incomplete. |
||||
|
</p> |
||||
|
} |
||||
|
<div class="row mb-3"> |
||||
|
<div class="col-md-4 mb-3"> |
||||
|
<mat-card appearance="outlined" |
||||
|
><mat-card-content> |
||||
|
<div class="text-body-secondary small" i18n>Portfolio value</div> |
||||
|
<div class="h3 mb-0 text-break"> |
||||
|
<gf-value |
||||
|
[isCurrency]="true" |
||||
|
[locale]="user?.settings.locale" |
||||
|
[unit]="user?.settings.baseCurrency" |
||||
|
[value]="result.totalValue" |
||||
|
/> |
||||
|
</div> </mat-card-content |
||||
|
></mat-card> |
||||
|
</div> |
||||
|
<div class="col-md-4 mb-3"> |
||||
|
<mat-card appearance="outlined" |
||||
|
><mat-card-content> |
||||
|
<div class="text-body-secondary small" i18n> |
||||
|
Total allocation drift |
||||
|
</div> |
||||
|
<div class="h3 mb-0"> |
||||
|
{{ result.totalDrift | targetPercent: user?.settings.locale }} |
||||
|
</div> |
||||
|
</mat-card-content></mat-card |
||||
|
> |
||||
|
</div> |
||||
|
<div class="col-md-4 mb-3"> |
||||
|
<mat-card appearance="outlined" |
||||
|
><mat-card-content> |
||||
|
<div class="text-body-secondary small" i18n>Maximum deviation</div> |
||||
|
<div class="h3 mb-0"> |
||||
|
{{ result.maxDrift | targetPercent: user?.settings.locale }} |
||||
|
</div> |
||||
|
</mat-card-content></mat-card |
||||
|
> |
||||
|
</div> |
||||
|
</div> |
||||
|
|
||||
|
<mat-card appearance="outlined" class="mb-3"> |
||||
|
<mat-card-header |
||||
|
><mat-card-title i18n |
||||
|
>Actual vs target allocation</mat-card-title |
||||
|
></mat-card-header |
||||
|
> |
||||
|
<mat-card-content class="mt-3"> |
||||
|
<div class="comparison-legend small"> |
||||
|
<span class="legend-item"> |
||||
|
<span |
||||
|
aria-hidden="true" |
||||
|
class="legend-marker current-marker" |
||||
|
></span> |
||||
|
<span i18n>Actual</span> |
||||
|
</span> |
||||
|
<span class="legend-item"> |
||||
|
<span aria-hidden="true" class="legend-marker target-marker"></span> |
||||
|
<span i18n>Target</span> |
||||
|
</span> |
||||
|
</div> |
||||
|
@for (row of displayedRows; track row.assetClass) { |
||||
|
<div |
||||
|
class="comparison-row mb-3" |
||||
|
matTooltipClass="targets-allocation-tooltip" |
||||
|
matTooltipPosition="above" |
||||
|
matTooltipTouchGestures="off" |
||||
|
role="group" |
||||
|
tabindex="0" |
||||
|
[attr.aria-label]="formatClass(row.assetClass)" |
||||
|
[matTooltip]="allocationTooltip(row)" |
||||
|
[matTooltipPositionAtOrigin]="true" |
||||
|
[matTooltipShowDelay]="150" |
||||
|
> |
||||
|
<div class="d-flex justify-content-between mb-1"> |
||||
|
<span>{{ formatClass(row.assetClass) }}</span> |
||||
|
<span [class.text-danger]="row.outOfTolerance"> |
||||
|
{{ |
||||
|
row.drift | targetPercent: user?.settings.locale : 2 : true |
||||
|
}} |
||||
|
</span> |
||||
|
</div> |
||||
|
<div class="comparison-track"> |
||||
|
<div |
||||
|
class="comparison-bar current-bar" |
||||
|
[style.width.%]="row.actual * 100" |
||||
|
></div> |
||||
|
</div> |
||||
|
<div class="comparison-track"> |
||||
|
<div |
||||
|
class="comparison-bar target-bar" |
||||
|
[style.width.%]="row.target * 100" |
||||
|
></div> |
||||
|
</div> |
||||
|
</div> |
||||
|
} |
||||
|
</mat-card-content> |
||||
|
</mat-card> |
||||
|
|
||||
|
<mat-card appearance="outlined"> |
||||
|
<mat-card-header |
||||
|
><mat-card-title i18n id="targets-deviation-title" |
||||
|
>Deviation details</mat-card-title |
||||
|
></mat-card-header |
||||
|
> |
||||
|
<mat-card-content class="targets-table-container mt-3"> |
||||
|
<table aria-labelledby="targets-deviation-title" class="targets-table"> |
||||
|
<thead> |
||||
|
<tr> |
||||
|
<th i18n scope="col">Asset class</th> |
||||
|
<th class="numeric-column" i18n scope="col">Actual</th> |
||||
|
<th class="numeric-column" i18n scope="col">Target</th> |
||||
|
<th class="numeric-column" i18n scope="col">Deviation</th> |
||||
|
<th class="status-column" i18n scope="col">Status</th> |
||||
|
</tr> |
||||
|
</thead> |
||||
|
<tbody> |
||||
|
@for (row of displayedRows; track row.assetClass) { |
||||
|
<tr> |
||||
|
<th scope="row">{{ formatClass(row.assetClass) }}</th> |
||||
|
<td class="numeric-column"> |
||||
|
{{ row.actual | targetPercent: user?.settings.locale }} |
||||
|
</td> |
||||
|
<td class="numeric-column"> |
||||
|
{{ row.target | targetPercent: user?.settings.locale }} |
||||
|
</td> |
||||
|
<td class="numeric-column"> |
||||
|
{{ |
||||
|
row.drift | targetPercent: user?.settings.locale : 2 : true |
||||
|
}} |
||||
|
</td> |
||||
|
<td class="status-column"> |
||||
|
@if (row.outOfTolerance) { |
||||
|
<span class="text-danger" i18n>Outside tolerance</span> |
||||
|
} @else { |
||||
|
<span class="text-success" i18n>Within tolerance</span> |
||||
|
} |
||||
|
</td> |
||||
|
</tr> |
||||
|
} |
||||
|
</tbody> |
||||
|
</table> |
||||
|
</mat-card-content> |
||||
|
</mat-card> |
||||
|
} |
||||
|
</div> |
||||
@ -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` |
||||
|
} |
||||
|
]; |
||||
@ -0,0 +1,119 @@ |
|||||
|
:host { |
||||
|
display: block; |
||||
|
} |
||||
|
|
||||
|
.account-select { |
||||
|
width: min(320px, 100%); |
||||
|
} |
||||
|
|
||||
|
.comparison-legend { |
||||
|
display: flex; |
||||
|
flex-wrap: wrap; |
||||
|
align-items: center; |
||||
|
justify-content: flex-end; |
||||
|
gap: 1.25rem; |
||||
|
margin-bottom: 1.25rem; |
||||
|
} |
||||
|
|
||||
|
.legend-item { |
||||
|
display: inline-flex; |
||||
|
align-items: center; |
||||
|
gap: 0.45rem; |
||||
|
} |
||||
|
|
||||
|
.legend-marker { |
||||
|
flex: none; |
||||
|
width: 0.65rem; |
||||
|
height: 0.65rem; |
||||
|
border-radius: 0.15rem; |
||||
|
} |
||||
|
|
||||
|
.comparison-row { |
||||
|
border-radius: 0.35rem; |
||||
|
cursor: help; |
||||
|
|
||||
|
&:focus-visible { |
||||
|
outline: 2px solid currentColor; |
||||
|
outline-offset: 6px; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.comparison-track { |
||||
|
height: 0.62rem; |
||||
|
background: rgba(128, 128, 128, 0.11); |
||||
|
border-radius: 0.35rem; |
||||
|
margin-bottom: 0.3rem; |
||||
|
overflow: hidden; |
||||
|
} |
||||
|
|
||||
|
.comparison-bar { |
||||
|
height: 100%; |
||||
|
border-radius: 0.35rem; |
||||
|
} |
||||
|
|
||||
|
.current-bar, |
||||
|
.current-marker { |
||||
|
background: #36cfcc; |
||||
|
} |
||||
|
|
||||
|
.target-bar, |
||||
|
.target-marker { |
||||
|
background: #3686cf; |
||||
|
} |
||||
|
|
||||
|
.targets-table-container { |
||||
|
min-width: 0; |
||||
|
overflow-x: auto; |
||||
|
} |
||||
|
|
||||
|
.targets-table { |
||||
|
width: 100%; |
||||
|
min-width: 40rem; |
||||
|
margin: 0; |
||||
|
border-collapse: collapse; |
||||
|
|
||||
|
th, |
||||
|
td { |
||||
|
padding: 0.875rem 1rem; |
||||
|
border-bottom: 1px solid rgba(128, 128, 128, 0.2); |
||||
|
vertical-align: middle; |
||||
|
|
||||
|
&:first-child { |
||||
|
width: 32%; |
||||
|
padding-left: 0; |
||||
|
text-align: left; |
||||
|
} |
||||
|
|
||||
|
&:last-child { |
||||
|
padding-right: 0; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
thead th { |
||||
|
font-weight: 600; |
||||
|
} |
||||
|
|
||||
|
tbody th { |
||||
|
font-weight: inherit; |
||||
|
} |
||||
|
|
||||
|
tbody tr:last-child { |
||||
|
th, |
||||
|
td { |
||||
|
border-bottom: 0; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
.numeric-column { |
||||
|
width: 15%; |
||||
|
text-align: right; |
||||
|
white-space: nowrap; |
||||
|
font-variant-numeric: tabular-nums; |
||||
|
} |
||||
|
|
||||
|
.status-column { |
||||
|
width: 23%; |
||||
|
text-align: right; |
||||
|
white-space: nowrap; |
||||
|
} |
||||
|
} |
||||
@ -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<AssetClass, number>; |
||||
|
/** Maximum absolute drift per asset class, as a fraction (0.05 = 5%). */ |
||||
|
tolerance: number; |
||||
|
} |
||||
|
|
||||
|
export interface PortfolioTargetsSettings { |
||||
|
version: 1; |
||||
|
activeProfileId: string; |
||||
|
profiles: PortfolioTargetProfile[]; |
||||
|
} |
||||
@ -0,0 +1,696 @@ |
|||||
|
import { PortfolioDetails } from '@ghostfolio/common/interfaces'; |
||||
|
import { AssetClass, AssetSubClass } 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<PortfolioDetails, 'accounts' | 'holdings' | 'summary'> { |
||||
|
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, |
||||
|
summary: { |
||||
|
accountCashInBaseCurrency: cash, |
||||
|
cash, |
||||
|
emergencyFund: { cash: 0 }, |
||||
|
filteredValueInBaseCurrency: equity + bonds, |
||||
|
liabilitiesInBaseCurrency: 0 |
||||
|
} as PortfolioDetails['summary'] |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
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'); |
||||
|
}); |
||||
|
it('does not misclassify an omitted snapshot position as cash', () => { |
||||
|
const details = makeDetails({ equity: 100, cash: 25 }); |
||||
|
details.holdings = []; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('inconsistent'); |
||||
|
expect(result.rows).toEqual([]); |
||||
|
}); |
||||
|
|
||||
|
it('requires independently verifiable cash and a snapshot total', () => { |
||||
|
const details = makeDetails({ equity: 100 }); |
||||
|
delete details.summary; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unavailable'); |
||||
|
}); |
||||
|
|
||||
|
it.each([-100, -0.0000000001])( |
||||
|
'reports negative cash %s as unsupported, not inconsistent', |
||||
|
(cash) => { |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details: makeDetails({ equity: 200, cash }), |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('unsupported'); |
||||
|
expect(result.rows).toEqual([]); |
||||
|
} |
||||
|
); |
||||
|
|
||||
|
it('does not hide a negative account balance with another account balance', () => { |
||||
|
const details = makeDetails({ equity: 200, cash: 100 }); |
||||
|
details.accounts.example.balance = -10; |
||||
|
details.accounts.other = { |
||||
|
balance: 110, |
||||
|
currency: 'EUR', |
||||
|
name: 'Other', |
||||
|
valueInBaseCurrency: 110 |
||||
|
}; |
||||
|
details.accounts.example.valueInBaseCurrency = 190; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unsupported'); |
||||
|
}); |
||||
|
|
||||
|
it('reports short holdings and liabilities as unsupported', () => { |
||||
|
const details = makeDetails({ equity: -100, cash: 200 }); |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unsupported'); |
||||
|
const liabilityDetails = makeDetails({ equity: 100 }); |
||||
|
liabilityDetails.summary.liabilitiesInBaseCurrency = 10; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details: liabilityDetails, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unsupported'); |
||||
|
}); |
||||
|
|
||||
|
it('reconciles securities-only portfolios including positions without an account', () => { |
||||
|
const details = makeDetails({ equity: 600, bonds: 400 }); |
||||
|
details.accounts = { |
||||
|
UNKNOWN: { ...details.accounts.example, currency: undefined } |
||||
|
}; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.accountCashValue).toBe(0); |
||||
|
expect(result.unclassifiedValue).toBe(0); |
||||
|
expect(result.totalDrift).toBe(0); |
||||
|
}); |
||||
|
|
||||
|
it('uses converted base-currency amounts rather than summing native balances', () => { |
||||
|
const details = makeDetails({ equity: 600, bonds: 300, cash: 100 }); |
||||
|
details.accounts = { |
||||
|
euro: { |
||||
|
balance: 20, |
||||
|
currency: 'EUR', |
||||
|
name: 'Euro', |
||||
|
valueInBaseCurrency: 620 |
||||
|
}, |
||||
|
dollar: { |
||||
|
balance: 100, |
||||
|
currency: 'USD', |
||||
|
name: 'Dollar', |
||||
|
valueInBaseCurrency: 380 |
||||
|
} |
||||
|
}; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.accountCashValue).toBe(100); |
||||
|
expect(result.totalValue).toBe(1000); |
||||
|
}); |
||||
|
|
||||
|
it('preserves cash reserved for an emergency fund', () => { |
||||
|
const details = makeDetails({ cash: 100 }); |
||||
|
details.summary.cash = 40; |
||||
|
details.summary.emergencyFund.cash = 60; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).accountCashValue |
||||
|
).toBe(100); |
||||
|
}); |
||||
|
|
||||
|
it('shows unclassified holdings separately and applies the same tolerance', () => { |
||||
|
const details = makeDetails({ equity: 95, cash: 5 }); |
||||
|
details.holdings[0].assetProfile.assetClass = undefined; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 1 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.unclassifiedValue).toBe(95); |
||||
|
expect( |
||||
|
result.rows.find(({ assetClass }) => assetClass === 'UNKNOWN')?.actual |
||||
|
).toBe(0.95); |
||||
|
expect(result.outOfToleranceCount).toBe(0); |
||||
|
expect( |
||||
|
result.rows.reduce((sum, { actual }) => sum + actual, 0) |
||||
|
).toBeCloseTo(1); |
||||
|
expect(result.totalDrift).toBeCloseTo(1); |
||||
|
}); |
||||
|
|
||||
|
it('permits only floating-point summation noise without normalizing values', () => { |
||||
|
const details = makeDetails({ equity: 0.1, bonds: 0.2 }); |
||||
|
details.accounts.example.valueInBaseCurrency = 0.3; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.accountCashValue).toBe(0); |
||||
|
details.accounts.example.valueInBaseCurrency -= 1e-10; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('inconsistent'); |
||||
|
}); |
||||
|
|
||||
|
it('does not treat a small but nonzero portfolio as empty', () => { |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details: makeDetails({ cash: 1e-12 }), |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('ready'); |
||||
|
}); |
||||
|
|
||||
|
it('treats the tolerance boundary inclusively', () => { |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details: makeDetails({ equity: 650, bonds: 350 }), |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.outOfToleranceCount).toBe(0); |
||||
|
}); |
||||
|
|
||||
|
it('treats redacted account values as unavailable', () => { |
||||
|
const details = makeDetails({ cash: 100 }); |
||||
|
details.accounts.example.valueInBaseCurrency = undefined; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unavailable'); |
||||
|
}); |
||||
|
function includeAccountCash( |
||||
|
details: ReturnType<typeof makeDetails>, |
||||
|
cash: number, |
||||
|
currency = 'USD' |
||||
|
) { |
||||
|
details.holdings.push({ |
||||
|
assetProfile: { |
||||
|
assetClass: AssetClass.LIQUIDITY, |
||||
|
assetSubClass: AssetSubClass.CASH, |
||||
|
currency, |
||||
|
symbol: currency |
||||
|
}, |
||||
|
quantity: cash, |
||||
|
valueInBaseCurrency: cash |
||||
|
} as PortfolioDetails['holdings'][number]); |
||||
|
details.summary.filteredValueInBaseCurrency += cash; |
||||
|
return details; |
||||
|
} |
||||
|
|
||||
|
it.each([false, true])( |
||||
|
'accepts summary cancellation for a 0.01 balance and 10000 fund (cash holding: %s)', |
||||
|
(withCashHolding) => { |
||||
|
const details = makeDetails({ cash: 0.01 }); |
||||
|
// Actual getSummary output: Big(0.01).minus(10000).toNumber().
|
||||
|
// The two serialized fields cannot reconstruct 0.01 exactly in binary.
|
||||
|
details.summary.cash = -9999.99; |
||||
|
details.summary.emergencyFund.cash = 10000; |
||||
|
if (withCashHolding) { |
||||
|
includeAccountCash(details, 0.01); |
||||
|
} |
||||
|
|
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
|
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.accountCashValue).toBe(0.01); |
||||
|
expect(result.totalValue).toBe(0.01); |
||||
|
expect( |
||||
|
result.rows.find( |
||||
|
({ assetClass }) => assetClass === AssetClass.LIQUIDITY |
||||
|
)?.actual |
||||
|
).toBe(1); |
||||
|
} |
||||
|
); |
||||
|
|
||||
|
it('rejects a one-dollar cash discrepancy beside 1e15 in securities', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 1e15, cash: 100 }), |
||||
|
99 |
||||
|
); |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
|
||||
|
expect(result.status).toBe('inconsistent'); |
||||
|
expect(result.rows).toEqual([]); |
||||
|
}); |
||||
|
|
||||
|
it.each( |
||||
|
[1e4, 1e15, 3e15, 1e16].flatMap((fund) => |
||||
|
[99, 100].map((cash) => ({ fund, cash })) |
||||
|
) |
||||
|
)( |
||||
|
'reconciles two accounts with fund $fund and synthetic cash $cash', |
||||
|
({ fund, cash }) => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 1e15, cash: 100 }), |
||||
|
cash |
||||
|
); |
||||
|
details.accounts = { |
||||
|
securities: { |
||||
|
balance: 0, |
||||
|
currency: 'USD', |
||||
|
name: 'Securities', |
||||
|
valueInBaseCurrency: 1e15 |
||||
|
}, |
||||
|
cash: { |
||||
|
balance: 100, |
||||
|
currency: 'USD', |
||||
|
name: 'Cash', |
||||
|
valueInBaseCurrency: 100 |
||||
|
} |
||||
|
}; |
||||
|
details.summary.cash = 100 - fund; |
||||
|
details.summary.emergencyFund.cash = fund; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe(cash === 100 ? 'ready' : 'inconsistent'); |
||||
|
if (cash === 99) expect(result.rows).toEqual([]); |
||||
|
} |
||||
|
); |
||||
|
|
||||
|
it.each([undefined, null, NaN, Infinity, -Infinity])( |
||||
|
'requires finite independent cash (%s), without a legacy fallback', |
||||
|
(cash) => { |
||||
|
const details = makeDetails({ cash: 100 }); |
||||
|
details.summary.accountCashInBaseCurrency = cash; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unavailable'); |
||||
|
} |
||||
|
); |
||||
|
|
||||
|
it('treats a legacy response without independent cash as unavailable', () => { |
||||
|
const details = makeDetails({ cash: 100 }); |
||||
|
delete details.summary.accountCashInBaseCurrency; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unavailable'); |
||||
|
}); |
||||
|
|
||||
|
it('does not depend on the adjusted summary fields', () => { |
||||
|
const details = makeDetails({ cash: 100 }); |
||||
|
delete details.summary.cash; |
||||
|
delete details.summary.emergencyFund; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('ready'); |
||||
|
}); |
||||
|
|
||||
|
it('keeps negative independent cash unsupported', () => { |
||||
|
const details = makeDetails({ equity: 100 }); |
||||
|
details.summary.accountCashInBaseCurrency = -1; |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('unsupported'); |
||||
|
}); |
||||
|
|
||||
|
it.each([0, 1])( |
||||
|
'checks independently converted multi-currency cash with FX difference %s', |
||||
|
(difference) => { |
||||
|
const details = makeDetails({ equity: 600, cash: 100 }); |
||||
|
details.accounts = { |
||||
|
euro: { |
||||
|
balance: 20, |
||||
|
currency: 'EUR', |
||||
|
name: 'Euro', |
||||
|
valueInBaseCurrency: 640 |
||||
|
}, |
||||
|
dollar: { |
||||
|
balance: 60, |
||||
|
currency: 'USD', |
||||
|
name: 'Dollar', |
||||
|
valueInBaseCurrency: 60 |
||||
|
} |
||||
|
}; |
||||
|
includeAccountCash(details, 40 + difference, 'EUR'); |
||||
|
includeAccountCash(details, 60, 'USD'); |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe(difference ? 'inconsistent' : 'ready'); |
||||
|
} |
||||
|
); |
||||
|
|
||||
|
it.each(['security', 'cash'])('rejects a duplicated %s holding', (kind) => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 100, cash: 50 }), |
||||
|
50 |
||||
|
); |
||||
|
details.holdings.push({ ...details.holdings[kind === 'security' ? 0 : 1] }); |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('inconsistent'); |
||||
|
}); |
||||
|
|
||||
|
it('distinguishes a separately valued CASH instrument from synthetic account cash', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 20, cash: 10 }), |
||||
|
10 |
||||
|
); |
||||
|
details.holdings[0].assetProfile = { |
||||
|
assetClass: AssetClass.LIQUIDITY, |
||||
|
assetSubClass: AssetSubClass.CASH, |
||||
|
currency: 'USD', |
||||
|
symbol: 'separate-cash-instrument' |
||||
|
} as PortfolioDetails['holdings'][number]['assetProfile']; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.accountCashValue).toBe(10); |
||||
|
expect(result.totalValue).toBe(30); |
||||
|
}); |
||||
|
|
||||
|
it('accepts coherent cash beside 1e15 in securities', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 1e15, cash: 100 }), |
||||
|
100 |
||||
|
); |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('ready'); |
||||
|
}); |
||||
|
|
||||
|
it('does not apply a large emergency fund budget to missing securities', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 1, cash: 0.01 }), |
||||
|
0.01 |
||||
|
); |
||||
|
details.summary.cash = -999999999999.99; |
||||
|
details.summary.emergencyFund.cash = 1e12; |
||||
|
// Emergency-fund adjustments must not affect any reconciliation budget.
|
||||
|
details.holdings[0].valueInBaseCurrency -= 0.0001; |
||||
|
|
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('inconsistent'); |
||||
|
}); |
||||
|
|
||||
|
it('reconciles the real queue snapshot without double-counting account cash', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 600, bonds: 300, cash: 100 }), |
||||
|
100 |
||||
|
); |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
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.totalDrift).toBeCloseTo(0.1); |
||||
|
expect(result.outOfToleranceCount).toBe(2); |
||||
|
}); |
||||
|
|
||||
|
it('accepts a cash-only queue snapshot', () => { |
||||
|
const details = includeAccountCash(makeDetails({ cash: 250 }), 250); |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.totalValue).toBe(250); |
||||
|
expect( |
||||
|
result.rows.find(({ assetClass }) => assetClass === AssetClass.LIQUIDITY) |
||||
|
?.actual |
||||
|
).toBe(1); |
||||
|
}); |
||||
|
|
||||
|
it('reconciles multiple synthetic currency holdings by their base-currency values', () => { |
||||
|
const details = makeDetails({ equity: 600, cash: 100 }); |
||||
|
includeAccountCash(details, 40, 'EUR'); |
||||
|
includeAccountCash(details, 60, 'USD'); |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.totalValue).toBe(700); |
||||
|
expect(result.accountCashValue).toBe(100); |
||||
|
}); |
||||
|
|
||||
|
it('rejects incomplete cash positions even if an unrelated holding hides the difference', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 600, cash: 100 }), |
||||
|
50 |
||||
|
); |
||||
|
details.holdings[0].valueInBaseCurrency = 650; |
||||
|
details.summary.filteredValueInBaseCurrency += 50; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('inconsistent'); |
||||
|
expect(result.rows).toEqual([]); |
||||
|
}); |
||||
|
|
||||
|
it('does not confuse a separately held cash instrument with an account balance', () => { |
||||
|
const details = makeDetails({ equity: 100, cash: 50 }); |
||||
|
details.holdings[0].assetProfile = { |
||||
|
assetClass: AssetClass.LIQUIDITY, |
||||
|
assetSubClass: AssetSubClass.CASH, |
||||
|
currency: 'USD', |
||||
|
symbol: 'synthetic-cash-instrument' |
||||
|
} as PortfolioDetails['holdings'][number]['assetProfile']; |
||||
|
const result = calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}); |
||||
|
expect(result.status).toBe('ready'); |
||||
|
expect(result.totalValue).toBe(150); |
||||
|
expect( |
||||
|
result.rows.find(({ assetClass }) => assetClass === AssetClass.LIQUIDITY) |
||||
|
?.actual |
||||
|
).toBe(1); |
||||
|
}); |
||||
|
|
||||
|
it('still rejects omitted securities in a snapshot which already contains cash', () => { |
||||
|
const details = includeAccountCash( |
||||
|
makeDetails({ equity: 600, cash: 100 }), |
||||
|
100 |
||||
|
); |
||||
|
details.holdings.shift(); |
||||
|
expect( |
||||
|
calculatePortfolioTargets({ |
||||
|
details, |
||||
|
targets: allocations, |
||||
|
tolerance: 0.05 |
||||
|
}).status |
||||
|
).toBe('inconsistent'); |
||||
|
}); |
||||
|
}); |
||||
@ -0,0 +1,303 @@ |
|||||
|
import { UNKNOWN_KEY } from '@ghostfolio/common/config'; |
||||
|
import { |
||||
|
PortfolioDetails, |
||||
|
PortfolioTargetsSettings |
||||
|
} from '@ghostfolio/common/interfaces'; |
||||
|
import { AssetClass, AssetSubClass } from '@ghostfolio/prisma/enums'; |
||||
|
|
||||
|
export const TARGET_ASSET_CLASSES = Object.values(AssetClass); |
||||
|
|
||||
|
export type TargetAllocationKey = AssetClass | typeof UNKNOWN_KEY; |
||||
|
|
||||
|
/** |
||||
|
* Forward-error bound gamma(n) * magnitude for n rounding steps. EPSILON |
||||
|
* conservatively bounds unit roundoff (EPSILON / 2), including evaluation of |
||||
|
* the bound from already rounded, nonnegative magnitudes. No currency units |
||||
|
* or decimal-place assumptions enter this calculation. |
||||
|
*/ |
||||
|
function roundoffBudget(magnitude: number, operations: number) { |
||||
|
const error = operations * Number.EPSILON; |
||||
|
return (error / (1 - error)) * Math.abs(magnitude); |
||||
|
} |
||||
|
|
||||
|
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; |
||||
|
/** Independently verified account cash, whether already represented in holdings or not. */ |
||||
|
accountCashValue: number; |
||||
|
/** Half of the absolute drifts, including unclassified holdings. */ |
||||
|
totalDrift: number; |
||||
|
maxDrift: number; |
||||
|
outOfToleranceCount: number; |
||||
|
unclassifiedValue: number; |
||||
|
status: 'ready' | 'empty' | 'unavailable' | 'inconsistent' | 'unsupported'; |
||||
|
} |
||||
|
|
||||
|
/** 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<Record<AssetClass, number>>, |
||||
|
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. Cached snapshots computed by the queue worker already |
||||
|
* include account cash as currency holdings. Never add that cash a second time. |
||||
|
* |
||||
|
* 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<PortfolioDetails, 'accounts' | 'holdings' | 'summary'>; |
||||
|
targets: Partial<Record<AssetClass, number>>; |
||||
|
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<TargetAllocationKey, number>( |
||||
|
TARGET_ASSET_CLASSES.map((assetClass) => [assetClass, 0]) |
||||
|
); |
||||
|
|
||||
|
let holdingsValue = 0; |
||||
|
let cashHoldingsValue = 0; |
||||
|
let cashHoldingsCount = 0; |
||||
|
let hasCashHoldings = false; |
||||
|
for (const holding of details.holdings) { |
||||
|
const value = holding.valueInBaseCurrency; |
||||
|
if (value === undefined || !Number.isFinite(value)) { |
||||
|
return empty('unavailable'); |
||||
|
} |
||||
|
|
||||
|
if (value < 0 || holding.quantity < 0) { |
||||
|
return empty('unsupported'); |
||||
|
} |
||||
|
|
||||
|
holdingsValue += value; |
||||
|
|
||||
|
const profile = holding.assetProfile; |
||||
|
// The backend's synthetic currency positions use the currency code as
|
||||
|
// their symbol. Ordinary cash instruments have their own symbol and must
|
||||
|
// not be confused with an account's balance.
|
||||
|
if ( |
||||
|
profile?.assetClass === AssetClass.LIQUIDITY && |
||||
|
profile.assetSubClass === AssetSubClass.CASH && |
||||
|
typeof profile.currency === 'string' && |
||||
|
profile.symbol === profile.currency |
||||
|
) { |
||||
|
hasCashHoldings = true; |
||||
|
cashHoldingsCount++; |
||||
|
cashHoldingsValue += 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, balance }) => |
||||
|
!Number.isFinite(valueInBaseCurrency) || !Number.isFinite(balance) |
||||
|
) |
||||
|
) { |
||||
|
return empty('unavailable'); |
||||
|
} |
||||
|
|
||||
|
// Negative balances and short positions are legitimate, but the v1
|
||||
|
// long-only comparison cannot represent them. Never normalize them away.
|
||||
|
if ( |
||||
|
accountValues.some( |
||||
|
({ balance, valueInBaseCurrency }) => |
||||
|
balance < 0 || valueInBaseCurrency < 0 |
||||
|
) |
||||
|
) { |
||||
|
return empty('unsupported'); |
||||
|
} |
||||
|
|
||||
|
const accountsTotal = accountValues.reduce( |
||||
|
(sum, account) => sum + account.valueInBaseCurrency, |
||||
|
0 |
||||
|
); |
||||
|
|
||||
|
if (accountValues.length === 0 && holdingsValue > 0) { |
||||
|
return empty('unavailable'); |
||||
|
} |
||||
|
|
||||
|
// A positive residual alone is not proof of cash: getDetails can omit a
|
||||
|
// position whose symbol profile is missing. Its existing summary provides
|
||||
|
// the snapshot total and independently converted account cash, for this
|
||||
|
// same unfiltered/account-only selection.
|
||||
|
const summary = details.summary; |
||||
|
const snapshotValue = summary?.filteredValueInBaseCurrency; |
||||
|
const accountCashValue = summary?.accountCashInBaseCurrency; |
||||
|
if ( |
||||
|
typeof snapshotValue !== 'number' || |
||||
|
typeof accountCashValue !== 'number' || |
||||
|
!summary || |
||||
|
![ |
||||
|
summary.filteredValueInBaseCurrency, |
||||
|
accountCashValue, |
||||
|
summary.liabilitiesInBaseCurrency |
||||
|
].every((value) => typeof value === 'number' && Number.isFinite(value)) |
||||
|
) { |
||||
|
return empty('unavailable'); |
||||
|
} |
||||
|
|
||||
|
if (accountCashValue < 0 || summary.liabilitiesInBaseCurrency !== 0) { |
||||
|
return empty('unsupported'); |
||||
|
} |
||||
|
|
||||
|
const cashNotInHoldings = hasCashHoldings ? 0 : accountCashValue; |
||||
|
const totalValue = holdingsValue + cashNotInHoldings; |
||||
|
if ( |
||||
|
![holdingsValue, accountsTotal, accountCashValue, totalValue].every( |
||||
|
Number.isFinite |
||||
|
) |
||||
|
) { |
||||
|
return empty('unavailable'); |
||||
|
} |
||||
|
|
||||
|
// Holdings: one Big-to-number conversion per value, then n - 1 additions.
|
||||
|
// The snapshot independently converts the Big sum once.
|
||||
|
const holdingsError = roundoffBudget(holdingsValue, details.holdings.length); |
||||
|
const snapshotError = roundoffBudget(snapshotValue, 1); |
||||
|
|
||||
|
// Accounts: up to two FX multiplications (an indirect rate and the amount)
|
||||
|
// or a serialized snapshot price, a final conversion, then n - 1 additions.
|
||||
|
const accountsError = roundoffBudget(accountsTotal, accountValues.length + 2); |
||||
|
|
||||
|
// AccountService converts each nonnegative balance with up to two FX
|
||||
|
// multiplications, sums using Big and converts the sum once. These three
|
||||
|
// rounding steps stay at cash scale, independently of securities/funds.
|
||||
|
const cashError = roundoffBudget(accountCashValue, 3); |
||||
|
const cashHoldingsError = roundoffBudget( |
||||
|
cashHoldingsValue, |
||||
|
cashHoldingsCount |
||||
|
); |
||||
|
const totalError = hasCashHoldings |
||||
|
? holdingsError |
||||
|
: holdingsError + cashError + roundoffBudget(totalValue, 1); |
||||
|
|
||||
|
if ( |
||||
|
![holdingsError, snapshotError, accountsError, cashError, totalError].every( |
||||
|
Number.isFinite |
||||
|
) |
||||
|
) { |
||||
|
return empty('unavailable'); |
||||
|
} |
||||
|
|
||||
|
// Each comparison uses only its own operands. In particular, a large
|
||||
|
// security position must never enlarge the independent cash error budget.
|
||||
|
if ( |
||||
|
Math.abs(holdingsValue - snapshotValue) > holdingsError + snapshotError || |
||||
|
Math.abs(accountsTotal - totalValue) > accountsError + totalError || |
||||
|
(hasCashHoldings && |
||||
|
Math.abs(cashHoldingsValue - accountCashValue) > |
||||
|
cashHoldingsError + cashError) |
||||
|
) { |
||||
|
return empty('inconsistent'); |
||||
|
} |
||||
|
|
||||
|
if (totalValue === 0) { |
||||
|
return empty('empty'); |
||||
|
} |
||||
|
|
||||
|
values.set( |
||||
|
AssetClass.LIQUIDITY, |
||||
|
(values.get(AssetClass.LIQUIDITY) ?? 0) + cashNotInHoldings |
||||
|
); |
||||
|
|
||||
|
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: unclassifiedValue / totalValue > tolerance + 1e-10 |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
const drifts = rows.map(({ drift }) => Math.abs(drift)); |
||||
|
|
||||
|
return { |
||||
|
rows, |
||||
|
totalValue, |
||||
|
accountCashValue, |
||||
|
totalDrift: drifts.reduce((sum, value) => sum + value, 0) / 2, |
||||
|
maxDrift: Math.max(...drifts), |
||||
|
outOfToleranceCount: rows.filter(({ outOfTolerance }) => outOfTolerance) |
||||
|
.length, |
||||
|
unclassifiedValue, |
||||
|
status: 'ready' |
||||
|
}; |
||||
|
} |
||||
@ -0,0 +1,50 @@ |
|||||
|
import { UpdateUserSettingDto } from '@ghostfolio/common/dtos/update-user-setting.dto'; |
||||
|
|
||||
|
import { validate } from 'class-validator'; |
||||
|
|
||||
|
import { createDefaultPortfolioTarget } from './portfolio-targets-presets'; |
||||
|
|
||||
|
function makeDto() { |
||||
|
return Object.assign(new UpdateUserSettingDto(), { |
||||
|
portfolioTargets: { |
||||
|
version: 1 as const, |
||||
|
activeProfileId: 'global', |
||||
|
profiles: [createDefaultPortfolioTarget()] |
||||
|
} |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
describe('Portfolio targets HTTP validation', () => { |
||||
|
it('accepts the versioned target and existing users without one', async () => { |
||||
|
expect(await validate(makeDto())).toEqual([]); |
||||
|
expect(await validate(new UpdateUserSettingDto())).toEqual([]); |
||||
|
}); |
||||
|
|
||||
|
it.each([-0.01, 1.01, NaN, Infinity])( |
||||
|
'rejects tolerance %s', |
||||
|
async (tolerance) => { |
||||
|
const dto = makeDto(); |
||||
|
dto.portfolioTargets.profiles[0].tolerance = tolerance; |
||||
|
expect(await validate(dto)).toEqual( |
||||
|
expect.arrayContaining([ |
||||
|
expect.objectContaining({ property: 'portfolioTargets' }) |
||||
|
]) |
||||
|
); |
||||
|
} |
||||
|
); |
||||
|
|
||||
|
it('rejects null instead of storing an unversioned target', async () => { |
||||
|
const dto = Object.assign(makeDto(), { portfolioTargets: null }); |
||||
|
expect(await validate(dto)).toHaveLength(1); |
||||
|
}); |
||||
|
|
||||
|
it('rejects incomplete allocations and unsupported versions', async () => { |
||||
|
const dto = makeDto(); |
||||
|
delete dto.portfolioTargets.profiles[0].allocations.COMMODITY; |
||||
|
expect(await validate(dto)).toHaveLength(1); |
||||
|
const unsupported = Object.assign(makeDto(), { |
||||
|
portfolioTargets: { ...makeDto().portfolioTargets, version: 2 } |
||||
|
}); |
||||
|
expect(await validate(unsupported)).toHaveLength(1); |
||||
|
}); |
||||
|
}); |
||||
@ -0,0 +1,37 @@ |
|||||
|
import { AssetClass } from '@ghostfolio/prisma/enums'; |
||||
|
|
||||
|
import { isValidPortfolioTarget } from './portfolio-targets-calculator'; |
||||
|
import { |
||||
|
createDefaultPortfolioTarget, |
||||
|
PORTFOLIO_TARGET_PRESETS |
||||
|
} from './portfolio-targets-presets'; |
||||
|
|
||||
|
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); |
||||
|
}); |
||||
|
}); |
||||
@ -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<AssetClass, number>; |
||||
|
} |
||||
|
|
||||
|
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('cautious-20-80', 'Cautious (20/80)', 0.2, 0.8), |
||||
|
makePreset('conservative-40-60', 'Conservative (40/60)', 0.4, 0.6), |
||||
|
makePreset('moderate-60-40', 'Moderate (60/40)', 0.6, 0.4), |
||||
|
makePreset('aggressive-80-20', 'Aggressive (80/20)', 0.8, 0.2), |
||||
|
makePreset('golden-butterfly', 'Golden Butterfly (simplified)', 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 |
||||
|
}; |
||||
|
} |
||||
@ -0,0 +1,86 @@ |
|||||
|
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); |
||||
|
}); |
||||
|
}); |
||||
@ -0,0 +1,71 @@ |
|||||
|
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<PortfolioTargetsSettings>; |
||||
|
|
||||
|
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 |
||||
|
); |
||||
|
} |
||||
Loading…
Reference in new issue