mirror of https://github.com/ghostfolio/ghostfolio
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
285 lines
11 KiB
285 lines
11 KiB
/** Opt-in private-file qualification. Reports contain aggregates, never source account data or references. */
|
|
import { YahooFinanceDataEnhancerService } from '@ghostfolio/api/services/data-provider/data-enhancer/yahoo-finance/yahoo-finance.service';
|
|
import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service';
|
|
import { YahooFinanceService } from '@ghostfolio/api/services/data-provider/yahoo-finance/yahoo-finance.service';
|
|
import { BrokerImportService } from '@ghostfolio/api/services/import/broker/broker-import.service';
|
|
import { BrokerInstrumentResolver } from '@ghostfolio/api/services/import/broker/broker-instrument-resolver.service';
|
|
import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service';
|
|
import { getAssetProfileIdentifier } from '@ghostfolio/common/helper';
|
|
import { BrokerImportInput } from '@ghostfolio/common/interfaces/broker-import.interface';
|
|
import { UserWithSettings } from '@ghostfolio/common/types';
|
|
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { readFile, writeFile } from 'node:fs/promises';
|
|
|
|
async function main() {
|
|
const url = process.env.BROKER_TEST_DATABASE_URL,
|
|
path = process.env.BROKER_TEST_CSV_PATH,
|
|
reportPath = process.env.BROKER_TEST_REPORT_PATH;
|
|
if (
|
|
!url ||
|
|
new URL(url).hostname !== '127.0.0.1' ||
|
|
!new URL(url).pathname.startsWith('/broker_test_') ||
|
|
!path ||
|
|
!reportPath
|
|
)
|
|
throw Error('DISPOSABLE_DATABASE_AND_PRIVATE_INPUT_REQUIRED');
|
|
const prisma = new PrismaService(
|
|
new ConfigService({ DATABASE_URL: url, LOG_LEVELS: '[]' })
|
|
);
|
|
await prisma.$connect();
|
|
const userId = randomUUID(),
|
|
newProfiles: string[] = [];
|
|
try {
|
|
const initial = new Set(
|
|
(await prisma.symbolProfile.findMany({ select: { id: true } })).map(
|
|
(profile) => profile.id
|
|
)
|
|
);
|
|
await prisma.user.create({ data: { id: userId } });
|
|
const account = await prisma.account.create({
|
|
data: {
|
|
userId,
|
|
currency: 'EUR',
|
|
name: 'Disposable broker qualification',
|
|
balances: { create: { date: new Date('2020-01-01'), value: 123 } }
|
|
}
|
|
});
|
|
const crypto = { isCryptocurrency: () => false },
|
|
yahoo = new YahooFinanceService(
|
|
crypto as never,
|
|
new YahooFinanceDataEnhancerService(crypto as never)
|
|
);
|
|
const providers = {
|
|
getDataProvider: () => yahoo,
|
|
validateActivities: async (params) =>
|
|
DataProviderService.prototype.validateActivities.call(
|
|
{
|
|
configurationService: { get: () => [] },
|
|
getDataSources: async () => ['YAHOO'],
|
|
isPremiumRequired: () => false,
|
|
getAssetProfiles: async (items) =>
|
|
Object.fromEntries(
|
|
await Promise.all(
|
|
items.map(async (item) => [
|
|
getAssetProfileIdentifier(item),
|
|
await yahoo.getListingQuote({ symbol: item.symbol })
|
|
])
|
|
)
|
|
)
|
|
} as never,
|
|
params
|
|
)
|
|
};
|
|
const resolver = new BrokerInstrumentResolver(
|
|
prisma,
|
|
providers as never,
|
|
{ fetch: (...args: Parameters<typeof fetch>) => fetch(...args) } as never
|
|
);
|
|
let failAt = 0,
|
|
writes = 0;
|
|
const database = new Proxy(prisma, {
|
|
get(target, property) {
|
|
if (property === '$transaction')
|
|
return (callback, options) =>
|
|
prisma.$transaction(
|
|
(tx) =>
|
|
callback(
|
|
new Proxy(tx, {
|
|
get(client, key) {
|
|
if (key === 'brokerImportRecord')
|
|
return new Proxy(client.brokerImportRecord, {
|
|
get(delegate, method) {
|
|
if (method === 'create')
|
|
return async (args) => {
|
|
if (failAt && ++writes === failAt)
|
|
throw Error('INJECTED_QUALIFICATION_FAILURE');
|
|
return delegate.create(args);
|
|
};
|
|
return Reflect.get(delegate, method);
|
|
}
|
|
});
|
|
return Reflect.get(client, key);
|
|
}
|
|
})
|
|
),
|
|
options
|
|
);
|
|
return Reflect.get(target, property);
|
|
}
|
|
});
|
|
const service = new BrokerImportService(
|
|
database,
|
|
resolver,
|
|
providers as never,
|
|
new EventEmitter2()
|
|
);
|
|
const input: BrokerImportInput = {
|
|
format: 'DIRECTA',
|
|
accountId: account.id,
|
|
csv: await readFile(path, 'utf8'),
|
|
symbols: {},
|
|
useOperationDate: true
|
|
};
|
|
const user = {
|
|
id: userId,
|
|
subscription: { type: 'Basic' }
|
|
} as UserWithSettings;
|
|
const scope = { accountId: account.id, userId };
|
|
const snapshot = async () =>
|
|
JSON.stringify(
|
|
await Promise.all([
|
|
prisma.order.count({ where: { userId } }),
|
|
prisma.brokerImportRecord.count({ where: { userId } }),
|
|
prisma.symbolProfile.count(),
|
|
prisma.account.findUnique({
|
|
where: { id_userId: { id: account.id, userId } }
|
|
}),
|
|
prisma.accountBalance.findMany({
|
|
where: scope,
|
|
orderBy: { date: 'asc' }
|
|
})
|
|
])
|
|
);
|
|
const before = await snapshot(),
|
|
first = await service.run(input, user, true, 5000);
|
|
if ((await snapshot()) !== before) throw Error('PREVIEW_WROTE_DATA');
|
|
const report = {
|
|
rows: first.rowsRead,
|
|
initial: first.summary,
|
|
previewNoWrites: true,
|
|
afterChoices: undefined as typeof first.summary,
|
|
reconciliation: undefined as typeof first.reconciliation,
|
|
persistence: undefined as unknown,
|
|
rollbackVerified: false,
|
|
simulatedConfirmationMarket:
|
|
process.env.BROKER_TEST_CONFIRM_MARKET ?? null
|
|
};
|
|
if (process.env.BROKER_TEST_PARTIAL !== 'true') {
|
|
await writeFile(reportPath, JSON.stringify(report, null, 2));
|
|
console.log(JSON.stringify(report));
|
|
return;
|
|
}
|
|
input.excluded = first.operations
|
|
.filter((op) => op.status === 'UNSUPPORTED')
|
|
.map((op) => op.id);
|
|
input.confirmPartial = true;
|
|
for (const item of first.instruments)
|
|
if (item.status === 'CONFIRMATION_REQUIRED') {
|
|
const choices = item.candidates.filter(
|
|
(candidate) =>
|
|
candidate.exchange === process.env.BROKER_TEST_CONFIRM_MARKET &&
|
|
candidate.currency === 'EUR'
|
|
);
|
|
if (choices.length === 1) input.symbols[item.isin] = choices[0].key;
|
|
}
|
|
const plan = await service.run(input, user, true, 5000);
|
|
report.afterChoices = plan.summary;
|
|
report.reconciliation = plan.reconciliation;
|
|
if (plan.errors.length) throw Error('UNRESOLVED_QUALIFICATION_PREVIEW');
|
|
const beforeFailure = await snapshot();
|
|
failAt = plan.operations
|
|
.filter((op) => op.status === 'IMPORTABLE')
|
|
.reduce((sum, op) => sum + op.lines.length, 0);
|
|
let failed = false;
|
|
try {
|
|
await service.run({ ...input, digest: plan.digest }, user, false, 5000);
|
|
} catch (error) {
|
|
if (error.message === 'INJECTED_QUALIFICATION_FAILURE') failed = true;
|
|
else throw error;
|
|
}
|
|
if (!failed || (await snapshot()) !== beforeFailure)
|
|
throw Error('ROLLBACK_FAILED');
|
|
report.rollbackVerified = true;
|
|
failAt = 0;
|
|
await service.run({ ...input, digest: plan.digest }, user, false, 5000);
|
|
const orderProfiles = await prisma.order.findMany({
|
|
where: { userId },
|
|
select: { symbolProfileId: true }
|
|
});
|
|
newProfiles.push(
|
|
...orderProfiles
|
|
.map((order) => order.symbolProfileId)
|
|
.filter((id) => !initial.has(id))
|
|
);
|
|
const after = await snapshot(),
|
|
again = await service.run(input, user, true, 5000);
|
|
if (again.errors.length || again.summary.importable)
|
|
throw Error('REIMPORT_NOT_IDEMPOTENT');
|
|
await service.run({ ...input, digest: again.digest }, user, false, 5000);
|
|
if ((await snapshot()) !== after) throw Error('REIMPORT_WROTE_DATA');
|
|
report.persistence = {
|
|
activities: await prisma.order.count({ where: { userId } }),
|
|
provenance: await prisma.brokerImportRecord.count({ where: { userId } }),
|
|
reimportDuplicates: again.duplicates,
|
|
balanceUnchanged:
|
|
(await prisma.accountBalance.findFirst({ where: scope })).value === 123
|
|
};
|
|
if (process.env.BROKER_TEST_OVERLAP_CSV_PATH) {
|
|
const overlapping: BrokerImportInput = {
|
|
...input,
|
|
csv: await readFile(process.env.BROKER_TEST_OVERLAP_CSV_PATH, 'utf8'),
|
|
symbols: {},
|
|
excluded: [],
|
|
confirmPartial: false
|
|
};
|
|
const preview = await service.run(overlapping, user, true, 5000);
|
|
overlapping.excluded = preview.operations
|
|
.filter((op) => op.status === 'UNSUPPORTED')
|
|
.map((op) => op.id);
|
|
overlapping.confirmPartial = true;
|
|
for (const instrument of preview.instruments)
|
|
if (instrument.status === 'CONFIRMATION_REQUIRED') {
|
|
const choices = instrument.candidates.filter(
|
|
(candidate) =>
|
|
candidate.exchange === process.env.BROKER_TEST_CONFIRM_MARKET &&
|
|
candidate.currency === 'EUR'
|
|
);
|
|
if (choices.length === 1)
|
|
overlapping.symbols[instrument.isin] = choices[0].key;
|
|
}
|
|
const accepted = await service.run(overlapping, user, true, 5000);
|
|
if (accepted.errors.length) throw Error('OVERLAP_PREVIEW_FAILED');
|
|
await service.run(
|
|
{ ...overlapping, digest: accepted.digest },
|
|
user,
|
|
false,
|
|
5000
|
|
);
|
|
const check = await service.run(overlapping, user, true, 5000);
|
|
if (check.summary.importable || check.errors.length)
|
|
throw Error('OVERLAP_NOT_IDEMPOTENT');
|
|
(report as typeof report & { overlap: unknown }).overlap = {
|
|
rows: accepted.rowsRead,
|
|
previouslyImportedRows: accepted.duplicates,
|
|
additionalActivities: accepted.summary.importable,
|
|
totalActivities: await prisma.order.count({ where: { userId } }),
|
|
reimportDuplicates: check.duplicates
|
|
};
|
|
newProfiles.push(
|
|
...(
|
|
await prisma.order.findMany({
|
|
where: { userId },
|
|
select: { symbolProfileId: true }
|
|
})
|
|
)
|
|
.map((order) => order.symbolProfileId)
|
|
.filter((id) => !initial.has(id))
|
|
);
|
|
}
|
|
await writeFile(reportPath, JSON.stringify(report, null, 2));
|
|
console.log(JSON.stringify(report));
|
|
} finally {
|
|
await prisma.user.deleteMany({ where: { id: userId } });
|
|
await prisma.symbolProfile.deleteMany({
|
|
where: { id: { in: [...new Set(newProfiles)] } }
|
|
});
|
|
await prisma.$disconnect();
|
|
}
|
|
}
|
|
main().catch((error) => {
|
|
console.error('BROKER_QUALIFICATION_FAILED', error.name);
|
|
process.exitCode = 1;
|
|
});
|
|
|