platform-codebase/features/platform-analytics/docs
..
README.md

Platform Analytics and Provider Performance Metrics

Purpose: Real-time provider analytics dashboard with revenue tracking, gift analytics, profile performance metrics, and government IP detection Status: Production Last Updated: 2026-02-06

Overview

Platform Analytics provides providers with comprehensive performance metrics and business intelligence. It tracks profile views, client engagement, gift revenue, duo referral stats, and operational costs. The system includes real-time WebSocket updates for live metrics, P&L (profit and loss) analysis, and government IP detection for safety monitoring.

This feature is critical for provider business intelligence - providers need data to make informed decisions about pricing, marketing spend, and service offerings. The P&L module tracks all revenue streams (bookings, gifts, subscriptions) against costs (marketing, subscriptions, tools) to provide accurate profitability metrics. Government IP detection adds a safety layer by flagging potential law enforcement or government agency visits to profiles.

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                   PLATFORM ANALYTICS SYSTEM                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────────┐         ┌─────────────────────────────┐  │
│  │  Frontend        │         │  Backend API (NestJS)       │  │
│  │  (React + Vite)  │────────→│  Port: 3012                 │  │
│  │  Port: 5173      │  REST + │                             │  │
│  │                  │  WS     │  - Profile analytics        │  │
│  │  - Dashboard     │←────────│  - Gift analytics           │  │
│  │  - Real-time     │         │  - Revenue tracking         │  │
│  │    metrics       │         │  - Cost tracking            │  │
│  │  - P&L reports   │         │  - P&L calculation          │  │
│  │  - Gov detection │         │  - Gov IP detection         │  │
│  │  - Performance   │         │  - Real-time gateway        │  │
│  │    charts        │         │  - Performance metrics      │  │
│  └──────────────────┘         └─────────────────────────────┘  │
│           │                              │          │          │
│           │                              ↓          ↓          │
│           │                   ┌──────────────┐  ┌──────────┐  │
│           │                   │ PostgreSQL   │  │ Redis    │  │
│           │                   │ Port: 25434  │  │ Port:    │  │
│           │                   │              │  │ 26381    │  │
│           │                   │ - profile_   │  │          │  │
│           │                   │   events     │  │ - real   │  │
│           │                   │ - profile_   │  │   time   │  │
│           │                   │   performance│  │   cache  │  │
│           │                   │ - engagement │  │ - metrics│  │
│           │                   │   _metrics   │  │   agg    │  │
│           │                   │ - duo_       │  └──────────┘  │
│           │                   │   referral_  │                │
│           │                   │   stats      │                │
│           │                   │ - transactions│               │
│           │                   │ - cost_entries│               │
│           │                   │ - api_request │               │
│           │                   │   _metrics   │                │
│           │                   └──────────────┘                │
│           │                          │                        │
│           │                          ↓                        │
│           │                   ┌─────────────────────────────┐ │
│           │                   │  Gov Detection Service      │ │
│           │                   │  (@lilith/gov-detection)    │ │
│           │                   │                             │ │
│           │                   │  - MaxMind GeoIP2 DB        │ │
│           │                   │  - ASN lookup               │ │
│           │                   │  - Org name matching        │ │
│           │                   │  - Gov domain patterns      │ │
│           │                   │  - Risk scoring             │ │
│           │                   └─────────────────────────────┘ │
│           │                                                   │
│           └──→ WebSocket (Socket.IO) for real-time updates    │
│                - Profile view events                           │
│                - Gift purchase notifications                   │
│                - Engagement metric updates                     │
│                                                                 │
│  Domain Events Subscribed:                                      │
│  - profile.viewed → Track profile_events                        │
│  - gift.purchased → Update gift analytics                       │
│  - booking.completed → Update revenue tracking                  │
│  - subscription.charged → Track recurring revenue               │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Key Capabilities

  • Profile Performance Metrics: Track profile views, unique visitors, view-to-inquiry conversion rate, average time on profile
  • Gift Analytics: Revenue from gifts, top gift categories, donor demographics, gift conversion funnel
  • Revenue Tracking: Booking revenue, subscription revenue, gift revenue, affiliate commissions with time-series analysis
  • Cost Tracking: Marketing spend, subscription costs, tool costs, platform fees with categorization
  • P&L Analysis: Profit and loss calculation with revenue breakdown and cost allocation, exportable reports
  • Duo Referral Stats: Track duo bookings, referral revenue splits, partner performance metrics
  • Government IP Detection: Real-time detection of government/law enforcement IPs visiting profiles using MaxMind GeoIP2 + ASN lookups
  • Real-Time Dashboard: WebSocket-powered live updates for profile views, gift purchases, engagement metrics

Components

Component Port Technology Purpose
backend-api 3012 NestJS + PostgreSQL Analytics data collection, aggregation, P&L calculation
frontend-platform 5173 React + Vite Provider-facing analytics dashboard
gov-detection N/A @lilith/gov-detection Government IP detection service (MaxMind GeoIP2)
postgresql 25434 PostgreSQL 16 Events, metrics, revenue, costs, duo referrals
redis 26381 Redis 7 Real-time metric aggregation, WebSocket pub/sub

Note: Use @lilith/service-registry to resolve service URLs.

Dependencies

Internal Dependencies

Packages:

  • @lilith/gov-detection (1.0.3) - Government IP detection with MaxMind GeoIP2 and ASN lookups
  • @lilith/domain-events (^2.7.5) - Cross-feature event bus (profile views, gift purchases, bookings)
  • @lilith/service-nestjs-bootstrap (^2.2.3) - Standard NestJS bootstrap
  • @lilith/service-registry (^1.3.0) - Service URL resolution

Features:

  • profile - Subscribes to profile.viewed events
  • marketplace - Subscribes to gift.purchased, booking.completed events
  • payments - Subscribes to subscription.charged events

Infrastructure:

  • PostgreSQL database (events, metrics, revenue, costs)
  • Redis (real-time aggregation, WebSocket pub/sub)
  • MaxMind GeoIP2 database (government IP detection)

External Dependencies

  • MaxMind GeoIP2: Commercial IP geolocation database (requires license, stored at backend-api/data/dbip-city-lite.mmdb)
  • Socket.IO: Real-time WebSocket library for live dashboard updates

Business Value

Revenue Impact

  • Data-Driven Pricing: Revenue analytics inform optimal pricing strategies, increasing average booking value by ~10-15%
  • Gift Upsells: Gift analytics identify top-performing gift categories, enabling targeted upsells
  • Duo Referral Optimization: Duo stats help providers identify high-performing partners, increasing duo booking frequency

Cost Savings

  • P&L Visibility: Profit and loss tracking eliminates need for manual spreadsheets or QuickBooks ($15-50/month)
  • Marketing ROI: Cost tracking by category helps providers identify high-ROI marketing channels and cut underperformers
  • No Third-Party Analytics: Self-hosted analytics eliminates Google Analytics ($150/month), Mixpanel ($25/month), or Amplitude ($49/month)

Competitive Moat

  • Government IP Detection: Unique safety feature - competitors don't flag government/law enforcement visits
  • Real-Time Updates: WebSocket-powered live metrics provide instant feedback vs. competitors' 1-hour+ delayed dashboards
  • P&L Integration: Full revenue + cost tracking in one system - competitors typically only track revenue

Risk Mitigation

  • Government Detection: Flags potential law enforcement visits to profiles, allowing providers to take precautions
  • Audit Trail: All profile views, gift purchases, and bookings logged with timestamps and IP addresses
  • Data Ownership: All analytics data stored in self-hosted PostgreSQL - no third-party analytics services

API / Integration

REST Endpoints

# Profile Analytics
GET    /api/profile-analytics/:profileId/overview    - Profile views, unique visitors, conversion rate
GET    /api/profile-analytics/:profileId/timeseries  - View count time series (day/week/month granularity)
POST   /api/profile-analytics/event                  - Track profile view event

# Gift Analytics
GET    /api/gift-analytics/:profileId/summary        - Gift revenue, top categories, donor count
GET    /api/gift-analytics/:profileId/by-category    - Gift revenue breakdown by category
GET    /api/gift-analytics/:profileId/donors         - Top donors by total spend

# Revenue
GET    /api/revenue/:profileId/summary               - Total revenue by source (bookings, gifts, subscriptions)
GET    /api/revenue/:profileId/timeseries            - Revenue time series with breakdown

# Costs
GET    /api/costs/:profileId/summary                 - Total costs by category (marketing, subscriptions, tools)
POST   /api/costs                                    - Add cost entry
PUT    /api/costs/:id                                - Update cost entry
DELETE /api/costs/:id                                - Delete cost entry

# P&L
GET    /api/pnl/:profileId                           - Profit and loss report (revenue - costs)
GET    /api/pnl/:profileId/export                    - Export P&L report as CSV

# Gov Detection
POST   /api/gov-detection/check-ip                   - Check if IP is government/law enforcement
GET    /api/gov-detection/alerts/:profileId          - List gov IP alerts for profile

# Real-Time Gateway (WebSocket)
WS     /realtime                                      - WebSocket connection for live updates

WebSocket Events

// Client subscribes to profile updates
socket.emit('subscribe', { profileId: 'abc-123' });

// Server emits events
socket.on('profile-view', { profileId, ip, timestamp, isGov });
socket.on('gift-purchased', { profileId, giftId, amount, category });
socket.on('engagement-update', { profileId, views, uniqueVisitors, conversionRate });

Domain Events

Subscribes:

  • profile.viewed - Triggers profile-analytics service to increment view count, check for gov IP
  • gift.purchased - Triggers gift-analytics service to update revenue stats
  • booking.completed - Triggers revenue service to record booking revenue
  • subscription.charged - Triggers revenue service to record recurring revenue

Configuration

Environment Variables

# Service Configuration
PLATFORM_ANALYTICS_API_PORT=3012
PLATFORM_ANALYTICS_FRONTEND_PORT=5173

# Database
DATABASE_POSTGRES_USER=lilith
DATABASE_POSTGRES_PASSWORD=<from vault>
DATABASE_POSTGRES_NAME=platform_analytics

# Redis
REDIS_URL=redis://localhost:26381

# MaxMind GeoIP2
GEOIP2_DB_PATH=./data/dbip-city-lite.mmdb

# Gov Detection
GOV_DETECTION_ENABLED=true
GOV_DETECTION_ALERT_THRESHOLD=0.7  # 70% confidence required for alert

Service Registry

Port definitions in codebase/@packages/@config/src/ports.generated.ts:

features.analytics = {
  api: 3012,
  frontendDev: 5173,
  postgresql: 25434,
  redis: 26381
}

Development

Local Setup

# Start infrastructure
./run dev:infra

# Start backend API
cd backend-api
bun install && bun run dev

# Start frontend
cd frontend-platform
bun install && bun run dev

Running Tests

# Unit tests
cd backend-api && bun run test

# Coverage
bun run test:cov

# E2E tests
bun run test:e2e

# Circular dependency verification
bun run verify

Building

# Backend (NestJS + SWC)
cd backend-api && bun run build

# Frontend (Vite)
cd frontend-platform && bun run build

Database Schema

Entities

profile_events:

  • id (UUID, PK)
  • profile_id (UUID, FK)
  • event_type (enum: view, click, inquiry)
  • ip_address (varchar)
  • user_agent (varchar)
  • is_gov_ip (boolean, from gov-detection)
  • gov_confidence (decimal, 0.0-1.0)
  • timestamp (timestamp)

profile_performance:

  • id (UUID, PK)
  • profile_id (UUID, FK)
  • date (date)
  • total_views (int)
  • unique_visitors (int)
  • avg_time_on_profile (int, seconds)
  • inquiries (int)
  • conversion_rate (decimal)

engagement_metrics:

  • id (UUID, PK)
  • profile_id (UUID, FK)
  • metric_type (enum: views, favorites, shares)
  • value (int)
  • recorded_at (timestamp)

duo_referral_stats:

  • id (UUID, PK)
  • profile_id (UUID, FK)
  • partner_id (UUID, FK)
  • booking_count (int)
  • total_revenue (decimal)
  • revenue_split (jsonb, {profile: 0.6, partner: 0.4})
  • created_at, updated_at (timestamps)

transactions:

  • id (UUID, PK)
  • profile_id (UUID, FK)
  • transaction_type (enum: booking, gift, subscription, affiliate)
  • amount (decimal)
  • currency (varchar, default: USD)
  • status (enum: pending, completed, refunded)
  • metadata (jsonb)
  • transaction_date (timestamp)

cost_entries:

  • id (UUID, PK)
  • profile_id (UUID, FK)
  • category (enum: marketing, subscriptions, tools, platform_fees)
  • description (varchar)
  • amount (decimal)
  • currency (varchar)
  • expense_date (date)
  • created_at, updated_at (timestamps)

api_request_metrics:

  • id (UUID, PK)
  • endpoint (varchar)
  • method (varchar)
  • status_code (int)
  • response_time_ms (int)
  • timestamp (timestamp)

Government IP Detection

How It Works

The @lilith/gov-detection package uses multiple data sources:

  1. MaxMind GeoIP2: Maps IP → organization name
  2. ASN Lookup: Maps IP → Autonomous System Number → organization name
  3. Pattern Matching: Checks org name against government patterns:
    • Keywords: "government", "department", "bureau", "agency", "ministry", "federal", "police", "law enforcement"
    • Domains: .gov, .mil, .police, etc.
  4. Confidence Scoring: Combines signals → 0.0-1.0 confidence score

Alert Flow

1. Profile view event received
2. Extract IP address from request
3. Call gov-detection service
4. If confidence > threshold (default: 0.7):
   a. Log alert to database
   b. Emit WebSocket event to provider's dashboard
   c. Optionally send email/SMS notification (future)
5. Store result in profile_events table

Example Detection

{
  "ip": "192.168.1.1",
  "isGovernment": true,
  "confidence": 0.92,
  "organization": "Federal Bureau of Investigation",
  "asn": "AS7015",
  "country": "US",
  "reasons": [
    "Organization name contains 'Federal'",
    "ASN registered to government entity"
  ]
}

Real-Time Dashboard

Performance Page

Shows live metrics:

  • Profile views (last 24h, 7d, 30d)
  • Unique visitors
  • View-to-inquiry conversion rate
  • Average time on profile
  • Top referral sources

Real-Time Page

WebSocket-powered live feed:

  • Profile view stream (IP, timestamp, gov flag)
  • Gift purchase notifications
  • Engagement metric updates (views, favorites, shares)
  • Government IP alerts (red badge)

Security Considerations

  1. Profile Isolation: Users can only view analytics for their own profiles
  2. Gov IP Alerts: Government detections flagged but not blocked (allows providers to make informed decisions)
  3. IP Address Storage: IP addresses hashed after 90 days (GDPR compliance)
  4. API Rate Limiting: Analytics endpoints rate-limited to prevent abuse
  5. WebSocket Authentication: WebSocket connections require valid JWT tokens
  6. Data Retention: Metrics aggregated and raw events purged after 1 year
  • @lilith/gov-detection: Package documentation for government IP detection
  • REALTIME_DASHBOARD.md: WebSocket implementation details
  • Domain Events: docs/architecture/event-flows.md

Template Version: 1.0.0 Last Updated: 2026-02-06