ifixkart-backend/app/api/v1/routers/GoogleAnalyticsRouter.py

117 lines
3.8 KiB
Python

import re
from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from typing import Dict, Any, List
from app.core.database.db_session import get_db
from app.core.config.Config import settings
from app.core.integrations.google_analytics_service import GoogleAnalyticsService
from app.models.ProductModel import Product
from app.models.CategoryModel import Category
router = APIRouter(
prefix="/api/v1/analytics/google",
tags=["Google Analytics 4"]
)
_ga_service = None
def get_ga_service() -> GoogleAnalyticsService:
global _ga_service
if _ga_service is None:
_ga_service = GoogleAnalyticsService(settings.GA4_PROPERTY_ID)
return _ga_service
@router.get("/status")
def get_ga4_status():
"""Verify GA4 configuration and service status."""
service = get_ga_service()
return {
"enabled": settings.GA4_ENABLED,
"property_id": settings.GA4_PROPERTY_ID,
"is_ready": service.is_ready,
"credentials_configured": bool(settings.GA4_CREDENTIALS_JSON_PATH)
}
@router.get("/overview")
def get_overview(
days: int = Query(7, ge=1, le=90),
db: Session = Depends(get_db)
):
"""Fetch high-level overview metrics, daily trends, sources, and top pages."""
service = get_ga_service()
summary = service.get_summary_metrics(days)
trend = service.get_users_over_time(days)
sources = service.get_traffic_sources(days)
raw_pages = service.get_top_pages(days)
# Enrich product and category page URLs with readable DB titles
enhanced_pages = []
for p in raw_pages:
path = p.get("path", "")
title = path
# Check /product/{slug_or_id}
product_match = re.search(r'/product/([^/?#]+)', path)
if product_match:
slug_or_id = product_match.group(1)
prod = db.query(Product).filter(
(Product.slug == slug_or_id) | (Product.product_id == slug_or_id)
).first()
if prod:
title = prod.name
else:
title = f"Product: {slug_or_id.replace('-', ' ').title()}"
elif path in ("/", ""):
title = "Storefront Home Page"
elif path.startswith("/category/"):
cat_slug = path.replace("/category/", "").split("?")[0]
cat = db.query(Category).filter(
(Category.slug == cat_slug) | (Category.name == cat_slug)
).first()
title = f"Category: {cat.name if cat else cat_slug.replace('-', ' ').title()}"
elif "/repair" in path or "/service" in path:
title = "Repair & Service Booking"
elif "/checkout" in path:
title = "Checkout Funnel"
elif "/cart" in path:
title = "Shopping Cart"
enhanced_pages.append({
"path": path,
"title": title,
"views": p.get("views", 0)
})
return {
"status": "success",
"days": days,
"property_id": settings.GA4_PROPERTY_ID,
"summary": summary,
"trend": trend,
"sources": sources,
"pages": enhanced_pages,
}
@router.get("/realtime")
def get_realtime():
"""Fetch realtime active users and active locations."""
service = get_ga_service()
realtime_data = service.get_realtime_users()
total_active = sum(item.get("active_users", 0) for item in realtime_data)
return {
"status": "success",
"total_active_users": total_active,
"locations": realtime_data
}
@router.get("/events")
def get_top_events(days: int = Query(7, ge=1, le=90)):
"""Fetch top tracking events (e.g. page_view, add_to_cart, purchase)."""
service = get_ga_service()
return {
"status": "success",
"events": service.get_top_events(days)
}