Browse Source

Task/improve type safety in import service (#8467)

Improve type safety
main
Kenrick Tandrian 12 hours ago
committed by GitHub
parent
commit
9cad9e1027
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 206
      apps/api/src/services/import/import.service.ts

206
apps/api/src/services/import/import.service.ts

@ -14,6 +14,7 @@ import { SymbolProfileService } from '@ghostfolio/api/services/symbol-profile/sy
import { TagService } from '@ghostfolio/api/services/tag/tag.service'; import { TagService } from '@ghostfolio/api/services/tag/tag.service';
import { import {
DATA_GATHERING_QUEUE_PRIORITY_HIGH, DATA_GATHERING_QUEUE_PRIORITY_HIGH,
DEFAULT_CURRENCY,
ghostfolioPrefix, ghostfolioPrefix,
NON_INVESTMENT_ACTIVITY_TYPES, NON_INVESTMENT_ACTIVITY_TYPES,
TAG_ID_DRAFT, TAG_ID_DRAFT,
@ -34,7 +35,8 @@ import {
import { import {
Activity, Activity,
ActivityError, ActivityError,
AssetProfileIdentifier AssetProfileIdentifier,
EnhancedAssetProfile
} from '@ghostfolio/common/interfaces'; } from '@ghostfolio/common/interfaces';
import { hasPermission, permissions } from '@ghostfolio/common/permissions'; import { hasPermission, permissions } from '@ghostfolio/common/permissions';
import { import {
@ -45,7 +47,12 @@ import {
} from '@ghostfolio/common/types'; } from '@ghostfolio/common/types';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { Account, DataSource, Prisma } from '@prisma/client'; import {
Account,
DataSource,
Prisma,
Type as ActivityType
} from '@prisma/client';
import { Big } from 'big.js'; import { Big } from 'big.js';
import { isISIN } from 'class-validator'; import { isISIN } from 'class-validator';
import { isSameSecond, parseISO, subDays } from 'date-fns'; import { isSameSecond, parseISO, subDays } from 'date-fns';
@ -99,6 +106,11 @@ export class ImportService {
}); });
const { dateOfFirstActivity, historicalData } = holding; const { dateOfFirstActivity, historicalData } = holding;
const firstActivityDate = parseDate(dateOfFirstActivity);
if (!firstActivityDate) {
return [];
}
const [{ accounts }, { activities }, [assetProfile], dividends] = const [{ accounts }, { activities }, [assetProfile], dividends] =
await Promise.all([ await Promise.all([
@ -112,7 +124,7 @@ export class ImportService {
userCurrency, userCurrency,
userId, userId,
includeDrafts: true, includeDrafts: true,
startDate: subDays(parseDate(dateOfFirstActivity), 1), startDate: subDays(firstActivityDate, 1),
withExcludedAccountsAndActivities: true withExcludedAccountsAndActivities: true
}), }),
this.symbolProfileService.getSymbolProfiles([ this.symbolProfileService.getSymbolProfiles([
@ -124,7 +136,7 @@ export class ImportService {
this.dataProviderService.getDividends({ this.dataProviderService.getDividends({
dataSource, dataSource,
symbol, symbol,
from: parseDate(dateOfFirstActivity), from: firstActivityDate,
granularity: 'day', granularity: 'day',
to: new Date() to: new Date()
}) })
@ -133,9 +145,13 @@ export class ImportService {
const account = this.isUniqueAccount(accounts) ? accounts[0] : undefined; const account = this.isUniqueAccount(accounts) ? accounts[0] : undefined;
return await Promise.all( return await Promise.all(
Object.entries(dividends).map(([dateString, { marketPrice }]) => { Object.entries(dividends).flatMap(([dateString, { marketPrice }]) => {
const date = parseDate(dateString); const date = parseDate(dateString);
if (!date) {
return [];
}
const quantity = const quantity =
historicalData.find((historicalDataItem) => { historicalData.find((historicalDataItem) => {
return historicalDataItem.date === dateString; return historicalDataItem.date === dateString;
@ -155,22 +171,24 @@ export class ImportService {
); );
}); });
const error: ActivityError = isDuplicate const error: ActivityError | undefined = isDuplicate
? { code: 'IS_DUPLICATE' } ? { code: 'IS_DUPLICATE' }
: undefined; : undefined;
return { return [
{
account, account,
assetProfile, assetProfile,
date, date,
error, error,
quantity, quantity,
userId,
value, value,
accountId: account?.id, accountId: account?.id ?? null,
accountUserId: undefined, accountUserId: null,
comment: undefined, comment: null,
currency: undefined, currency: null,
createdAt: undefined, createdAt: new Date(),
fee: 0, fee: 0,
feeInAssetProfileCurrency: 0, feeInAssetProfileCurrency: 0,
feeInBaseCurrency: 0, feeInBaseCurrency: 0,
@ -179,10 +197,10 @@ export class ImportService {
type: 'DIVIDEND', type: 'DIVIDEND',
unitPrice: marketPrice, unitPrice: marketPrice,
unitPriceInAssetProfileCurrency: marketPrice, unitPriceInAssetProfileCurrency: marketPrice,
updatedAt: undefined, updatedAt: new Date(),
userId: account?.userId,
valueInBaseCurrency: value valueInBaseCurrency: value
}; }
];
}) })
); );
} catch { } catch {
@ -226,7 +244,8 @@ export class ImportService {
const maxActivitiesToImport = this.getMaxActivitiesToImport({ user }); const maxActivitiesToImport = this.getMaxActivitiesToImport({ user });
const platformIdMapping: { [oldPlatformId: string]: string } = {}; const platformIdMapping: { [oldPlatformId: string]: string } = {};
const tagIdMapping: { [oldTagId: string]: string } = {}; const tagIdMapping: { [oldTagId: string]: string } = {};
const userCurrency = user.settings.settings.baseCurrency; const userCurrency =
user.settings.settings.baseCurrency ?? DEFAULT_CURRENCY;
// Validate the symbols before any data is persisted // Validate the symbols before any data is persisted
for (const [index, assetProfileWithMarketData] of ( for (const [index, assetProfileWithMarketData] of (
@ -279,6 +298,7 @@ export class ImportService {
`activities.${index}.symbol ("${activity.symbol}") must be a UUID or start with the prefix "${ghostfolioPrefix}_" for the data source ("${DataSource.MANUAL}")` `activities.${index}.symbol ("${activity.symbol}") must be a UUID or start with the prefix "${ghostfolioPrefix}_" for the data source ("${DataSource.MANUAL}")`
); );
} else if ( } else if (
activity.dataSource &&
activity.dataSource !== DataSource.MANUAL && activity.dataSource !== DataSource.MANUAL &&
isValidCustomAssetProfileSymbol(activity.symbol) isValidCustomAssetProfileSymbol(activity.symbol)
) { ) {
@ -296,13 +316,15 @@ export class ImportService {
// Resolve the symbols with an ISIN to the symbol of the data provider // Resolve the symbols with an ISIN to the symbol of the data provider
// before the asset profiles are created and the duplicates are detected // before the asset profiles are created and the duplicates are detected
const assetProfileIdentifiersWithIsin: AssetProfileIdentifier[] = uniqBy( const assetProfileIdentifiersWithIsin: AssetProfileIdentifier[] = uniqBy(
[...(assetProfilesWithMarketDataDto ?? []), ...activitiesDto] [...(assetProfilesWithMarketDataDto ?? []), ...activitiesDto].flatMap(
.filter(({ dataSource, symbol }) => { ({ dataSource, symbol }) => {
return dataSource !== DataSource.MANUAL && isISIN(symbol); return dataSource &&
}) dataSource !== DataSource.MANUAL &&
.map(({ dataSource, symbol }) => { isISIN(symbol)
return { dataSource, symbol }; ? [{ dataSource, symbol }]
}), : [];
}
),
getAssetProfileIdentifier getAssetProfileIdentifier
); );
@ -448,12 +470,12 @@ export class ImportService {
where: { where: {
id: { id: {
in: accountsWithBalancesDto in: accountsWithBalancesDto
.filter(({ id }) => {
return Boolean(id);
})
.map(({ id }) => { .map(({ id }) => {
return id; return id;
}) })
.filter((id): id is string => {
return Boolean(id);
})
}, },
userId: { not: user.id } userId: { not: user.id }
} }
@ -520,14 +542,15 @@ export class ImportService {
'balance', 'balance',
'balances', 'balances',
'isExcluded', 'isExcluded',
'platformId',
'tags' 'tags'
]); ]);
let oldAccountId: string | undefined; let oldAccountId: string | undefined;
const platformId = const platformId = accountWithBalances.platformId
platformIdMapping[account.platformId] ?? account.platformId; ? (platformIdMapping[accountWithBalances.platformId] ??
accountWithBalances.platformId)
delete account.platformId; : undefined;
if (accountWithSameIdOfOtherUser) { if (accountWithSameIdOfOtherUser) {
oldAccountId = account.id; oldAccountId = account.id;
@ -561,6 +584,7 @@ export class ImportService {
}; };
if ( if (
platformId &&
existingPlatforms.some(({ id }) => { existingPlatforms.some(({ id }) => {
return id === platformId; return id === platformId;
}) })
@ -589,9 +613,16 @@ export class ImportService {
if (assetProfilesWithMarketDataDto?.length) { if (assetProfilesWithMarketDataDto?.length) {
const customAssetProfileNames = assetProfilesWithMarketDataDto const customAssetProfileNames = assetProfilesWithMarketDataDto
.filter(({ dataSource, name }) => { .filter(
return dataSource === DataSource.MANUAL && Boolean(name); (
}) assetProfile
): assetProfile is typeof assetProfile & { name: string } => {
return (
assetProfile.dataSource === DataSource.MANUAL &&
Boolean(assetProfile.name)
);
}
)
.map(({ name }) => { .map(({ name }) => {
return name; return name;
}); });
@ -745,7 +776,7 @@ export class ImportService {
} }
// If an account is created or reused, then update the accountId in all activities // If an account is created or reused, then update the accountId in all activities
if (accountIdMapping[activity.accountId]) { if (activity.accountId && accountIdMapping[activity.accountId]) {
activity.accountId = accountIdMapping[activity.accountId]; activity.accountId = accountIdMapping[activity.accountId];
} }
@ -780,18 +811,24 @@ export class ImportService {
return { id, name, platform }; return { id, name, platform };
}); });
if (isDryRun) { if (isDryRun && accountsWithBalancesDto?.length) {
accountsWithBalancesDto accountsWithBalancesDto
.filter(({ id }) => { .filter(
// Skip the accounts which are reused or which already belong to the (
// user, since they are part of the accounts of the user above account
): account is CreateAccountWithBalancesDto & { id: string } => {
if (!account.id) {
return false;
}
return ( return (
!accountIdMapping[id] && !accountIdMapping[account.id] &&
!accounts.some(({ id: accountId }) => { !accounts.some(({ id: accountId }) => {
return accountId === id; return accountId === account.id;
}) })
); );
}) }
)
.forEach(({ id, name }) => { .forEach(({ id, name }) => {
accounts.push({ id, name }); accounts.push({ id, name });
}); });
@ -818,12 +855,15 @@ export class ImportService {
} }
); );
if (isDryRun) { if (isDryRun && tagsDto?.length) {
tagsDto tagsDto
.filter(({ id }) => { .filter((tag): tag is typeof tag & { id: string } => {
return !tags.some(({ id: tagId }) => { return (
return tagId === id; Boolean(tag.id) &&
}); !tags.some(({ id: tagId }) => {
return tagId === tag.id;
})
);
}) })
.forEach(({ id, name }) => { .forEach(({ id, name }) => {
tags.push({ id, name }); tags.push({ id, name });
@ -892,8 +932,12 @@ export class ImportService {
let order: let order:
| OrderWithAccount | OrderWithAccount
| (Omit<OrderWithAccount, 'account' | 'SymbolProfile' | 'tags'> & { | (Omit<
OrderWithAccount,
'account' | 'SymbolProfile' | 'symbolProfileId' | 'tags'
> & {
account?: Pick<AccountWithPlatform, 'id' | 'name' | 'platform'>; account?: Pick<AccountWithPlatform, 'id' | 'name' | 'platform'>;
symbolProfileId?: string;
tags?: { id: string; name: string }[]; tags?: { id: string; name: string }[];
}); });
@ -906,7 +950,7 @@ export class ImportService {
}); });
order = { order = {
comment, comment: comment ?? null,
currency, currency,
date, date,
fee, fee,
@ -914,8 +958,8 @@ export class ImportService {
type, type,
unitPrice, unitPrice,
account: validatedAccount, account: validatedAccount,
accountId: validatedAccount?.id, accountId: validatedAccount?.id ?? null,
accountUserId: undefined, accountUserId: null,
createdAt: new Date(), createdAt: new Date(),
id: randomUUID(), id: randomUUID(),
symbolProfileId: undefined, symbolProfileId: undefined,
@ -934,8 +978,19 @@ export class ImportService {
? customAssetProfileSymbols[assetProfileIdentifier] ? customAssetProfileSymbols[assetProfileIdentifier]
: undefined; : undefined;
const { dataSource, name } = assetProfile; const dataSource =
const symbol = customAssetProfileSymbol ?? assetProfile.symbol; assetProfile.dataSource ?? activity.assetProfile.dataSource;
const name = assetProfile.name;
const symbol =
customAssetProfileSymbol ??
assetProfile.symbol ??
activity.assetProfile.symbol;
if (!assetProfile.currency) {
throw new ImportValidationError(
`Asset profile ("${symbol}") has no currency`
);
}
const createdActivity = await this.activitiesService.createActivity({ const createdActivity = await this.activitiesService.createActivity({
comment, comment,
@ -1038,10 +1093,24 @@ export class ImportService {
userCurrency, userCurrency,
userId userId
}: { }: {
activitiesDto: Partial<CreateOrderDto>[]; activitiesDto: CreateOrderDto[];
userCurrency: string; userCurrency: string;
userId: string; userId: string;
}): Promise<(Partial<Activity> & Pick<Activity, 'assetProfile'>)[]> { }): Promise<
{
accountId?: string;
assetProfile: Pick<EnhancedAssetProfile, 'dataSource' | 'symbol'>;
comment?: string | null;
currency: string;
date: Date;
error?: ActivityError;
fee: number;
quantity: number;
tagIds?: string[];
type: ActivityType;
unitPrice: number;
}[]
> {
const { activities: existingActivities } = const { activities: existingActivities } =
await this.activitiesService.getActivities({ await this.activitiesService.getActivities({
userCurrency, userCurrency,
@ -1081,7 +1150,7 @@ export class ImportService {
); );
}); });
const error: ActivityError = isDuplicate const error: ActivityError | undefined = isDuplicate
? { code: 'IS_DUPLICATE' } ? { code: 'IS_DUPLICATE' }
: undefined; : undefined;
@ -1096,19 +1165,11 @@ export class ImportService {
type, type,
unitPrice, unitPrice,
assetProfile: { assetProfile: {
dataSource, // The data source of each activity is already set in import(). The
symbol, // fallback only satisfies the type, since MANUAL is not the default
activitiesCount: undefined, // data source of investment activities.
assetClass: undefined, dataSource: dataSource ?? DataSource.MANUAL,
assetSubClass: undefined, symbol
countries: undefined,
createdAt: undefined,
currency: undefined,
holdings: undefined,
id: undefined,
isActive: true,
sectors: undefined,
updatedAt: undefined
}, },
tagIds: tags tagIds: tags
}; };
@ -1133,7 +1194,7 @@ export class ImportService {
accountWithBalances: CreateAccountWithBalancesDto; accountWithBalances: CreateAccountWithBalancesDto;
accountsWithBalancesDto: ImportDataDto['accounts']; accountsWithBalancesDto: ImportDataDto['accounts'];
existingAccountsOfUser: Account[]; existingAccountsOfUser: Account[];
}): Account { }): Account | undefined {
const matchingAccountsOfUser = existingAccountsOfUser.filter( const matchingAccountsOfUser = existingAccountsOfUser.filter(
({ currency, name }) => { ({ currency, name }) => {
return ( return (
@ -1143,7 +1204,7 @@ export class ImportService {
} }
); );
const matchingAccountsToImport = accountsWithBalancesDto.filter( const matchingAccountsToImport = (accountsWithBalancesDto ?? []).filter(
({ currency, name }) => { ({ currency, name }) => {
return ( return (
currency === accountWithBalances.currency && currency === accountWithBalances.currency &&
@ -1166,7 +1227,10 @@ export class ImportService {
activities, activities,
assetProfiles assetProfiles
}: { }: {
activities: Pick<Activity, 'assetProfile' | 'error'>[]; activities: {
assetProfile: Pick<EnhancedAssetProfile, 'dataSource' | 'symbol'>;
error?: ActivityError;
}[];
assetProfiles: AssetProfileToCreate[]; assetProfiles: AssetProfileToCreate[];
}) { }) {
const assetProfileIdentifiersToImport = new Set( const assetProfileIdentifiersToImport = new Set(

Loading…
Cancel
Save