from typing import Any, Dict, List, Mapping from analytics.constants import cache from analytics.logic import data_availability from analytics.logic.permissions import get_cross_attribution_pairs from analytics.queries.account import ( AccountProductsByDownloadsCustomPeriod, AccountProductsByDownloadsFixedPeriod, AccountProductsByStreamsCustomPeriod, AccountProductsByStreamsFixedPeriod, ) from analytics.queries.format import format_row from analytics.utils.cache import cache_in_redis @cache_in_redis(ttl=cache.ONE_DAY) def get_products( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ) -> List[Dict]: """Get releases (products) for an account.""" query_params["max_available_date"] = str(data_availability.get_max_available_date()) order_by = query_params.get("order_by", "").lower() is_custom_period = query_params.get("start_date", "") if not is_custom_period and "streams" in order_by: query = AccountProductsByStreamsFixedPeriod({**query_params, **permissions}) elif not is_custom_period and "downloads" in order_by: query = AccountProductsByDownloadsFixedPeriod({**query_params, **permissions}) elif is_custom_period and "streams" in order_by: # Custom-period streams reads the BY_ACCOUNT _DAILY view (clustered on # label_id), scoped via account_scope_filter. Co-owner pairs are inlined # so Snowflake prunes the label_id clusters for transferred products. if query_params.get("transfer_product_ownership_enabled"): query_params["cross_attribution_pairs"] = get_cross_attribution_pairs( query_params["account_id"], query_params["account_type"] ) query = AccountProductsByStreamsCustomPeriod({**query_params, **permissions}) elif is_custom_period and "downloads" in order_by: query = AccountProductsByDownloadsCustomPeriod({**query_params, **permissions}) else: raise ValueError( f"Unsupported combination of order_by: {order_by} " f"and is_custom_period: {is_custom_period}" ) result = [] for data_point in query.execute(): item = format_row(data_point) result.append({"product_id": item["product_id"]}) return result