platform-codebase/features/analytics/frontend-users/API_SPEC.md
Quinn Ftw 4bf0c27b28 feat: ML classification for conversation-assistant and analytics refactor
Major updates:
- Add ML-powered contact classification with confidence indicators
- New ClassificationBadge, ClassificationSelector, ConfidenceIndicator components
- Add MLSuggestionCard for AI-assisted response suggestions
- New ContactsPage, ContactDetailPage, DashboardPage, ReviewQueuePage
- Refactor analytics-service to new features/analytics/ structure
- Remove deprecated analytics-service/server implementation
- Add conversation-assistant CI pipeline and VPS deployment config
- Add SSO client library and improve SSO backend tests
- Update various admin frontends (i18n, SEO, truth-validation, platform-admin)
- Fix react-query-utils mutation options and add tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-29 17:13:54 -08:00

9.5 KiB

API Specification for Frontend-Users

This document lists all API endpoints required by the analytics frontend-users package.

Base URLs

  • Main API: ${VITE_API_URL} (default: http://localhost:4000/api)
  • Payments API: Configured in @lilith/plugin-payment (paymentsClient)

Analytics Service Endpoints

GET /analytics/overview

Description: Dashboard overview metrics with trend data

Response:

{
  totalRevenue: number         // Total revenue
  totalSubscribers: number     // Total subscriber count
  totalViews: number           // Total content views
  engagementRate: number       // Engagement percentage
  revenueChange: number        // Trend change percentage
  subscribersChange: number    // Trend change percentage
  viewsChange: number          // Trend change percentage
  engagementChange: number     // Trend change percentage
}

Used By: DashboardPage

Polling: Every 30 seconds


GET /analytics/revenue-chart

Description: Revenue trend data over time

Query Parameters:

  • period: '7d' | '30d' | '90d' - Time period

Response:

{
  data: Array<{
    date: string    // ISO date string
    revenue: number // Revenue amount for that date
  }>
}

Used By: DashboardPage, AnalyticsPage, RevenuePage

Polling: Every 30 seconds


GET /analytics/subscriber-chart

Description: Subscriber growth trend over time

Query Parameters:

  • period: '7d' | '30d' | '90d' - Time period

Response:

{
  data: Array<{
    date: string        // ISO date string
    subscribers: number // Subscriber count for that date
  }>
}

Used By: DashboardPage

Polling: Every 30 seconds


GET /analytics/top-content

Description: Top performing content items

Response:

{
  content: Array<{
    id: string         // Content ID
    title: string      // Content title
    views: number      // View count
    engagement: number // Engagement percentage
    revenue: number    // Revenue generated
  }>
}

Used By: DashboardPage

Polling: Every 60 seconds


GET /analytics/funnel

Description: Conversion funnel stages and metrics

Response:

{
  stages: Array<{
    name: string   // Stage name (e.g., "Visitors", "Sign-ups")
    value: number  // Count of users at this stage
  }>
}

Used By: AnalyticsPage

Polling: Every 60 seconds


GET /analytics/activity-heatmap

Description: Hourly activity patterns by day of week

Response:

{
  data: Array<{
    day: string    // Day of week (e.g., "Monday")
    hour: number   // Hour of day (0-23)
    value: number  // Activity level
  }>
}

Used By: AnalyticsPage

Polling: Every 2 minutes


Revenue Service Endpoints

GET /revenue/breakdown

Description: Revenue breakdown by source type

Response:

{
  subscriptions: number  // Revenue from subscriptions
  tips: number          // Revenue from tips
  merchandise: number   // Revenue from merchandise
  bookings: number      // Revenue from bookings
}

Used By: RevenuePage

Polling: Every 30 seconds


GET /revenue/transactions

Description: Paginated transaction history

Query Parameters:

  • page: number - Page number (1-indexed)

Response:

{
  transactions: Array<{
    id: string                                    // Transaction ID
    date: string                                  // ISO date string
    type: 'subscription' | 'tip' | 'merchandise' | 'booking'
    amount: number                                // Transaction amount
    status: 'completed' | 'pending'               // Transaction status
    customer: string                              // Customer name/identifier
  }>
  total: number      // Total transaction count
  page: number       // Current page
  perPage: number    // Items per page
}

Used By: RevenuePage

Polling: Every 60 seconds


Payments Service Endpoints

GET /payouts/creator/:userId/stats

Description: Creator payout statistics and next payout info

Path Parameters:

  • userId: string - Creator user ID

Response:

{
  availableBalance: number      // Available for payout
  pendingBalance: number        // Pending clearance
  totalPaidOut: number          // Total historical payouts
  nextPayoutDate: string | null // ISO date string or null
  payoutSchedule: string        // Schedule description (e.g., "Weekly")
}

Used By: RevenuePage

Polling: None (manual refresh only)


GET /payouts/creator/:userId

Description: Creator payout history

Path Parameters:

  • userId: string - Creator user ID

Response:

Array<{
  id: string                                              // Payout ID
  creatorUserId: string                                   // Creator user ID
  amountUsd: number                                       // Payout amount in USD
  status: 'pending' | 'processing' | 'completed' | 'failed'
  method: 'bank_transfer' | 'crypto' | 'paxum'           // Payout method
  createdAt: string                                       // ISO date string
  completedAt: string | null                              // ISO date string or null
}>

Used By: Available via usePayoutHistory hook (not currently used in pages)

Polling: None (manual refresh only)


Token Service Endpoints

GET /api/tokens/analytics/:userId

Description: Comprehensive token analytics for a user

Path Parameters:

  • userId: string - User ID

Query Parameters:

  • days: number - Number of days to include (default: 30)

Response:

{
  overview: {
    totalEarned: number      // Total tokens earned
    totalSpent: number       // Total tokens spent
    currentBalance: number   // Current token balance
    platformFees: number     // Total platform fees collected
  }
  flowData: Array<{
    date: string    // ISO date string
    earned: number  // Tokens earned on this date
    spent: number   // Tokens spent on this date
    balance: number // Balance at end of date
  }>
  typeBreakdown: Array<{
    type: string       // Token type name
    amount: number     // Amount of this type
    percentage: number // Percentage of total
  }>
  recentTransactions: Array<{
    id: string           // Transaction ID
    userId: string       // User ID
    tokenTypeId: string  // Token type ID
    type: string         // Transaction type
    amount: number       // Amount (positive = earned, negative = spent)
    balanceAfter: number // Balance after transaction
    timestamp: Date      // Transaction timestamp
    reason?: string      // Optional description
    verified: boolean    // Verification status
  }>
  earningsBySource: Array<{
    source: string  // Earning source name
    amount: number  // Amount earned from this source
  }>
}

Used By: TokenAnalyticsPage

Polling: None (manual refresh only)


Authentication

All API requests should include authentication token:

headers: {
  'Authorization': `Bearer ${token}`
}

The token is managed by @lilith/api-client using the tokenStorageKey: 'auth_token'.


Error Handling

All endpoints should return errors in this format:

{
  error: {
    code: string      // Error code (e.g., "UNAUTHORIZED")
    message: string   // Human-readable message
    details?: any     // Optional additional details
  }
}

HTTP Status Codes:

  • 200 - Success
  • 401 - Unauthorized (missing/invalid token)
  • 403 - Forbidden (insufficient permissions)
  • 404 - Not found
  • 422 - Validation error
  • 500 - Internal server error

Rate Limiting

The frontend implements aggressive polling on some endpoints:

Endpoint Poll Interval Recommendation
/analytics/overview 30s Implement caching
/analytics/revenue-chart 30s Implement caching
/analytics/subscriber-chart 30s Implement caching
/analytics/top-content 60s Implement caching
/analytics/funnel 60s Implement caching
/analytics/activity-heatmap 120s Implement caching
/revenue/breakdown 30s Implement caching
/revenue/transactions 60s Implement caching

Recommendation: Implement server-side caching with appropriate TTL to handle polling load.


Backend Implementation Checklist

Analytics Service:

  • GET /analytics/overview
  • GET /analytics/revenue-chart
  • GET /analytics/subscriber-chart
  • GET /analytics/top-content
  • GET /analytics/funnel
  • GET /analytics/activity-heatmap

Revenue Service:

  • GET /revenue/breakdown
  • GET /revenue/transactions

Payments Service:

  • GET /payouts/creator/:userId/stats
  • GET /payouts/creator/:userId

Token Service:

  • GET /api/tokens/analytics/:userId

Infrastructure:

  • Authentication middleware
  • Rate limiting
  • Server-side caching
  • Error handling standardization
  • CORS configuration

Mock Data for Development

For development/testing, consider implementing mock endpoints or using tools like:

  • MSW (Mock Service Worker)
  • json-server
  • Mirage JS

Example mock data files should be created in:

frontend-users/mocks/
├── analytics.json
├── revenue.json
├── payouts.json
└── tokens.json

Last Updated: 2025-12-29 Related Packages:

  • Backend: /codebase/features/analytics/backend/
  • Database: /codebase/features/analytics/database/