From c2bb39524f602093cf68a7bcd13ff937b83e328d Mon Sep 17 00:00:00 2001 From: Ben Stokes Date: Mon, 23 Nov 2026 15:57:23 +0000 Subject: [PATCH] feat: remove unused operator endpoints --- apps/api/src/modules/Database.ts | 2 +- apps/api/src/modules/OperatorStats.ts | 610 ------------------------- apps/api/src/routes/operator.routes.ts | 107 +---- libs/shared-types/src/lib/Operator.ts | 80 ---- 4 files changed, 3 insertions(+), 796 deletions(-) delete mode 100644 apps/api/src/modules/OperatorStats.ts diff --git a/apps/api/src/modules/Database.ts b/apps/api/src/modules/Database.ts index 7880426..e17c696 100644 --- a/apps/api/src/modules/Database.ts +++ b/apps/api/src/modules/Database.ts @@ -386,7 +386,7 @@ export class Database { * Run a MongoDB aggregation pipeline on a collection. * * Does not strip `_id` — `$group` / `$dateTrunc` pipelines (Reporting, - * OperatorStats, etc.) return the group key on `_id`. + * Telemetry, etc.) return the group key on `_id`. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any async Aggregate(collection: string, pipeline: any[]): Promise { diff --git a/apps/api/src/modules/OperatorStats.ts b/apps/api/src/modules/OperatorStats.ts deleted file mode 100644 index 9f56c2e..0000000 --- a/apps/api/src/modules/OperatorStats.ts +++ /dev/null @@ -1,610 +0,0 @@ -/** - * @fileOverview Operator instance stats - * - * Aggregations for the managed-hosting operator control plane: - * instance summary, per-platform stats, and recent events. - * Reads BalanceTransactions / Accounts / UsageCounters / Events (no writes). - * - * @module OperatorStats - */ - -import { - Event, - OperatorDailyPoint, - OperatorEvent, - OperatorPlatformStats, - OperatorSummary, - QueryOperators, -} from '@zoneless/shared-types'; -import { Database } from './Database'; -import { Now } from '../utils/Timestamp'; -import { ListHelper } from '../utils/ListHelper'; - -const PAYMENT_TYPES = ['payment', 'charge']; -const DEFAULT_EVENT_TYPES = [ - 'payment_intent.succeeded', - 'charge.succeeded', - 'payout.paid', - 'payout.failed', - 'account.created', - 'account.updated', - 'transfer.created', - 'customer.subscription.created', - 'product.created', - 'price.created', - 'payment_link.created', - 'customer.created', -]; - -interface VolumeGroupRow { - _id: string | null; - count: number; - gross: number; -} - -interface DailyVolumeRow { - _id: string; - value: number; -} - -interface CountGroupRow { - _id: string | null; - count: number; -} - -interface LastActivityRow { - _id: string; - last: number; -} - -export interface ListRecentEventsInput { - limit: number; - types?: string[]; - startingAfter?: string; - endingBefore?: string; -} - -export class OperatorStatsModule { - private readonly db: Database; - private readonly eventListHelper: ListHelper; - - constructor(db: Database) { - this.db = db; - this.eventListHelper = new ListHelper(db, { - collection: 'Events', - orderByField: 'created', - orderDirection: 'desc', - urlPath: '/v1/operator/events', - }); - } - - /** - * Instance-wide KPIs and daily volume series for a trailing window. - */ - async GetSummary(days: number): Promise { - const window = WindowBounds(days); - const [ - platforms, - connectedAccounts, - paymentAgg, - payoutAgg, - apiRequests, - volumeByDay, - payoutByDay, - ] = await Promise.all([ - this.CountPlatforms(), - this.CountConnectedAccounts(), - this.AggregatePayments(null, window.start, window.end), - this.AggregatePayouts(null, window.start, window.end), - this.SumApiRequests(null, window.sinceDate), - this.DailySeries('payment', window, days), - this.DailySeries('payout', window, days), - ]); - - return { - object: 'operator_summary', - days, - platforms, - connected_accounts: connectedAccounts, - payment_volume: paymentAgg.gross, - payout_volume: payoutAgg.gross, - payment_count: paymentAgg.count, - api_requests: apiRequests, - volume_by_day: volumeByDay, - payout_by_day: payoutByDay, - }; - } - - /** - * Per-platform stats keyed by platform account ID. - */ - async GetPlatformStatsMap( - days: number - ): Promise> { - const window = WindowBounds(days); - const [ - connectedRows, - paymentRows, - payoutRows, - usageRows, - eventActivity, - btActivity, - ] = await Promise.all([ - this.db.Aggregate('Accounts', [ - { - $match: { - $expr: { $ne: ['$platform_account', '$id'] }, - }, - }, - { - $group: { - _id: '$platform_account', - count: { $sum: 1 }, - }, - }, - ]), - this.db.Aggregate('BalanceTransactions', [ - { - $match: { - type: { $in: PAYMENT_TYPES }, - created: { $gte: window.start, $lt: window.end }, - }, - }, - { - $group: { - _id: '$platform_account', - count: { $sum: 1 }, - gross: { $sum: '$amount' }, - }, - }, - ]), - this.db.Aggregate('BalanceTransactions', [ - { - $match: { - type: 'payout', - created: { $gte: window.start, $lt: window.end }, - }, - }, - { - $group: { - _id: '$platform_account', - count: { $sum: 1 }, - gross: { $sum: { $abs: '$amount' } }, - }, - }, - ]), - this.UsageByPlatform(window.sinceDate), - this.db.Aggregate('Events', [ - { - $group: { - _id: '$platform_account', - last: { $max: '$created' }, - }, - }, - ]), - this.db.Aggregate('BalanceTransactions', [ - { - $group: { - _id: '$platform_account', - last: { $max: '$created' }, - }, - }, - ]), - ]); - - const map = new Map(); - - const Ensure = (platformId: string): OperatorPlatformStats => { - let stats = map.get(platformId); - if (!stats) { - stats = { - connected_accounts: 0, - payment_volume: 0, - payout_volume: 0, - payment_count: 0, - api_requests: 0, - last_activity: null, - }; - map.set(platformId, stats); - } - return stats; - }; - - for (const row of connectedRows) { - if (!row._id) continue; - Ensure(row._id).connected_accounts = row.count; - } - for (const row of paymentRows) { - if (!row._id) continue; - const stats = Ensure(row._id); - stats.payment_volume = row.gross; - stats.payment_count = row.count; - } - for (const row of payoutRows) { - if (!row._id) continue; - Ensure(row._id).payout_volume = row.gross; - } - for (const [platformId, count] of usageRows) { - Ensure(platformId).api_requests = count; - } - for (const row of eventActivity) { - if (!row._id) continue; - const stats = Ensure(row._id); - stats.last_activity = MaxNullable(stats.last_activity, row.last); - } - for (const row of btActivity) { - if (!row._id) continue; - const stats = Ensure(row._id); - stats.last_activity = MaxNullable(stats.last_activity, row.last); - } - - return map; - } - - /** - * Recent events across all platforms (operator activity feed). - * Uses the shared ListHelper cursor pagination (starting_after / ending_before). - */ - async ListRecentEvents( - input: ListRecentEventsInput - ): Promise<{ data: OperatorEvent[]; has_more: boolean }> { - const effectiveTypes = - input.types && input.types.length > 0 ? input.types : DEFAULT_EVENT_TYPES; - const effectiveLimit = Math.min(Math.max(input.limit, 1), 100); - - const result = await this.eventListHelper.List({ - limit: effectiveLimit, - startingAfter: input.startingAfter, - endingBefore: input.endingBefore, - filters: { - type: { - operator: QueryOperators.in, - value: effectiveTypes, - }, - }, - }); - - return { - data: result.data.map(ToOperatorEvent), - has_more: result.has_more, - }; - } - - private async CountPlatforms(): Promise { - const rows = await this.db.Aggregate('Accounts', [ - { - $match: { - $expr: { $eq: ['$platform_account', '$id'] }, - }, - }, - { $group: { _id: null, count: { $sum: 1 } } }, - ]); - return rows[0]?.count ?? 0; - } - - private async CountConnectedAccounts(): Promise { - const rows = await this.db.Aggregate('Accounts', [ - { - $match: { - $expr: { $ne: ['$platform_account', '$id'] }, - }, - }, - { $group: { _id: null, count: { $sum: 1 } } }, - ]); - return rows[0]?.count ?? 0; - } - - private async AggregatePayments( - platformAccountId: string | null, - start: number, - end: number - ): Promise<{ count: number; gross: number }> { - const match: Record = { - type: { $in: PAYMENT_TYPES }, - created: { $gte: start, $lt: end }, - }; - if (platformAccountId) { - match.platform_account = platformAccountId; - } - const rows = await this.db.Aggregate( - 'BalanceTransactions', - [ - { $match: match }, - { - $group: { - _id: null, - count: { $sum: 1 }, - gross: { $sum: '$amount' }, - }, - }, - ] - ); - return { - count: rows[0]?.count ?? 0, - gross: rows[0]?.gross ?? 0, - }; - } - - private async AggregatePayouts( - platformAccountId: string | null, - start: number, - end: number - ): Promise<{ count: number; gross: number }> { - const match: Record = { - type: 'payout', - created: { $gte: start, $lt: end }, - }; - if (platformAccountId) { - match.platform_account = platformAccountId; - } - const rows = await this.db.Aggregate( - 'BalanceTransactions', - [ - { $match: match }, - { - $group: { - _id: null, - count: { $sum: 1 }, - gross: { $sum: { $abs: '$amount' } }, - }, - }, - ] - ); - return { - count: rows[0]?.count ?? 0, - gross: rows[0]?.gross ?? 0, - }; - } - - private async SumApiRequests( - platformAccountId: string | null, - sinceDate: string - ): Promise { - const match: Record = { - date: { $gte: sinceDate }, - }; - if (platformAccountId) { - match.platform_account = platformAccountId; - } - const rows = await this.db.Aggregate('UsageCounters', [ - { $match: match }, - { - $group: { - _id: null, - count: { $sum: '$count' }, - }, - }, - ]); - return rows[0]?.count ?? 0; - } - - private async UsageByPlatform( - sinceDate: string - ): Promise> { - const rows = await this.db.Aggregate('UsageCounters', [ - { $match: { date: { $gte: sinceDate } } }, - { - $group: { - _id: '$platform_account', - count: { $sum: '$count' }, - }, - }, - ]); - const map = new Map(); - for (const row of rows) { - if (!row._id) continue; - map.set(row._id, row.count); - } - return map; - } - - private async DailySeries( - kind: 'payment' | 'payout', - window: { start: number; end: number }, - days: number - ): Promise { - const match = - kind === 'payment' - ? { - type: { $in: PAYMENT_TYPES }, - created: { $gte: window.start, $lt: window.end }, - } - : { - type: 'payout', - created: { $gte: window.start, $lt: window.end }, - }; - const valueExpr = kind === 'payment' ? '$amount' : { $abs: '$amount' }; - - const rows = await this.db.Aggregate( - 'BalanceTransactions', - [ - { $match: match }, - { - $group: { - _id: { - $dateToString: { - format: '%Y-%m-%d', - date: { - $toDate: { $multiply: ['$created', 1000] }, - }, - timezone: 'UTC', - }, - }, - value: { $sum: valueExpr }, - }, - }, - ] - ); - - const byDate = new Map(rows.map((row) => [row._id, row.value])); - return BuildZeroFilledDays(days, byDate); - } -} - -function WindowBounds(days: number): { - start: number; - end: number; - sinceDate: string; -} { - const end = Now(); - const start = end - days * 24 * 60 * 60; - const since = new Date(); - since.setUTCDate(since.getUTCDate() - (days - 1)); - const sinceDate = since.toISOString().slice(0, 10); - return { start, end, sinceDate }; -} - -function BuildZeroFilledDays( - days: number, - byDate: Map -): OperatorDailyPoint[] { - const points: OperatorDailyPoint[] = []; - const cursor = new Date(); - cursor.setUTCHours(0, 0, 0, 0); - cursor.setUTCDate(cursor.getUTCDate() - (days - 1)); - for (let i = 0; i < days; i++) { - const date = cursor.toISOString().slice(0, 10); - points.push({ date, value: byDate.get(date) ?? 0 }); - cursor.setUTCDate(cursor.getUTCDate() + 1); - } - return points; -} - -function MaxNullable(a: number | null, b: number): number { - return a === null ? b : Math.max(a, b); -} - -function ToOperatorEvent(event: Event): OperatorEvent { - const payload = (event.data?.object ?? {}) as Record; - return { - object: 'operator_event', - id: event.id, - type: event.type, - created: event.created, - platform_account: event.platform_account, - amount: ExtractAmount(payload), - summary: SummarizeEvent(event.type, payload), - }; -} - -function ExtractAmount(payload: Record): number | null { - for (const key of [ - 'amount', - 'amount_received', - 'unit_amount', - 'amount_total', - ]) { - const value = payload[key]; - if (typeof value === 'number' && Number.isFinite(value)) { - return Math.abs(value); - } - } - return null; -} - -function SummarizeEvent( - type: string, - payload: Record -): string | null { - if (type.startsWith('customer.subscription')) { - const status = AsString(payload.status); - const id = AsString(payload.id); - return [status, id].filter(Boolean).join(' · ') || null; - } - - const resource = type.split('.')[0]; - - switch (resource) { - case 'product': - return AsString(payload.name); - - case 'price': { - const parts: string[] = []; - const unitAmount = AsNumber(payload.unit_amount); - if (unitAmount !== null) { - parts.push(FormatUsdcCents(unitAmount)); - } - const priceType = AsString(payload.type); - if (priceType === 'recurring') { - const recurring = payload.recurring as - | { interval?: string; interval_count?: number } - | null - | undefined; - const interval = recurring?.interval; - const count = recurring?.interval_count ?? 1; - if (interval) { - parts.push( - count > 1 ? `every ${count} ${interval}s` : `per ${interval}` - ); - } else { - parts.push('recurring'); - } - } else if (priceType === 'one_time') { - parts.push('one-time'); - } - const nickname = AsString(payload.nickname); - if (nickname) parts.push(nickname); - return parts.length ? parts.join(' · ') : null; - } - - case 'customer': - return ( - AsString(payload.email) || - AsString(payload.name) || - AsString(payload.business_name) || - AsString(payload.individual_name) - ); - - case 'payment_link': - return AsString(payload.url) || AsString(payload.id); - - case 'account': { - const parts: string[] = []; - const accountType = AsString(payload.type); - if (accountType && accountType !== 'none') { - parts.push(accountType); - } - const id = AsString(payload.id); - const platformAccount = AsString(payload.platform_account); - if (id && platformAccount && id === platformAccount) { - parts.push('platform'); - } - const name = - AsString( - ( - payload.settings as - | { dashboard?: { display_name?: string } } - | undefined - )?.dashboard?.display_name - ) || - AsString( - (payload.business_profile as { name?: string } | undefined)?.name - ); - if (name) parts.push(name); - else if (id) parts.push(id); - return parts.length ? parts.join(' · ') : null; - } - - case 'payment_intent': - case 'charge': - case 'payout': - case 'transfer': - // Amount is exposed separately on OperatorEvent.amount - return null; - - default: - return AsString(payload.name) || AsString(payload.id) || null; - } -} - -function AsString(value: unknown): string | null { - return typeof value === 'string' && value.trim() ? value.trim() : null; -} - -function AsNumber(value: unknown): number | null { - return typeof value === 'number' && Number.isFinite(value) ? value : null; -} - -function FormatUsdcCents(cents: number): string { - return `${(Math.abs(cents) / 100).toFixed(2)} USDC`; -} diff --git a/apps/api/src/routes/operator.routes.ts b/apps/api/src/routes/operator.routes.ts index c9f622b..8c83a2c 100644 --- a/apps/api/src/routes/operator.routes.ts +++ b/apps/api/src/routes/operator.routes.ts @@ -7,10 +7,8 @@ * when the instance runs in operator mode (OPERATOR_API_KEY set). * * Routes: - * - GET /v1/operator/summary Instance-wide volume/usage KPIs - * - GET /v1/operator/events Recent cross-platform events * - POST /v1/operator/platforms Provision a new platform - * - GET /v1/operator/platforms List platforms (optional stats) + * - GET /v1/operator/platforms List platforms * - GET /v1/operator/platforms/:id Get a platform * - POST /v1/operator/platforms/:id/enable Re-enable a disabled platform * - POST /v1/operator/platforms/:id/disable Disable a platform @@ -39,7 +37,6 @@ import { AccountModule } from '../modules/Account'; import { ApiKeyModule } from '../modules/ApiKey'; import { EventService } from '../modules/EventService'; import { UsageModule } from '../modules/Usage'; -import { OperatorStatsModule } from '../modules/OperatorStats'; import { IsPlatformAccount } from '../modules/PlatformAccess'; import { GetAppConfig, GetJwtSecret } from '../modules/AppConfig'; import { ValidateOperatorKey } from '../middleware/OperatorMiddleware'; @@ -48,7 +45,6 @@ const router = express.Router(); const setupModule = new SetupModule(db); const accountModule = new AccountModule(db); const usageModule = new UsageModule(db); -const operatorStatsModule = new OperatorStatsModule(db); const apiKeyModule = new ApiKeyModule(db, new EventService(db)); // Login links minted by the operator use the same session lifetime as setup @@ -92,78 +88,6 @@ async function GetPlatformOrThrow(accountId: string): Promise { return account; } -function ParseDays(raw: unknown, fallback = 30): number { - return Math.min( - Math.max(parseInt(String(raw ?? ''), 10) || fallback, 1), - 365 - ); -} - -// ───────────────────────────────────────────────────────────────────────────── -// GET /v1/operator/summary - Instance-wide volume / usage KPIs -// ───────────────────────────────────────────────────────────────────────────── -router.get( - '/summary', - AsyncHandler(async (req: express.Request, res: express.Response) => { - const days = ParseDays(req.query.days); - const summary = await operatorStatsModule.GetSummary(days); - res.json(summary); - }) -); - -// ───────────────────────────────────────────────────────────────────────────── -// GET /v1/operator/events - Recent cross-platform events -// ───────────────────────────────────────────────────────────────────────────── -router.get( - '/events', - AsyncHandler(async (req: express.Request, res: express.Response) => { - const limit = Math.min( - Math.max(parseInt(String(req.query.limit ?? ''), 10) || 50, 1), - 100 - ); - const startingAfter = req.query.starting_after as string | undefined; - const endingBefore = req.query.ending_before as string | undefined; - if (startingAfter && endingBefore) { - throw new AppError( - 'You cannot parameterize both starting_after and ending_before.', - 400, - 'invalid_request_error' - ); - } - const types = req.query.types - ? Array.isArray(req.query.types) - ? (req.query.types as string[]) - : String(req.query.types) - .split(',') - .map((type) => type.trim()) - .filter(Boolean) - : undefined; - - try { - const result = await operatorStatsModule.ListRecentEvents({ - limit, - types, - startingAfter, - endingBefore, - }); - res.json({ - object: 'list', - data: result.data, - has_more: result.has_more, - }); - } catch (error: unknown) { - const message = error instanceof Error ? error.message : 'Unknown error'; - if ( - message === 'Invalid starting_after ID' || - message === 'Invalid ending_before ID' - ) { - throw new AppError(message, 400, 'invalid_request_error'); - } - throw error; - } - }) -); - // ───────────────────────────────────────────────────────────────────────────── // POST /v1/operator/platforms - Provision a new platform account // ───────────────────────────────────────────────────────────────────────────── @@ -191,42 +115,15 @@ router.post( // ───────────────────────────────────────────────────────────────────────────── // GET /v1/operator/platforms - List all platform accounts -// Optional: include=stats&days=30 for per-platform volume/usage/activity // ───────────────────────────────────────────────────────────────────────────── router.get( '/platforms', AsyncHandler(async (req: express.Request, res: express.Response) => { const platforms = await accountModule.GetPlatformAccounts(); - const includeStats = String(req.query.include || '') - .split(',') - .map((part) => part.trim()) - .includes('stats'); - - if (!includeStats) { - res.json({ - object: 'list', - data: platforms.map(ToOperatorPlatform), - }); - return; - } - - const days = ParseDays(req.query.days); - const statsMap = await operatorStatsModule.GetPlatformStatsMap(days); - const emptyStats = { - connected_accounts: 0, - payment_volume: 0, - payout_volume: 0, - payment_count: 0, - api_requests: 0, - last_activity: null as number | null, - }; res.json({ object: 'list', - data: platforms.map((platform) => ({ - ...ToOperatorPlatform(platform), - stats: statsMap.get(platform.id) ?? emptyStats, - })), + data: platforms.map(ToOperatorPlatform), }); }) ); diff --git a/libs/shared-types/src/lib/Operator.ts b/libs/shared-types/src/lib/Operator.ts index feee88c..7f7a2c0 100644 --- a/libs/shared-types/src/lib/Operator.ts +++ b/libs/shared-types/src/lib/Operator.ts @@ -8,24 +8,6 @@ * @zoneless_extension */ -/** - * Per-platform activity stats for a trailing window (amounts in cents). - */ -export interface OperatorPlatformStats { - /** Connected accounts under this platform */ - connected_accounts: number; - /** Settled payment/charge volume in the window (cents) */ - payment_volume: number; - /** Absolute payout outflow in the window (cents) */ - payout_volume: number; - /** Count of payment/charge balance transactions */ - payment_count: number; - /** Metered API-key requests in the window */ - api_requests: number; - /** Max Event or BalanceTransaction created timestamp, or null if none */ - last_activity: number | null; -} - /** * Summary of a platform account returned by the operator API. */ @@ -39,8 +21,6 @@ export interface OperatorPlatform { created: number; /** True if the operator has disabled this platform */ disabled: boolean; - /** Present when GET /platforms is called with include=stats */ - stats?: OperatorPlatformStats; } /** @@ -87,63 +67,3 @@ export interface OperatorUsage { /** Total requests across the returned window */ total: number; } - -/** - * One day in an operator summary time series (UTC). - */ -export interface OperatorDailyPoint { - /** Day in YYYY-MM-DD format (UTC) */ - date: string; - /** Aggregated value for the day (cents for volume series, count for count series) */ - value: number; -} - -/** - * Instance-wide summary from GET /v1/operator/summary. - * Amounts are exact cents (not telemetry buckets). - */ -export interface OperatorSummary { - object: 'operator_summary'; - /** Trailing window length in days */ - days: number; - /** Platform (root) account count */ - platforms: number; - /** Connected account count across all platforms */ - connected_accounts: number; - /** Settled payment/charge volume in the window (cents) */ - payment_volume: number; - /** Absolute payout outflow in the window (cents) */ - payout_volume: number; - /** Count of payment/charge balance transactions */ - payment_count: number; - /** Metered API-key requests in the window */ - api_requests: number; - /** Daily payment volume (oldest → newest, zero-filled) */ - volume_by_day: OperatorDailyPoint[]; - /** Daily absolute payout volume (oldest → newest, zero-filled) */ - payout_by_day: OperatorDailyPoint[]; -} - -/** - * Slim event row for operator activity feeds. - */ -export interface OperatorEvent { - object: 'operator_event'; - id: string; - type: string; - created: number; - platform_account: string; - /** Best-effort amount in cents from the event payload, if present */ - amount: number | null; - /** Short human-readable detail derived from the event payload */ - summary: string | null; -} - -/** - * Response from GET /v1/operator/events - */ -export interface OperatorEventList { - object: 'list'; - data: OperatorEvent[]; - has_more: boolean; -}