"""Logic for the /product-metrics endpoint.""" from typing import Any, Mapping from ddtrace import tracer from analytics.constants import cache from analytics.queries.format import format_row from analytics.queries.product_metrics import ( ProductMetrics, ProductMetricsByParticipant, ) from analytics.schemas.product import ProductMetricsSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis @tracer.wrap(name="get_product_metrics") @cache_in_redis(ttl=cache.ONE_DAY) def get_product_metrics( query_params: Mapping[str, Any], permissions: Mapping[str, Any] ): """Fetch product metrics.""" query_cls = ( ProductMetricsByParticipant if query_params.get("global_participant_ids") else ProductMetrics ) rows = query_cls( { **query_params, "is_feed_data_available": store_availability.is_apple_spotify_data_in_sync(), **permissions, } ).execute() metrics = [format_row(row) for row in rows] total_records = metrics[0].pop("total_records", 0) if metrics else 0 for row in metrics[1:]: row.pop("total_records", None) return ProductMetricsSchema.normalized_response( {"metrics": metrics, "total_products": total_records} )