Browse Source

Merge 81cff728e4 into 618e6c9d27

pull/8411/merge
MoisesRoig 16 hours ago
committed by GitHub
parent
commit
dc3e9a0066
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 1
      CHANGELOG.md
  2. 26
      apps/api/src/app/portfolio/portfolio.service.spec.ts
  3. 15
      apps/api/src/app/portfolio/portfolio.service.ts
  4. 10
      apps/api/src/services/account-balance/account-balance.service.ts
  5. 18
      apps/client/src/app/components/header/header.component.ts
  6. 12
      apps/client/src/app/services/user/user.service.ts
  7. 27
      libs/ui/src/lib/account-selector/account-selector.component.html
  8. 18
      libs/ui/src/lib/account-selector/account-selector.component.stories.ts
  9. 65
      libs/ui/src/lib/account-selector/account-selector.component.ts
  10. 27
      libs/ui/src/lib/assistant/assistant.component.ts
  11. 6
      libs/ui/src/lib/portfolio-filter-form/interfaces/portfolio-filter-form-value.interface.ts
  12. 10
      libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.html
  13. 22
      libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.ts
  14. 101
      libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.util.spec.ts
  15. 51
      libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.util.ts

1
CHANGELOG.md

@ -37,6 +37,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `comment` to the `AccountBalance` database schema as a preparation for notes in the account balances
- Added the discovery endpoints of OAuth 2.1 to the server of the Model Context Protocol (MCP) (experimental)
- Added support for selecting multiple accounts, asset classes and tags in the portfolio filters of the assistant
### Changed

26
apps/api/src/app/portfolio/portfolio.service.spec.ts

@ -1771,7 +1771,31 @@ describe('PortfolioService', () => {
expect(accountsSpy).toHaveBeenCalledWith(
expect.objectContaining({
where: { userId: userDummyData.id, id: account.id }
where: { userId: userDummyData.id, id: { in: [account.id] } }
})
);
});
it('should only consider accounts of the current user if the activities are filtered by multiple accounts', async () => {
const accountsSpy = jest.spyOn(accountService, 'accounts');
await getValueOfAccountsAndPlatforms({
activities: [],
filters: [
{ id: account.id, type: 'ACCOUNT' },
{ id: 'f7d5e4c3-b2a1-4f0e-9d8c-7b6a5f4e3d2c', type: 'ACCOUNT' }
],
portfolioItemsNow: {},
userCurrency: 'USD',
userId: userDummyData.id
});
expect(accountsSpy).toHaveBeenCalledWith(
expect.objectContaining({
where: {
userId: userDummyData.id,
id: { in: [account.id, 'f7d5e4c3-b2a1-4f0e-9d8c-7b6a5f4e3d2c'] }
}
})
);
});

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

@ -2429,10 +2429,21 @@ export class PortfolioService {
if (filters.length === 0) {
currentAccounts = await this.accountService.getAccounts(userId);
} else if (filters.length === 1 && filters[0].type === 'ACCOUNT') {
} else if (
filters.every(({ type }) => {
return type === 'ACCOUNT';
})
) {
currentAccounts = await this.accountService.accounts({
include: { platform: true, tags: true },
where: { userId, id: filters[0].id }
where: {
userId,
id: {
in: filters.map(({ id }) => {
return id;
})
}
}
});
} else {
const accountIds = Array.from(

10
apps/api/src/services/account-balance/account-balance.service.ts

@ -163,12 +163,16 @@ export class AccountBalanceService {
}): Promise<AccountBalancesResponse> {
const where: Prisma.AccountBalanceWhereInput = { userId };
const { ACCOUNT: [filterByAccount] = [] } = groupBy(filters, ({ type }) => {
const { ACCOUNT: filtersByAccount = [] } = groupBy(filters, ({ type }) => {
return type;
});
if (filterByAccount) {
where.accountId = filterByAccount.id;
if (filtersByAccount.length > 0) {
where.accountId = {
in: filtersByAccount.map(({ id }) => {
return id;
})
};
}
if (withExcludedAccounts === false) {

18
apps/client/src/app/components/header/header.component.ts

@ -249,17 +249,29 @@ export class GfHeaderComponent implements OnChanges {
protected onFiltersChanged(filters: Filter[]) {
const userSetting: UpdateUserSettingDto = {};
const getIds = (type: Filter['type']) => {
const ids = filters
.filter((filter) => {
return filter.type === type && !!filter.id;
})
.map(({ id }) => {
return id;
});
return ids.length > 0 ? ids : null;
};
for (const filter of filters) {
if (filter.type === 'ACCOUNT') {
userSetting['filters.accounts'] = filter.id ? [filter.id] : null;
userSetting['filters.accounts'] = getIds('ACCOUNT');
} else if (filter.type === 'ASSET_CLASS') {
userSetting['filters.assetClasses'] = filter.id ? [filter.id] : null;
userSetting['filters.assetClasses'] = getIds('ASSET_CLASS');
} else if (filter.type === 'DATA_SOURCE') {
userSetting['filters.dataSource'] = filter.id ? filter.id : null;
} else if (filter.type === 'SYMBOL') {
userSetting['filters.symbol'] = filter.id ? filter.id : null;
} else if (filter.type === 'TAG') {
userSetting['filters.tags'] = filter.id ? [filter.id] : null;
userSetting['filters.tags'] = getIds('TAG');
}
}

12
apps/client/src/app/services/user/user.service.ts

@ -54,16 +54,16 @@ export class UserService extends ObservableStore<UserStoreState> {
const filters: Filter[] = [];
const user = this.getState().user;
if (user?.settings['filters.accounts']) {
for (const id of user?.settings['filters.accounts'] ?? []) {
filters.push({
id: user.settings['filters.accounts'][0],
id,
type: 'ACCOUNT'
});
}
if (user?.settings['filters.assetClasses']) {
for (const id of user?.settings['filters.assetClasses'] ?? []) {
filters.push({
id: user.settings['filters.assetClasses'][0],
id,
type: 'ASSET_CLASS'
});
}
@ -82,9 +82,9 @@ export class UserService extends ObservableStore<UserStoreState> {
});
}
if (user?.settings['filters.tags']) {
for (const id of user?.settings['filters.tags'] ?? []) {
filters.push({
id: user.settings['filters.tags'][0],
id,
type: 'TAG'
});
}

27
libs/ui/src/lib/account-selector/account-selector.component.html

@ -7,23 +7,28 @@
<mat-select
[errorStateMatcher]="errorStateMatcher"
[formControl]="control"
[multiple]="multiple()"
[required]="isRequired()"
(closed)="onPanelClosed()"
>
<mat-select-trigger>
<div class="align-items-center align-middle d-inline-flex lh-1">
@if (selectedAccount()?.platform?.url) {
<gf-entity-logo
class="me-1"
[tooltip]="selectedAccount()?.platform?.name ?? ''"
[url]="selectedAccount()?.platform?.url ?? ''"
/>
}
<span>{{ selectedAccount()?.name }}</span>
</div>
@if (multiple()) {
<span>{{ selectedAccountNames() }}</span>
} @else {
<div class="align-items-center align-middle d-inline-flex lh-1">
@if (selectedAccount()?.platform?.url) {
<gf-entity-logo
class="me-1"
[tooltip]="selectedAccount()?.platform?.name ?? ''"
[url]="selectedAccount()?.platform?.url ?? ''"
/>
}
<span>{{ selectedAccount()?.name }}</span>
</div>
}
</mat-select-trigger>
@if (hasNullOption()) {
@if (hasNullOption() && !multiple()) {
<mat-option [value]="null" />
}

18
libs/ui/src/lib/account-selector/account-selector.component.stories.ts

@ -73,7 +73,7 @@ const ACCOUNTS: AccountWithPlatform[] = [
];
type AccountSelectorStory = GfAccountSelectorComponent & {
value: string | null;
value: string | string[] | null;
};
const meta: Meta<AccountSelectorStory> = {
@ -97,13 +97,14 @@ const meta: Meta<AccountSelectorStory> = {
imports: [GfAccountSelectorComponent, ReactiveFormsModule]
})
],
render: ({ accounts, hasHint, hasNullOption, label, value }) => {
render: ({ accounts, hasHint, hasNullOption, label, multiple, value }) => {
return {
props: {
accounts,
hasHint,
hasNullOption,
label,
multiple,
formGroup: new FormGroup({
account: new FormControl(value)
})
@ -116,6 +117,7 @@ const meta: Meta<AccountSelectorStory> = {
[hasHint]="hasHint"
[hasNullOption]="hasNullOption"
[label]="label"
[multiple]="multiple ?? false"
/>
</form>
`
@ -135,6 +137,18 @@ export const Default: Story = {
}
};
export const Multiple: Story = {
args: {
accounts: ACCOUNTS,
label: 'Accounts',
multiple: true,
value: [
'267ec888-cb57-45d0-8085-938017417a2e',
'9da3a8a7-4795-43e3-a6db-ccb914189737'
]
}
};
export const WithNullOption: Story = {
args: {
accounts: ACCOUNTS,

65
libs/ui/src/lib/account-selector/account-selector.component.ts

@ -22,6 +22,8 @@ import { ErrorStateMatcher } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatSelectModule } from '@angular/material/select';
export type AccountSelectorValue = string | string[] | null;
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'd-block' },
@ -38,7 +40,7 @@ export class GfAccountSelectorComponent
implements ControlValueAccessor, OnInit
{
public readonly accounts = input.required<AccountWithPlatform[]>();
public readonly control = new FormControl<string | null>(null);
public readonly control = new FormControl<AccountSelectorValue>(null);
public readonly errorStateMatcher: ErrorStateMatcher = {
isErrorState: () => {
@ -53,14 +55,32 @@ export class GfAccountSelectorComponent
public readonly isRequired = signal(false);
public readonly label = input.required<string>();
public readonly selectedAccount = computed(() => {
const selectedAccountId = this.selectedAccountId();
/**
* Allows the selection of multiple accounts. The value is an array of
* account ids in this case. Must not be changed after initialization.
*/
public readonly multiple = input(false);
return this.accounts().find(({ id }) => {
return id === selectedAccountId;
public readonly selectedAccounts = computed(() => {
const selectedAccountIds = this.selectedAccountIds();
return this.sortedAccounts().filter(({ id }) => {
return selectedAccountIds.includes(id);
});
});
public readonly selectedAccount = computed(() => {
return this.selectedAccounts()[0];
});
public readonly selectedAccountNames = computed(() => {
return this.selectedAccounts()
.map(({ name }) => {
return name;
})
.join(', ');
});
public readonly sortedAccounts = computed(() => {
return [...this.accounts()].sort((a, b) => {
return (a.name ?? '')
@ -74,7 +94,7 @@ export class GfAccountSelectorComponent
self: true
});
private readonly selectedAccountId = signal<string | null>(null);
private readonly selectedAccountIds = signal<string[]>([]);
public constructor() {
// Register as the value accessor manually, because injecting NgControl
@ -83,12 +103,10 @@ export class GfAccountSelectorComponent
this.ngControl.valueAccessor = this;
}
this.control.valueChanges
.pipe(takeUntilDestroyed())
.subscribe((accountId) => {
this.selectedAccountId.set(accountId);
this.onChange(accountId);
});
this.control.valueChanges.pipe(takeUntilDestroyed()).subscribe((value) => {
this.selectedAccountIds.set(this.getAccountIds(value));
this.onChange(value);
});
}
public ngOnInit() {
@ -101,7 +119,7 @@ export class GfAccountSelectorComponent
this.onTouched();
}
public registerOnChange(fn: (accountId: string | null) => void) {
public registerOnChange(fn: (value: AccountSelectorValue) => void) {
this.onChange = fn;
}
@ -117,12 +135,25 @@ export class GfAccountSelectorComponent
}
}
public writeValue(accountId: string | null) {
this.control.setValue(accountId ?? null, { emitEvent: false });
this.selectedAccountId.set(accountId ?? null);
public writeValue(value: AccountSelectorValue) {
const accountIds = this.getAccountIds(value);
this.control.setValue(
this.multiple() ? accountIds : (accountIds[0] ?? null),
{ emitEvent: false }
);
this.selectedAccountIds.set(accountIds);
}
private getAccountIds(value: AccountSelectorValue) {
if (Array.isArray(value)) {
return value;
}
return value ? [value] : [];
}
private onChange: (accountId: string | null) => void = () => {
private onChange: (value: AccountSelectorValue) => void = () => {
// ControlValueAccessor onChange callback
};

27
libs/ui/src/lib/assistant/assistant.component.ts

@ -123,10 +123,10 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
public portfolioFilterFormControl = new FormControl<PortfolioFilterFormValue>(
{
account: null,
assetClass: null,
accounts: [],
assetClasses: [],
holding: null,
tag: null
tags: []
}
);
@ -738,14 +738,12 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
const settings = this.user?.settings;
const filters = [
{
id: settings?.['filters.accounts']?.[0] ?? '',
type: 'ACCOUNT'
},
{
id: settings?.['filters.assetClasses']?.[0] ?? '',
type: 'ASSET_CLASS'
},
...(settings?.['filters.accounts'] ?? []).map((id) => {
return { id, type: 'ACCOUNT' };
}),
...(settings?.['filters.assetClasses'] ?? []).map((id) => {
return { id, type: 'ASSET_CLASS' };
}),
{
id: settings?.['filters.dataSource'] ?? '',
type: 'DATA_SOURCE'
@ -754,10 +752,9 @@ export class GfAssistantComponent implements OnChanges, OnDestroy, OnInit {
id: settings?.['filters.symbol'] ?? '',
type: 'SYMBOL'
},
{
id: settings?.['filters.tags']?.[0] ?? '',
type: 'TAG'
}
...(settings?.['filters.tags'] ?? []).map((id) => {
return { id, type: 'TAG' };
})
].filter(({ id }) => {
return !!id;
}) as Filter[];

6
libs/ui/src/lib/portfolio-filter-form/interfaces/portfolio-filter-form-value.interface.ts

@ -1,8 +1,8 @@
import { PortfolioPosition } from '@ghostfolio/common/interfaces';
export interface PortfolioFilterFormValue {
account: string | null;
assetClass: string | null;
accounts: string[];
assetClasses: string[];
holding: PortfolioPosition | null;
tag: string | null;
tags: string[];
}

10
libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.html

@ -1,11 +1,11 @@
<form [formGroup]="filterForm">
<div class="mb-3">
<gf-account-selector
formControlName="account"
formControlName="accounts"
[accounts]="accounts()"
[hasHint]="false"
[hasNullOption]="true"
[label]="labelAccount"
[multiple]="true"
/>
</div>
<div class="mb-3">
@ -37,8 +37,7 @@
<div class="mb-3">
<mat-form-field appearance="outline" class="w-100 without-hint">
<mat-label i18n>Tag</mat-label>
<mat-select formControlName="tag">
<mat-option [value]="null" />
<mat-select formControlName="tags" multiple>
@for (tag of tags(); track tag.id) {
<mat-option [value]="tag.id">{{ tag.label }}</mat-option>
}
@ -48,8 +47,7 @@
<div class="mb-3">
<mat-form-field appearance="outline" class="w-100 without-hint">
<mat-label i18n>Asset Class</mat-label>
<mat-select formControlName="assetClass">
<mat-option [value]="null" />
<mat-select formControlName="assetClasses" multiple>
@for (assetClass of assetClasses(); track assetClass.id) {
<mat-option [value]="assetClass.id">{{
assetClass.label

22
libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.component.ts

@ -63,10 +63,10 @@ export class GfPortfolioFilterFormComponent
public readonly tags = input<Filter[]>([]);
public filterForm: FormGroup<{
account: FormControl<string | null>;
assetClass: FormControl<string | null>;
accounts: FormControl<string[]>;
assetClasses: FormControl<string[]>;
holding: FormControl<PortfolioPosition | null>;
tag: FormControl<string | null>;
tags: FormControl<string[]>;
}>;
public readonly labelAccount = translate('ACCOUNT');
@ -77,10 +77,10 @@ export class GfPortfolioFilterFormComponent
public constructor() {
this.filterForm = this.formBuilder.group({
account: new FormControl<string | null>(null),
assetClass: new FormControl<string | null>(null),
accounts: new FormControl<string[]>([], { nonNullable: true }),
assetClasses: new FormControl<string[]>([], { nonNullable: true }),
holding: new FormControl<PortfolioPosition | null>(null),
tag: new FormControl<string | null>(null)
tags: new FormControl<string[]>([], { nonNullable: true })
});
}
@ -97,7 +97,7 @@ export class GfPortfolioFilterFormComponent
const formValue = this.filterForm.value;
return Object.values(formValue).some((value) => {
return !!value;
return Array.isArray(value) ? value.length > 0 : !!value;
});
}
@ -122,7 +122,7 @@ export class GfPortfolioFilterFormComponent
this.filterForm.enable({ emitEvent: false });
}
const tagControl = this.filterForm.get('tag');
const tagControl = this.filterForm.get('tags');
if (this.tags().length === 0) {
tagControl?.disable({ emitEvent: false });
@ -157,10 +157,10 @@ export class GfPortfolioFilterFormComponent
if (value) {
this.filterForm.setValue(
{
account: value.account ?? null,
assetClass: value.assetClass ?? null,
accounts: value.accounts ?? [],
assetClasses: value.assetClasses ?? [],
holding: value.holding ?? null,
tag: value.tag ?? null
tags: value.tags ?? []
},
{ emitEvent: false }
);

101
libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.util.spec.ts

@ -0,0 +1,101 @@
import { Filter, PortfolioPosition } from '@ghostfolio/common/interfaces';
import {
getFiltersFromPortfolioFilterFormValue,
getPortfolioFilterFormValue
} from './portfolio-filter-form.util';
describe('PortfolioFilterFormUtil', () => {
const holding = {
assetProfile: {
dataSource: 'YAHOO',
name: 'Apple Inc.',
symbol: 'AAPL'
}
} as PortfolioPosition;
describe('getFiltersFromPortfolioFilterFormValue', () => {
it('should return one filter per selected account, asset class and tag', () => {
expect(
getFiltersFromPortfolioFilterFormValue({
holding,
accounts: ['account-1', 'account-2'],
assetClasses: ['EQUITY', 'FIXED_INCOME'],
tags: ['tag-1', 'tag-2']
})
).toEqual([
{ id: 'account-1', type: 'ACCOUNT' },
{ id: 'account-2', type: 'ACCOUNT' },
{ id: 'EQUITY', type: 'ASSET_CLASS' },
{ id: 'FIXED_INCOME', type: 'ASSET_CLASS' },
{ id: 'YAHOO', type: 'DATA_SOURCE' },
{ id: 'AAPL', type: 'SYMBOL' },
{ id: 'tag-1', type: 'TAG' },
{ id: 'tag-2', type: 'TAG' }
]);
});
it('should return no filters for an empty value', () => {
expect(
getFiltersFromPortfolioFilterFormValue({
accounts: [],
assetClasses: [],
holding: null,
tags: []
})
).toEqual([]);
expect(getFiltersFromPortfolioFilterFormValue(null)).toEqual([]);
});
it('should return an empty filter per type if includeEmpty is set', () => {
expect(
getFiltersFromPortfolioFilterFormValue(
{
accounts: ['account-1'],
assetClasses: [],
holding: null,
tags: []
},
{ includeEmpty: true }
)
).toEqual([
{ id: 'account-1', type: 'ACCOUNT' },
{ id: '', type: 'ASSET_CLASS' },
{ id: '', type: 'DATA_SOURCE' },
{ id: '', type: 'SYMBOL' },
{ id: '', type: 'TAG' }
]);
});
});
describe('getPortfolioFilterFormValue', () => {
it('should collect all ids of accounts, asset classes and tags', () => {
const filters: Filter[] = [
{ id: 'account-1', type: 'ACCOUNT' },
{ id: 'account-2', type: 'ACCOUNT' },
{ id: 'EQUITY', type: 'ASSET_CLASS' },
{ id: 'YAHOO', type: 'DATA_SOURCE' },
{ id: 'AAPL', type: 'SYMBOL' },
{ id: 'tag-1', type: 'TAG' },
{ id: 'tag-2', type: 'TAG' }
];
expect(getPortfolioFilterFormValue(filters, [holding])).toEqual({
holding,
accounts: ['account-1', 'account-2'],
assetClasses: ['EQUITY'],
tags: ['tag-1', 'tag-2']
});
});
it('should return an empty value without filters', () => {
expect(getPortfolioFilterFormValue([], [holding])).toEqual({
accounts: [],
assetClasses: [],
holding: null,
tags: []
});
});
});
});

51
libs/ui/src/lib/portfolio-filter-form/portfolio-filter-form.util.ts

@ -25,15 +25,29 @@ export function getFiltersFromPortfolioFilterFormValue(
value: PortfolioFilterFormValue | null,
{ includeEmpty = false }: { includeEmpty?: boolean } = {}
) {
const getFiltersOfType = (
ids: string[] | undefined,
type: Filter['type']
) => {
const filtersOfType = (ids ?? [])
.filter((id) => {
return !!id;
})
.map((id) => {
return { id, type } satisfies Filter;
});
// An empty filter signals that the filter of this type has been reset
if (filtersOfType.length === 0 && includeEmpty) {
return [{ type, id: '' } satisfies Filter];
}
return filtersOfType;
};
const filters: Filter[] = [
{
id: value?.account ?? '',
type: 'ACCOUNT'
},
{
id: value?.assetClass ?? '',
type: 'ASSET_CLASS'
},
...getFiltersOfType(value?.accounts, 'ACCOUNT'),
...getFiltersOfType(value?.assetClasses, 'ASSET_CLASS'),
{
id: value?.holding?.assetProfile?.dataSource ?? '',
type: 'DATA_SOURCE'
@ -42,10 +56,7 @@ export function getFiltersFromPortfolioFilterFormValue(
id: value?.holding?.assetProfile?.symbol ?? '',
type: 'SYMBOL'
},
{
id: value?.tag ?? '',
type: 'TAG'
}
...getFiltersOfType(value?.tags, 'TAG')
];
return includeEmpty
@ -82,6 +93,16 @@ export function getPortfolioFilterFormValue(
);
};
const getFilterIds = (type: Filter['type']) => {
return (filters ?? [])
.filter((filter) => {
return filter.type === type && !!filter.id;
})
.map(({ id }) => {
return id;
});
};
const dataSource = getFilterId('DATA_SOURCE') as DataSource;
const symbol = getFilterId('SYMBOL');
@ -94,10 +115,10 @@ export function getPortfolioFilterFormValue(
});
return {
account: getFilterId('ACCOUNT'),
assetClass: getFilterId('ASSET_CLASS'),
accounts: getFilterIds('ACCOUNT'),
assetClasses: getFilterIds('ASSET_CLASS'),
holding: holding ?? null,
tag: getFilterId('TAG')
tags: getFilterIds('TAG')
};
}

Loading…
Cancel
Save