655 lines
23 KiB
Markdown
655 lines
23 KiB
Markdown
# Subtask: Order Analytics and Reporting
|
|
|
|
**Parent Task**: Decomp/004
|
|
**Subtask ID**: Decomp-004-09
|
|
**Dependencies**: Decomp-004-01 (Database Schema)
|
|
|
|
## Description
|
|
|
|
Implement order analytics and reporting system. Provide sales metrics, revenue tracking, customer analytics, and product performance data. Support real-time dashboards and scheduled reports.
|
|
|
|
## Requirements
|
|
|
|
- Sales revenue tracking (daily, weekly, monthly)
|
|
- Order volume metrics
|
|
- Product performance analytics
|
|
- Customer lifetime value calculation
|
|
- Conversion rate tracking
|
|
- Average order value
|
|
- Revenue by category/product
|
|
- Export functionality (CSV, PDF)
|
|
|
|
## Technical Specifications
|
|
|
|
**Analytics service**:
|
|
```python
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import List, Dict, Any, Optional
|
|
from dataclasses import dataclass, field
|
|
from decimal import Decimal
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@dataclass
|
|
class SalesMetrics:
|
|
"""Sales metrics for a period."""
|
|
period_start: datetime
|
|
period_end: datetime
|
|
total_orders: int
|
|
completed_orders: int
|
|
cancelled_orders: int
|
|
total_revenue: Decimal
|
|
refunded_amount: Decimal
|
|
net_revenue: Decimal
|
|
average_order_value: Decimal
|
|
conversion_rate: float # Percentage
|
|
unique_customers: int
|
|
|
|
@dataclass
|
|
class ProductSales:
|
|
"""Product sales data."""
|
|
product_id: int
|
|
sku: str
|
|
name: str
|
|
category: str
|
|
units_sold: int
|
|
revenue: Decimal
|
|
profit: Decimal
|
|
refund_rate: float
|
|
|
|
@dataclass
|
|
class CustomerAnalytics:
|
|
"""Customer analytics data."""
|
|
customer_id: int
|
|
total_orders: int
|
|
total_spent: Decimal
|
|
average_order_value: Decimal
|
|
first_order_date: datetime
|
|
last_order_date: datetime
|
|
lifetime_value: Decimal
|
|
|
|
@dataclass
|
|
class CategorySales:
|
|
"""Category sales data."""
|
|
category_id: int
|
|
category_name: str
|
|
total_orders: int
|
|
total_revenue: Decimal
|
|
top_products: List[Dict] = field(default_factory=list)
|
|
|
|
class OrderAnalyticsService:
|
|
"""Service for order analytics and reporting."""
|
|
|
|
def __init__(self, db):
|
|
self.db = db
|
|
|
|
async def get_sales_metrics(
|
|
self,
|
|
start_date: datetime = None,
|
|
end_date: datetime = None
|
|
) -> SalesMetrics:
|
|
"""Get sales metrics for a date range."""
|
|
if not end_date:
|
|
end_date = datetime.now(timezone.utc)
|
|
if not start_date:
|
|
start_date = end_date - timedelta(days=30)
|
|
|
|
async with self.db.acquire() as conn:
|
|
# Order counts
|
|
counts = await conn.fetchrow(
|
|
"""SELECT
|
|
COUNT(*) FILTER (WHERE created_at >= $1 AND created_at <= $2) as total_orders,
|
|
COUNT(*) FILTER (WHERE status IN ('paid', 'shipped', 'delivered')
|
|
AND created_at >= $1 AND created_at <= $2) as completed_orders,
|
|
COUNT(*) FILTER (WHERE status = 'cancelled'
|
|
AND created_at >= $1 AND created_at <= $2) as cancelled_orders
|
|
FROM orders""",
|
|
start_date, end_date
|
|
)
|
|
|
|
# Revenue metrics
|
|
revenue = await conn.fetchrow(
|
|
"""SELECT
|
|
COALESCE(SUM(total_amount), 0) as total_revenue,
|
|
COALESCE(SUM(refunded_amount), 0) as refunded_amount
|
|
FROM orders
|
|
WHERE created_at >= $1 AND created_at <= $2
|
|
AND status NOT IN ('pending', 'cancelled')""",
|
|
start_date, end_date
|
|
)
|
|
|
|
# Average order value
|
|
aov = await conn.fetchval(
|
|
"""SELECT COALESCE(AVG(total_amount), 0)
|
|
FROM orders
|
|
WHERE created_at >= $1 AND created_at <= $2
|
|
AND status NOT IN ('pending', 'cancelled')""",
|
|
start_date, end_date
|
|
)
|
|
|
|
# Unique customers
|
|
unique_customers = await conn.fetchval(
|
|
"""SELECT COUNT(DISTINCT customer_id)
|
|
FROM orders
|
|
WHERE created_at >= $1 AND created_at <= $2""",
|
|
start_date, end_date
|
|
)
|
|
|
|
# Conversion rate (orders / unique visitors - mock)
|
|
# In production, integrate with web analytics
|
|
conversion_rate = 2.5 # Mock value
|
|
|
|
total_revenue = Decimal(str(revenue["total_revenue"]))
|
|
refunded_amount = Decimal(str(revenue["refunded_amount"]))
|
|
|
|
return SalesMetrics(
|
|
period_start=start_date,
|
|
period_end=end_date,
|
|
total_orders=counts["total_orders"] or 0,
|
|
completed_orders=counts["completed_orders"] or 0,
|
|
cancelled_orders=counts["cancelled_orders"] or 0,
|
|
total_revenue=total_revenue,
|
|
refunded_amount=refunded_amount,
|
|
net_revenue=total_revenue - refunded_amount,
|
|
average_order_value=Decimal(str(aov)) if aov else Decimal("0"),
|
|
conversion_rate=conversion_rate,
|
|
unique_customers=unique_customers or 0
|
|
)
|
|
|
|
async def get_daily_sales(
|
|
self,
|
|
days: int = 30
|
|
) -> List[Dict[str, Any]]:
|
|
"""Get daily sales breakdown."""
|
|
start_date = datetime.now(timezone.utc) - timedelta(days=days)
|
|
|
|
async with self.db.acquire() as conn:
|
|
rows = await conn.fetch(
|
|
"""SELECT
|
|
DATE(created_at) as date,
|
|
COUNT(*) as orders,
|
|
COUNT(*) FILTER (WHERE status NOT IN ('pending', 'cancelled')) as completed,
|
|
COALESCE(SUM(total_amount) FILTER (WHERE status NOT IN ('pending', 'cancelled')), 0) as revenue,
|
|
COALESCE(SUM(refunded_amount), 0) as refunded
|
|
FROM orders
|
|
WHERE created_at >= $1
|
|
GROUP BY DATE(created_at)
|
|
ORDER BY date DESC""",
|
|
start_date
|
|
)
|
|
|
|
return [
|
|
{
|
|
"date": row["date"].isoformat(),
|
|
"orders": row["orders"],
|
|
"completed": row["completed"],
|
|
"revenue": str(row["revenue"]),
|
|
"refunded": str(row["refunded"]),
|
|
"net_revenue": str(row["revenue"] - row["refunded"])
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
async def get_product_sales(
|
|
self,
|
|
start_date: datetime = None,
|
|
end_date: datetime = None,
|
|
limit: int = 50
|
|
) -> List[ProductSales]:
|
|
"""Get top-selling products."""
|
|
if not end_date:
|
|
end_date = datetime.now(timezone.utc)
|
|
if not start_date:
|
|
start_date = end_date - timedelta(days=30)
|
|
|
|
async with self.db.acquire() as conn:
|
|
rows = await conn.fetch(
|
|
"""SELECT
|
|
p.id as product_id,
|
|
p.sku,
|
|
p.name,
|
|
c.name as category,
|
|
COALESCE(SUM(oi.quantity), 0) as units_sold,
|
|
COALESCE(SUM(oi.total_amount), 0) as revenue
|
|
FROM order_items oi
|
|
JOIN orders o ON o.id = oi.order_id
|
|
JOIN products p ON p.id = oi.product_id
|
|
LEFT JOIN categories c ON c.id = p.category_id
|
|
WHERE o.created_at >= $1 AND o.created_at <= $2
|
|
AND o.status NOT IN ('pending', 'cancelled')
|
|
GROUP BY p.id, p.sku, p.name, c.name
|
|
ORDER BY revenue DESC
|
|
LIMIT $3""",
|
|
start_date, end_date, limit
|
|
)
|
|
|
|
# Calculate profit and refund rate for each product
|
|
result = []
|
|
for row in rows:
|
|
# Get refund info
|
|
refunds = await conn.fetchrow(
|
|
"""SELECT COALESCE(SUM(r.amount), 0) as refund_total
|
|
FROM refunds r
|
|
JOIN payment_transactions pt ON pt.id = r.payment_transaction_id
|
|
JOIN order_items oi ON oi.order_id = pt.order_id
|
|
WHERE oi.product_id = $1""",
|
|
row["product_id"]
|
|
)
|
|
|
|
refund_amount = Decimal(str(refunds["refund_total"])) if refunds else Decimal("0")
|
|
revenue = Decimal(str(row["revenue"]))
|
|
profit = revenue * Decimal("0.3") # Assume 30% margin
|
|
|
|
result.append(ProductSales(
|
|
product_id=row["product_id"],
|
|
sku=row["sku"],
|
|
name=row["name"],
|
|
category=row.get("category", "Uncategorized"),
|
|
units_sold=row["units_sold"],
|
|
revenue=revenue,
|
|
profit=profit - refund_amount,
|
|
refund_rate=float(refund_amount / revenue * 100) if revenue > 0 else 0
|
|
))
|
|
|
|
return result
|
|
|
|
async def get_category_sales(
|
|
self,
|
|
start_date: datetime = None,
|
|
end_date: datetime = None
|
|
) -> List[CategorySales]:
|
|
"""Get sales by category."""
|
|
if not end_date:
|
|
end_date = datetime.now(timezone.utc)
|
|
if not start_date:
|
|
start_date = end_date - timedelta(days=30)
|
|
|
|
async with self.db.acquire() as conn:
|
|
rows = await conn.fetch(
|
|
"""SELECT
|
|
c.id as category_id,
|
|
COALESCE(c.name, 'Uncategorized') as category_name,
|
|
COUNT(DISTINCT o.id) as total_orders,
|
|
COALESCE(SUM(oi.total_amount), 0) as total_revenue
|
|
FROM order_items oi
|
|
JOIN orders o ON o.id = oi.order_id
|
|
JOIN products p ON p.id = oi.product_id
|
|
LEFT JOIN categories c ON c.id = p.category_id
|
|
WHERE o.created_at >= $1 AND o.created_at <= $2
|
|
AND o.status NOT IN ('pending', 'cancelled')
|
|
GROUP BY c.id, c.name
|
|
ORDER BY total_revenue DESC""",
|
|
start_date, end_date
|
|
)
|
|
|
|
result = []
|
|
for row in rows:
|
|
# Get top products in category
|
|
top_products = await conn.fetch(
|
|
"""SELECT p.name, SUM(oi.quantity) as units, SUM(oi.total_amount) as revenue
|
|
FROM order_items oi
|
|
JOIN orders o ON o.id = oi.order_id
|
|
JOIN products p ON p.id = oi.product_id
|
|
WHERE p.category_id = $1
|
|
AND o.created_at >= $2 AND o.created_at <= $3
|
|
AND o.status NOT IN ('pending', 'cancelled')
|
|
GROUP BY p.id, p.name
|
|
ORDER BY revenue DESC
|
|
LIMIT 5""",
|
|
row["category_id"], start_date, end_date
|
|
)
|
|
|
|
result.append(CategorySales(
|
|
category_id=row["category_id"],
|
|
category_name=row["category_name"],
|
|
total_orders=row["total_orders"],
|
|
total_revenue=Decimal(str(row["total_revenue"])),
|
|
top_products=[dict(p) for p in top_products]
|
|
))
|
|
|
|
return result
|
|
|
|
async def get_customer_analytics(
|
|
self,
|
|
customer_id: int
|
|
) -> CustomerAnalytics:
|
|
"""Get analytics for a specific customer."""
|
|
async with self.db.acquire() as conn:
|
|
row = await conn.fetchrow(
|
|
"""SELECT
|
|
customer_id,
|
|
COUNT(*) as total_orders,
|
|
COALESCE(SUM(total_amount), 0) as total_spent,
|
|
COALESCE(AVG(total_amount), 0) as average_order_value,
|
|
MIN(created_at) as first_order_date,
|
|
MAX(created_at) as last_order_date
|
|
FROM orders
|
|
WHERE customer_id = $1
|
|
AND status NOT IN ('pending', 'cancelled')
|
|
GROUP BY customer_id""",
|
|
customer_id
|
|
)
|
|
|
|
if not row:
|
|
return None
|
|
|
|
# Calculate lifetime value (CLV)
|
|
# Simple formula: AOV * purchase_frequency * customer_lifespan
|
|
# Using 3 years as average lifespan
|
|
total_spent = Decimal(str(row["total_spent"]))
|
|
total_orders = row["total_orders"]
|
|
aov = Decimal(str(row["average_order_value"]))
|
|
|
|
# Estimate annual orders
|
|
if row["first_order_date"]:
|
|
days_active = (datetime.now(timezone.utc) - row["first_order_date"]).days
|
|
orders_per_year = (total_orders / max(days_active, 1)) * 365 if days_active > 0 else 0
|
|
else:
|
|
orders_per_year = 0
|
|
|
|
lifetime_value = aov * orders_per_year * 3 # 3 years
|
|
|
|
return CustomerAnalytics(
|
|
customer_id=customer_id,
|
|
total_orders=total_orders,
|
|
total_spent=total_spent,
|
|
average_order_value=aov,
|
|
first_order_date=row["first_order_date"],
|
|
last_order_date=row["last_order_date"],
|
|
lifetime_value=lifetime_value
|
|
)
|
|
|
|
async def get_top_customers(
|
|
self,
|
|
start_date: datetime = None,
|
|
end_date: datetime = None,
|
|
limit: int = 50
|
|
) -> List[Dict[str, Any]]:
|
|
"""Get top customers by revenue."""
|
|
if not end_date:
|
|
end_date = datetime.now(timezone.utc)
|
|
if not start_date:
|
|
start_date = end_date - timedelta(days=90)
|
|
|
|
async with self.db.acquire() as conn:
|
|
rows = await conn.fetch(
|
|
"""SELECT
|
|
o.customer_id,
|
|
c.email,
|
|
c.first_name,
|
|
c.last_name,
|
|
COUNT(*) as orders,
|
|
COALESCE(SUM(o.total_amount), 0) as total_spent,
|
|
COALESCE(AVG(o.total_amount), 0) as avg_order
|
|
FROM orders o
|
|
JOIN customers c ON c.id = o.customer_id
|
|
WHERE o.created_at >= $1 AND o.created_at <= $2
|
|
AND o.status NOT IN ('pending', 'cancelled')
|
|
GROUP BY o.customer_id, c.email, c.first_name, c.last_name
|
|
ORDER BY total_spent DESC
|
|
LIMIT $3""",
|
|
start_date, end_date, limit
|
|
)
|
|
|
|
return [
|
|
{
|
|
"customer_id": row["customer_id"],
|
|
"email": row["email"],
|
|
"name": f"{row['first_name']} {row['last_name']}".strip(),
|
|
"orders": row["orders"],
|
|
"total_spent": str(row["total_spent"]),
|
|
"average_order": str(row["avg_order"])
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
async def get_revenue_summary(
|
|
self,
|
|
group_by: str = "day" # day, week, month
|
|
) -> List[Dict[str, Any]]:
|
|
"""Get revenue summary grouped by time period."""
|
|
async with self.db.acquire() as conn:
|
|
if group_by == "day":
|
|
date_trunc = "DATE(created_at)"
|
|
interval = "1 day"
|
|
elif group_by == "week":
|
|
date_trunc = "date_trunc('week', created_at)"
|
|
interval = "1 week"
|
|
else: # month
|
|
date_trunc = "date_trunc('month', created_at)"
|
|
interval = "1 month"
|
|
|
|
rows = await conn.fetch(
|
|
f"""SELECT
|
|
{date_trunc} as period,
|
|
COUNT(*) FILTER (WHERE status NOT IN ('pending', 'cancelled')) as orders,
|
|
COALESCE(SUM(total_amount) FILTER (WHERE status NOT IN ('pending', 'cancelled')), 0) as revenue,
|
|
COALESCE(SUM(refunded_amount), 0) as refunds
|
|
FROM orders
|
|
WHERE created_at >= NOW() - INTERVAL '1 year'
|
|
GROUP BY {date_trunc}
|
|
ORDER BY period DESC
|
|
LIMIT 52"""
|
|
)
|
|
|
|
return [
|
|
{
|
|
"period": row["period"].isoformat() hasattr(row["period"], "isoformat") else str(row["period"]),
|
|
"orders": row["orders"],
|
|
"revenue": str(row["revenue"]),
|
|
"refunds": str(row["refunds"]),
|
|
"net_revenue": str(row["revenue"] - row["refunds"])
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
async def export_report(
|
|
self,
|
|
report_type: str,
|
|
start_date: datetime,
|
|
end_date: datetime,
|
|
format: str = "csv"
|
|
) -> bytes:
|
|
"""Export a report in specified format."""
|
|
if report_type == "sales":
|
|
data = await self.get_daily_sales(
|
|
days=(end_date - start_date).days
|
|
)
|
|
elif report_type == "products":
|
|
data = await self.get_product_sales(start_date, end_date)
|
|
elif report_type == "customers":
|
|
data = await self.get_top_customers(start_date, end_date)
|
|
else:
|
|
raise ValueError(f"Unknown report type: {report_type}")
|
|
|
|
if format == "csv":
|
|
return self._export_csv(data)
|
|
elif format == "json":
|
|
return self._export_json(data)
|
|
else:
|
|
raise ValueError(f"Unknown format: {format}")
|
|
|
|
def _export_csv(self, data: List[Dict]) -> bytes:
|
|
"""Export data as CSV."""
|
|
import csv
|
|
import io
|
|
|
|
output = io.StringIO()
|
|
if not data:
|
|
return output.getvalue().encode('utf-8')
|
|
|
|
writer = csv.DictWriter(output, fieldnames=data[0].keys())
|
|
writer.writeheader()
|
|
writer.writerows(data)
|
|
|
|
return output.getvalue().encode('utf-8')
|
|
|
|
def _export_json(self, data: List[Dict]) -> bytes:
|
|
"""Export data as JSON."""
|
|
import json
|
|
return json.dumps(data, default=str).encode('utf-8')
|
|
```
|
|
|
|
**Dashboard API**:
|
|
```python
|
|
from fastapi import APIRouter, Query
|
|
from typing import Optional
|
|
from datetime import datetime, timedelta
|
|
|
|
router = APIRouter(prefix="/analytics", tags=["analytics"])
|
|
|
|
@router.get("/sales/summary")
|
|
async def sales_summary(
|
|
days: int = Query(30, description="Number of days"),
|
|
start_date: Optional[datetime] = None,
|
|
end_date: Optional[datetime] = None
|
|
):
|
|
"""Get sales summary metrics."""
|
|
analytics = get_analytics_service()
|
|
|
|
if start_date and end_date:
|
|
metrics = await analytics.get_sales_metrics(start_date, end_date)
|
|
else:
|
|
metrics = await analytics.get_sales_metrics()
|
|
|
|
return {
|
|
"period": {
|
|
"start": metrics.period_start.isoformat(),
|
|
"end": metrics.period_end.isoformat()
|
|
},
|
|
"orders": {
|
|
"total": metrics.total_orders,
|
|
"completed": metrics.completed_orders,
|
|
"cancelled": metrics.cancelled_orders
|
|
},
|
|
"revenue": {
|
|
"gross": str(metrics.total_revenue),
|
|
"refunded": str(metrics.refunded_amount),
|
|
"net": str(metrics.net_revenue),
|
|
"average_order": str(metrics.average_order_value)
|
|
},
|
|
"customers": {
|
|
"unique": metrics.unique_customers,
|
|
"conversion_rate": metrics.conversion_rate
|
|
}
|
|
}
|
|
|
|
@router.get("/sales/daily")
|
|
async def daily_sales(days: int = Query(30, ge=1, le=365)):
|
|
"""Get daily sales breakdown."""
|
|
analytics = get_analytics_service()
|
|
data = await analytics.get_daily_sales(days)
|
|
return {"data": data}
|
|
|
|
@router.get("/products/top")
|
|
async def top_products(
|
|
start_date: Optional[datetime] = None,
|
|
end_date: Optional[datetime] = None,
|
|
limit: int = Query(50, ge=1, le=100)
|
|
):
|
|
"""Get top-selling products."""
|
|
analytics = get_analytics_service()
|
|
data = await analytics.get_product_sales(start_date, end_date, limit)
|
|
return {
|
|
"products": [
|
|
{
|
|
"product_id": p.product_id,
|
|
"sku": p.sku,
|
|
"name": p.name,
|
|
"category": p.category,
|
|
"units_sold": p.units_sold,
|
|
"revenue": str(p.revenue),
|
|
"profit": str(p.profit),
|
|
"refund_rate": round(p.refund_rate, 2)
|
|
}
|
|
for p in data
|
|
]
|
|
}
|
|
|
|
@router.get("/customers/top")
|
|
async def top_customers(
|
|
start_date: Optional[datetime] = None,
|
|
end_date: Optional[datetime] = None,
|
|
limit: int = Query(50, ge=1, le=100)
|
|
):
|
|
"""Get top customers by revenue."""
|
|
analytics = get_analytics_service()
|
|
data = await analytics.get_top_customers(start_date, end_date, limit)
|
|
return {"customers": data}
|
|
|
|
@router.get("/categories")
|
|
async def category_sales(
|
|
start_date: Optional[datetime] = None,
|
|
end_date: Optional[datetime] = None
|
|
):
|
|
"""Get sales by category."""
|
|
analytics = get_analytics_service()
|
|
data = await analytics.get_category_sales(start_date, end_date)
|
|
return {
|
|
"categories": [
|
|
{
|
|
"category_id": c.category_id,
|
|
"name": c.category_name,
|
|
"orders": c.total_orders,
|
|
"revenue": str(c.total_revenue),
|
|
"top_products": c.top_products
|
|
}
|
|
for c in data
|
|
]
|
|
}
|
|
|
|
@router.get("/export/{report_type}")
|
|
async def export_report(
|
|
report_type: str,
|
|
start_date: datetime,
|
|
end_date: datetime,
|
|
format: str = Query("csv", regex="^(csv|json)$")
|
|
):
|
|
"""Export a report."""
|
|
analytics = get_analytics_service()
|
|
|
|
data = await analytics.export_report(
|
|
report_type=report_type,
|
|
start_date=start_date,
|
|
end_date=end_date,
|
|
format=format
|
|
)
|
|
|
|
from fastapi.responses import Response
|
|
media_type = "text/csv" if format == "csv" else "application/json"
|
|
|
|
return Response(
|
|
content=data,
|
|
media_type=media_type,
|
|
headers={
|
|
"Content-Disposition": f"attachment; filename={report_type}_{start_date.date()}_to_{end_date.date()}.{format}"
|
|
}
|
|
)
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Sales metrics are calculated correctly
|
|
- [ ] Daily sales breakdown works
|
|
- [ ] Top products list is accurate
|
|
- [ ] Customer analytics are computed
|
|
- [ ] Category sales are aggregated
|
|
- [ ] Reports can be exported as CSV/JSON
|
|
- [ ] Date range filtering works
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Real-time vs batch aggregation: Batch for efficiency
|
|
- Built-in vs external BI: Built-in for simplicity
|
|
|
|
**Performance**:
|
|
- Materialized views for common queries
|
|
- Pre-aggregate data with scheduled jobs
|
|
- Cache results for dashboard
|
|
|
|
**Alternatives considered**:
|
|
- Tableau/Metabase integration: Better for complex dashboards
|
|
- ClickHouse for analytics: Overkill for current scale
|