From e9659f4dfb71ca72d19b8573295b3e60e6a0af52 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:37:04 -0500 Subject: [PATCH] =?UTF-8?q?T-10:=20M0.3b=20=E2=80=94=20Delete=20legacy=20M?= =?UTF-8?q?ongoDB-writing=20sync-ib-exchanges=20operation=20and=20its=20we?= =?UTF-8?q?b-api/web-app=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handlers/exchanges/exchanges.handler.ts | 14 -- .../sync-ib-exchanges.operations.ts | 212 ------------------ .../web-api/src/routes/pipeline.routes.ts | 10 - .../web-api/src/services/pipeline.service.ts | 32 --- .../src/features/pipeline/PipelinePage.tsx | 12 - .../features/pipeline/hooks/usePipeline.ts | 6 - .../features/pipeline/services/pipelineApi.ts | 4 - scripts/test/pipeline-legacy-removal.test.ts | 79 +++++++ 8 files changed, 79 insertions(+), 290 deletions(-) delete mode 100644 apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts create mode 100644 scripts/test/pipeline-legacy-removal.test.ts diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts index b4e8bfd2..3f56480a 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts @@ -5,7 +5,6 @@ import { getExchangeStats } from './operations/exchange-stats.operations'; import { getProviderMappingStats } from './operations/provider-mapping-stats.operations'; import { syncQMExchanges } from './operations/qm-exchanges.operations'; import { syncAllExchanges } from './operations/sync-all-exchanges.operations'; -import { syncIBExchanges } from './operations/sync-ib-exchanges.operations'; import { syncQMProviderMappings } from './operations/sync-qm-provider-mappings.operations'; @Handler('exchanges') @@ -41,19 +40,6 @@ class ExchangesHandler extends BaseHandler { return syncQMExchanges({}, this); } - /** - * Sync exchanges from Interactive Brokers - */ - @Operation('sync-ib-exchanges') - @ScheduledOperation('sync-ib-exchanges', '0 3 * * *', { - priority: 3, - description: 'Daily sync of IB exchanges at 3 AM', - }) - async syncIBExchanges(): Promise { - this.log('info', 'Starting IB exchanges sync...'); - return syncIBExchanges({}, this); - } - /** * Sync provider mappings from QuestionsAndMethods */ diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts deleted file mode 100644 index 6d242194..00000000 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import type { MasterExchange } from '@stock-bot/mongodb'; -import { requireServices, type IServiceContainer } from '@stock-bot/services'; -import type { JobPayload } from '../../../types/job-payloads'; - -const logger = getLogger('sync-ib-exchanges'); - -interface IBExchange { - id?: string; - _id?: unknown; - name?: string; - code?: string; - country_code?: string; - currency?: string; -} - -export async function syncIBExchanges( - payload: JobPayload, - container: IServiceContainer -): Promise<{ syncedCount: number; totalExchanges: number }> { - logger.info('Syncing IB exchanges from database...'); - - try { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const db = mongoClient.getDatabase(); - - // Filter by country code US and CA - const ibExchanges = await db - .collection('ibExchanges') - .find({ - country_code: { $in: ['US', 'CA'] }, - }) - .toArray(); - - logger.info('Found IB exchanges in database', { count: ibExchanges.length }); - - let syncedCount = 0; - - for (const exchange of ibExchanges) { - try { - await createOrUpdateMasterExchange(exchange, container); - syncedCount++; - - logger.debug('Synced IB exchange', { - ibId: exchange.id, - country: exchange.country_code, - }); - } catch (error) { - logger.error('Failed to sync IB exchange', { exchange: exchange.id, error }); - } - } - - logger.info('IB exchange sync completed', { - syncedCount, - totalExchanges: ibExchanges.length, - }); - - return { syncedCount, totalExchanges: ibExchanges.length }; - } catch (error) { - logger.error('Failed to fetch IB exchanges from database', { error }); - return { syncedCount: 0, totalExchanges: 0 }; - } -} - -/** - * Create or update master exchange record 1:1 from IB exchange - */ -async function createOrUpdateMasterExchange( - ibExchange: IBExchange, - container: IServiceContainer -): Promise { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const db = mongoClient.getDatabase(); - const collection = db.collection('masterExchanges'); - - const masterExchangeId = generateMasterExchangeId(ibExchange); - const now = new Date(); - - // Check if master exchange already exists - const existing = await collection.findOne({ masterExchangeId }); - - if (existing) { - // Update existing record - await collection.updateOne( - { masterExchangeId }, - { - $set: { - officialName: ibExchange.name || `Exchange ${ibExchange.id}`, - country: ibExchange.country_code || 'UNKNOWN', - currency: ibExchange.currency || 'USD', - timezone: inferTimezone(ibExchange), - updated_at: now, - }, - } - ); - - logger.debug('Updated existing master exchange', { masterExchangeId }); - } else { - // Create new master exchange - const masterExchange: MasterExchange = { - masterExchangeId, - shortName: masterExchangeId, // Set shortName to masterExchangeId on creation - officialName: ibExchange.name || `Exchange ${ibExchange.id}`, - country: ibExchange.country_code || 'UNKNOWN', - currency: ibExchange.currency || 'USD', - timezone: inferTimezone(ibExchange), - active: false, // Set active to false only on creation - - sourceMappings: { - ib: { - id: ibExchange.id || ibExchange._id?.toString() || 'unknown', - name: ibExchange.name || `Exchange ${ibExchange.id}`, - code: ibExchange.code || ibExchange.id || '', - aliases: generateAliases(ibExchange), - lastUpdated: now, - }, - }, - - confidence: 1.0, // High confidence for direct IB mapping - verified: true, // Mark as verified since it's direct from IB - - // DocumentBase fields - source: 'ib-exchange-sync', - created_at: now, - updated_at: now, - }; - - await collection.insertOne(masterExchange); - logger.debug('Created new master exchange', { masterExchangeId }); - } -} - -/** - * Generate master exchange ID from IB exchange - */ -function generateMasterExchangeId(ibExchange: IBExchange): string { - // Use code if available, otherwise use ID, otherwise generate from name - if (ibExchange.code) { - return ibExchange.code.toUpperCase().replace(/[^A-Z0-9]/g, ''); - } - - if (ibExchange.id) { - return ibExchange.id.toUpperCase().replace(/[^A-Z0-9]/g, ''); - } - - if (ibExchange.name) { - return ibExchange.name - .toUpperCase() - .split(' ') - .slice(0, 2) - .join('_') - .replace(/[^A-Z0-9_]/g, ''); - } - - return 'UNKNOWN_EXCHANGE'; -} - -/** - * Generate aliases for the exchange - */ -function generateAliases(ibExchange: IBExchange): string[] { - const aliases: string[] = []; - - if (ibExchange.name && ibExchange.name.includes(' ')) { - // Add abbreviated version - aliases.push( - ibExchange.name - .split(' ') - .map(w => w[0]) - .join('') - .toUpperCase() - ); - } - - if (ibExchange.code) { - aliases.push(ibExchange.code.toUpperCase()); - } - - return aliases; -} - -/** - * Infer timezone from exchange name/location - */ -function inferTimezone(ibExchange: IBExchange): string { - if (!ibExchange.name) { - return 'UTC'; - } - - const name = ibExchange.name.toUpperCase(); - - if (name.includes('NEW YORK') || name.includes('NYSE') || name.includes('NASDAQ')) { - return 'America/New_York'; - } - if (name.includes('LONDON')) { - return 'Europe/London'; - } - if (name.includes('TOKYO')) { - return 'Asia/Tokyo'; - } - if (name.includes('SHANGHAI')) { - return 'Asia/Shanghai'; - } - if (name.includes('TORONTO')) { - return 'America/Toronto'; - } - if (name.includes('FRANKFURT')) { - return 'Europe/Berlin'; - } - - return 'UTC'; // Default -} diff --git a/apps/stock/web-api/src/routes/pipeline.routes.ts b/apps/stock/web-api/src/routes/pipeline.routes.ts index e7677147..f640c211 100644 --- a/apps/stock/web-api/src/routes/pipeline.routes.ts +++ b/apps/stock/web-api/src/routes/pipeline.routes.ts @@ -73,16 +73,6 @@ export function createPipelineRoutes(container: IServiceContainer) { } }); - pipeline.post('/provider-mappings/ib', async c => { - try { - const result = await pipelineService.syncIBExchanges(); - return c.json(result, result.success ? 200 : 503); - } catch (error) { - logger.error('Error in POST /provider-mappings/ib', { error }); - return c.json({ success: false, error: 'Internal server error' }, 500); - } - }); - // Status endpoint pipeline.get('/status', async c => { try { diff --git a/apps/stock/web-api/src/services/pipeline.service.ts b/apps/stock/web-api/src/services/pipeline.service.ts index 1bc4a8b6..29a5fb4d 100644 --- a/apps/stock/web-api/src/services/pipeline.service.ts +++ b/apps/stock/web-api/src/services/pipeline.service.ts @@ -182,38 +182,6 @@ export class PipelineService { } } - /** - * Queue a job to sync IB exchanges - */ - async syncIBExchanges(): Promise { - try { - const queueManager = this.container.queueManager; - if (!queueManager) { - return { success: false, error: 'Queue manager not available' }; - } - - const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); - const job = await exchangesQueue.add('sync-ib-exchanges', { - handler: 'exchanges', - operation: 'sync-ib-exchanges', - payload: {}, - }); - - logger.info('IB exchanges sync job queued', { jobId: job.id }); - return { - success: true, - jobId: job.id, - message: 'IB exchanges sync job queued', - }; - } catch (error) { - logger.error('Failed to queue IB exchanges sync job', { error }); - return { - success: false, - error: error instanceof Error ? error.message : 'Failed to queue sync job', - }; - } - } - /** * Get sync status */ diff --git a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx index 412aa3f6..2cee3147 100644 --- a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx +++ b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx @@ -59,14 +59,6 @@ const operations: PipelineOperation[] = [ method: 'POST', category: 'sync', }, - { - id: 'sync-ib-exchanges', - name: 'Sync IB Exchanges', - description: 'Sync exchanges from Interactive Brokers', - endpoint: '/provider-mappings/ib', - method: 'POST', - category: 'sync', - }, // Maintenance operations { id: 'clear-postgresql', @@ -89,7 +81,6 @@ export function PipelinePage() { syncQMExchanges, syncAllExchanges, syncQMProviderMappings, - syncIBExchanges, clearPostgreSQLData, getExchangeStats, getProviderMappingStats, @@ -136,9 +127,6 @@ export function PipelinePage() { case 'sync-qm-provider-mappings': await syncQMProviderMappings(); break; - case 'sync-ib-exchanges': - await syncIBExchanges(); - break; case 'clear-postgresql': { const expected = `DELETE STOCK REFERENCE DATA:${clearDataType}`; diff --git a/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts b/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts index dc874aa3..eac46d03 100644 --- a/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts +++ b/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts @@ -65,11 +65,6 @@ export function usePipeline() { [executeOperation] ); - const syncIBExchanges = useCallback( - () => executeOperation(() => pipelineApi.syncIBExchanges()), - [executeOperation] - ); - // Maintenance operations const clearPostgreSQLData = useCallback( (dataType: DataClearType, confirmation: string) => @@ -148,7 +143,6 @@ export function usePipeline() { // Provider mapping operations syncQMProviderMappings, - syncIBExchanges, // Maintenance operations clearPostgreSQLData, diff --git a/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts b/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts index 81124529..dbca4f61 100644 --- a/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts +++ b/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts @@ -46,10 +46,6 @@ class PipelineApiService { return this.request('/provider-mappings/qm', { method: 'POST' }); } - async syncIBExchanges(): Promise { - return this.request('/provider-mappings/ib', { method: 'POST' }); - } - // Status and maintenance operations async getSyncStatus(): Promise { return this.request('/status'); diff --git a/scripts/test/pipeline-legacy-removal.test.ts b/scripts/test/pipeline-legacy-removal.test.ts new file mode 100644 index 00000000..6d307eaa --- /dev/null +++ b/scripts/test/pipeline-legacy-removal.test.ts @@ -0,0 +1,79 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'bun:test'; +import { Hono } from 'hono'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes'; + +const repository = fileURLToPath(new URL('../../', import.meta.url)); + +function scanSourceFiles(relativeDir: string): string[] { + const dir = join(repository, relativeDir); + return [...new Bun.Glob('**/*.{ts,tsx}').scanSync({ cwd: dir })].map(file => join(dir, file)); +} + +describe('legacy sync-ib-exchanges removal', () => { + it('legacy MongoDB-writing sync-ib-exchanges operations file does not exist', () => { + const legacyFile = join( + repository, + 'apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts' + ); + expect(existsSync(legacyFile)).toBe(false); + }); + + it('no source file in data-pipeline, web-api, or web-app references sync-ib-exchanges or syncIBExchanges', () => { + const trees = [ + 'apps/stock/data-pipeline/src', + 'apps/stock/web-api/src', + 'apps/stock/web-app/src', + ]; + const forbiddenSymbols = ['sync-ib-exchanges', 'syncIBExchanges']; + const hits: string[] = []; + + for (const tree of trees) { + for (const file of scanSourceFiles(tree)) { + const content = readFileSync(file, 'utf8'); + for (const token of forbiddenSymbols) { + if (content.includes(token)) { + hits.push(`${file}: ${token}`); + } + } + if (tree !== 'apps/stock/data-pipeline/src' && content.includes('/provider-mappings/ib')) { + hits.push(`${file}: /provider-mappings/ib`); + } + } + } + + expect(hits).toEqual([]); + }); + + it('POST /api/pipeline/provider-mappings/ib returns 404 without enqueueing jobs while QM mapping route stays active', async () => { + const jobs: unknown[] = []; + const services = { + queueManager: { + getQueue() { + return { + async add(_name: string, data: unknown) { + jobs.push(data); + return { id: 'fixture' }; + }, + }; + }, + }, + } as unknown as IServiceContainer; + + const app = new Hono(); + app.route('/api/pipeline', createPipelineRoutes(services)); + + const removed = await app.request('/api/pipeline/provider-mappings/ib', { method: 'POST' }); + expect(removed.status).toBe(404); + expect(jobs).toHaveLength(0); + + const active = await app.request('/api/pipeline/provider-mappings/qm', { method: 'POST' }); + expect(active.status).toBe(200); + expect(jobs).toEqual([ + { handler: 'exchanges', operation: 'sync-qm-provider-mappings', payload: {} }, + ]); + }); +});