mirror of https://github.com/ghostfolio/ghostfolio
42 changed files with 7609 additions and 288 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,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,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,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([]); |
|||
}); |
|||
}); |
|||
@ -1,7 +1,119 @@ |
|||
:host { display: block; } |
|||
.account-select { width: min(320px, 100%); } |
|||
.comparison-track { height: 0.62rem; background: rgba(128,128,128,.11); border-radius: .35rem; margin-bottom: .3rem; overflow: hidden; } |
|||
.comparison-bar { height: 100%; border-radius: .35rem; } |
|||
.current-bar, .current-marker { background: #36cfcc; } |
|||
.target-bar, .target-marker { background: #3686cf; } |
|||
.legend-marker { display: inline-block; width: .65rem; height: .65rem; border-radius: .15rem; } |
|||
: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,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); |
|||
}); |
|||
}); |
|||
Loading…
Reference in new issue