"""Top Markets model.""" from ddtrace import tracer from sound_recordings.connectors import snowflake from sound_recordings.constants import cache from sound_recordings.utils import format_sql, store_availability from sound_recordings.utils.cache import cache_in_redis TOP_MARKETS_FIELDS = [ "country_code", "orchard_region_name", "streams_7_days", "growth_percentage", ] SQLLoader = snowflake.SQLLoader(__file__) @tracer.wrap(name="get_top_markets") @cache_in_redis(ttl=cache.SECONDS_PER_HOUR) def get_top_markets(permissions_filter, isrc, distributors, store_ids=[], countries=[]): """Get top markets for given isrc. Args: permissions_filter (dict): dict containing resources users can access isrc (str): ISRC of track to fetch breakdown for distributors (list): List of distributors names store_ids (list): List of store ids to filter by Returns: list: top markets """ if len(store_ids) == 0: store_ids = store_availability.get_store_ids() else: store_ids = sorted( list(set(store_ids).intersection(store_availability.get_store_ids())) ) if len(store_ids) == 0: return [] params = { **permissions_filter, "isrc": isrc, "distributors": distributors, "store_ids": store_ids, } if len(countries) > 0: params["country_codes"] = countries query_table = "top_markets_by_country" else: query_table = "top_markets" sql = SQLLoader.load_query(query_table) sql = format_sql.format_with_permissions_filter(sql, permissions_filter) top_markets = snowflake.fetchall(sql, params) return [dict(zip(TOP_MARKETS_FIELDS, top_market)) for top_market in top_markets]