"""Logic for POST /sound-recording/aggregate-streams.""" from typing import Any, Mapping from ddtrace import tracer from oto import response as oto_response from analytics.constants import cache from analytics.logic.streams_helpers import ( build_bulk_query_input, group_by_isrc, rows_to_dicts, ) from analytics.queries.sound_recording_streams_bulk import AggregateStreamsBulk from analytics.schemas.streams import AggregateStreamsSchema from analytics.utils import store_availability from analytics.utils.cache import cache_in_redis from analytics.validation.schema import schema_dump @cache_in_redis(ttl=cache.ONE_DAY) @tracer.wrap(name="get_aggregate_streams") def get_aggregate_streams( query_params: Mapping[str, Any], permissions: Mapping[str, Any], ): """Return aggregate (all-time) streams per ISRC for a list of ISRCs. Args: query_params: Dict with isrcs, distributors, country_ids, store_ids. permissions: Dict with permission_* keys. Returns: oto.response.Response keyed by ISRC with streams_all_time and growth_percentage_7_days. """ isrcs = query_params["isrcs"] schema = AggregateStreamsSchema() empty_body = {"streams_all_time": 0, "growth_percentage_7_days": None} store_ids = store_availability.get_query_store_ids( query_params.get("store_ids") or [] ) if not store_ids: return oto_response.Response( {isrc: schema_dump(schema, empty_body) for isrc in isrcs} ) query_input = build_bulk_query_input(isrcs, store_ids, query_params, permissions) streams = rows_to_dicts(AggregateStreamsBulk(query_input).execute()) streams_by_isrc = group_by_isrc(streams) result = {} for isrc in isrcs: if not streams_by_isrc[isrc]: result[isrc] = schema_dump(schema, empty_body) continue body = { "streams_all_time": sum( e["streams_all_time"] for e in streams_by_isrc[isrc] ), "growth_percentage_7_days": sum( e["growth_percentage"] for e in streams_by_isrc[isrc] ), } result[isrc] = schema_dump(schema, body) return oto_response.Response(result)