Skip to content

Open Source Wealth Management Software. Angular + NestJS + Prisma + Nx + TypeScript 🤍

Feature/add tags support in accounts (#7242)

Thomas Kaul79e382a8f721
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f1f165adaa..f6dc69bf69 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- Added support for tags in the account (experimental)
- Exposed the `PROCESSOR_PORTFOLIO_SNAPSHOT_COMPUTATION_REMOVE_ON_FAIL` environment variable to control the removal of failed jobs in the portfolio snapshot computation queue
### Changed
@@ -18,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Set the change detection strategy to `OnPush` in the prompt dialog component
- Set the change detection strategy to `OnPush` in the overview of the admin control panel
- Set the change detection strategy to `OnPush` in the portfolio page
+- Deprecated the `isExcluded` attribute of the account in favor of the _Exclude from Analysis_ tag
- Improved the language localization in the users table of the admin control panel
- Improved the language localization for German (`de`)
- Upgraded `envalid` from version `8.1.1` to `8.2.0`
@@ -25,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Fixed an issue with the custom tags of the user in the import functionality
- Fixed the creation of the _Stripe_ checkout session for languages not supported by _Stripe_ (`ca` and `uk`)
- Fixed the error handling in the endpoint to create a _Stripe_ checkout session
diff --git a/apps/api/src/app/account-balance/account-balance.service.ts b/apps/api/src/app/account-balance/account-balance.service.ts
index 4851a12937..656fc2f630 100644
--- a/apps/api/src/app/account-balance/account-balance.service.ts
+++ b/apps/api/src/app/account-balance/account-balance.service.ts
@@ -1,4 +1,5 @@
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event';
+import { WHERE_ACCOUNT_NOT_EXCLUDED } from '@ghostfolio/api/helper/account.helper';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
@@ -154,7 +155,7 @@ export class AccountBalanceService {
}
if (withExcludedAccounts === false) {
- where.account = { isExcluded: false };
+ where.account = WHERE_ACCOUNT_NOT_EXCLUDED;
}
const balances = await this.prismaService.accountBalance.findMany({
diff --git a/apps/api/src/app/account/account.controller.ts b/apps/api/src/app/account/account.controller.ts
index d44b716c03..6466a13b20 100644
--- a/apps/api/src/app/account/account.controller.ts
+++ b/apps/api/src/app/account/account.controller.ts
@@ -156,27 +156,31 @@ export class AccountController {
public async createAccount(
@Body() data: CreateAccountDto
): Promise<AccountModel> {
- if (data.platformId) {
- const platformId = data.platformId;
- delete data.platformId;
+ const { tags: tagIds, ...accountData } = data;
+
+ if (accountData.platformId) {
+ const platformId = accountData.platformId;
+ delete accountData.platformId;
return this.accountService.createAccount(
{
- ...data,
+ ...accountData,
platform: { connect: { id: platformId } },
user: { connect: { id: this.request.user.id } }
},
- this.request.user.id
+ this.request.user.id,
+ tagIds
);
} else {
- delete data.platformId;
+ delete accountData.platformId;
return this.accountService.createAccount(
{
- ...data,
+ ...accountData,
user: { connect: { id: this.request.user.id } }
},
- this.request.user.id
+ this.request.user.id,
+ tagIds
);
}
}
@@ -253,14 +257,16 @@ export class AccountController {
);
}
- if (data.platformId) {
- const platformId = data.platformId;
- delete data.platformId;
+ const { tags: tagIds, ...accountData } = data;
+
+ if (accountData.platformId) {
+ const platformId = accountData.platformId;
+ delete accountData.platformId;
return this.accountService.updateAccount(
{
data: {
- ...data,
+ ...accountData,
platform: { connect: { id: platformId } },
user: { connect: { id: this.request.user.id } }
},
@@ -271,16 +277,17 @@ export class AccountController {
}
}
},
- this.request.user.id
+ this.request.user.id,
+ tagIds
);
} else {
// platformId is null, remove it
- delete data.platformId;
+ delete accountData.platformId;
return this.accountService.updateAccount(
{
data: {
- ...data,
+ ...accountData,
platform: originalAccount.platformId
? { disconnect: true }
: undefined,
@@ -293,7 +300,8 @@ export class AccountController {
}
}
},
- this.request.user.id
+ this.request.user.id,
+ tagIds
);
}
}
diff --git a/apps/api/src/app/account/account.service.ts b/apps/api/src/app/account/account.service.ts
index f030b73da7..d1f4009a91 100644
--- a/apps/api/src/app/account/account.service.ts
+++ b/apps/api/src/app/account/account.service.ts
@@ -1,11 +1,12 @@
import { AccountBalanceService } from '@ghostfolio/api/app/account-balance/account-balance.service';
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event';
+import { WHERE_ACCOUNT_NOT_EXCLUDED } from '@ghostfolio/api/helper/account.helper';
import { ExchangeRateDataService } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.service';
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
import { DATE_FORMAT } from '@ghostfolio/common/helper';
import { Filter } from '@ghostfolio/common/interfaces';
-import { Injectable } from '@nestjs/common';
+import { HttpException, Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import {
Account,
@@ -13,10 +14,12 @@ import {
Order,
Platform,
Prisma,
- SymbolProfile
+ SymbolProfile,
+ Tag
} from '@prisma/client';
import { Big } from 'big.js';
import { format } from 'date-fns';
+import { StatusCodes, getReasonPhrase } from 'http-status-codes';
import { groupBy } from 'lodash';
import { CashDetails } from './interfaces/cash-details.interface';
@@ -66,17 +69,27 @@ export class AccountService {
activities?: (Order & { SymbolProfile?: SymbolProfile })[];
balances?: AccountBalance[];
platform?: Platform;
+ tags?: Tag[];
})[]
> {
const { include = {}, skip, take, cursor, where, orderBy } = params;
const isBalancesIncluded = !!include.balances;
+ const isTagsIncluded = !!include.tags;
include.balances = {
orderBy: { date: 'desc' },
...(isBalancesIncluded ? {} : { take: 1 })
};
+ if (isTagsIncluded) {
+ include.tags = {
+ include: {
+ tag: true
+ }
+ };
+ }
+
const accounts = await this.prismaService.account.findMany({
cursor,
include,
@@ -87,22 +100,48 @@ export class AccountService {
});
return accounts.map((account) => {
- account = { ...account, balance: account.balances[0]?.value ?? 0 };
+ const result = {
+ ...account,
+ balance: account.balances[0]?.value ?? 0,
+ tags: isTagsIncluded
+ ? (account.tags as unknown as { tag: Tag }[]).map(({ tag }) => {
+ return tag;
+ })
+ : undefined
+ };
if (!isBalancesIncluded) {
- delete account.balances;
+ delete result.balances;
+ }
+
+ if (!isTagsIncluded) {
+ delete result.tags;
}
- return account;
+ return result;
});
}
public async createAccount(
data: Prisma.AccountCreateInput,
- aUserId: string
+ aUserId: string,
+ tagIds?: string[]
): Promise<Account> {
+ await this.validateTagIds(tagIds, aUserId);
+
const account = await this.prismaService.account.create({
- data
+ data: {
+ ...data,
+ tags: tagIds
+ ? {
+ create: tagIds.map((tagId) => {
+ return {
+ tag: { connect: { id: tagId } }
+ };
+ })
+ }
+ : undefined
+ }
});
await this.accountBalanceService.createOrUpdateAccountBalance({
@@ -143,7 +182,8 @@ export class AccountService {
const accounts = await this.accounts({
include: {
activities: true,
- platform: true
+ platform: true,
+ tags: true
},
orderBy: { name: 'asc' },
where: { userId: aUserId }
@@ -184,7 +224,7 @@ export class AccountService {
};
if (withExcludedAccounts === false) {
- where.isExcluded = false;
+ where.AND = [WHERE_ACCOUNT_NOT_EXCLUDED];
}
const { ACCOUNT: filtersByAccount = [] } = groupBy(filters, ({ type }) => {
@@ -222,22 +262,37 @@ export class AccountService {
where: Prisma.AccountWhereUniqueInput;
data: Prisma.AccountUpdateInput;
},
- aUserId: string
+ aUserId: string,
+ tagIds?: string[]
): Promise<Account> {
const { data, where } = params;
+ await this.validateTagIds(tagIds, aUserId);
+
+ const account = await this.prismaService.account.update({
+ data: {
+ ...data,
+ tags: tagIds
+ ? {
+ create: tagIds.map((tagId) => {
+ return {
+ tag: { connect: { id: tagId } }
+ };
+ }),
+ deleteMany: {}
+ }
+ : undefined
+ },
+ where
+ });
+
await this.accountBalanceService.createOrUpdateAccountBalance({
- accountId: data.id as string,
+ accountId: account.id,
balance: data.balance as number,
date: format(new Date(), DATE_FORMAT),
userId: aUserId
});
- const account = await this.prismaService.account.update({
- data,
- where
- });
-
this.eventEmitter.emit(
PortfolioChangedEvent.getName(),
new PortfolioChangedEvent({
@@ -285,4 +340,26 @@ export class AccountService {
});
}
}
+
+ private async validateTagIds(tagIds: string[], userId: string) {
+ if (!tagIds?.length) {
+ return;
+ }
+
+ const uniqueTagIds = Array.from(new Set(tagIds));
+
+ const tagsCount = await this.prismaService.tag.count({
+ where: {
+ id: { in: uniqueTagIds },
+ OR: [{ userId }, { userId: null }]
+ }
+ });
+
+ if (tagsCount !== uniqueTagIds.length) {
+ throw new HttpException(
+ getReasonPhrase(StatusCodes.BAD_REQUEST),
+ StatusCodes.BAD_REQUEST
+ );
+ }
+ }
}
diff --git a/apps/api/src/app/activities/activities.service.ts b/apps/api/src/app/activities/activities.service.ts
index 816d2328d5..b404b6a37a 100644
--- a/apps/api/src/app/activities/activities.service.ts
+++ b/apps/api/src/app/activities/activities.service.ts
@@ -3,6 +3,7 @@ import { AccountService } from '@ghostfolio/api/app/account/account.service';
import { CashDetails } from '@ghostfolio/api/app/account/interfaces/cash-details.interface';
import { AssetProfileChangedEvent } from '@ghostfolio/api/events/asset-profile-changed.event';
import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event';
+import { WHERE_ACCOUNT_NOT_EXCLUDED } from '@ghostfolio/api/helper/account.helper';
import { LogPerformance } from '@ghostfolio/api/interceptors/performance-logging/performance-logging.interceptor';
import { BenchmarkService } from '@ghostfolio/api/services/benchmark/benchmark.service';
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
@@ -568,18 +569,15 @@ export class ActivitiesService {
{ date: 'asc' }
];
- const where: Prisma.OrderWhereInput = { userId };
+ const andConditions: Prisma.OrderWhereInput[] = [];
+ const where: Prisma.OrderWhereInput = { userId, AND: andConditions };
- if (endDate || startDate) {
- where.AND = [];
-
- if (endDate) {
- where.AND.push({ date: { lte: endDate } });
- }
+ if (endDate) {
+ andConditions.push({ date: { lte: endDate } });
+ }
- if (startDate) {
- where.AND.push({ date: { gt: startDate } });
- }
+ if (startDate) {
+ andConditions.push({ date: { gt: startDate } });
}
const {
@@ -682,13 +680,30 @@ export class ActivitiesService {
}
if (filtersByTag.length > 0) {
- where.tags = {
- some: {
- OR: filtersByTag.map(({ id }) => {
- return { id };
- })
- }
- };
+ andConditions.push({
+ OR: [
+ {
+ tags: {
+ some: {
+ OR: filtersByTag.map(({ id }) => {
+ return { id };
+ })
+ }
+ }
+ },
+ {
+ account: {
+ tags: {
+ some: {
+ OR: filtersByTag.map(({ id }) => {
+ return { tagId: id };
+ })
+ }
+ }
+ }
+ }
+ ]
+ });
}
if (sortColumn) {
@@ -700,13 +715,9 @@ export class ActivitiesService {
}
if (withExcludedAccountsAndActivities === false) {
- where.OR = [
- { account: null },
- { account: { NOT: { isExcluded: true } } }
- ];
+ where.OR = [{ account: null }, { account: WHERE_ACCOUNT_NOT_EXCLUDED }];
where.tags = {
- ...where.tags,
none: {
id: TAG_ID_EXCLUDE_FROM_ANALYSIS
}
@@ -721,7 +732,12 @@ export class ActivitiesService {
include: {
account: {
include: {
- platform: true
+ platform: true,
+ tags: {
+ include: {
+ tag: true
+ }
+ }
}
},
// eslint-disable-next-line @typescript-eslint/naming-convention
@@ -733,6 +749,16 @@ export class ActivitiesService {
this.prismaService.order.count({ where })
]);
+ for (const order of orders) {
+ if (order.account) {
+ order.account.tags = (
+ order.account.tags as unknown as { tag: Tag }[]
+ ).map(({ tag }) => {
+ return tag;
+ });
+ }
+ }
+
const assetProfileIdentifiers = uniqBy(
orders.map(({ SymbolProfile }) => {
return {
diff --git a/apps/api/src/app/endpoints/tags/tags.controller.ts b/apps/api/src/app/endpoints/tags/tags.controller.ts
index 925e1e0edc..21e29c6abb 100644
--- a/apps/api/src/app/endpoints/tags/tags.controller.ts
+++ b/apps/api/src/app/endpoints/tags/tags.controller.ts
@@ -83,7 +83,7 @@ export class TagsController {
@HasPermission(permissions.readTags)
@UseGuards(AuthGuard('jwt'), HasPermissionGuard)
public async getTags() {
- return this.tagService.getTagsWithActivityCount();
+ return this.tagService.getTagsWithAccountAndActivityCount();
}
@HasPermission(permissions.updateTag)
diff --git a/apps/api/src/app/export/export.service.ts b/apps/api/src/app/export/export.service.ts
index b94b2aa74c..8ebfde13db 100644
--- a/apps/api/src/app/export/export.service.ts
+++ b/apps/api/src/app/export/export.service.ts
@@ -72,7 +72,8 @@ export class ExportService {
where,
include: {
balances: true,
- platform: true
+ platform: true,
+ tags: true
},
orderBy: {
name: 'asc'
@@ -96,7 +97,8 @@ export class ExportService {
isExcluded,
name,
platform,
- platformId
+ platformId,
+ tags
}) => {
if (platformId) {
platformsMap[platformId] = platform;
@@ -112,7 +114,10 @@ export class ExportService {
id,
isExcluded,
name,
- platformId
+ platformId,
+ tags: tags.map(({ id: tagId }) => {
+ return tagId;
+ })
};
}
);
@@ -151,11 +156,14 @@ export class ExportService {
.filter(({ id, isUsed }) => {
return (
isUsed &&
- activities.some((activity) => {
- return activity.tags.some(({ id: tagId }) => {
- return tagId === id;
- });
- })
+ (accounts.some(({ tags: tagIds }) => {
+ return tagIds.includes(id);
+ }) ||
+ activities.some((activity) => {
+ return activity.tags.some(({ id: tagId }) => {
+ return tagId === id;
+ });
+ }))
);
})
.map(({ id, name }) => {
diff --git a/apps/api/src/app/import/import.service.ts b/apps/api/src/app/import/import.service.ts
index c7dab98236..9b1aa417cf 100644
--- a/apps/api/src/app/import/import.service.ts
+++ b/apps/api/src/app/import/import.service.ts
@@ -10,11 +10,7 @@ import { DataGatheringService } from '@ghostfolio/api/services/queues/data-gathe
import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/symbol-profile.service';
import { TagService } from '@ghostfolio/api/services/tag/tag.service';
import { DATA_GATHERING_QUEUE_PRIORITY_HIGH } from '@ghostfolio/common/config';
-import {
- CreateAssetProfileDto,
- CreateAccountDto,
- CreateOrderDto
-} from '@ghostfolio/common/dtos';
+import { CreateAssetProfileDto, CreateOrderDto } from '@ghostfolio/common/dtos';
import {
getAssetProfileIdentifier,
parseDate
@@ -194,6 +190,60 @@ export class ImportService {
const tagIdMapping: { [oldTagId: string]: string } = {};
const userCurrency = user.settings.settings.baseCurrency;
+ const existingTagsOfUser =
+ tagsDto?.length || (!isDryRun && accountsWithBalancesDto?.length)
+ ? await this.tagService.getTagsForUser(user.id)
+ : [];
+
+ if (tagsDto?.length) {
+ const canCreateOwnTag = hasPermission(
+ user.permissions,
+ permissions.createOwnTag
+ );
+
+ for (const tag of tagsDto) {
+ const existingTagOfUser = existingTagsOfUser.find(({ id }) => {
+ return id === tag.id;
+ });
+
+ if (!existingTagOfUser) {
+ if (!canCreateOwnTag) {
+ throw new Error(
+ `Insufficient permissions to create custom tag ("${tag.name}")`
+ );
+ }
+
+ if (!isDryRun) {
+ const existingTag = await this.tagService.getTag({ id: tag.id });
+ let oldTagId: string;
+
+ if (existingTag) {
+ oldTagId = tag.id;
+ delete tag.id;
+ }
+
+ const tagObject: Prisma.TagCreateInput = {
+ ...tag,
+ user: { connect: { id: user.id } }
+ };
+
+ const newTag = await this.tagService.createTag(tagObject);
+
+ if (existingTag && oldTagId) {
+ tagIdMapping[oldTagId] = newTag.id;
+ }
+
+ existingTagsOfUser.push({
+ id: newTag.id,
+ isUsed: false,
+ name: newTag.name,
+ userId: newTag.userId
+ });
+ }
+ }
+ }
+ }
+
if (!isDryRun && accountsWithBalancesDto?.length) {
const [existingAccounts, existingPlatforms] = await Promise.all([
this.accountService.accounts({
@@ -208,6 +258,12 @@ export class ImportService {
this.platformService.getPlatforms()
]);
+ const existingTagIds = new Set(
+ existingTagsOfUser.map(({ id }) => {
+ return id;
+ })
+ );
+
for (const accountWithBalances of accountsWithBalancesDto) {
// Check if there is any existing account with the same ID
const accountWithSameId = existingAccounts.find((existingAccount) => {
@@ -216,10 +272,7 @@ export class ImportService {
// If there is no account or if the account belongs to a different user then create a new account
if (!accountWithSameId || accountWithSameId.userId !== user.id) {
- const account: CreateAccountDto = omit(
- accountWithBalances,
- 'balances'
- );
+ const account = omit(accountWithBalances, ['balances', 'tags']);
let oldAccountId: string;
const platformId = account.platformId;
@@ -231,6 +284,14 @@ export class ImportService {
delete account.id;
}
+ const tagIds = (accountWithBalances.tags ?? [])
+ .map((tagId) => {
+ return tagIdMapping[tagId] ?? tagId;
+ })
+ .filter((tagId) => {
+ return existingTagIds.has(tagId);
+ });
+
let accountObject: Prisma.AccountCreateInput = {
...account,
balances: {
@@ -252,7 +313,8 @@ export class ImportService {
const newAccount = await this.accountService.createAccount(
accountObject,
- user.id
+ user.id,
+ tagIds
);
// Store the new to old account ID mappings for updating activities
@@ -320,50 +382,6 @@ export class ImportService {
}
}
- if (tagsDto?.length) {
- const existingTagsOfUser = await this.tagService.getTagsForUser(user.id);
-
- const canCreateOwnTag = hasPermission(
- user.permissions,
- permissions.createOwnTag
- );
-
- for (const tag of tagsDto) {
- const existingTagOfUser = existingTagsOfUser.find(({ id }) => {
- return id === tag.id;
- });
-
- if (!existingTagOfUser || existingTagOfUser.userId !== null) {
- if (!canCreateOwnTag) {
- throw new Error(
- `Insufficient permissions to create custom tag ("${tag.name}")`
- );
- }
-
- if (!isDryRun) {
- const existingTag = await this.tagService.getTag({ id: tag.id });
- let oldTagId: string;
-
- if (existingTag) {
- oldTagId = tag.id;
- delete tag.id;
- }
-
- const tagObject: Prisma.TagCreateInput = {
- ...tag,
- user: { connect: { id: user.id } }
- };
-
- const newTag = await this.tagService.createTag(tagObject);
-
- if (existingTag && oldTagId) {
- tagIdMapping[oldTagId] = newTag.id;
- }
- }
- }
- }
- }
-
for (const activity of activitiesDto) {
if (!activity.dataSource) {
if (['FEE', 'INTEREST', 'LIABILITY'].includes(activity.type)) {
diff --git a/apps/api/src/app/portfolio/portfolio.service.ts b/apps/api/src/app/portfolio/portfolio.service.ts
index b5ea9ba006..e75e548903 100644
--- a/apps/api/src/app/portfolio/portfolio.service.ts
+++ b/apps/api/src/app/portfolio/portfolio.service.ts
@@ -41,6 +41,7 @@ import {
DATE_FORMAT,
getAssetProfileIdentifier,
getSum,
+ isAccountExcluded,
parseDate
} from '@ghostfolio/common/helper';
import {
@@ -169,7 +170,8 @@ export class PortfolioService {
where,
include: {
activities: { include: { SymbolProfile: true } },
- platform: true
+ platform: true,
+ tags: true
},
orderBy: { name: 'asc' }
}),
@@ -1879,7 +1881,7 @@ export class PortfolioService {
for (const activity of activities) {
if (
- activity.account?.isExcluded ||
+ (activity.account && isAccountExcluded(activity.account)) ||
activity.tags?.some(({ id }) => {
return id === TAG_ID_EXCLUDE_FROM_ANALYSIS;
})
@@ -2123,13 +2125,14 @@ export class PortfolioService {
let currentAccounts: (Account & {
Order?: Order[];
platform?: Platform;
+ tags?: Tag[];
})[] = [];
if (filters.length === 0) {
currentAccounts = await this.accountService.getAccounts(userId);
} else if (filters.length === 1 && filters[0].type === 'ACCOUNT') {
currentAccounts = await this.accountService.accounts({
- include: { platform: true },
+ include: { platform: true, tags: true },
where: { id: filters[0].id }
});
} else {
@@ -2146,13 +2149,13 @@ export class PortfolioService {
);
currentAccounts = await this.accountService.accounts({
- include: { platform: true },
+ include: { platform: true, tags: true },
where: { id: { in: accountIds } }
});
}
currentAccounts = currentAccounts.filter((account) => {
- return withExcludedAccounts || account.isExcluded === false;
+ return withExcludedAccounts || !isAccountExcluded(account);
});
// Iterate over the accounts plus a null entry to group activities without
diff --git a/apps/api/src/helper/account.helper.ts b/apps/api/src/helper/account.helper.ts
new file mode 100644
index 0000000000..0800c022e2
--- /dev/null
+++ b/apps/api/src/helper/account.helper.ts
@@ -0,0 +1,12 @@
+import { TAG_ID_EXCLUDE_FROM_ANALYSIS } from '@ghostfolio/common/config';
+
+import { Prisma } from '@prisma/client';
+
+export const WHERE_ACCOUNT_NOT_EXCLUDED: Prisma.AccountWhereInput = {
+ isExcluded: false,
+ tags: {
+ none: {
+ tagId: TAG_ID_EXCLUDE_FROM_ANALYSIS
+ }
+ }
+};
diff --git a/apps/api/src/services/tag/tag.service.ts b/apps/api/src/services/tag/tag.service.ts
index f4cbd4cb15..d967ce8540 100644
--- a/apps/api/src/services/tag/tag.service.ts
+++ b/apps/api/src/services/tag/tag.service.ts
@@ -52,6 +52,11 @@ export class TagService {
include: {
_count: {
select: {
+ accounts: {
+ where: {
+ userId
+ }
+ },
activities: {
where: {
userId
@@ -80,27 +85,28 @@ export class TagService {
id,
name,
userId,
- isUsed: _count.activities > 0
+ isUsed: _count.accounts > 0 || _count.activities > 0
}))
.sort((a, b) => {
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
}
- public async getTagsWithActivityCount() {
- const tagsWithOrderCount = await this.prismaService.tag.findMany({
+ public async getTagsWithAccountAndActivityCount() {
+ const tagsWithAccountAndOrderCount = await this.prismaService.tag.findMany({
include: {
_count: {
- select: { activities: true }
+ select: { accounts: true, activities: true }
}
}
});
- return tagsWithOrderCount.map(({ _count, id, name, userId }) => {
+ return tagsWithAccountAndOrderCount.map(({ _count, id, name, userId }) => {
return {
id,
name,
userId,
+ accountCount: _count.accounts,
activityCount: _count.activities
};
});
diff --git a/apps/client/src/app/components/admin-tag/admin-tag.component.html b/apps/client/src/app/components/admin-tag/admin-tag.component.html
index a84cbb2830..14b011ddcf 100644
--- a/apps/client/src/app/components/admin-tag/admin-tag.component.html
+++ b/apps/client/src/app/components/admin-tag/admin-tag.component.html
@@ -35,6 +35,24 @@
</td>
</ng-container>
+ <ng-container matColumnDef="accounts">
+ <th
+ *matHeaderCellDef
+ class="justify-content-end px-1"
+ mat-header-cell
+ mat-sort-header="accountCount"
+ >
+ <ng-container i18n>Accounts</ng-container>
+ </th>
+ <td *matCellDef="let element" class="px-1 text-right" mat-cell>
+ <gf-value
+ class="d-inline-block justify-content-end"
+ [locale]="locale()"
+ [value]="element.accountCount"
+ />
+ </td>
+ </ng-container>
+
<ng-container matColumnDef="activities">
<th
*matHeaderCellDef
@@ -74,7 +92,7 @@
<hr class="m-0" />
<button
mat-menu-item
- [disabled]="element.activityCount > 0"
+ [disabled]="element.accountCount > 0 || element.activityCount > 0"
(click)="onDeleteTag(element.id)"
>
<span class="align-items-center d-flex">
diff --git a/apps/client/src/app/components/admin-tag/admin-tag.component.ts b/apps/client/src/app/components/admin-tag/admin-tag.component.ts
index 7bd69c964c..5fb2317f44 100644
--- a/apps/client/src/app/components/admin-tag/admin-tag.component.ts
+++ b/apps/client/src/app/components/admin-tag/admin-tag.component.ts
@@ -62,6 +62,7 @@ export class GfAdminTagComponent implements OnInit {
protected readonly displayedColumns = [
'name',
'userId',
+ 'accounts',
'activities',
'actions'
];
diff --git a/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.component.ts b/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.component.ts
index 3ddcd4e194..b2cdedbc5b 100644
--- a/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.component.ts
+++ b/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.component.ts
@@ -77,7 +77,7 @@ import {
swapVerticalOutline,
walletOutline
} from 'ionicons/icons';
-import { isNumber, round } from 'lodash';
+import { isNumber, round, uniqBy } from 'lodash';
import { NgxSkeletonLoaderModule } from 'ngx-skeleton-loader';
import { switchMap } from 'rxjs/operators';
@@ -179,6 +179,7 @@ export class GfHoldingDetailDialogComponent implements OnInit {
protected sortColumn = 'date';
protected sortDirection: SortDirection = 'desc';
protected tagsAvailable: Tag[];
+ protected tagsOfAccounts: Tag[];
protected readonly translate = translate;
protected user: User;
protected value: number;
@@ -265,6 +266,18 @@ export class GfHoldingDetailDialogComponent implements OnInit {
.subscribe(({ accounts }) => {
this.accounts = accounts;
+ this.tagsOfAccounts = uniqBy(
+ accounts.flatMap(({ tags }) => {
+ return tags ?? [];
+ }),
+ 'id'
+ ).map((tag) => {
+ return {
+ ...tag,
+ name: translate(tag.name)
+ };
+ });
+
this.changeDetectorRef.markForCheck();
});
diff --git a/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.html b/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.html
index 0007bedc55..04388bddbd 100644
--- a/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.html
+++ b/apps/client/src/app/components/holding-detail-dialog/holding-detail-dialog.html
@@ -427,6 +427,7 @@
[hasPermissionToCreateTag]="hasPermissionToCreateOwnTag"
[readonly]="!data.hasPermissionToUpdateActivity"
[tagsAvailable]="tagsAvailable"
+ [tagsReadOnly]="tagsOfAccounts"
/>
</form>
diff --git a/apps/client/src/app/pages/accounts/accounts-page.component.ts b/apps/client/src/app/pages/accounts/accounts-page.component.ts
index c99fc40ac2..907b39d372 100644
--- a/apps/client/src/app/pages/accounts/accounts-page.component.ts
+++ b/apps/client/src/app/pages/accounts/accounts-page.component.ts
@@ -25,7 +25,7 @@ import {
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
-import { Account as AccountModel } from '@prisma/client';
+import { Account as AccountModel, Tag } from '@prisma/client';
import { DeviceDetectorService } from 'ngx-device-detector';
import { EMPTY } from 'rxjs';
import { catchError } from 'rxjs/operators';
@@ -188,8 +188,9 @@ export class GfAccountsPageComponent implements OnInit {
id,
isExcluded,
name,
- platformId
- }: AccountModel) {
+ platformId,
+ tags
+ }: AccountModel & { tags?: Tag[] }) {
const dialogRef = this.dialog.open<
GfCreateOrUpdateAccountDialogComponent,
CreateOrUpdateAccountDialogParams
@@ -202,8 +203,10 @@ export class GfAccountsPageComponent implements OnInit {
id,
isExcluded,
name,
- platformId
- }
+ platformId,
+ tags
+ },
+ user: this.user
},
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
@@ -277,8 +280,10 @@ export class GfAccountsPageComponent implements OnInit {
id: null,
isExcluded: false,
name: null,
- platformId: null
- }
+ platformId: null,
+ tags: []
+ },
+ user: this.user
} satisfies CreateOrUpdateAccountDialogParams,
height: this.deviceType() === 'mobile' ? '98vh' : '80vh',
width: this.deviceType() === 'mobile' ? '100vw' : '50rem'
diff --git a/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.component.ts b/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.component.ts
index 8319999eb9..ca88120cac 100644
--- a/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.component.ts
+++ b/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.component.ts
@@ -1,11 +1,22 @@
+import { UserService } from '@ghostfolio/client/services/user/user.service';
+import { TAG_ID_EXCLUDE_FROM_ANALYSIS } from '@ghostfolio/common/config';
import { CreateAccountDto, UpdateAccountDto } from '@ghostfolio/common/dtos';
+import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { validateObjectForForm } from '@ghostfolio/common/utils';
import { GfCurrencySelectorComponent } from '@ghostfolio/ui/currency-selector';
import { GfEntityLogoComponent } from '@ghostfolio/ui/entity-logo';
+import { translate } from '@ghostfolio/ui/i18n';
import { DataService } from '@ghostfolio/ui/services';
+import { GfTagsSelectorComponent } from '@ghostfolio/ui/tags-selector';
import { CommonModule } from '@angular/common';
-import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
+import {
+ ChangeDetectionStrategy,
+ Component,
+ DestroyRef,
+ inject
+} from '@angular/core';
+import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
AbstractControl,
FormBuilder,
@@ -24,7 +35,7 @@ import {
} from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
-import { Platform } from '@prisma/client';
+import { Platform, Tag } from '@prisma/client';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
@@ -37,6 +48,7 @@ import { CreateOrUpdateAccountDialogParams } from './interfaces/interfaces';
CommonModule,
GfCurrencySelectorComponent,
GfEntityLogoComponent,
+ GfTagsSelectorComponent,
MatAutocompleteModule,
MatButtonModule,
MatCheckboxModule,
@@ -53,19 +65,41 @@ export class GfCreateOrUpdateAccountDialogComponent {
protected accountForm: FormGroup;
protected currencies: string[] = [];
protected filteredPlatforms: Observable<Platform[]> | undefined;
+ protected hasPermissionToCreateOwnTag: boolean | undefined;
protected platforms: Platform[] = [];
+ protected tagsAvailable: Tag[] = [];
protected readonly data =
inject<CreateOrUpdateAccountDialogParams>(MAT_DIALOG_DATA);
private readonly dataService = inject(DataService);
+ private readonly destroyRef = inject(DestroyRef);
private readonly dialogRef =
inject<MatDialogRef<GfCreateOrUpdateAccountDialogComponent>>(MatDialogRef);
private readonly formBuilder = inject(FormBuilder);
+ private readonly userService = inject(UserService);
public ngOnInit() {
const { currencies } = this.dataService.fetchInfo();
this.currencies = currencies;
+ this.hasPermissionToCreateOwnTag =
+ this.data.user?.settings?.isExperimentalFeatures &&
+ hasPermission(this.data.user?.permissions, permissions.createOwnTag);
+
+ this.tagsAvailable = [
+ ...(this.data.user?.tags ?? []),
+ {
+ id: TAG_ID_EXCLUDE_FROM_ANALYSIS,
+ name: 'EXCLUDE_FROM_ANALYSIS',
+ userId: null
+ }
+ ].map((tag) => {
+ return {
+ ...tag,
+ name: translate(tag.name)
+ };
+ });
+
this.accountForm = this.formBuilder.group({
accountId: [{ disabled: true, value: this.data.account.id }],
balance: [this.data.account.balance, Validators.required],
@@ -73,9 +107,48 @@ export class GfCreateOrUpdateAccountDialogComponent {
currency: [this.data.account.currency, Validators.required],
isExcluded: [this.data.account.isExcluded],
name: [this.data.account.name, Validators.required],
- platformId: [null, this.autocompleteObjectValidator()]
+ platformId: [null, this.autocompleteObjectValidator()],
+ tags: [
+ this.data.account.tags?.map(({ id, name }) => {
+ return {
+ id,
+ name: translate(name)
+ };
+ })
+ ]
});
+ this.accountForm
+ .get('tags')
+ ?.valueChanges.pipe(takeUntilDestroyed(this.destroyRef))
+ .subscribe((tags: Tag[]) => {
+ const newTag = tags.find(({ id }) => {
+ return id === undefined;
+ });
+
+ if (newTag && this.hasPermissionToCreateOwnTag) {
+ this.dataService
+ .postTag({ ...newTag, userId: this.data.user.id })
+ .pipe(takeUntilDestroyed(this.destroyRef))
+ .subscribe((tag) => {
+ this.accountForm.get('tags')?.setValue(
+ tags.map((currentTag) => {
+ if (currentTag.id === undefined) {
+ return tag;
+ }
+
+ return currentTag;
+ })
+ );
+
+ this.userService
+ .get(true)
+ .pipe(takeUntilDestroyed(this.destroyRef))
+ .subscribe();
+ });
+ }
+ });
+
this.dataService.fetchPlatforms().subscribe(({ platforms }) => {
this.platforms = platforms;
@@ -132,7 +205,16 @@ export class GfCreateOrUpdateAccountDialogComponent {
id: this.accountForm.get('accountId')?.value,
isExcluded: this.accountForm.get('isExcluded')?.value,
name: this.accountForm.get('name')?.value,
- platformId: this.accountForm.get('platformId')?.value?.id || null
+ platformId: this.accountForm.get('platformId')?.value?.id || null,
+ tags: this.accountForm
+ .get('tags')
+ ?.value?.filter(({ id }: Tag) => {
+ // Skip tags which have not been created yet
+ return !!id;
+ })
+ .map(({ id }: Tag) => {
+ return id;
+ })
};
try {
diff --git a/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.html b/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.html
index c90c9c4406..c707a9402c 100644
--- a/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.html
+++ b/apps/client/src/app/pages/accounts/create-or-update-account-dialog/create-or-update-account-dialog.html
@@ -85,6 +85,15 @@
></textarea>
</mat-form-field>
</div>
+ @if (data.user?.settings?.isExperimentalFeatures) {
+ <div class="mb-3">
+ <gf-tags-selector
+ formControlName="tags"
+ [hasPermissionToCreateTag]="hasPermissionToCreateOwnTag"
+ [tagsAvailable]="tagsAvailable"
+ />
+ </div>
+ }
<div class="mb-3 px-2">
<mat-checkbox color="primary" formControlName="isExcluded" i18n
>Exclude from Analysis</mat-checkbox
diff --git a/apps/client/src/app/pages/accounts/create-or-update-account-dialog/interfaces/interfaces.ts b/apps/client/src/app/pages/accounts/create-or-update-account-dialog/interfaces/interfaces.ts
index 469ebc8449..c51503277f 100644
--- a/apps/client/src/app/pages/accounts/create-or-update-account-dialog/interfaces/interfaces.ts
+++ b/apps/client/src/app/pages/accounts/create-or-update-account-dialog/interfaces/interfaces.ts
@@ -1,7 +1,11 @@
-import { Account } from '@prisma/client';
+import { User } from '@ghostfolio/common/interfaces';
+
+import { Account, Tag } from '@prisma/client';
export interface CreateOrUpdateAccountDialogParams {
account: Omit<Account, 'createdAt' | 'id' | 'updatedAt' | 'userId'> & {
id: string | null;
+ tags?: Tag[];
};
+ user: User;
}
diff --git a/libs/common/src/lib/dtos/create-account.dto.ts b/libs/common/src/lib/dtos/create-account.dto.ts
index fa88580f1a..b04193020d 100644
--- a/libs/common/src/lib/dtos/create-account.dto.ts
+++ b/libs/common/src/lib/dtos/create-account.dto.ts
@@ -2,6 +2,8 @@ import { IsCurrencyCode } from '@ghostfolio/common/validators/is-currency-code';
import { Transform, TransformFnParams } from 'class-transformer';
import {
+ ArrayUnique,
+ IsArray,
IsBoolean,
IsNumber,
IsOptional,
@@ -28,6 +30,9 @@ export class CreateAccountDto {
@IsString()
id?: string;
+ /**
+ * @deprecated Use the "Exclude from Analysis" tag (`TAG_ID_EXCLUDE_FROM_ANALYSIS`) instead
+ */
@IsBoolean()
@IsOptional()
isExcluded?: boolean;
@@ -38,4 +43,10 @@ export class CreateAccountDto {
@IsString()
@ValidateIf((_object, value) => value !== null)
platformId: string | null;
+
+ @ArrayUnique()
+ @IsArray()
+ @IsOptional()
+ @IsString({ each: true })
+ tags?: string[];
}
diff --git a/libs/common/src/lib/dtos/update-account.dto.ts b/libs/common/src/lib/dtos/update-account.dto.ts
index 066bacbfd5..7a33da2dfc 100644
--- a/libs/common/src/lib/dtos/update-account.dto.ts
+++ b/libs/common/src/lib/dtos/update-account.dto.ts
@@ -2,6 +2,8 @@ import { IsCurrencyCode } from '@ghostfolio/common/validators/is-currency-code';
import { Transform, TransformFnParams } from 'class-transformer';
import {
+ ArrayUnique,
+ IsArray,
IsBoolean,
IsNumber,
IsOptional,
@@ -27,6 +29,9 @@ export class UpdateAccountDto {
@IsString()
id: string;
+ /**
+ * @deprecated Use the "Exclude from Analysis" tag (`TAG_ID_EXCLUDE_FROM_ANALYSIS`) instead
+ */
@IsBoolean()
@IsOptional()
isExcluded?: boolean;
@@ -37,4 +42,10 @@ export class UpdateAccountDto {
@IsString()
@ValidateIf((_object, value) => value !== null)
platformId: string | null;
+
+ @ArrayUnique()
+ @IsArray()
+ @IsOptional()
+ @IsString({ each: true })
+ tags?: string[];
}
diff --git a/libs/common/src/lib/helper.ts b/libs/common/src/lib/helper.ts
index ef66b52519..f9dcd52cf2 100644
--- a/libs/common/src/lib/helper.ts
+++ b/libs/common/src/lib/helper.ts
@@ -40,7 +40,8 @@ import {
DERIVED_CURRENCIES,
ghostfolioFearAndGreedIndexSymbolCryptocurrencies,
ghostfolioFearAndGreedIndexSymbolStocks,
- ghostfolioScraperApiSymbolPrefix
+ ghostfolioScraperApiSymbolPrefix,
+ TAG_ID_EXCLUDE_FROM_ANALYSIS
} from './config';
import {
AssetProfileIdentifier,
@@ -419,6 +420,18 @@ export function interpolate(template: string, context: any) {
});
}
+export function isAccountExcluded(account: {
+ isExcluded: boolean;
+ tags?: { id: string }[];
+}) {
+ return (
+ account.isExcluded ||
+ account.tags?.some(({ id }) => {
+ return id === TAG_ID_EXCLUDE_FROM_ANALYSIS;
+ }) === true
+ );
+}
+
export function isCurrency(aCurrency: string) {
if (!aCurrency) {
return false;
diff --git a/libs/common/src/lib/interfaces/responses/export-response.interface.ts b/libs/common/src/lib/interfaces/responses/export-response.interface.ts
index beffad7f18..89c54d8845 100644
--- a/libs/common/src/lib/interfaces/responses/export-response.interface.ts
+++ b/libs/common/src/lib/interfaces/responses/export-response.interface.ts
@@ -8,6 +8,7 @@ import { UserSettings } from '../user-settings.interface';
export interface ExportResponse {
accounts: (Omit<Account, 'createdAt' | 'updatedAt' | 'userId'> & {
balances: AccountBalance[];
+ tags?: string[];
})[];
activities: (Omit<
Order,
diff --git a/libs/common/src/lib/types/account-with-platform.type.ts b/libs/common/src/lib/types/account-with-platform.type.ts
index fbaa473933..640245e3bc 100644
--- a/libs/common/src/lib/types/account-with-platform.type.ts
+++ b/libs/common/src/lib/types/account-with-platform.type.ts
@@ -1,3 +1,6 @@
-import { Account, Platform } from '@prisma/client';
+import { Account, Platform, Tag } from '@prisma/client';
-export type AccountWithPlatform = Account & { platform?: Platform };
+export type AccountWithPlatform = Account & {
+ platform?: Platform;
+ tags?: Tag[];
+};
diff --git a/libs/common/src/lib/types/account-with-value.type.ts b/libs/common/src/lib/types/account-with-value.type.ts
index 23cb147492..a135306321 100644
--- a/libs/common/src/lib/types/account-with-value.type.ts
+++ b/libs/common/src/lib/types/account-with-value.type.ts
@@ -1,4 +1,4 @@
-import { Account as AccountModel, Platform } from '@prisma/client';
+import { Account as AccountModel, Platform, Tag } from '@prisma/client';
export type AccountWithValue = AccountModel & {
activitiesCount: number;
@@ -7,6 +7,7 @@ export type AccountWithValue = AccountModel & {
dividendInBaseCurrency: number;
interestInBaseCurrency: number;
platform?: Platform;
+ tags?: Tag[];
value: number;
valueInBaseCurrency: number;
};
diff --git a/libs/ui/src/lib/accounts-table/accounts-table.component.html b/libs/ui/src/lib/accounts-table/accounts-table.component.html
index f73c6dfe53..d252b1488a 100644
--- a/libs/ui/src/lib/accounts-table/accounts-table.component.html
+++ b/libs/ui/src/lib/accounts-table/accounts-table.component.html
@@ -33,7 +33,7 @@
mat-cell
>
<div class="d-flex justify-content-center">
- @if (element.isExcluded) {
+ @if (isExcluded(element)) {
<ion-icon name="eye-off-outline" />
}
</div>
diff --git a/libs/ui/src/lib/accounts-table/accounts-table.component.ts b/libs/ui/src/lib/accounts-table/accounts-table.component.ts
index 1526ffea54..3e531e844c 100644
--- a/libs/ui/src/lib/accounts-table/accounts-table.component.ts
+++ b/libs/ui/src/lib/accounts-table/accounts-table.component.ts
@@ -1,5 +1,9 @@
import { ConfirmationDialogType } from '@ghostfolio/common/enums';
-import { getLocale, getLowercase } from '@ghostfolio/common/helper';
+import {
+ getLocale,
+ getLowercase,
+ isAccountExcluded
+} from '@ghostfolio/common/helper';
import { GfEntityLogoComponent } from '@ghostfolio/ui/entity-logo';
import { NotificationService } from '@ghostfolio/ui/notifications';
import { GfValueComponent } from '@ghostfolio/ui/value';
@@ -137,6 +141,10 @@ export class GfAccountsTableComponent {
});
}
+ protected isExcluded(account: Account & { tags?: { id: string }[] }) {
+ return isAccountExcluded(account);
+ }
+
protected onDeleteAccount(aId: string) {
this.notificationService.confirm({
confirmFn: () => {
diff --git a/libs/ui/src/lib/activities-table/activities-table.component.ts b/libs/ui/src/lib/activities-table/activities-table.component.ts
index 766abcc233..dd792ca354 100644
--- a/libs/ui/src/lib/activities-table/activities-table.component.ts
+++ b/libs/ui/src/lib/activities-table/activities-table.component.ts
@@ -3,7 +3,7 @@ import {
TAG_ID_EXCLUDE_FROM_ANALYSIS
} from '@ghostfolio/common/config';
import { ConfirmationDialogType } from '@ghostfolio/common/enums';
-import { getLocale } from '@ghostfolio/common/helper';
+import { getLocale, isAccountExcluded } from '@ghostfolio/common/helper';
import {
Activity,
AssetProfileIdentifier
@@ -267,10 +267,10 @@ export class GfActivitiesTableComponent implements AfterViewInit, OnInit {
public isExcludedFromAnalysis(activity: Activity) {
return (
- activity.account?.isExcluded ??
+ (activity.account && isAccountExcluded(activity.account)) ||
activity.tags?.some(({ id }) => {
return id === TAG_ID_EXCLUDE_FROM_ANALYSIS;
- })
+ }) === true
);
}
diff --git a/libs/ui/src/lib/tags-selector/tags-selector.component.html b/libs/ui/src/lib/tags-selector/tags-selector.component.html
index 82f4655558..92ea2b2106 100644
--- a/libs/ui/src/lib/tags-selector/tags-selector.component.html
+++ b/libs/ui/src/lib/tags-selector/tags-selector.component.html
@@ -2,10 +2,19 @@
<div class="col">
@if (readonly) {
<div class="h5" i18n>Tags</div>
- @if (tags && tags.length > 0) {
+ @if (
+ (tags && tags.length > 0) || (tagsReadOnly && tagsReadOnly.length > 0)
+ ) {
<mat-chip-listbox>
- @for (tag of tags; track tag) {
- <mat-chip-option disabled>{{ tag.name }}</mat-chip-option>
+ @if (tagsReadOnly) {
+ @for (tag of tagsReadOnly; track tag) {
+ <mat-chip-option disabled>{{ tag.name }}</mat-chip-option>
+ }
+ }
+ @if (tags) {
+ @for (tag of tags; track tag) {
+ <mat-chip-option disabled>{{ tag.name }}</mat-chip-option>
+ }
}
</mat-chip-listbox>
} @else {
@@ -15,6 +24,13 @@
<mat-form-field appearance="outline" class="w-100 without-hint">
<mat-label i18n>Tags</mat-label>
<mat-chip-grid #tagsChipList>
+ @if (tagsReadOnly) {
+ @for (tag of tagsReadOnly; track tag.id) {
+ <mat-chip-row disabled [removable]="false">
+ {{ tag.name }}
+ </mat-chip-row>
+ }
+ }
@for (tag of tagsSelected(); track tag.id) {
<mat-chip-row
matChipRemove
diff --git a/libs/ui/src/lib/tags-selector/tags-selector.component.ts b/libs/ui/src/lib/tags-selector/tags-selector.component.ts
index 36e17f9c19..c0d5fe6a6f 100644
--- a/libs/ui/src/lib/tags-selector/tags-selector.component.ts
+++ b/libs/ui/src/lib/tags-selector/tags-selector.component.ts
@@ -9,6 +9,7 @@ import {
OnChanges,
OnInit,
signal,
+ SimpleChanges,
viewChild
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@@ -27,7 +28,6 @@ import { MatChipsModule } from '@angular/material/chips';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { IonIcon } from '@ionic/angular/standalone';
-import { Tag } from '@prisma/client';
import { addIcons } from 'ionicons';
import { addCircleOutline, closeOutline } from 'ionicons/icons';
import { BehaviorSubject, Subject } from 'rxjs';
@@ -65,6 +65,7 @@ export class GfTagsSelectorComponent
@Input() readonly = false;
@Input() tags: SelectedTag[];
@Input() tagsAvailable: SelectedTag[];
+ @Input() tagsReadOnly: SelectedTag[];
public readonly filteredOptions: Subject<SelectedTag[]> = new BehaviorSubject(
[]
@@ -87,12 +88,15 @@ export class GfTagsSelectorComponent
}
public ngOnInit() {
- this.tagsSelected.set(this.tags);
+ this.tagsSelected.set(this.tags ?? []);
this.updateFilters();
}
- public ngOnChanges() {
- this.tagsSelected.set(this.tags);
+ public ngOnChanges(changes: SimpleChanges) {
+ if (changes.tags) {
+ this.tagsSelected.set(this.tags ?? []);
+ }
+
this.updateFilters();
}
@@ -123,7 +127,7 @@ export class GfTagsSelectorComponent
this.tagInputControl.setValue(null);
}
- public onRemoveTag(tag: Tag) {
+ public onRemoveTag(tag: SelectedTag) {
this.tagsSelected.update((tags) => {
return tags.filter(({ id }) => {
return id !== tag.id;
@@ -159,15 +163,20 @@ export class GfTagsSelectorComponent
private filterTags(query: string = ''): SelectedTag[] {
const tags = this.tagsSelected() ?? [];
- const tagIds = tags.map(({ id }) => {
+ const tagIds = [...tags, ...(this.tagsReadOnly ?? [])].map(({ id }) => {
return id;
});
- return this.tagsAvailable.filter(({ id, name }) => {
- return (
- !tagIds.includes(id) && name.toLowerCase().includes(query.toLowerCase())
- );
- });
+ return this.tagsAvailable
+ .filter(({ id, name }) => {
+ return (
+ !tagIds.includes(id) &&
+ name.toLowerCase().includes(query.toLowerCase())
+ );
+ })
+ .sort((a, b) => {
+ return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
+ });
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
diff --git a/prisma/migrations/20260705095904_added_tags_on_accounts/migration.sql b/prisma/migrations/20260705095904_added_tags_on_accounts/migration.sql
new file mode 100644
index 0000000000..c2fdf4e5d2
--- /dev/null
+++ b/prisma/migrations/20260705095904_added_tags_on_accounts/migration.sql
@@ -0,0 +1,20 @@
+-- CreateTable
+CREATE TABLE "TagsOnAccounts" (
+ "accountId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "tagId" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ "userId" TEXT NOT NULL,
+
+ CONSTRAINT "TagsOnAccounts_pkey" PRIMARY KEY ("accountId","tagId","userId")
+);
+
+-- CreateIndex
+CREATE INDEX "TagsOnAccounts_tagId_idx" ON "TagsOnAccounts"("tagId");
+
+-- AddForeignKey
+ALTER TABLE "TagsOnAccounts" ADD CONSTRAINT "TagsOnAccounts_accountId_userId_fkey" FOREIGN KEY ("accountId", "userId") REFERENCES "Account"("id", "userId") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "TagsOnAccounts" ADD CONSTRAINT "TagsOnAccounts_tagId_fkey" FOREIGN KEY ("tagId") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 2c39667eed..233a636886 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -33,10 +33,12 @@ model Account {
createdAt DateTime @default(now())
currency String?
id String @default(uuid())
+ /// @deprecated Use the "Exclude from Analysis" tag (`TAG_ID_EXCLUDE_FROM_ANALYSIS`) instead
isExcluded Boolean @default(false)
name String?
platform Platform? @relation(fields: [platformId], references: [id])
platformId String?
+ tags TagsOnAccounts[]
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], onDelete: Cascade, references: [id])
userId String
@@ -251,16 +253,30 @@ model Subscription {
}
model Tag {
+ accounts TagsOnAccounts[]
activities Order[]
- id String @id @default(uuid())
+ id String @id @default(uuid())
name String
- user User? @relation(fields: [userId], onDelete: Cascade, references: [id])
+ user User? @relation(fields: [userId], onDelete: Cascade, references: [id])
userId String?
@@unique([name, userId])
@@index([name])
}
+model TagsOnAccounts {
+ account Account @relation(fields: [accountId, userId], onDelete: Cascade, references: [id, userId])
+ accountId String
+ createdAt DateTime @default(now())
+ tag Tag @relation(fields: [tagId], onDelete: Cascade, references: [id])
+ tagId String
+ updatedAt DateTime @updatedAt
+ userId String
+
+ @@id([accountId, tagId, userId])
+ @@index([tagId])
+}
+
model User {
accessesGet Access[] @relation("accessGet")
accessesGive Access[] @relation("accessGive")