Hanzo
CommerceGuides

Analytics

ClickHouse-powered analytics with real-time dashboards

Hanzo Commerce includes a powerful analytics system built on ClickHouse, providing real-time insights into sales, customers, products, and AI-powered recommendations.

Overview

The analytics system captures:

  • Sales metrics: Revenue, orders, AOV, conversion rates
  • Customer analytics: Acquisition, retention, lifetime value
  • Product performance: Top sellers, inventory velocity
  • Funnel analysis: Cart abandonment, checkout completion
  • AI recommendations: Personalized product suggestions

Architecture

Events → Kafka → ClickHouse → API → Dashboard

              AI Recommendations

Configuration

ClickHouse Setup

CLICKHOUSE_URL=http://localhost:8123
CLICKHOUSE_DATABASE=commerce
CLICKHOUSE_USER=default
CLICKHOUSE_PASSWORD=...

BigQuery Alternative

For Google Cloud environments:

BIGQUERY_PROJECT=your-project
BIGQUERY_DATASET=commerce_analytics
GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json

Event Tracking

Automatic Events

These events are tracked automatically:

EventTrigger
page_viewUser visits a page
product_viewUser views a product
add_to_cartItem added to cart
remove_from_cartItem removed from cart
checkout_startedCheckout initiated
order_completedOrder placed successfully
payment_completedPayment processed

Custom Events

Track custom events via the API:

curl -X POST https://api.hanzo.ai/analytics/event \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "event": "product_shared",
    "userId": "user_xyz789",
    "properties": {
      "productId": "prod_abc123",
      "channel": "twitter"
    }
  }'

Client-Side Tracking

<script src="https://cdn.hanzo.ai/analytics.js"></script>
<script>
  hanzo.init('YOUR_PUBLIC_KEY');

  // Track page view
  hanzo.page();

  // Track product view
  hanzo.track('product_view', {
    productId: 'prod_abc123',
    name: 'Premium T-Shirt',
    price: 29.99
  });

  // Track add to cart
  hanzo.track('add_to_cart', {
    productId: 'prod_abc123',
    quantity: 2
  });
</script>

Dashboard Queries

Sales Overview

curl "https://api.hanzo.ai/analytics/sales?period=30d" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Response:

{
  "period": "30d",
  "revenue": 125000,
  "orders": 450,
  "averageOrderValue": 27778,
  "currency": "USD",
  "growth": {
    "revenue": 12.5,
    "orders": 8.3
  },
  "daily": [
    {"date": "2024-01-15", "revenue": 4500, "orders": 16},
    {"date": "2024-01-14", "revenue": 3800, "orders": 14}
  ]
}

Product Performance

curl "https://api.hanzo.ai/analytics/products?period=30d&limit=10" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Response:

{
  "topSellers": [
    {
      "productId": "prod_abc123",
      "name": "Premium T-Shirt",
      "revenue": 15000,
      "unitsSold": 500,
      "views": 2500,
      "conversionRate": 20.0
    }
  ],
  "lowStock": [
    {
      "productId": "prod_def456",
      "name": "Limited Edition Hoodie",
      "stock": 5,
      "velocity": 2.5
    }
  ]
}

Customer Analytics

curl "https://api.hanzo.ai/analytics/customers?period=30d" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Response:

{
  "totalCustomers": 1250,
  "newCustomers": 180,
  "returningCustomers": 95,
  "averageLTV": 15000,
  "cohorts": [
    {
      "month": "2024-01",
      "acquired": 180,
      "retained": {
        "month1": 45,
        "month2": 32,
        "month3": 28
      }
    }
  ]
}

Funnel Analysis

curl "https://api.hanzo.ai/analytics/funnel?period=7d" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Response:

{
  "stages": [
    {"name": "Product Views", "count": 10000, "rate": 100},
    {"name": "Add to Cart", "count": 2500, "rate": 25},
    {"name": "Checkout Started", "count": 1200, "rate": 48},
    {"name": "Payment Completed", "count": 800, "rate": 66.7},
    {"name": "Order Confirmed", "count": 780, "rate": 97.5}
  ],
  "abandonmentRate": 68,
  "conversionRate": 7.8
}

AI Recommendations

Get Recommendations

curl "https://api.hanzo.ai/recommendations?userId=user_xyz789&type=similar&productId=prod_abc123" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Response:

{
  "recommendations": [
    {
      "productId": "prod_ghi789",
      "name": "Classic Polo",
      "score": 0.92,
      "reason": "similar_style"
    },
    {
      "productId": "prod_jkl012",
      "name": "Slim Fit Jeans",
      "score": 0.87,
      "reason": "frequently_bought_together"
    }
  ]
}

Recommendation Types

TypeDescription
similarProducts similar to a given product
complementaryProducts often bought together
personalizedBased on user browsing/purchase history
trendingCurrently popular products
new_arrivalsRecently added products

Personalized Homepage

curl "https://api.hanzo.ai/recommendations/homepage?userId=user_xyz789" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Response:

{
  "sections": [
    {
      "title": "Recommended for You",
      "type": "personalized",
      "products": [...]
    },
    {
      "title": "Continue Shopping",
      "type": "recently_viewed",
      "products": [...]
    },
    {
      "title": "Trending Now",
      "type": "trending",
      "products": [...]
    }
  ]
}

Real-Time Dashboard

WebSocket Connection

const ws = new WebSocket('wss://api.hanzo.ai/analytics/live');

ws.onopen = () => {
  ws.send(JSON.stringify({
    type: 'subscribe',
    channels: ['orders', 'revenue']
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  // Update dashboard
  console.log('New order:', data);
};

Live Metrics

{
  "type": "order",
  "data": {
    "orderId": "order_abc123",
    "total": 6578,
    "items": 2,
    "timestamp": "2024-01-15T10:35:00Z"
  }
}

Custom Reports

Create Report

curl -X POST https://api.hanzo.ai/analytics/report \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Weekly Sales Summary",
    "query": {
      "metrics": ["revenue", "orders", "aov"],
      "dimensions": ["product_category", "day"],
      "filters": {
        "period": "7d"
      }
    },
    "schedule": "weekly",
    "recipients": ["[email protected]"]
  }'

Export Data

curl "https://api.hanzo.ai/analytics/export?type=orders&period=30d&format=csv" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -o orders.csv

SDK Examples

JavaScript

import { Commerce } from '@hanzo/commerce'

const commerce = new Commerce({ apiKey: 'your_key' })

// Track event
await commerce.analytics.track('product_view', {
  productId: 'prod_abc123',
  userId: 'user_xyz789'
})

// Get sales overview
const sales = await commerce.analytics.getSales({ period: '30d' })

// Get recommendations
const recs = await commerce.analytics.getRecommendations({
  userId: 'user_xyz789',
  type: 'personalized',
  limit: 10
})

// Subscribe to real-time updates
commerce.analytics.subscribe(['orders', 'revenue'], (event) => {
  console.log('Real-time event:', event)
})

Go

// Track event
err := client.Analytics.Track(ctx, &sdk.AnalyticsEvent{
    Event:  "product_view",
    UserID: "user_xyz789",
    Properties: map[string]interface{}{
        "productId": "prod_abc123",
    },
})

// Get sales overview
sales, err := client.Analytics.GetSales(ctx, &sdk.SalesQuery{
    Period: "30d",
})

// Get recommendations
recs, err := client.Analytics.GetRecommendations(ctx, &sdk.RecommendationQuery{
    UserID: "user_xyz789",
    Type:   "personalized",
    Limit:  10,
})

Data Retention

Data TypeRetention
Raw events90 days
Aggregated metrics2 years
Customer profilesIndefinite
AI model data1 year

Configure retention in your dashboard settings or via API:

curl -X PATCH https://api.hanzo.ai/analytics/settings \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "retention": {
      "rawEvents": 90,
      "aggregatedMetrics": 730
    }
  }'

How is this guide?

Last updated on

On this page