diff --git a/apps/api/src/app/__snapshots__/app.module.spec.ts.snap b/apps/api/src/app/__snapshots__/app.module.spec.ts.snap index 546628c267..ffa935500d 100644 --- a/apps/api/src/app/__snapshots__/app.module.spec.ts.snap +++ b/apps/api/src/app/__snapshots__/app.module.spec.ts.snap @@ -1267,6 +1267,22 @@ exports[`AppModule should keep the security of each route 1`] = ` ], "permission": "createActivity", }, + "POST /import/broker": { + "guards": [ + "AuthGuard('jwt')", + "HasPermissionGuard", + ], + "interceptors": [], + "permission": "createActivity", + }, + "POST /import/broker/preview": { + "guards": [ + "AuthGuard('jwt')", + "HasPermissionGuard", + ], + "interceptors": [], + "permission": "createActivity", + }, "POST /market-data/:dataSource/:symbol": { "allowDuringImpersonation": true, "guards": [ diff --git a/apps/api/src/app/endpoints/import/broker-import.controller.spec.ts b/apps/api/src/app/endpoints/import/broker-import.controller.spec.ts new file mode 100644 index 0000000000..3b0d441df2 --- /dev/null +++ b/apps/api/src/app/endpoints/import/broker-import.controller.spec.ts @@ -0,0 +1,57 @@ +import { BrokerImportDto } from '@ghostfolio/api/services/import/broker/broker-import.dto'; + +import { BrokerImportController } from './broker-import.controller'; + +jest.mock( + '@ghostfolio/api/services/import/broker/broker-import.service', + () => ({ BrokerImportService: class BrokerImportService {} }) +); +jest.mock('@ghostfolio/api/services/import/import.service', () => ({ + ImportService: class ImportService {} +})); + +describe('Broker endpoint ownership and restrictions', () => { + const input = { + format: 'DIRECTA', + csv: 'synthetic', + accountId: 'own', + useOperationDate: true + } as BrokerImportDto; + function context(impersonated = false, restricted = false) { + const run = jest.fn(); + const user = { + id: 'owner', + settings: { settings: { isRestrictedView: restricted } } + }; + return { + run, + user, + controller: new BrokerImportController( + { run } as never, + { getMaxActivitiesToImport: () => 123 } as never, + { user, impersonation: { isActive: impersonated } } as never + ) + }; + } + it('binds both calls to the authenticated user and upstream activity limit', () => { + const { controller, run, user } = context(); + controller.preview(input); + controller.import(input); + expect(run.mock.calls).toEqual([ + [input, user, true, 123], + [input, user, false, 123] + ]); + }); + it.each([ + [true, false], + [false, true] + ])( + 'blocks impersonated and restricted imports', + (impersonated, restricted) => { + const { controller, run } = context(impersonated, restricted); + expect(() => controller.preview(input)).toThrow(); + expect(() => controller.import(input)).toThrow(); + expect(run).not.toHaveBeenCalled(); + } + ); +}); diff --git a/apps/api/src/app/endpoints/import/broker-import.controller.ts b/apps/api/src/app/endpoints/import/broker-import.controller.ts new file mode 100644 index 0000000000..a9bd673908 --- /dev/null +++ b/apps/api/src/app/endpoints/import/broker-import.controller.ts @@ -0,0 +1,51 @@ +import { HasPermission } from '@ghostfolio/api/decorators/has-permission.decorator'; +import { HasPermissionGuard } from '@ghostfolio/api/guards/has-permission.guard'; +import { BrokerImportDto } from '@ghostfolio/api/services/import/broker/broker-import.dto'; +import { BrokerImportService } from '@ghostfolio/api/services/import/broker/broker-import.service'; +import { ImportService } from '@ghostfolio/api/services/import/import.service'; +import { permissions } from '@ghostfolio/common/permissions'; +import type { RequestWithUser } from '@ghostfolio/common/types'; + +import { + Body, + Controller, + ForbiddenException, + Inject, + Post, + UseGuards +} from '@nestjs/common'; +import { REQUEST } from '@nestjs/core'; +import { AuthGuard } from '@nestjs/passport'; + +@Controller('import/broker') +@UseGuards(AuthGuard('jwt'), HasPermissionGuard) +export class BrokerImportController { + constructor( + private readonly broker: BrokerImportService, + private readonly imports: ImportService, + @Inject(REQUEST) private readonly request: RequestWithUser + ) {} + @Post('preview') + @HasPermission(permissions.createActivity) + preview(@Body() input: BrokerImportDto) { + return this.run(input, true); + } + @Post() + @HasPermission(permissions.createActivity) + import(@Body() input: BrokerImportDto) { + return this.run(input, false); + } + private run(input: BrokerImportDto, preview: boolean) { + if ( + this.request.impersonation?.isActive || + this.request.user.settings?.settings?.isRestrictedView + ) + throw new ForbiddenException(); + return this.broker.run( + input, + this.request.user, + preview, + this.imports.getMaxActivitiesToImport({ user: this.request.user }) + ); + } +} diff --git a/apps/api/src/app/endpoints/import/import.module.ts b/apps/api/src/app/endpoints/import/import.module.ts index c0d870a4f0..2c79f507ac 100644 --- a/apps/api/src/app/endpoints/import/import.module.ts +++ b/apps/api/src/app/endpoints/import/import.module.ts @@ -4,10 +4,11 @@ import { ImportModule as ImportServiceModule } from '@ghostfolio/api/services/im import { Module } from '@nestjs/common'; +import { BrokerImportController } from './broker-import.controller'; import { ImportController } from './import.controller'; @Module({ - controllers: [ImportController], + controllers: [ImportController, BrokerImportController], imports: [ ImportServiceModule, TransformDataSourceInRequestModule, diff --git a/apps/api/src/services/data-provider/interfaces/data-provider.interface.ts b/apps/api/src/services/data-provider/interfaces/data-provider.interface.ts index 380b7e6d20..a7309c5f9a 100644 --- a/apps/api/src/services/data-provider/interfaces/data-provider.interface.ts +++ b/apps/api/src/services/data-provider/interfaces/data-provider.interface.ts @@ -9,7 +9,19 @@ import { Granularity } from '@ghostfolio/common/types'; import { DataSource, SymbolProfile } from '@prisma/client'; +export interface ListingQuote { + symbol: string; + currency: string; + exchange: string; + name: string; + assetClass?: SymbolProfile['assetClass']; + assetSubClass?: SymbolProfile['assetSubClass']; +} export interface DataProviderInterface { + getListingQuote?( + params: GetAssetProfileParams + ): Promise; + canHandle(symbol: string): boolean; getAssetProfile({ diff --git a/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts b/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts index 098d888a71..7494208a3c 100644 --- a/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts +++ b/apps/api/src/services/data-provider/yahoo-finance/yahoo-finance.service.ts @@ -7,7 +7,8 @@ import { GetDividendsParams, GetHistoricalParams, GetQuotesParams, - GetSearchParams + GetSearchParams, + ListingQuote } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; import { DEFAULT_CURRENCY } from '@ghostfolio/common/config'; import { DATE_FORMAT } from '@ghostfolio/common/helper'; @@ -66,6 +67,39 @@ export class YahooFinanceService implements DataProviderInterface { ); } + /** Listing metadata, with a cancellable request; it does not establish the ISIN by itself. */ + public async getListingQuote({ + symbol, + requestTimeout = 8000 + }: GetAssetProfileParams): Promise { + const quote = await this.yahooFinance.quote( + symbol, + { + fields: [ + 'symbol', + 'currency', + 'exchange', + 'quoteType', + 'shortName', + 'longName' + ] + }, + { fetchOptions: { signal: AbortSignal.timeout(requestTimeout) } } + ); + if (!quote?.symbol || !quote.currency || !quote.exchange) return undefined; + const classes = this.yahooFinanceDataEnhancerService.parseAssetClass({ + quoteType: quote.quoteType, + shortName: quote.shortName + }); + return { + symbol: quote.symbol, + currency: quote.currency, + exchange: quote.exchange, + name: quote.longName ?? quote.shortName ?? quote.symbol, + ...classes + }; + } + public getDataProviderInfo(): DataProviderInfo { return { dataSource: DataSource.YAHOO, @@ -262,9 +296,14 @@ export class YahooFinanceService implements DataProviderInterface { public async search({ includeIndices = false, - query + query, + requestTimeout }: GetSearchParams): Promise { const items: LookupItem[] = []; + let unavailable = false; + const fetchOptions = requestTimeout + ? { signal: AbortSignal.timeout(requestTimeout) } + : undefined; try { const quoteTypes = ['EQUITY', 'ETF', 'FUTURE', 'MUTUALFUND']; @@ -273,7 +312,11 @@ export class YahooFinanceService implements DataProviderInterface { quoteTypes.push('INDEX'); } - const searchResult = await this.yahooFinance.search(query); + const searchResult = await this.yahooFinance.search( + query, + {}, + { fetchOptions } + ); const quotes = searchResult.quotes .filter( @@ -315,9 +358,12 @@ export class YahooFinanceService implements DataProviderInterface { return symbol; }).map(({ symbol }) => { return symbol; - }) + }), + {}, + { fetchOptions } ); } catch (error) { + unavailable = true; if (error?.result?.length > 0) { marketData = error.result; } @@ -355,6 +401,7 @@ export class YahooFinanceService implements DataProviderInterface { }); } } catch (error) { + unavailable = true; if (error?.name === 'BadRequestError') { this.logger.warn(`Could not search for "${query}": ${error.message}`); } else { @@ -362,7 +409,12 @@ export class YahooFinanceService implements DataProviderInterface { } } - return { items }; + return { + items, + ...(requestTimeout + ? { status: unavailable ? ('UNAVAILABLE' as const) : ('OK' as const) } + : {}) + }; } private convertToDividendResult( diff --git a/apps/api/src/services/fetch/fetch.service.spec.ts b/apps/api/src/services/fetch/fetch.service.spec.ts index e53fe4587b..622d1cdf9e 100644 --- a/apps/api/src/services/fetch/fetch.service.spec.ts +++ b/apps/api/src/services/fetch/fetch.service.spec.ts @@ -91,6 +91,17 @@ describe('FetchService', () => { directFetch.mockRestore(); }); + it('can require original provider bytes for financial identity verification', async () => { + const signal = AbortSignal.timeout(8000); + const response = await fetchService.fetch( + URL_WITH_ROUTE, + { signal }, + { allowWebFetch: false } + ); + await expect(response.text()).resolves.toBe('direct'); + expect(generateText).not.toHaveBeenCalled(); + expect(directFetch).toHaveBeenCalledWith(URL_WITH_ROUTE, { signal }); + }); it('should get the body from the text of the model', async () => { mockGenerateText({ text: `\`\`\`json\n${BODY}\n\`\`\`` }); diff --git a/apps/api/src/services/fetch/fetch.service.ts b/apps/api/src/services/fetch/fetch.service.ts index 9e1791cf3c..40892e6c5c 100644 --- a/apps/api/src/services/fetch/fetch.service.ts +++ b/apps/api/src/services/fetch/fetch.service.ts @@ -55,7 +55,11 @@ export class FetchService implements OnModuleInit { ); } - public async fetch(input: RequestInfo | URL, init?: RequestInit) { + public async fetch( + input: RequestInfo | URL, + init?: RequestInit, + options: { allowWebFetch?: boolean } = {} + ) { const method = ( init?.method ?? (input instanceof Request ? input.method : undefined) ?? @@ -67,7 +71,7 @@ export class FetchService implements OnModuleInit { this.logger.debug(`${method} ${urlRedacted}`); - if (method === 'GET') { + if (method === 'GET' && options.allowWebFetch !== false) { const webFetchRoute = this.getMatchingWebFetchRoute(url); if (webFetchRoute) { diff --git a/apps/api/src/services/import/broker/__fixtures__/directa-dividends.csv b/apps/api/src/services/import/broker/__fixtures__/directa-dividends.csv new file mode 100644 index 0000000000..dbb89f5c16 --- /dev/null +++ b/apps/api/src/services/import/broker/__fixtures__/directa-dividends.csv @@ -0,0 +1,8 @@ +Movimenti;;;;;;;;;;; +Conto : SYNTHETIC Dividend Cases;;;;;;;;;;; + +Data operazione;Data valuta;Tipo operazione;Ticker;Isin;Protocollo;Descrizione;Quantità;Importo euro;Importo Divisa;Divisa;Riferimento ordine +10-01-2026;12-01-2026;Incasso dividendi italia;SYN1;XX0000000002;INC-DOM;Synthetic domestic income;0;20;0;EUR;0 +10-01-2026;12-01-2026;Incasso dividendi esteri;SYN2;XX0000000010;INC-FOR;Synthetic foreign income;0;30;0;EUR;0 +10-01-2026;12-01-2026;Ritenuta dividendi esteri;SYN2;XX0000000010;TAX-FOR;Synthetic foreign withholding;0;-7,80;0;EUR;0 +10-01-2026;12-01-2026;Ritenuta dividendi italia;SYN1;XX0000000002;TAX-DOM;Synthetic domestic withholding;0;-5,20;0;EUR;0 diff --git a/apps/api/src/services/import/broker/__fixtures__/directa.csv b/apps/api/src/services/import/broker/__fixtures__/directa.csv new file mode 100644 index 0000000000..2f4a1b1382 --- /dev/null +++ b/apps/api/src/services/import/broker/__fixtures__/directa.csv @@ -0,0 +1,14 @@ +Movimenti;;;;;;;;;;; +Conto : SYNTHETIC Test Account;;;;;;;;;;; + +Data operazione;Data valuta;Tipo operazione;Ticker;Isin;Protocollo;Descrizione;Quantità;Importo euro;Importo Divisa;Divisa;Riferimento ordine +01-01-2026;01-01-2026;Conferimento con bonifico;;;D001;Synthetic deposit;0;1000;0;EUR; +02-01-2026;05-01-2026;Acquisto;SYN;XX0000000002;B001;Synthetic purchase;10;-100;0;EUR;O001 +02-01-2026;05-01-2026;Commissioni;SYN;XX0000000002;F001;Synthetic commission;0;-2;0;EUR;O001 +03-01-2026;03-01-2026;Incasso dividendi esteri;SYN;XX0000000002;I001;Synthetic dividend;0;10;0;EUR;0 +03-01-2026;03-01-2026;Ritenuta dividendi esteri;SYN;XX0000000002;T001;Synthetic withholding;0;-2,60;0;EUR;0 +04-01-2026;04-01-2026;Tobin tax italia;;;T002;Synthetic tax;0;-0,20;0;EUR;0 +05-01-2026;05-01-2026;Bollo portafoglio titoli*;;;E001;Synthetic stamp duty;0;-1;0;EUR;0 +06-01-2026;08-01-2026;Vendita;SYN;XX0000000002;S001;Synthetic sale;2;30;0;EUR;O002 +06-01-2026;08-01-2026;Commissioni;SYN;XX0000000002;F002;Synthetic commission;0;-1;0;EUR;O002 +06-01-2026;08-01-2026;Rit. etf;SYN;XX0000000002;T003;Synthetic ETF tax;0;-2;0;EUR;O002 diff --git a/apps/api/src/services/import/broker/broker-adapter.ts b/apps/api/src/services/import/broker/broker-adapter.ts new file mode 100644 index 0000000000..8ee069e478 --- /dev/null +++ b/apps/api/src/services/import/broker/broker-adapter.ts @@ -0,0 +1,15 @@ +import { + BrokerSourceRow, + BrokerFormat +} from '@ghostfolio/common/interfaces/broker-import.interface'; + +export interface BrokerAdapter { + readonly format: BrokerFormat; + incomeGroup?(row: BrokerSourceRow): string | undefined; + recognizes(csv: string): boolean; + parse(csv: string): { + sourceAccount: string; + rows: BrokerSourceRow[]; + ordering?: 'ASCENDING' | 'DESCENDING' | 'UNSPECIFIED'; + }; +} diff --git a/apps/api/src/services/import/broker/broker-import.dto.ts b/apps/api/src/services/import/broker/broker-import.dto.ts new file mode 100644 index 0000000000..f745c4c867 --- /dev/null +++ b/apps/api/src/services/import/broker/broker-import.dto.ts @@ -0,0 +1,29 @@ +import { BrokerImportInput } from '@ghostfolio/common/interfaces/broker-import.interface'; + +import { + IsArray, + IsBoolean, + IsIn, + IsObject, + IsOptional, + IsString, + MaxLength, + ArrayMaxSize +} from 'class-validator'; + +export class BrokerImportDto implements BrokerImportInput { + @IsIn(['DIRECTA']) format: 'DIRECTA'; + @IsString() @MaxLength(128) accountId: string; + @IsString() @MaxLength(2000000) csv: string; + @IsObject() @IsOptional() symbols?: Record; + @IsObject() @IsOptional() links?: Record; + @IsArray() + @IsString({ each: true }) + @MaxLength(128, { each: true }) + @ArrayMaxSize(5000) + @IsOptional() + excluded?: string[]; + @IsBoolean() useOperationDate: boolean; + @IsBoolean() @IsOptional() confirmPartial?: boolean; + @IsString() @MaxLength(64) @IsOptional() digest?: string; +} diff --git a/apps/api/src/services/import/broker/broker-import.integration.spec.ts b/apps/api/src/services/import/broker/broker-import.integration.spec.ts new file mode 100644 index 0000000000..5888ad9200 --- /dev/null +++ b/apps/api/src/services/import/broker/broker-import.integration.spec.ts @@ -0,0 +1,387 @@ +import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; +import { BrokerImportInput } from '@ghostfolio/common/interfaces/broker-import.interface'; + +import { ConfigService } from '@nestjs/config'; +import { EventEmitter2 } from '@nestjs/event-emitter'; +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { BrokerImportService } from './broker-import.service'; + +jest.mock('@ghostfolio/api/services/fetch/fetch.service', () => ({ + FetchService: class FetchService {} +})); + +const source = readFileSync( + join(__dirname, '__fixtures__/directa.csv'), + 'utf8' +); +const url = process.env.BROKER_TEST_DATABASE_URL; +const describeDb = url ? describe : describe.skip; +describeDb('Broker import on upstream PostgreSQL', () => { + let prisma: PrismaService, + service: BrokerImportService, + userId: string, + accountId: string, + symbol: string, + profileId: string; + let quoteCurrency = 'EUR'; + const users: string[] = [], + profiles: string[] = []; + const emitter = new EventEmitter2(), + providers = { validateActivities: jest.fn(async () => ({})) }; + const base = ( + changes: Partial = {} + ): BrokerImportInput => ({ + format: 'DIRECTA', + accountId, + csv: source, + symbols: { XX0000000002: symbol }, + useOperationDate: true, + ...changes + }); + const user = () => ({ id: userId, subscription: { type: 'Basic' } }) as never; + beforeAll(async () => { + const parsed = new URL(url); + if ( + parsed.hostname !== '127.0.0.1' || + !parsed.pathname.startsWith('/broker_test_') + ) + throw Error('Disposable broker_test_ DB required'); + prisma = new PrismaService( + new ConfigService({ DATABASE_URL: url, LOG_LEVELS: '[]' }) + ); + await prisma.$connect(); + service = new BrokerImportService( + prisma, + { + resolve: async (rows) => + rows.length + ? [ + { + isin: 'XX0000000002', + name: 'Synthetic equity', + status: 'AUTOMATIC', + reason: 'UNIQUE', + affectedOperations: rows.length, + selected: 'YAHOO:' + symbol, + candidates: [ + { + key: 'YAHOO:' + symbol, + id: profileId, + isin: 'XX0000000002', + name: 'Synthetic equity', + symbol, + dataSource: 'YAHOO', + currency: quoteCurrency, + exchange: 'Synthetic exchange', + sources: ['Synthetic proof'] + } + ] + } + ] + : [] + } as never, + providers as never, + emitter + ); + }); + beforeEach(async () => { + quoteCurrency = 'EUR'; + providers.validateActivities.mockResolvedValue({}); + userId = randomUUID(); + users.push(userId); + symbol = 'SYN-' + randomUUID(); + await prisma.user.create({ data: { id: userId } }); + const account = await prisma.account.create({ + data: { + userId, + currency: 'EUR', + name: 'Synthetic broker account', + balances: { create: { date: new Date('2025-01-01'), value: 123 } } + } + }); + accountId = account.id; + const profile = await prisma.symbolProfile.create({ + data: { + symbol, + isin: 'XX0000000002', + dataSource: 'YAHOO', + name: 'Synthetic equity', + currency: 'EUR' + } + }); + profileId = profile.id; + profiles.push(profileId); + }); + afterAll(async () => { + await prisma.user.deleteMany({ where: { id: { in: users } } }); + await prisma.symbolProfile.deleteMany({ where: { id: { in: profiles } } }); + await prisma.$disconnect(); + }); + const counts = () => + Promise.all([ + prisma.order.count({ where: { userId } }), + prisma.brokerImportRecord.count({ where: { userId } }), + prisma.accountBalance.count({ where: { userId } }), + prisma.symbolProfile.count() + ]); + const run = (input: BrokerImportInput, preview = true) => + service.run(input, user(), preview, 500); + async function accepted() { + const first = await run(base()); + return base({ + excluded: first.operations + .filter((op) => op.status === 'UNSUPPORTED') + .map((op) => op.id), + confirmPartial: true + }); + } + async function commit(input: BrokerImportInput) { + const plan = await run(input); + expect(plan.errors).toEqual([]); + await run({ ...input, digest: plan.digest }, false); + return plan; + } + it('marks unsupported tax and cash groups without writes or hiding gross/net amounts', async () => { + const before = await counts(), + balance = await prisma.accountBalance.findMany({ where: { userId } }); + const plan = await run(base()); + expect(await counts()).toEqual(before); + expect(plan.rowsRead).toBe(10); + expect(plan.operations.find((op) => op.id === 'T002').tax).toBe('0.2'); + expect(plan.errors).toContain('TAX_UNSUPPORTED'); + expect(plan.operations.find((op) => op.kind === 'DIVIDEND')).toMatchObject({ + status: 'UNSUPPORTED', + gross: '10', + tax: '2.6', + net: '7.4' + }); + expect(plan.operations.find((op) => op.kind === 'SELL').status).toBe( + 'UNSUPPORTED' + ); + expect(plan.summary.importable).toBe(1); + expect(await prisma.accountBalance.findMany({ where: { userId } })).toEqual( + balance + ); + }); + it('requires explicit partial confirmation and excludes the whole group including tax and commissions', async () => { + const input = await accepted(), + notConfirmed = await run({ ...input, confirmPartial: false }); + expect(notConfirmed.errors).toContain('PARTIAL_REQUIRED'); + await expect( + run( + { ...input, confirmPartial: false, digest: notConfirmed.digest }, + false + ) + ).rejects.toThrow(); + const balance = await prisma.accountBalance.findMany({ where: { userId } }); + const plan = await commit(input); + expect(plan.reconciliation[0].unresolved).toBe('0'); + expect( + await prisma.order.findMany({ + where: { userId }, + select: { type: true, fee: true, quantity: true, unitPrice: true } + }) + ).toEqual([{ type: 'BUY', fee: 2, quantity: 10, unitPrice: 10 }]); + expect(await prisma.brokerImportRecord.count({ where: { userId } })).toBe( + 2 + ); + expect(await prisma.accountBalance.findMany({ where: { userId } })).toEqual( + balance + ); + }); + it('preserves source EUR amounts for a verified USD listing using upstream activity currency', async () => { + quoteCurrency = 'USD'; + await prisma.symbolProfile.update({ + where: { id: profileId }, + data: { currency: 'USD' } + }); + const input = await accepted(); + await commit(input); + const order = await prisma.order.findFirst({ + where: { userId }, + include: { SymbolProfile: true } + }); + expect(order).toMatchObject({ + currency: 'EUR', + quantity: 10, + unitPrice: 10, + fee: 2, + SymbolProfile: { currency: 'USD' } + }); + expect((await run(input)).duplicates).toBe(2); + await prisma.symbolProfile.update({ + where: { id: profileId }, + data: { currency: 'GBP' } + }); + expect((await run(input)).errors).toContain('CHANGED_IMPORT'); + }); + it('deduplicates repeated files and overlapping periods while retaining distinct source protocols', async () => { + const input = await accepted(); + await commit(input); + const before = await counts(); + const again = await run(input); + expect(again.duplicates).toBe(2); + expect(again.summary.importable).toBe(0); + await run({ ...input, digest: again.digest }, false); + expect(await counts()).toEqual(before); + const subset = source + .split('\n') + .filter((line) => !line.includes(';F001;')) + .join('\n'); + const preview = await run({ ...input, csv: subset }); + expect(preview.errors).toEqual([]); + expect(preview.duplicates).toBe(1); + const trade = source + .split('\n') + .find((line) => line.includes(';B001;')) + .replace(';B001;', ';B002;') + .replace(';O001', ';O009'); + await commit({ ...input, csv: source + '\n' + trade }); + expect(await prisma.order.count({ where: { userId } })).toBe(2); + }); + it('ignores an identical repeated source reference without charging its commission twice', async () => { + const input = await accepted(), + fee = source.split('\n').find((line) => line.includes(';F001;')); + const plan = await commit({ ...input, csv: source + '\n' + fee }); + expect(plan.duplicates).toBe(1); + expect((await prisma.order.findFirst({ where: { userId } })).fee).toBe(2); + }); + it('serializes competing confirmations and prevents duplicate orders', async () => { + const input = await accepted(), + plan = await run(input), + outcomes = await Promise.allSettled([ + run({ ...input, digest: plan.digest }, false), + run({ ...input, digest: plan.digest }, false) + ]); + expect(outcomes.filter((item) => item.status === 'fulfilled')).toHaveLength( + 1 + ); + expect(await prisma.order.count({ where: { userId } })).toBe(1); + expect(await prisma.brokerImportRecord.count({ where: { userId } })).toBe( + 2 + ); + }); + it('blocks changed source/output and deleted activity tombstones even when exclusion is requested', async () => { + const input = await accepted(); + await commit(input); + expect( + (await run({ ...input, csv: source.replace(';-100;', ';-101;') })).errors + ).toContain('CHANGED_IMPORT'); + const order = await prisma.order.findFirst({ where: { userId } }); + await prisma.order.update({ where: { id: order.id }, data: { fee: 3 } }); + expect((await run(input)).errors).toContain('CHANGED_IMPORT'); + await prisma.order.delete({ where: { id: order.id } }); + expect( + await prisma.brokerImportRecord.count({ + where: { userId, orderId: null } + }) + ).toBe(2); + expect( + (await run({ ...input, excluded: [...input.excluded, 'B001'] })).errors + ).toContain('CHANGED_IMPORT'); + }); + it('rolls back order and provenance if a later audit write fails', async () => { + const input = await accepted(), + plan = await run(input), + before = await counts(), + original = prisma.$transaction.bind(prisma); + let writes = 0; + const spy = jest.spyOn(prisma, '$transaction').mockImplementationOnce((( + callback, + options + ) => + original( + async (tx) => + callback( + new Proxy(tx, { + get(target, property) { + if (property === 'brokerImportRecord') + return new Proxy(target.brokerImportRecord, { + get(delegate, method) { + if (method === 'create') + return async (args) => { + if (++writes === 2) + throw Error('Synthetic persistence failure'); + return delegate.create(args); + }; + return Reflect.get(delegate, method); + } + }); + return Reflect.get(target, property); + } + }) + ), + options + )) as never); + await expect(run({ ...input, digest: plan.digest }, false)).rejects.toThrow( + 'Synthetic persistence failure' + ); + spy.mockRestore(); + expect(await counts()).toEqual(before); + }); + it('keeps other users private profiles out of preview state and fingerprints', async () => { + const foreignUser = randomUUID(); + users.push(foreignUser); + await prisma.user.create({ data: { id: foreignUser } }); + const foreign = await prisma.symbolProfile.create({ + data: { + symbol: randomUUID(), + isin: 'XX0000000002', + currency: 'EUR', + dataSource: 'MANUAL', + name: 'Synthetic private profile', + userId: foreignUser + } + }); + const input = await accepted(), + plan = await run(input); + await prisma.symbolProfile.update({ + where: { id: foreign.id }, + data: { name: 'Updated private profile' } + }); + await run({ ...input, digest: plan.digest }, false); + expect(await prisma.order.count({ where: { userId } })).toBe(1); + }); + it('rejects stale previews and unauthorized accounts and applies configured activity limits', async () => { + const input = await accepted(), + plan = await run(input); + await prisma.account.update({ + where: { id_userId: { id: accountId, userId } }, + data: { name: 'Changed' } + }); + await expect(run({ ...input, digest: plan.digest }, false)).rejects.toThrow( + 'Preview again' + ); + await expect( + service.run(input, { id: randomUUID() } as never, true, 500) + ).rejects.toThrow(); + expect((await service.run(input, user(), true, 0)).errors).toContain( + 'LIMIT' + ); + }); + it('keeps a late cost for an imported activity blocked without editing existing data', async () => { + const input = await accepted(), + without = { + ...input, + csv: source + .split('\n') + .filter((line) => !line.includes(';F001;')) + .join('\n') + }; + await commit(without); + const before = await counts(); + expect((await run(input)).errors).toContain('CHANGED_IMPORT'); + expect(await counts()).toEqual(before); + }); + it('keeps provider validation failures blocked', async () => { + const input = await accepted(); + providers.validateActivities.mockRejectedValueOnce( + Error('Provider unavailable') + ); + expect((await run(input)).errors).toContain('PROVIDER_UNAVAILABLE'); + expect(await prisma.order.count({ where: { userId } })).toBe(0); + }); +}); diff --git a/apps/api/src/services/import/broker/broker-import.service.ts b/apps/api/src/services/import/broker/broker-import.service.ts new file mode 100644 index 0000000000..e8101972b3 --- /dev/null +++ b/apps/api/src/services/import/broker/broker-import.service.ts @@ -0,0 +1,784 @@ +import { AssetProfileChangedEvent } from '@ghostfolio/api/events/asset-profile-changed.event'; +import { PortfolioChangedEvent } from '@ghostfolio/api/events/portfolio-changed.event'; +import { getTagsWithDraftTag } from '@ghostfolio/api/helper/activity.helper'; +import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; +import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; +import { DataGatheringService } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.service'; +import { + TAG_ID_DRAFT, + DATA_GATHERING_QUEUE_PRIORITY_HIGH +} from '@ghostfolio/common/config'; +import { + BrokerSourceRow, + BrokerImportInput, + BrokerImportPreview, + BrokerPlannedOperation, + BrokerDiagnosticCode, + BrokerListingCandidate +} from '@ghostfolio/common/interfaces/broker-import.interface'; +import { UserWithSettings } from '@ghostfolio/common/types'; + +import { + BadRequestException, + ConflictException, + Injectable, + NotFoundException, + Optional +} from '@nestjs/common'; +import { EventEmitter2 } from '@nestjs/event-emitter'; +import { Prisma } from '@prisma/client'; +import { Big } from 'big.js'; +import { createHash } from 'node:crypto'; + +import { BrokerAdapter } from './broker-adapter'; +import { BrokerInstrumentResolver } from './broker-instrument-resolver.service'; +import { automaticallyMatchesCost, compatibleCost } from './cost-association'; +import { DirectaAdapter } from './directa.adapter'; + +export const brokerHash = (value: unknown) => + createHash('sha256').update(JSON.stringify(value)).digest('hex'); +export const brokerOutputFingerprint = (order: { + date: Date; + type: string; + quantity: number; + unitPrice: number; + fee: number; + currency: string | null; + accountId: string | null; + symbolProfileId: string; + SymbolProfile: { + symbol: string; + dataSource: string; + currency: string; + isin: string | null; + }; +}) => + brokerHash({ + date: order.date.toISOString(), + type: order.type, + quantity: order.quantity, + unitPrice: order.unitPrice, + fee: order.fee, + currency: order.currency ?? order.SymbolProfile.currency, + accountId: order.accountId, + symbolProfileId: order.symbolProfileId, + asset: { + symbol: order.SymbolProfile.symbol, + dataSource: order.SymbolProfile.dataSource, + isin: order.SymbolProfile.isin, + currency: order.SymbolProfile.currency + } + }); +interface Group { + primary: BrokerSourceRow; + rows: BrokerSourceRow[]; + fee: Big; + tax: Big; + net: Big; + issues: Set; + profile?: BrokerListingCandidate; +} +@Injectable() +export class BrokerImportService { + private readonly adapters: BrokerAdapter[] = [new DirectaAdapter()]; + constructor( + private readonly prisma: PrismaService, + private readonly resolver: BrokerInstrumentResolver, + private readonly providers: DataProviderService, + private readonly emitter: EventEmitter2, + @Optional() private readonly gathering?: DataGatheringService + ) {} + async run( + input: BrokerImportInput, + user: UserWithSettings, + preview: boolean, + maxActivitiesToImport: number + ): Promise { + const userId = user.id; + const adapter = this.adapters.find((item) => item.format === input.format); + if (!adapter?.recognizes(input.csv)) + throw new BadRequestException('Invalid broker format.'); + for (const map of [input.symbols, input.links]) + if ( + map && + (typeof map !== 'object' || + Array.isArray(map) || + Object.keys(map).length > 5000 || + Object.entries(map).some( + ([key, value]) => + key.length > 128 || + typeof value !== 'string' || + value.length > 128 + )) + ) + throw new BadRequestException('Invalid broker choices.'); + if ( + input.excluded && + (!Array.isArray(input.excluded) || + input.excluded.length > 5000 || + input.excluded.some((id) => typeof id !== 'string' || id.length > 128)) + ) + throw new BadRequestException('Invalid exclusions.'); + const scope = { accountId: input.accountId, userId }; + if ( + !(await this.prisma.account.findUnique({ + where: { id_userId: { id: input.accountId, userId } } + })) + ) + throw new NotFoundException(); + const parsed = adapter.parse(input.csv), + excluded = new Set(input.excluded ?? []), + unique: BrokerSourceRow[] = [], + seen = new Map(); + const key = (row: BrokerSourceRow) => + brokerHash([input.format, parsed.sourceAccount, row.protocol]); + const fingerprint = (row: BrokerSourceRow) => + brokerHash( + Object.fromEntries( + Object.entries(row).filter(([name]) => name !== 'line') + ) + ); + let conflictingSource = false; + for (const row of parsed.rows) { + const old = seen.get(key(row)); + if (old && old !== fingerprint(row)) conflictingSource = true; + if (!old) unique.push(row); + seen.set(key(row), fingerprint(row)); + } + if ( + Object.keys(input.symbols ?? {}).some( + (isin) => !unique.some((row) => row.isin === isin) + ) + ) + throw new BadRequestException('Unknown instrument choice.'); + const groups: Group[] = unique + .filter((row) => row.attachment === 'NONE') + .map((primary) => ({ + primary, + rows: [primary], + fee: new Big(0), + tax: new Big(0), + net: new Big(primary.amount), + issues: new Set( + ['BUY', 'SELL', 'DIVIDEND'].includes(primary.kind) + ? [] + : ['UNSUPPORTED'] + ) + })); + const associations: BrokerImportPreview['costAssociations'] = []; + for (const row of unique.filter((row) => row.attachment !== 'NONE')) { + const candidates = groups.filter((group) => + compatibleCost(row, group.primary, adapter) + ); + const explicit = input.links?.[row.protocol]; + const matches = explicit + ? candidates.filter((group) => group.primary.protocol === explicit) + : candidates.filter((group) => + automaticallyMatchesCost(row, group.primary, adapter) + ); + const association = { + sourceId: row.protocol, + line: row.line, + kind: row.kind as 'FEE' | 'TAX', + status: + matches.length === 1 + ? explicit + ? ('CONFIRMED' as const) + : ('AUTOMATIC' as const) + : candidates.length + ? ('CONFIRMATION_REQUIRED' as const) + : ('UNRESOLVED' as const), + targetId: + matches.length === 1 ? matches[0].primary.protocol : undefined, + candidates: candidates.map((group) => ({ + id: group.primary.protocol, + line: group.primary.line, + isin: group.primary.isin, + kind: group.primary.kind, + date: group.primary.operationDate, + gross: group.primary.amount + })) + }; + associations.push(association); + if (matches.length === 1) { + const group = matches[0]; + group.rows.push(row); + group[row.kind === 'FEE' ? 'fee' : 'tax'] = group[ + row.kind === 'FEE' ? 'fee' : 'tax' + ].minus(row.amount); + group.net = group.net.plus(row.amount); + if (row.kind === 'TAX') group.issues.add('TAX_UNSUPPORTED'); + } else { + // Never allow a plausible gross income/trade to escape an unassociated cost. + const related = groups.filter( + (group) => + ['BUY', 'SELL', 'DIVIDEND'].includes(group.primary.kind) && + group.primary.operationDate === row.operationDate && + (!row.isin || group.primary.isin === row.isin) && + (row.attachment === 'DIVIDEND' + ? group.primary.kind === 'DIVIDEND' + : row.attachment === 'SALE' + ? group.primary.kind === 'SELL' + : ['BUY', 'SELL'].includes(group.primary.kind)) + ); + for (const group of related) + group.issues.add( + row.kind === 'TAX' ? 'TAX_UNSUPPORTED' : 'COST_ASSOCIATION' + ); + groups.push({ + primary: row, + rows: [row], + fee: new Big(0), + tax: new Big(0), + net: new Big(row.amount), + issues: new Set([ + row.kind === 'TAX' ? 'TAX_UNSUPPORTED' : 'COST_ASSOCIATION' + ]) + }); + } + } + if ( + [...excluded].some( + (id) => !groups.some((group) => group.primary.protocol === id) + ) || + Object.keys(input.links ?? {}).some( + (id) => + !unique.some( + (row) => row.protocol === id && row.attachment !== 'NONE' + ) + ) + ) + throw new BadRequestException('Unknown operation choice.'); + for (const group of groups) { + if ( + !Number.isFinite(group.fee.toNumber()) || + !new Big(group.fee.toNumber()).eq(group.fee) + ) + group.issues.add('INVALID_SOURCE'); + const row = group.primary, + amount = new Big(row.amount), + quantity = new Big(row.quantity); + if ( + row.currency !== 'EUR' || + !new Big(row.originalAmount).eq(0) || + row.operationDate < '1970-01-02' || + (['BUY', 'SELL'].includes(row.kind) && + (!quantity.gt(0) || + (row.kind === 'BUY' ? !amount.lt(0) : !amount.gt(0)))) || + (row.kind === 'DIVIDEND' && !amount.gt(0)) || + group.fee.lt(0) + ) + group.issues.add('INVALID_SOURCE'); + if (['BUY', 'SELL', 'DIVIDEND'].includes(row.kind)) { + const q = row.kind === 'DIVIDEND' ? 1 : quantity.toNumber(); + if (!Number.isFinite(q) || q <= 0) { + group.issues.add('INVALID_SOURCE'); + continue; + } + const price = amount.abs().div(q).toNumber(); + if ( + !Number.isFinite(q) || + !Number.isFinite(price) || + !new Big(price).mul(q).round(2).eq(amount.abs()) || + (!new Big(q).eq(quantity) && row.kind !== 'DIVIDEND') + ) + group.issues.add('INVALID_SOURCE'); + } + } + const previous = await this.prisma.brokerImportRecord.findMany({ + where: scope + }); + const needingResolution = groups + .filter( + (group) => + !group.issues.size && + !excluded.has(group.primary.protocol) && + !previous.some((record) => record.key === key(group.primary)) + ) + .map((group) => group.primary); + const instruments = await this.resolver.resolve( + needingResolution, + userId, + input.symbols ?? {} + ); + for (const group of groups.filter( + (group) => !group.issues.size && !excluded.has(group.primary.protocol) + )) { + const item = instruments.find((item) => item.isin === group.primary.isin); + const candidate = item?.candidates.find( + (candidate) => candidate.key === item.selected + ); + if (candidate) { + group.profile = candidate; + } else if (!previous.some((record) => record.key === key(group.primary))) + group.issues.add( + item?.status === 'CONFIRMATION_REQUIRED' + ? 'INSTRUMENT_CHOICE' + : item?.reason === 'PROVIDER_UNAVAILABLE' + ? 'PROVIDER_UNAVAILABLE' + : 'INSTRUMENT_UNRESOLVED' + ); + } + const toValidate = groups.filter( + (group) => + !group.issues.size && + !!group.profile && + !excluded.has(group.primary.protocol) + ); + let providerFailure = false; + try { + if (toValidate.length && toValidate.length <= maxActivitiesToImport) + await this.providers.validateActivities({ + activitiesDto: toValidate.map((group) => ({ + accountId: input.accountId, + currency: group.primary.currency, + dataSource: group.profile.dataSource, + symbol: group.profile.symbol, + date: group.primary.operationDate + 'T00:00:00.000Z', + type: group.primary.kind as 'BUY' | 'SELL' | 'DIVIDEND', + quantity: + group.primary.kind === 'DIVIDEND' + ? 1 + : Number(group.primary.quantity), + unitPrice: new Big(group.primary.amount) + .abs() + .div( + group.primary.kind === 'DIVIDEND' ? 1 : group.primary.quantity + ) + .toNumber(), + fee: group.fee.toNumber() + })), + maxActivitiesToImport, + subscription: user.subscription, + userId + }); + } catch { + providerFailure = true; + } + groups.sort( + (a, b) => + a.primary.operationDate.localeCompare(b.primary.operationDate) || + a.primary.line - b.primary.line + ); + const result = await this.prisma + .$transaction( + async (tx) => { + await tx.$queryRaw`SELECT "id" FROM "Account" WHERE "id"=${input.accountId} AND "userId"=${userId} FOR UPDATE`; + const account = await tx.account.findUnique({ + where: { id_userId: { id: input.accountId, userId } } + }); + if (!account) throw new NotFoundException(); + const records = await tx.brokerImportRecord.findMany({ + where: scope, + orderBy: { key: 'asc' } + }), + orders = await tx.order.findMany({ + where: scope, + include: { SymbolProfile: true }, + orderBy: { id: 'asc' } + }); + const profiles = await tx.symbolProfile.findMany({ + where: { + AND: [ + { OR: [{ userId: null }, { userId }] }, + { + OR: [ + { + isin: { + in: unique.map((row) => row.isin).filter(Boolean) + } + }, + { + symbol: { + in: toValidate.map((group) => group.profile.symbol) + } + } + ] + } + ] + }, + orderBy: { id: 'asc' } + }); + const statuses = new Map(); + const errors = new Set(); + if (conflictingSource) errors.add('CHANGED_IMPORT'); + if (!input.useOperationDate) errors.add('DATE_POLICY'); + if (providerFailure) errors.add('PROVIDER_UNAVAILABLE'); + for (const group of groups) { + const matching = group.rows.map((row) => + records.find((record) => record.key === key(row)) + ); + const hasPrior = matching.some(Boolean); + const alias = group.rows.some( + (row) => + row.orderIdentity && + records.some( + (record) => + record.sourceIdentity === + brokerHash([input.format, row.orderIdentity]) && + record.key !== key(row) && + (record.details as { identitySource?: string }) + .identitySource !== row.identitySource + ) + ); + if (alias) group.issues.add('CHANGED_IMPORT'); + if (hasPrior) { + const intact = matching.every((record, i) => { + const order = orders.find( + (order) => order.id === record?.orderId + ); + return ( + record?.fingerprint === fingerprint(group.rows[i]) && + order && + record.outputFingerprint === brokerOutputFingerprint(order) + ); + }); + if (!intact) group.issues.add('CHANGED_IMPORT'); + else statuses.set(group, 'DUPLICATE'); + } + if (group.profile) { + const candidate = group.profile, + current = profiles.find( + (profile) => + profile.dataSource === candidate.dataSource && + profile.symbol === candidate.symbol + ); + if ( + (current && + ((current.userId && current.userId !== userId) || + (current.isin && current.isin !== candidate.isin) || + current.currency !== candidate.currency)) || + (candidate.id && current?.id !== candidate.id) + ) + group.issues.add('PROFILE_CONFLICT'); + const quantity = + group.primary.kind === 'DIVIDEND' + ? 1 + : Number(group.primary.quantity); + if ( + orders.some( + (order) => + order.SymbolProfile.dataSource === candidate.dataSource && + order.SymbolProfile.symbol === candidate.symbol && + order.type === group.primary.kind && + order.date.toISOString().slice(0, 10) === + group.primary.operationDate && + order.quantity === quantity && + new Big(order.unitPrice) + .mul(quantity) + .minus(new Big(group.primary.amount).abs()) + .abs() + .lt('0.005') && + !records.some((record) => record.orderId === order.id) + ) + ) + group.issues.add('EXISTING_RECORD'); + } + if (group.issues.has('CHANGED_IMPORT')) { + statuses.set(group, 'BLOCKED'); + errors.add('CHANGED_IMPORT'); + continue; + } + if (statuses.has(group)) continue; + if (excluded.has(group.primary.protocol)) + statuses.set(group, 'EXCLUDED'); + else if ( + group.issues.has('UNSUPPORTED') || + group.issues.has('TAX_UNSUPPORTED') + ) { + statuses.set(group, 'UNSUPPORTED'); + errors.add( + group.issues.has('TAX_UNSUPPORTED') + ? 'TAX_UNSUPPORTED' + : 'UNSUPPORTED' + ); + } else if (group.issues.size) { + statuses.set(group, 'BLOCKED'); + for (const code of group.issues) errors.add(code); + } else statuses.set(group, 'IMPORTABLE'); + } + const importable = groups.filter( + (group) => statuses.get(group) === 'IMPORTABLE' + ); + if (importable.length > maxActivitiesToImport) errors.add('LIMIT'); + if ( + groups.some((group) => statuses.get(group) === 'EXCLUDED') && + !input.confirmPartial + ) + errors.add('PARTIAL_REQUIRED'); + const displaySeen = new Set(); + const plan: BrokerImportPreview = { + format: input.format, + digest: '', + rowsRead: parsed.rows.length, + duplicates: + parsed.rows.length - + unique.length + + unique.filter((row) => { + const group = groups.find((group) => + group.rows.some((source) => source.protocol === row.protocol) + ); + return statuses.get(group) === 'DUPLICATE'; + }).length, + instruments, + costAssociations: associations, + operations: groups.map((group) => ({ + id: group.primary.protocol, + lines: group.rows.map((row) => row.line), + date: group.primary.operationDate, + valueDates: group.rows.map((row) => row.valueDate), + kind: group.primary.kind, + isin: group.primary.isin, + symbol: group.profile?.symbol, + gross: group.primary.amount, + fee: group.fee.toFixed(), + tax: (group.primary.kind === 'TAX' + ? group.tax.plus(new Big(group.primary.amount).abs()) + : group.tax + ).toFixed(), + net: group.net.toFixed(), + status: statuses.get(group), + diagnostics: [...group.issues] + })), + rows: parsed.rows.map((row) => { + const identity = key(row), + repeat = displaySeen.has(identity); + displaySeen.add(identity); + return { + ...row, + status: repeat + ? 'DUPLICATE' + : statuses.get( + groups.find((group) => + group.rows.some( + (source) => source.protocol === row.protocol + ) + ) + ) + }; + }), + errors: [...errors], + reconciliation: [], + summary: { + recognized: unique.filter((row) => row.kind !== 'UNSUPPORTED') + .length, + importable: importable.length, + blocked: groups.filter( + (group) => statuses.get(group) === 'BLOCKED' + ).length, + unsupported: groups.filter( + (group) => statuses.get(group) === 'UNSUPPORTED' + ).length, + excluded: groups.filter( + (group) => statuses.get(group) === 'EXCLUDED' + ).length, + automatic: instruments.filter( + (item) => item.status === 'AUTOMATIC' + ).length, + confirmed: instruments.filter( + (item) => item.status === 'CONFIRMED' + ).length, + needsConfirmation: instruments.filter( + (item) => item.status === 'CONFIRMATION_REQUIRED' + ).length, + unresolvable: instruments.filter( + (item) => item.status === 'UNRESOLVED' + ).length + } + }; + for (const currency of [ + ...new Set(unique.map((row) => row.currency)) + ]) { + const sum = (status?: BrokerPlannedOperation['status']) => + unique + .filter( + (row) => + row.currency === currency && + (!status || + statuses.get( + groups.find((group) => + group.rows.some( + (source) => source.protocol === row.protocol + ) + ) + ) === status) + ) + .reduce((sum, row) => sum.plus(row.amount), new Big(0)); + const source = sum(), + imported = sum('IMPORTABLE'), + duplicates = sum('DUPLICATE'), + omitted = sum('EXCLUDED'); + plan.reconciliation.push({ + currency, + source: source.toFixed(), + imported: imported.toFixed(), + duplicates: duplicates.toFixed(), + excluded: omitted.toFixed(), + unresolved: source + .minus(imported) + .minus(duplicates) + .minus(omitted) + .toFixed() + }); + } + plan.digest = brokerHash({ + input: { ...input, digest: undefined }, + account, + orders, + profiles, + records, + instruments, + operations: plan.operations, + maxActivitiesToImport + }); + if (preview) return plan; + if (input.digest !== plan.digest) + throw new ConflictException('Preview again.'); + if (errors.size) + throw new BadRequestException('Unresolved broker preview.'); + const draftTag = await tx.tag.findUnique({ + where: { id: TAG_ID_DRAFT } + }); + for (const group of importable) { + const profile = group.profile; + const stored = await tx.symbolProfile.upsert({ + where: { + dataSource_symbol: { + dataSource: profile.dataSource, + symbol: profile.symbol + } + }, + create: { + symbol: profile.symbol, + dataSource: profile.dataSource, + isin: profile.isin, + name: profile.name, + currency: profile.currency, + assetClass: profile.assetClass, + assetSubClass: profile.assetSubClass + }, + update: {} + }); + if ( + (stored.userId && stored.userId !== userId) || + (stored.isin && stored.isin !== profile.isin) || + stored.currency !== profile.currency + ) + throw new ConflictException('Instrument changed.'); + if (!stored.isin) + await tx.symbolProfile.update({ + where: { id: stored.id }, + data: { isin: profile.isin } + }); + const date = new Date( + group.primary.operationDate + 'T00:00:00.000Z' + ), + type = group.primary.kind as 'BUY' | 'SELL' | 'DIVIDEND'; + const tags = getTagsWithDraftTag({ + date, + type, + tags: [], + draftTag: { id: TAG_ID_DRAFT } + }); + if (tags.length && !draftTag) + throw new ConflictException('Draft tag unavailable.'); + const quantity = + type === 'DIVIDEND' ? 1 : Number(group.primary.quantity); + const order = await tx.order.create({ + data: { + userId, + accountUserId: userId, + accountId: input.accountId, + symbolProfileId: stored.id, + currency: + group.primary.currency === stored.currency + ? null + : group.primary.currency, + date, + type, + quantity, + unitPrice: new Big(group.primary.amount) + .abs() + .div(quantity) + .toNumber(), + fee: group.fee.toNumber(), + comment: 'Broker CSV: ' + input.format, + tags: { connect: tags } + }, + include: { SymbolProfile: true } + }); + for (const row of group.rows) + await tx.brokerImportRecord.create({ + data: { + ...scope, + key: key(row), + fingerprint: fingerprint(row), + sourceIdentity: row.orderIdentity + ? brokerHash([input.format, row.orderIdentity]) + : null, + orderId: order.id, + outputFingerprint: brokerOutputFingerprint(order), + details: { + format: input.format, + operationDate: row.operationDate, + valueDate: row.valueDate, + kind: row.kind, + identitySource: row.identitySource + } + } + }); + } + return { ...plan, restored: true }; + }, + { + isolationLevel: Prisma.TransactionIsolationLevel.Serializable, + timeout: 30000 + } + ) + .catch((error) => { + if (['P2034', 'P2002'].includes(error?.code)) + throw new ConflictException('Preview again.'); + throw error; + }); + if (!preview && result.summary.importable) { + this.emitter.emit( + PortfolioChangedEvent.getName(), + new PortfolioChangedEvent({ userId }) + ); + for (const group of groups.filter( + (group) => group.profile && !excluded.has(group.primary.protocol) + )) + this.emitter.emit( + AssetProfileChangedEvent.getName(), + new AssetProfileChangedEvent({ + symbol: group.profile.symbol, + dataSource: group.profile.dataSource, + currency: group.profile.currency + }) + ); + if (this.gathering) + void this.gathering + .gatherSymbols({ + priority: DATA_GATHERING_QUEUE_PRIORITY_HIGH, + dataGatheringItems: [ + ...new Map( + groups + .filter( + (group) => + group.profile && !excluded.has(group.primary.protocol) + ) + .map((group) => [ + group.profile.key, + { + dataSource: group.profile.dataSource, + symbol: group.profile.symbol + } + ]) + ).values() + ] + }) + .catch(() => undefined); + } + return result; + } +} diff --git a/apps/api/src/services/import/broker/broker-instrument-resolver.service.spec.ts b/apps/api/src/services/import/broker/broker-instrument-resolver.service.spec.ts new file mode 100644 index 0000000000..ac57daa761 --- /dev/null +++ b/apps/api/src/services/import/broker/broker-instrument-resolver.service.spec.ts @@ -0,0 +1,247 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { + BrokerInstrumentResolver, + parseBorsaListing, + parseVerifiedEtfListings +} from './broker-instrument-resolver.service'; +import { DirectaAdapter } from './directa.adapter'; + +jest.mock('@ghostfolio/api/services/fetch/fetch.service', () => ({ + FetchService: class FetchService {} +})); + +const ISIN = 'XX0000000002'; +const rows = new DirectaAdapter() + .parse(readFileSync(join(__dirname, '__fixtures__/directa.csv'), 'utf8')) + .rows.filter((row) => row.kind === 'BUY'); +const page = (ticker = 'SYN', isin = ISIN) => + `
Isin Code${isin}
Alphanumeric Code${ticker}
Market/SegmentEuronext Milan
`; +function setup( + options: { + body?: string; + search?: string[]; + quotes?: Record; + stored?: unknown; + down?: boolean; + mapping?: unknown; + } = {} +) { + const search = jest.fn(async () => ({ + items: (options.search ?? []).map((symbol) => ({ + symbol, + dataSource: 'YAHOO' + })) + })); + const quote = jest.fn( + async ({ symbol }) => + options.quotes?.[symbol] ?? + (symbol === 'SYN.MI' + ? { + symbol, + currency: 'EUR', + exchange: 'MIL', + name: 'Synthetic ordinary shares' + } + : undefined) + ); + const fetch = jest.fn(async (url: string) => { + if (options.down) throw Error('Provider unavailable'); + if (url.includes('openfigi')) + return new Response(JSON.stringify(options.mapping ?? [{}]), { + status: 200 + }); + return new Response( + url.includes('borsaitaliana') ? (options.body ?? page()) : '', + { status: 200 } + ); + }); + const prisma = { + symbolProfile: { + findMany: jest.fn(async () => []), + findUnique: jest.fn(async () => options.stored ?? null) + } + }; + return { + resolver: new BrokerInstrumentResolver( + prisma as never, + { getDataProvider: () => ({ search, getListingQuote: quote }) } as never, + { fetch } as never + ), + search, + quote, + fetch, + prisma + }; +} +describe('Broker instrument identity and listing proof', () => { + it('requires labeled identity fields, rejecting echoed identifiers and other instruments', () => { + expect(parseBorsaListing(`

${ISIN}

`, ISIN)).toEqual([]); + expect(parseBorsaListing(page('SYN', 'XX0000000010'), ISIN)).toEqual([]); + expect(parseBorsaListing(page(), ISIN)[0].symbol).toBe('SYN.MI'); + expect( + parseVerifiedEtfListings( + ``, + ISIN + ) + ).toEqual([]); + }); + it('verifies a new ETF using canonical ISIN and published exchange, Reuters ticker and currency', async () => { + const fields = { + listing: 'XETRA', + ticker: 'SYN', + reuters: 'SYN.DE', + 'trade-currency': 'EUR' + }; + const html = `${Object.entries( + fields + ) + .map( + ([key, value]) => + `${value}` + ) + .join('')}`; + expect(parseVerifiedEtfListings(html, ISIN)).toEqual([ + { symbol: 'SYN.DE', exchange: 'GER', currency: 'EUR', source: 'justETF' } + ]); + expect( + parseVerifiedEtfListings(html.replace('SYN.DE', 'OTHER.DE'), ISIN) + ).toEqual([]); + }); + it('discovers a new equity without a catalog mapping and deduplicates repeated ISIN work', async () => { + const { resolver, search, quote } = setup(); + const result = await resolver.resolve([...rows, ...rows], 'user'); + expect(result).toHaveLength(1); + expect(result[0]).toMatchObject({ + status: 'AUTOMATIC', + selected: 'YAHOO:SYN.MI', + affectedOperations: 2 + }); + expect(result[0].candidates[0]).toMatchObject({ + isin: ISIN, + currency: 'EUR', + exchange: 'Borsa Italiana', + sources: ['Borsa Italiana'] + }); + await resolver.resolve(rows, 'user'); + expect(search).toHaveBeenCalledTimes(1); + expect(quote).toHaveBeenCalledTimes(1); + }); + it('keeps genuinely valid alternatives pending until explicitly confirmed', async () => { + const { resolver } = setup({ + search: ['SYN.DE'], + quotes: { + 'SYN.DE': { + symbol: 'SYN.DE', + currency: 'EUR', + exchange: 'GER', + name: 'Synthetic shares' + } + }, + mapping: [{ data: [{ ticker: 'SYN', figi: 'SYNTHETIC-FIGI' }] }] + }); + expect((await resolver.resolve(rows, 'user'))[0]).toMatchObject({ + status: 'CONFIRMATION_REQUIRED', + reason: 'MULTIPLE_LISTINGS' + }); + const selected = ( + await resolver.resolve(rows, 'user', { [ISIN]: 'YAHOO:SYN.DE' }) + )[0]; + expect(selected).toMatchObject({ + status: 'CONFIRMED', + selected: 'YAHOO:SYN.DE' + }); + expect(selected.candidates).toHaveLength(2); + }); + it('does not accept manual symbols without independent identity evidence', async () => { + const { resolver } = setup({ + body: '', + quotes: { + 'WRONG.MI': { + symbol: 'WRONG.MI', + currency: 'EUR', + exchange: 'MIL', + name: 'Wrong instrument' + } + } + }); + expect( + (await resolver.resolve(rows, 'user', { [ISIN]: 'WRONG.MI' }))[0] + ).toMatchObject({ + status: 'UNRESOLVED', + reason: 'NO_EVIDENCE', + candidates: [] + }); + }); + it('rejects quote exchange mismatches and catalog identity conflicts', async () => { + const mismatch = setup({ + quotes: { + 'SYN.MI': { + symbol: 'SYN.MI', + currency: 'EUR', + exchange: 'GER', + name: 'Wrong market' + } + } + }); + expect( + (await mismatch.resolver.resolve(rows, 'user'))[0].candidates + ).toEqual([]); + const conflict = setup({ + stored: { + id: 'saved', + isin: 'XX0000000010', + currency: 'EUR', + userId: null + } + }); + expect((await conflict.resolver.resolve(rows, 'user'))[0]).toMatchObject({ + status: 'UNRESOLVED', + reason: 'PROFILE_CONFLICT' + }); + }); + it('distinguishes unavailable providers from unsupported identity and retries failures', async () => { + const context = setup({ down: true }); + expect((await context.resolver.resolve(rows, 'user'))[0]).toMatchObject({ + status: 'UNRESOLVED', + reason: 'PROVIDER_UNAVAILABLE' + }); + const before = context.fetch.mock.calls.length; + await context.resolver.resolve(rows, 'user'); + expect(context.fetch.mock.calls.length).toBeGreaterThan(before); + const invalid = await setup().resolver.resolve( + [{ ...rows[0], isin: 'XX0000000000' }], + 'user' + ); + expect(invalid[0].reason).toBe('INVALID_ISIN'); + }); + it('uses generic ISIN, MIC and currency mapping for a non-Italian equity', async () => { + const { resolver, fetch } = setup({ + body: '', + search: ['SYN'], + quotes: { + SYN: { + symbol: 'SYN', + currency: 'USD', + exchange: 'NMS', + name: 'Synthetic US equity' + } + }, + mapping: [{ data: [{ ticker: 'SYN', figi: 'SYNTHETIC-FIGI' }] }] + }); + const result = await resolver.resolve(rows, 'user'); + expect(result[0]).toMatchObject({ status: 'CONFIRMATION_REQUIRED' }); + expect(result[0].candidates[0]).toMatchObject({ + symbol: 'SYN', + currency: 'USD', + exchange: 'Nasdaq', + sources: ['OpenFIGI'] + }); + expect( + fetch.mock.calls.some( + ([url]) => url === 'https://api.openfigi.com/v3/mapping' + ) + ).toBe(true); + }); +}); diff --git a/apps/api/src/services/import/broker/broker-instrument-resolver.service.ts b/apps/api/src/services/import/broker/broker-instrument-resolver.service.ts new file mode 100644 index 0000000000..e8131900fc --- /dev/null +++ b/apps/api/src/services/import/broker/broker-instrument-resolver.service.ts @@ -0,0 +1,566 @@ +import { ConfigurationService } from '@ghostfolio/api/services/configuration/configuration.service'; +import { DataProviderService } from '@ghostfolio/api/services/data-provider/data-provider.service'; +import { ListingQuote } from '@ghostfolio/api/services/data-provider/interfaces/data-provider.interface'; +import { FetchService } from '@ghostfolio/api/services/fetch/fetch.service'; +import { PrismaService } from '@ghostfolio/api/services/prisma/prisma.service'; +import { + BrokerInstrumentResolution, + BrokerSourceRow +} from '@ghostfolio/common/interfaces/broker-import.interface'; + +import { Injectable, Optional } from '@nestjs/common'; +import { isISIN } from 'class-validator'; + +import { parseJustEtfListings } from './published-listings.parser'; + +interface PublishedListing { + symbol: string; + exchange: string; + currency?: string; + source: string; +} +interface Evidence { + listings: PublishedListing[]; + unavailable: boolean; +} +const TIMEOUT = 8000; +const MAX_CANDIDATES = 24; +const MARKETS: Record = { + MI: { code: 'MIL', name: 'Borsa Italiana', mic: 'XMIL' }, + DE: { code: 'GER', name: 'Xetra', mic: 'XETR' }, + AS: { code: 'AMS', name: 'Euronext Amsterdam', mic: 'XAMS' }, + PA: { code: 'PAR', name: 'Euronext Paris', mic: 'XPAR' }, + L: { code: 'LSE', name: 'London Stock Exchange', mic: 'XLON' }, + SW: { code: 'EBS', name: 'SIX Swiss Exchange', mic: 'XSWX' }, + F: { code: 'FRA', name: 'Frankfurt', mic: 'XFRA' } +}; +const PUBLISHED_MARKETS: Record = { + 'Borsa Italiana': 'MI', + XETRA: 'DE', + Xetra: 'DE', + 'Euronext Amsterdam': 'AS', + 'Euronext Paris': 'PA', + 'London Stock Exchange': 'L', + 'SIX Swiss Exchange': 'SW', + 'Frankfurt Stock Exchange': 'F' +}; +const QUOTE_MARKETS: Record = { + MIL: { name: 'Borsa Italiana', mic: 'XMIL' }, + GER: { name: 'Xetra', mic: 'XETR' }, + AMS: { name: 'Euronext Amsterdam', mic: 'XAMS' }, + PAR: { name: 'Euronext Paris', mic: 'XPAR' }, + LSE: { name: 'London Stock Exchange', mic: 'XLON' }, + EBS: { name: 'SIX Swiss Exchange', mic: 'XSWX' }, + FRA: { name: 'Frankfurt', mic: 'XFRA' }, + NMS: { name: 'Nasdaq', mic: 'XNAS' }, + NGM: { name: 'Nasdaq', mic: 'XNAS' }, + NCM: { name: 'Nasdaq', mic: 'XNAS' }, + NYQ: { name: 'NYSE', mic: 'XNYS' }, + PCX: { name: 'NYSE Arca', mic: 'ARCX' } +}; +function text(value: string) { + return value + .replace(/<[^>]*>/g, ' ') + .replace(/ | /g, ' ') + .replace(/&/g, '&') + .replace(/&#(?:x([0-9a-f]+)|(\d+));/gi, (_, hex, dec) => + String.fromCodePoint( + Math.min(0x10ffff, parseInt(hex ?? dec, hex ? 16 : 10)) + ) + ) + .replace(/\s+/g, ' ') + .trim(); +} +/** Identity is taken from labeled table cells, never an ISIN echoed in a URL or search text. */ +export function parseBorsaListing( + html: string, + isin: string +): PublishedListing[] { + const rows = (html.match(/]*>[\s\S]*?<\/tr>/gi) ?? []).map((row) => + (row.match(/<(?:td|th)\b[^>]*>[\s\S]*?<\/(?:td|th)>/gi) ?? []).map(text) + ); + const values = (labels: RegExp) => + rows + .filter((row) => row.length >= 2 && labels.test(row[0])) + .map((row) => row[1]); + const isins = values(/^(?:Isin Code|ISIN|Codice Isin)$/i), + tickers = values(/^(?:Alphanumeric Code|Codice Alfanumerico)$/i); + if ( + isins.length !== 1 || + isins[0] !== isin || + tickers.length !== 1 || + !/^[A-Z0-9][A-Z0-9.-]{0,24}$/.test(tickers[0]) + ) + return []; + const market = values(/^(?:Market\/Segment|Mercato\/Segmento)$/i); + if ( + market.length && + !/Euronext|Milan|Global Equity|MT[AAH]|GEM|TAH|Trading After/i.test( + market[0] + ) + ) + return []; + return [ + { symbol: tickers[0] + '.MI', exchange: 'MIL', source: 'Borsa Italiana' } + ]; +} +export function parseVerifiedEtfListings( + html: string, + isin: string +): PublishedListing[] { + const tags = (html.match(/]*>/gi) ?? []).filter((tag) => + /\brel=["']canonical["']/i.test(tag) + ); + if (tags.length !== 1) return []; + const href = /\bhref=["']([^"']+)["']/i.exec(tags[0])?.[1]; + if (!href) return []; + let url: URL; + try { + url = new URL(href.replace(/&/g, '&'), 'https://www.justetf.com'); + } catch { + return []; + } + if ( + url.hostname !== 'www.justetf.com' || + !url.pathname.endsWith('/etf-profile.html') || + url.searchParams.get('isin') !== isin + ) + return []; + return parseJustEtfListings(html).flatMap((row) => { + const suffix = PUBLISHED_MARKETS[row.exchange], + market = MARKETS[suffix]; + if ( + !market || + !row.reuters || + !row.reuters.toUpperCase().endsWith('.' + suffix) || + row.reuters.slice(0, -suffix.length - 1).toUpperCase() !== + row.ticker.toUpperCase() || + !/^[A-Z]{3}$/.test(row.currency) + ) + return []; + return [ + { + symbol: row.reuters.toUpperCase(), + exchange: market.code, + currency: row.currency, + source: 'justETF' + } + ]; + }); +} +@Injectable() +export class BrokerInstrumentResolver { + private readonly cache = new Map< + string, + { expires: number; value: Promise } + >(); + constructor( + private readonly prisma: PrismaService, + private readonly providers: DataProviderService, + private readonly fetcher: FetchService, + @Optional() private readonly configuration?: ConfigurationService + ) {} + private cached( + key: string, + load: () => Promise, + ttl = 300000 + ): Promise { + const prior = this.cache.get(key); + if (prior && prior.expires > Date.now()) return prior.value as Promise; + if (this.cache.size >= 300) + this.cache.delete(this.cache.keys().next().value); + const value = load().catch((error) => { + this.cache.delete(key); + throw error; + }); + this.cache.set(key, { expires: Date.now() + ttl, value }); + return value; + } + private async html(url: string): Promise<{ body: string; status: number }> { + const original = new URL(url); + let target = original; + for (let attempt = 0; attempt < 4; attempt++) { + const response = await this.fetcher.fetch( + target.toString(), + { + signal: AbortSignal.timeout(TIMEOUT), + redirect: 'manual' + }, + { allowWebFetch: false } + ); + if ([301, 302, 303, 307, 308].includes(response.status)) { + const location = response.headers.get('location'); + if (!location) throw new Error('Invalid provider redirect'); + const next = new URL(location, target); + if (next.origin !== original.origin) + throw new Error('Unexpected provider redirect'); + target = next; + continue; + } + if ([404, 410].includes(response.status)) + return { body: '', status: response.status }; + if (!response.ok) throw new Error('Provider unavailable'); + const reader = response.body?.getReader(); + if (!reader) throw new Error('Empty provider response'); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const part = await reader.read(); + if (part.done) break; + total += part.value.length; + if (total > 2500000) { + await reader.cancel(); + throw new Error('Provider response too large'); + } + chunks.push(part.value); + } + return { + body: Buffer.concat(chunks).toString('utf8'), + status: response.status + }; + } + throw new Error('Too many provider redirects'); + } + private async published(isin: string, hints: string[]): Promise { + return this.cached( + 'published:' + isin + ':' + hints.slice().sort().join(','), + async () => { + const result: Evidence = { listings: [], unavailable: false }; + const routes = [ + `/borsa/azioni/dati-completi.html?isin=${isin}`, + `/borsa/etf/scheda/${isin}.html?`, + `/borsa/etc-etn/scheda/${isin}.html?`, + `/borsa/azioni/global-equity-market/dati-completi.html?isin=${isin}`, + `/borsa/azioni/mercato-serale/dati-completi.html?isin=${isin}` + ]; + for (const route of routes) { + try { + const url = new URL('https://www.borsaitaliana.it' + route); + url.searchParams.set('lang', 'en'); + const page = await this.html(url.toString()); + const rows = parseBorsaListing(page.body, isin); + result.listings.push(...rows); + if (rows.some((row) => hints.includes(row.symbol.slice(0, -3)))) + break; + } catch { + result.unavailable = true; + break; + } + } + try { + const page = await this.html( + 'https://www.justetf.com/it/etf-profile.html?isin=' + isin + ); + result.listings.push(...parseVerifiedEtfListings(page.body, isin)); + } catch { + result.unavailable = true; + } + if (result.unavailable) + this.cache.delete( + 'published:' + isin + ':' + hints.slice().sort().join(',') + ); + return result; + } + ); + } + private async quote(symbol: string): Promise { + return this.cached('quote:' + symbol, async () => { + const provider = this.providers.getDataProvider('YAHOO'); + if (!provider.getListingQuote) + throw new Error('Listing quote unavailable'); + let quote: ListingQuote | undefined; + try { + quote = await provider.getListingQuote({ + symbol, + requestTimeout: TIMEOUT + }); + } catch (error) { + if (['NotFoundError', 'BadRequestError'].includes(error?.name)) + return undefined; + throw error; + } + if ( + quote?.symbol.toUpperCase() !== symbol.toUpperCase() || + !/^[A-Z]{3}$/.test(quote.currency) || + !QUOTE_MARKETS[quote.exchange] + ) + return undefined; + const suffix = symbol.includes('.') + ? symbol.slice(symbol.lastIndexOf('.') + 1) + : ''; + if (MARKETS[suffix] && MARKETS[suffix].code !== quote.exchange) + return undefined; + return quote; + }); + } + private async figi( + isin: string, + quotes: ListingQuote[] + ): Promise { + if (!quotes.length) return []; + const key = + 'figi:' + + isin + + ':' + + quotes + .map((q) => q.symbol + ':' + q.currency) + .sort() + .join(','); + return this.cached(key, async () => { + const jobs = [ + ...new Map( + quotes.map((quote) => { + const market = QUOTE_MARKETS[quote.exchange]; + return [ + market.mic + ':' + quote.currency, + { + idType: 'ID_ISIN', + idValue: isin, + micCode: market.mic, + currency: quote.currency + } + ]; + }) + ).values() + ].slice(0, 10); + const apiKey = this.configuration?.get('API_KEY_OPEN_FIGI'); + const response = await this.fetcher.fetch( + 'https://api.openfigi.com/v3/mapping', + { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(apiKey ? { 'X-OPENFIGI-APIKEY': apiKey } : {}) + }, + body: JSON.stringify(jobs), + signal: AbortSignal.timeout(TIMEOUT) + } + ); + if (!response.ok) throw new Error('Mapping provider unavailable'); + const data = (await response.json()) as { + data?: { ticker?: string; figi?: string }[]; + error?: string; + }[]; + if ( + !Array.isArray(data) || + data.length !== jobs.length || + data.some((item) => item.error) + ) + throw new Error('Invalid mapping response'); + return quotes.flatMap((quote) => { + const market = QUOTE_MARKETS[quote.exchange], + index = jobs.findIndex( + (job) => + job.micCode === market.mic && job.currency === quote.currency + ); + const bare = Object.keys(MARKETS).some((suffix) => + quote.symbol.endsWith('.' + suffix) + ) + ? quote.symbol.slice(0, quote.symbol.lastIndexOf('.')) + : quote.symbol; + const matches = + data[index]?.data?.filter( + (item) => item.ticker === bare && typeof item.figi === 'string' + ) ?? []; + return matches.length === 1 + ? [ + { + symbol: quote.symbol, + exchange: quote.exchange, + currency: quote.currency, + source: 'OpenFIGI' + } + ] + : []; + }); + }); + } + async resolve( + rows: BrokerSourceRow[], + userId: string, + choices: Record = {} + ): Promise { + const groups = [...new Set(rows.map((row) => row.isin))]; + const profiles = await this.prisma.symbolProfile.findMany({ + where: { isin: { in: groups }, OR: [{ userId: null }, { userId }] } + }); + const result: BrokerInstrumentResolution[] = new Array(groups.length); + let cursor = 0; + const worker = async () => { + for (;;) { + const index = cursor++; + if (index >= groups.length) return; + const isin = groups[index], + source = rows.filter((row) => row.isin === isin), + hints = [ + ...new Set( + source.map((row) => row.ticker.toUpperCase()).filter(Boolean) + ) + ], + currencies = [...new Set(source.map((row) => row.currency))]; + const resolution: BrokerInstrumentResolution = { + isin, + name: '', + status: 'UNRESOLVED', + reason: 'NO_EVIDENCE', + affectedOperations: source.length, + candidates: [] + }; + result[index] = resolution; + if (!isISIN(isin)) { + resolution.reason = 'INVALID_ISIN'; + continue; + } + let unavailable = false; + try { + const evidence = structuredClone(await this.published(isin, hints)); + unavailable = evidence.unavailable; + const symbols = new Set(evidence.listings.map((row) => row.symbol)); + for (const profile of profiles.filter( + (profile) => profile.isin === isin && profile.dataSource === 'YAHOO' + )) + symbols.add(profile.symbol); + const choice = choices[isin]?.replace(/^YAHOO:/, ''); + if (choice) symbols.add(choice); + try { + const search = await this.cached('search:' + isin, () => + this.providers + .getDataProvider('YAHOO') + .search({ query: isin, requestTimeout: TIMEOUT }) + ); + if (search.status === 'UNAVAILABLE') { + unavailable = true; + this.cache.delete('search:' + isin); + } + for (const item of search.items ?? []) + if (item.dataSource === 'YAHOO') symbols.add(item.symbol); + } catch { + unavailable = true; + } + const quotes: ListingQuote[] = []; + for (const symbol of [...symbols].slice(0, MAX_CANDIDATES)) { + try { + const quote = await this.quote(symbol); + if (quote) quotes.push(quote); + } catch { + unavailable = true; + } + } + const unverified = quotes.filter( + (quote) => + !evidence.listings.some( + (listing) => + listing.symbol === quote.symbol && + listing.exchange === quote.exchange && + (!listing.currency || listing.currency === quote.currency) + ) + ); + if (unverified.length) { + try { + evidence.listings.push(...(await this.figi(isin, unverified))); + } catch { + unavailable = true; + } + } + let conflict = false; + for (const quote of quotes) { + if ( + evidence.listings.some( + (listing) => + listing.symbol === quote.symbol && + listing.exchange === quote.exchange && + listing.currency && + listing.currency !== quote.currency + ) + ) { + conflict = true; + continue; + } + const proof = evidence.listings.filter( + (listing) => + listing.symbol === quote.symbol && + listing.exchange === quote.exchange && + (!listing.currency || listing.currency === quote.currency) + ); + if (!proof.length) continue; + const stored = await this.prisma.symbolProfile.findUnique({ + where: { + dataSource_symbol: { dataSource: 'YAHOO', symbol: quote.symbol } + } + }); + const same = stored ? [stored] : []; + if ( + same.some( + (profile) => + (profile.userId && profile.userId !== userId) || + (profile.isin && profile.isin !== isin) || + profile.currency !== quote.currency + ) + ) { + conflict = true; + continue; + } + resolution.candidates.push({ + key: 'YAHOO:' + quote.symbol, + id: same[0]?.id, + isin, + symbol: quote.symbol, + dataSource: 'YAHOO', + name: quote.name, + exchange: QUOTE_MARKETS[quote.exchange].name, + currency: quote.currency, + sources: [...new Set(proof.map((row) => row.source))], + assetClass: quote.assetClass, + assetSubClass: quote.assetSubClass + }); + } + resolution.candidates.sort((a, b) => a.key.localeCompare(b.key)); + resolution.name = resolution.candidates[0]?.name ?? ''; + const selected = resolution.candidates.filter( + (candidate) => + choices[isin] === candidate.key || + choices[isin] === candidate.symbol + ); + if (choices[isin] && selected.length === 1) { + resolution.status = 'CONFIRMED'; + resolution.selected = selected[0].key; + resolution.reason = 'UNIQUE'; + continue; + } + const preferred = resolution.candidates.filter( + (candidate) => + hints.length === 1 && + currencies.length === 1 && + candidate.currency === currencies[0] && + hints[0] === + (candidate.symbol.endsWith('.MI') || + candidate.symbol.includes('.') + ? candidate.symbol.slice(0, candidate.symbol.lastIndexOf('.')) + : candidate.symbol) + ); + if (!choices[isin] && preferred.length === 1 && !unavailable) { + resolution.status = 'AUTOMATIC'; + resolution.selected = preferred[0].key; + resolution.reason = 'UNIQUE'; + } else if (resolution.candidates.length) { + resolution.status = 'CONFIRMATION_REQUIRED'; + resolution.reason = unavailable + ? 'PROVIDER_UNAVAILABLE' + : preferred.length > 1 + ? 'MULTIPLE_LISTINGS' + : 'MARKET_CONFIRMATION'; + } else + resolution.reason = conflict + ? 'PROFILE_CONFLICT' + : unavailable + ? 'PROVIDER_UNAVAILABLE' + : 'NO_EVIDENCE'; + } catch { + resolution.reason = 'PROVIDER_UNAVAILABLE'; + } + } + }; + await Promise.all([worker(), worker()]); + return result; + } +} diff --git a/apps/api/src/services/import/broker/cost-association.spec.ts b/apps/api/src/services/import/broker/cost-association.spec.ts new file mode 100644 index 0000000000..8444dbeaa9 --- /dev/null +++ b/apps/api/src/services/import/broker/cost-association.spec.ts @@ -0,0 +1,66 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { automaticallyMatchesCost, compatibleCost } from './cost-association'; +import { DirectaAdapter } from './directa.adapter'; + +const adapter = new DirectaAdapter(); +const rows = adapter.parse( + readFileSync(join(__dirname, '__fixtures__/directa.csv'), 'utf8') +).rows; +const dividend = rows.find((row) => row.kind === 'DIVIDEND'), + tax = rows.find((row) => row.attachment === 'DIVIDEND'); +describe('Compound withholding identity', () => { + it('matches only the complete income identity, never adjacency or date alone', () => { + expect(automaticallyMatchesCost(tax, dividend, adapter)).toBe(true); + for (const change of [ + { isin: 'XX0000000010' }, + { isin: '' }, + { currency: 'USD' }, + { valueDate: '2026-01-04' }, + { operationDate: '2026-01-04' }, + { amount: '-11' }, + { amount: '1' }, + { sourceType: 'Ritenuta dividendi italia' }, + { orderReference: 'UNRELATED' } + ]) + expect(compatibleCost({ ...tax, ...change }, dividend, adapter)).toBe( + false + ); + }); + it('requires stable references for automatic trade costs', () => { + const fee = rows.find((row) => row.kind === 'FEE'), + buy = rows.find((row) => row.kind === 'BUY'); + expect(automaticallyMatchesCost(fee, buy, adapter)).toBe(true); + expect(compatibleCost({ ...fee, orderReference: '' }, buy, adapter)).toBe( + true + ); + expect( + automaticallyMatchesCost({ ...fee, orderReference: '' }, buy, adapter) + ).toBe(false); + }); + it('separates domestic and foreign dividends on the same date regardless of row order', () => { + const source = adapter.parse( + readFileSync( + join(__dirname, '__fixtures__/directa-dividends.csv'), + 'utf8' + ) + ).rows; + const incomes = source.filter((row) => row.kind === 'DIVIDEND'), + withholdings = source.filter((row) => row.kind === 'TAX'); + expect( + withholdings.map((cost) => + incomes + .filter((income) => automaticallyMatchesCost(cost, income, adapter)) + .map((income) => income.protocol) + ) + ).toEqual([['INC-FOR'], ['INC-DOM']]); + expect( + withholdings.map((cost) => + incomes.filter((income) => + automaticallyMatchesCost({ ...cost, isin: '' }, income, adapter) + ) + ) + ).toEqual([[], []]); + }); +}); diff --git a/apps/api/src/services/import/broker/cost-association.ts b/apps/api/src/services/import/broker/cost-association.ts new file mode 100644 index 0000000000..66cba261cd --- /dev/null +++ b/apps/api/src/services/import/broker/cost-association.ts @@ -0,0 +1,55 @@ +import { BrokerSourceRow } from '@ghostfolio/common/interfaces/broker-import.interface'; + +import { Big } from 'big.js'; + +import { BrokerAdapter } from './broker-adapter'; + +/** Candidate eligibility is independent of source ordering and of earlier assignments. */ +export function compatibleCost( + cost: BrokerSourceRow, + activity: BrokerSourceRow, + adapter: BrokerAdapter +): boolean { + if ( + !['BUY', 'SELL', 'DIVIDEND'].includes(activity.kind) || + !new Big(cost.amount).lt(0) || + cost.currency !== activity.currency || + cost.operationDate !== activity.operationDate + ) + return false; + if (cost.isin && cost.isin !== activity.isin) return false; + const referenced = + !!cost.orderReference && cost.orderReference === activity.orderReference; + if (cost.orderReference && !referenced) return false; + if (!cost.isin && !referenced) return false; + if (cost.kind === 'FEE') return ['BUY', 'SELL'].includes(activity.kind); + if (cost.attachment === 'SALE') return activity.kind === 'SELL'; + if (cost.attachment === 'TRADE') + return ['BUY', 'SELL'].includes(activity.kind); + if (cost.attachment === 'DIVIDEND') { + const family = adapter.incomeGroup?.(cost); + return ( + activity.kind === 'DIVIDEND' && + !!family && + family === adapter.incomeGroup?.(activity) && + cost.valueDate === activity.valueDate && + new Big(activity.amount).gt(0) && + new Big(cost.amount).abs().lte(activity.amount) + ); + } + return false; +} +export function automaticallyMatchesCost( + cost: BrokerSourceRow, + activity: BrokerSourceRow, + adapter: BrokerAdapter +): boolean { + if (!compatibleCost(cost, activity, adapter)) return false; + if (cost.orderReference) + return cost.orderReference === activity.orderReference; + // The complete compound identity, family, two dates, currency and amount are + // mandatory. Adjacency and a date alone never establish a tax relationship. + return ( + cost.attachment === 'DIVIDEND' && !!cost.isin && cost.isin === activity.isin + ); +} diff --git a/apps/api/src/services/import/broker/directa.adapter.spec.ts b/apps/api/src/services/import/broker/directa.adapter.spec.ts new file mode 100644 index 0000000000..f651e14166 --- /dev/null +++ b/apps/api/src/services/import/broker/directa.adapter.spec.ts @@ -0,0 +1,87 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { DirectaAdapter, italiana } from './directa.adapter'; + +const csv = readFileSync(join(__dirname, '__fixtures__/directa.csv'), 'utf8'); +describe('Directa adapter', () => { + const adapter = new DirectaAdapter(); + it('reads BOM, metadata, dates, zero dividend quantity, signed cents and order references', () => { + const result = adapter.parse(csv); + expect(adapter.recognizes(csv)).toBe(true); + expect(result.sourceAccount).toBe('SYNTHETIC'); + expect(result.rows).toHaveLength(10); + expect(result.rows[1]).toMatchObject({ + line: 6, + kind: 'BUY', + quantity: '10', + amount: '-100', + operationDate: '2026-01-02', + valueDate: '2026-01-05', + orderReference: 'O001' + }); + expect(result.rows[4]).toMatchObject({ + kind: 'TAX', + amount: '-2.6', + orderReference: '' + }); + }); + it.each(['-1.234,56', '0', '12,345'])( + 'parses an Italian number %s', + (value) => expect(() => italiana(value)).not.toThrow() + ); + it.each(['1,234.56', '1.23', '1e3', '1 000', 'NaN', '', ',5', '-'])( + 'rejects malformed number %s', + (value) => expect(() => italiana(value)).toThrow() + ); + it('rejects missing, extra and duplicate columns, malformed dates, invalid encoding and oversized input', () => { + for (const data of [ + csv.replace('Protocollo;', ';'), + csv.replace('Protocollo;', 'Protocollo;Extra;'), + csv.replace('02-01-2026', '31-02-2026'), + csv.replace('Conto : SYNTHETIC', 'Account'), + csv + '\uFFFD', + 'x'.repeat(2_000_001) + ]) + expect(() => adapter.parse(data)).toThrow(); + }); + it('requires an explicit recognized format and preserves unknown operation types', () => { + expect(adapter.recognizes('Date,Type,Symbol')).toBe(false); + expect( + adapter.parse( + csv.replace(';Bollo portafoglio titoli*;', ';Unknown event;') + ).rows[6].kind + ).toBe('UNSUPPORTED'); + }); + it('localizes both source-menu entries in every supported locale', () => { + const directory = join(__dirname, '../../../../../client/src/locales'); + const files = readdirSync(directory).filter((name) => + /^messages\..+\.xlf$/.test(name) + ); + expect(files.length).toBe(13); + for (const file of files) { + const text = readFileSync(join(directory, file), 'utf8'); + for (const id of [ + 'brokerUpstream_fromGhostfolio', + 'brokerUpstream_fromDirecta', + 'brokerUpstream_sourceMenu' + ]) + expect(text).toMatch( + new RegExp('id="' + id + '"[\\s\\S]*?]*>[^<]+') + ); + } + }); + + it('uses the order reference when Directa omits trade protocols and blocks indistinguishable executions', () => { + const data = csv.replace(';B001;', ';;').replace(';F001;', ';;'); + const rows = adapter.parse(data).rows; + expect(rows[1].identitySource).toBe('ORDER_REFERENCE'); + expect(rows[1].protocol).toMatch(/^order:/); + expect(rows[1].protocol).not.toBe(rows[2].protocol); + expect( + adapter.parse(data.replace(';-100;', ';-101;')).rows[1].protocol + ).toBe(rows[1].protocol); + const trade = data.split('\n').find((line) => line.includes(';Acquisto;')); + expect(() => adapter.parse(data + '\n' + trade)).toThrow('ambiguous'); + }); +}); diff --git a/apps/api/src/services/import/broker/directa.adapter.ts b/apps/api/src/services/import/broker/directa.adapter.ts new file mode 100644 index 0000000000..e9464fdf82 --- /dev/null +++ b/apps/api/src/services/import/broker/directa.adapter.ts @@ -0,0 +1,223 @@ +import { BrokerSourceRow } from '@ghostfolio/common/interfaces/broker-import.interface'; + +import { BadRequestException } from '@nestjs/common'; +import { Big } from 'big.js'; +import { createHash } from 'node:crypto'; +import { parse } from 'papaparse'; + +import { BrokerAdapter } from './broker-adapter'; + +export const DIRECTA_COLUMNS = [ + 'Data operazione', + 'Data valuta', + 'Tipo operazione', + 'Ticker', + 'Isin', + 'Protocollo', + 'Descrizione', + 'Quantità', + 'Importo euro', + 'Importo Divisa', + 'Divisa', + 'Riferimento ordine' +]; +export function italiana(value: string): string { + if (!/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value)) + throw new BadRequestException('Invalid Italian decimal number.'); + const number = new Big(value.replace(/\./g, '').replace(',', '.')); + if (number.abs().gte('1e20') || !number.eq(number.round(12, Big.roundDown))) + throw new BadRequestException( + 'Broker amount exceeds the supported precision.' + ); + return number.toFixed(); +} +function date(value: string) { + const match = /^(\d{2})[-/](\d{2})[-/](\d{4})$/.exec(value); + const iso = match ? `${match[3]}-${match[2]}-${match[1]}` : ''; + const parsed = new Date(`${iso}T00:00:00Z`); + if ( + !iso || + !Number.isFinite(parsed.getTime()) || + parsed.toISOString().slice(0, 10) !== iso || + iso < '1900-01-01' + ) + throw new BadRequestException('Invalid broker date.'); + return iso; +} +const kinds: Record = { + Acquisto: 'BUY', + Vendita: 'SELL', + Commissioni: 'FEE', + 'Incasso dividendi italia': 'DIVIDEND', + 'Incasso dividendi esteri': 'DIVIDEND', + 'Ritenuta dividendi italia': 'TAX', + 'Ritenuta dividendi esteri': 'TAX', + 'Rit. etf': 'TAX', + 'Ritenuta su plusvalenza': 'TAX', + 'Tobin tax italia': 'TAX', + 'Conferimento con bonifico': 'DEPOSIT', + 'Prelievo con bonifico': 'WITHDRAWAL', + 'Bollo portafoglio titoli*': 'EXPENSE', + 'Bollo portafoglio titoli': 'EXPENSE' +}; +export class DirectaAdapter implements BrokerAdapter { + readonly format = 'DIRECTA' as const; + incomeGroup(row: BrokerSourceRow): string | undefined { + if ( + ['Incasso dividendi italia', 'Ritenuta dividendi italia'].includes( + row.sourceType + ) + ) + return 'DOMESTIC_DIVIDEND'; + if ( + ['Incasso dividendi esteri', 'Ritenuta dividendi esteri'].includes( + row.sourceType + ) + ) + return 'FOREIGN_DIVIDEND'; + return undefined; + } + recognizes(csv: string) { + return ( + csv.includes('Data operazione;Data valuta;Tipo operazione;') || + csv.includes('"Data operazione";"Data valuta";"Tipo operazione"') + ); + } + parse(csv: string) { + if ( + typeof csv !== 'string' || + Buffer.byteLength(csv, 'utf8') > 2_000_000 || + csv.includes('\uFFFD') || + csv.includes('\0') + ) + throw new BadRequestException('Use a UTF-8 CSV under 2 MB.'); + const parsed = parse(csv.replace(/^\uFEFF/, ''), { + delimiter: ';', + skipEmptyLines: false, + dynamicTyping: false + }); + if (parsed.errors.length) + throw new BadRequestException('Invalid Directa CSV quoting.'); + const header = parsed.data.findIndex( + (r) => r[0]?.trim() === 'Data operazione' + ); + if ( + header < 0 || + header > 30 || + parsed.data[header].length !== DIRECTA_COLUMNS.length || + parsed.data[header].some((v, i) => v.trim() !== DIRECTA_COLUMNS[i]) + ) + throw new BadRequestException('Unsupported Directa columns.'); + const account = parsed.data + .slice(0, header) + .flat() + .map((c) => /^Conto\s*:\s*([A-Z0-9-]+)/i.exec(c.trim())?.[1]) + .filter(Boolean); + if (account.length !== 1) + throw new BadRequestException( + 'A single Directa source account is required in the file metadata.' + ); + const data = parsed.data + .slice(header + 1) + .map((r, i) => ({ r, line: header + i + 2 })) + .filter(({ r }) => r.some((c) => c.trim())); + if (!data.length || data.length > 5000) + throw new BadRequestException('Import between 1 and 5000 rows.'); + const rows: BrokerSourceRow[] = data.map(({ r, line }, i) => { + if (r.length !== DIRECTA_COLUMNS.length || r.some((c) => c.length > 1000)) + throw new BadRequestException( + `Invalid structure at data row ${i + 1}.` + ); + const [ + operationDate, + valueDate, + sourceType, + ticker, + isin, + rawProtocol, + , + quantity, + amount, + originalAmount, + currency, + reference + ] = r.map((c) => c.trim()); + const hasProtocol = !!rawProtocol && rawProtocol !== '0'; + const hasOrder = !['', '0', '-'].includes(reference); + if ( + (!hasProtocol && !hasOrder) || + rawProtocol.length > 128 || + reference.length > 128 + ) + throw new BadRequestException( + `Missing or invalid broker identity at data row ${i + 1}.` + ); + // Trade exports omit Protocollo. The order reference and component role, + // not the row amount/hash, identify that broker record. + const role = ['Acquisto', 'Vendita'].includes(sourceType) + ? 'TRADE' + : sourceType; + const protocol = hasProtocol + ? rawProtocol + : `order:${createHash('sha256') + .update(JSON.stringify([reference, role])) + .digest('hex')}`; + return { + line, + operationDate: date(operationDate), + valueDate: date(valueDate), + attachment: + sourceType === 'Commissioni' + ? 'TRADE' + : sourceType.startsWith('Ritenuta dividendi') + ? 'DIVIDEND' + : sourceType === 'Rit. etf' + ? 'SALE' + : sourceType === 'Tobin tax italia' && + !['', '0', '-'].includes(reference) + ? 'TRADE' + : 'NONE', + sourceType, + ticker, + isin: isin.toUpperCase(), + protocol, + identitySource: hasProtocol ? 'PROTOCOL' : 'ORDER_REFERENCE', + orderIdentity: hasOrder + ? createHash('sha256') + .update( + JSON.stringify([account[0].toUpperCase(), reference, role]) + ) + .digest('hex') + : '', + quantity: italiana(quantity), + amount: italiana(amount), + originalAmount: italiana(originalAmount), + currency, + orderReference: ['', '0', '-'].includes(reference) ? '' : reference, + kind: kinds[sourceType] ?? 'UNSUPPORTED' + }; + }); + const references = rows + .filter((row) => row.identitySource === 'ORDER_REFERENCE') + .map((row) => row.protocol); + if (new Set(references).size !== references.length) + throw new BadRequestException( + 'Multiple executions share an order reference and component role. Their identities are ambiguous; automatic import is blocked.' + ); + const ascending = rows.every( + (row, index) => + !index || rows[index - 1].operationDate <= row.operationDate + ); + const descending = rows.every( + (row, index) => + !index || rows[index - 1].operationDate >= row.operationDate + ); + const ordering = + ascending && !descending + ? ('ASCENDING' as const) + : descending && !ascending + ? ('DESCENDING' as const) + : ('UNSPECIFIED' as const); + return { sourceAccount: account[0].toUpperCase(), rows, ordering }; + } +} diff --git a/apps/api/src/services/import/broker/published-listings.parser.ts b/apps/api/src/services/import/broker/published-listings.parser.ts new file mode 100644 index 0000000000..92fb1f008d --- /dev/null +++ b/apps/api/src/services/import/broker/published-listings.parser.ts @@ -0,0 +1,48 @@ +export interface JustEtfListing { + exchange: string; + ticker: string; + reuters: string; + currency: string; +} + +function decodeHtml(value: string): string { + return value + .replace(/&/g, '&') + .replace(/'/g, "'") + .replace(/"/g, '"') + .replace(/ /g, ' '); +} + +function stripHtml(value: string): string { + return decodeHtml(value.replace(/<[^>]*>/g, '')).trim(); +} + +export function parseJustEtfListings(html: string): JustEtfListing[] { + if (typeof html !== 'string' || html.length === 0) { + return []; + } + + const rows = + html.match( + /]*data-testid="etf-trade-data-panel_row-[^"]+"[^>]*>[\s\S]*?<\/tr>/g + ) ?? []; + + return rows.map((row) => { + const getField = (field: string): string => { + const pattern = new RegExp( + `data-testid="etf-trade-data-panel_row-[^"]+_${field}"[^>]*>([\\s\\S]*?)<\\/` + ); + + const match = row.match(pattern); + + return match ? stripHtml(match[1]) : ''; + }; + + return { + exchange: getField('listing'), + ticker: getField('ticker'), + reuters: getField('reuters'), + currency: getField('trade-currency') + }; + }); +} diff --git a/apps/api/src/services/import/import.module.ts b/apps/api/src/services/import/import.module.ts index 8ccf27dfd9..0004d069bb 100644 --- a/apps/api/src/services/import/import.module.ts +++ b/apps/api/src/services/import/import.module.ts @@ -5,19 +5,25 @@ import { ApiModule } from '@ghostfolio/api/services/api/api.module'; import { ConfigurationModule } from '@ghostfolio/api/services/configuration/configuration.module'; import { DataProviderModule } from '@ghostfolio/api/services/data-provider/data-provider.module'; import { ExchangeRateDataModule } from '@ghostfolio/api/services/exchange-rate-data/exchange-rate-data.module'; +import { FetchModule } from '@ghostfolio/api/services/fetch/fetch.module'; import { MarketDataModule } from '@ghostfolio/api/services/market-data/market-data.module'; import { PlatformModule } from '@ghostfolio/api/services/platform/platform.module'; +import { PrismaModule } from '@ghostfolio/api/services/prisma/prisma.module'; import { DataGatheringQueueModule } from '@ghostfolio/api/services/queues/data-gathering/data-gathering.module'; import { SymbolProfileModule } from '@ghostfolio/api/services/symbol-profile/symbol-profile.module'; import { TagModule } from '@ghostfolio/api/services/tag/tag.module'; import { Module } from '@nestjs/common'; +import { BrokerImportService } from './broker/broker-import.service'; +import { BrokerInstrumentResolver } from './broker/broker-instrument-resolver.service'; import { ImportService } from './import.service'; @Module({ - exports: [ImportService], + exports: [ImportService, BrokerImportService], imports: [ + PrismaModule, + FetchModule, AccountModule, ActivitiesModule, ApiModule, @@ -31,6 +37,6 @@ import { ImportService } from './import.service'; SymbolProfileModule, TagModule ], - providers: [ImportService] + providers: [ImportService, BrokerImportService, BrokerInstrumentResolver] }) export class ImportModule {} diff --git a/libs/common/src/lib/interfaces/broker-import.interface.ts b/libs/common/src/lib/interfaces/broker-import.interface.ts new file mode 100644 index 0000000000..758bd4dda5 --- /dev/null +++ b/libs/common/src/lib/interfaces/broker-import.interface.ts @@ -0,0 +1,146 @@ +export interface BrokerSourceRow { + line: number; + protocol: string; + identitySource: 'PROTOCOL' | 'ORDER_REFERENCE'; + orderIdentity: string; + orderReference: string; + operationDate: string; + valueDate: string; + sourceType: string; + attachment: 'NONE' | 'TRADE' | 'SALE' | 'DIVIDEND'; + kind: + | 'BUY' + | 'SELL' + | 'DIVIDEND' + | 'FEE' + | 'TAX' + | 'DEPOSIT' + | 'WITHDRAWAL' + | 'EXPENSE' + | 'UNSUPPORTED'; + isin: string; + ticker: string; + quantity: string; + amount: string; + originalAmount: string; + currency: string; +} +export type BrokerResolutionStatus = + 'AUTOMATIC' | 'CONFIRMATION_REQUIRED' | 'CONFIRMED' | 'UNRESOLVED'; +export interface BrokerListingCandidate { + key: string; + id?: string; + isin: string; + symbol: string; + dataSource: 'YAHOO'; + name: string; + exchange: string; + currency: string; + sources: string[]; + assetClass?: import('@ghostfolio/prisma/enums').AssetClass | null; + assetSubClass?: import('@ghostfolio/prisma/enums').AssetSubClass | null; +} +export interface BrokerInstrumentResolution { + isin: string; + name: string; + status: BrokerResolutionStatus; + reason: + | 'UNIQUE' + | 'MULTIPLE_LISTINGS' + | 'MARKET_CONFIRMATION' + | 'NO_EVIDENCE' + | 'PROVIDER_UNAVAILABLE' + | 'INVALID_ISIN' + | 'PROFILE_CONFLICT'; + affectedOperations: number; + candidates: BrokerListingCandidate[]; + selected?: string; +} +export interface BrokerCostAssociation { + sourceId: string; + line: number; + kind: 'FEE' | 'TAX'; + status: BrokerResolutionStatus; + targetId?: string; + candidates: { + id: string; + line: number; + isin: string; + kind: string; + date: string; + gross: string; + }[]; +} + +export type BrokerFormat = 'DIRECTA'; +export interface BrokerImportInput { + format: BrokerFormat; + accountId: string; + csv: string; + symbols?: Record; + links?: Record; + excluded?: string[]; + useOperationDate: boolean; + confirmPartial?: boolean; + digest?: string; +} +export type BrokerDiagnosticCode = + | 'UNSUPPORTED' + | 'TAX_UNSUPPORTED' + | 'COST_ASSOCIATION' + | 'INVALID_SOURCE' + | 'INSTRUMENT_CHOICE' + | 'INSTRUMENT_UNRESOLVED' + | 'PROVIDER_UNAVAILABLE' + | 'PROFILE_CONFLICT' + | 'CHANGED_IMPORT' + | 'EXISTING_RECORD' + | 'DATE_POLICY' + | 'PARTIAL_REQUIRED' + | 'LIMIT'; +export interface BrokerPlannedOperation { + id: string; + lines: number[]; + date: string; + valueDates: string[]; + kind: string; + isin: string; + symbol?: string; + gross: string; + fee: string; + tax: string; + net: string; + status: 'IMPORTABLE' | 'BLOCKED' | 'UNSUPPORTED' | 'EXCLUDED' | 'DUPLICATE'; + diagnostics: BrokerDiagnosticCode[]; +} +export interface BrokerImportPreview { + format: BrokerFormat; + digest: string; + rowsRead: number; + duplicates: number; + instruments: BrokerInstrumentResolution[]; + costAssociations: BrokerCostAssociation[]; + operations: BrokerPlannedOperation[]; + errors: BrokerDiagnosticCode[]; + restored?: boolean; + rows: (BrokerSourceRow & { status: BrokerPlannedOperation['status'] })[]; + reconciliation: { + currency: string; + source: string; + imported: string; + duplicates: string; + excluded: string; + unresolved: string; + }[]; + summary: { + recognized: number; + importable: number; + blocked: number; + unsupported: number; + excluded: number; + automatic: number; + confirmed: number; + needsConfirmation: number; + unresolvable: number; + }; +} diff --git a/libs/common/src/lib/interfaces/responses/lookup-response.interface.ts b/libs/common/src/lib/interfaces/responses/lookup-response.interface.ts index 579be9d011..e7e394ca69 100644 --- a/libs/common/src/lib/interfaces/responses/lookup-response.interface.ts +++ b/libs/common/src/lib/interfaces/responses/lookup-response.interface.ts @@ -2,4 +2,5 @@ import { LookupItem } from '../lookup-item.interface'; export interface LookupResponse { items: LookupItem[]; + status?: 'OK' | 'UNAVAILABLE'; } diff --git a/prisma/migrations/20261129000000_added_broker_import_provenance/migration.sql b/prisma/migrations/20261129000000_added_broker_import_provenance/migration.sql new file mode 100644 index 0000000000..a6fbae5e98 --- /dev/null +++ b/prisma/migrations/20261129000000_added_broker_import_provenance/migration.sql @@ -0,0 +1,11 @@ +CREATE TABLE "BrokerImportRecord" ( + "accountId" TEXT NOT NULL, "userId" TEXT NOT NULL, "key" TEXT NOT NULL, + "fingerprint" TEXT NOT NULL, "sourceIdentity" TEXT, "orderId" TEXT, + "outputFingerprint" TEXT NOT NULL, "details" JSONB NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "BrokerImportRecord_pkey" PRIMARY KEY ("accountId","userId","key") +); +CREATE INDEX "BrokerImportRecord_orderId_idx" ON "BrokerImportRecord"("orderId"); +CREATE INDEX "BrokerImportRecord_accountId_userId_sourceIdentity_idx" ON "BrokerImportRecord"("accountId","userId","sourceIdentity"); +ALTER TABLE "BrokerImportRecord" ADD CONSTRAINT "BrokerImportRecord_accountId_userId_fkey" FOREIGN KEY ("accountId","userId") REFERENCES "Account"("id","userId") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "BrokerImportRecord" ADD CONSTRAINT "BrokerImportRecord_orderId_fkey" FOREIGN KEY ("orderId") REFERENCES "Order"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 89bbc12021..d48b5bfda6 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -34,19 +34,20 @@ model Access { } model Account { - activities Order[] - balances AccountBalance[] - comment String? - createdAt DateTime @default(now()) - currency String? - id String @default(uuid()) - 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 + brokerImports BrokerImportRecord[] + activities Order[] + balances AccountBalance[] + comment String? + createdAt DateTime @default(now()) + currency String? + id String @default(uuid()) + 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 @@id([id, userId]) @@index([currency]) @@ -182,24 +183,25 @@ model MarketData { } model Order { - account Account? @relation(fields: [accountId, accountUserId], references: [id, userId]) + brokerImports BrokerImportRecord[] + account Account? @relation(fields: [accountId, accountUserId], references: [id, userId]) accountId String? accountUserId String? comment String? - createdAt DateTime @default(now()) + createdAt DateTime @default(now()) currency String? date DateTime fee Float - id String @id @default(uuid()) + id String @id @default(uuid()) quantity Float symbolProfileId String tags Tag[] type Type unitPrice Float - updatedAt DateTime @updatedAt - user User @relation(fields: [userId], onDelete: Cascade, references: [id]) + updatedAt DateTime @updatedAt + user User @relation(fields: [userId], onDelete: Cascade, references: [id]) userId String - SymbolProfile SymbolProfile @relation(fields: [symbolProfileId], references: [id]) + SymbolProfile SymbolProfile @relation(fields: [symbolProfileId], references: [id]) @@index([accountId]) @@index([date]) @@ -424,3 +426,22 @@ enum ViewMode { DEFAULT ZEN } + +// Deduplication provenance, not a cash ledger. Deleting an activity leaves a tombstone. +model BrokerImportRecord { + account Account @relation(fields: [accountId, userId], references: [id, userId], onDelete: Cascade) + accountId String + userId String + key String + fingerprint String + sourceIdentity String? + order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull) + orderId String? + outputFingerprint String + details Json + createdAt DateTime @default(now()) + + @@id([accountId, userId, key]) + @@index([orderId]) + @@index([accountId, userId, sourceIdentity]) +}