from dataclasses import dataclass from anydi import singleton from fansifter_common.auth.types import Permission from pydantic import TypeAdapter from dmp.adapters.db import ReportingDB from dmp.artists.cache import ArtistCache, cached_artist_data from dmp.artists.dtos import FansSegmentValue from dmp.artists.requests import ArtistFanReportFilterRequest from dmp.artists.services import ArtistAccessService from dmp.fandata.enums import FanSegment @dataclass class GetArtistFansCountBySegmentRequest(ArtistFanReportFilterRequest): countries: list[str] | None = None FanSegmentValueListValidator = TypeAdapter(list[FansSegmentValue]) @singleton class GetArtistFansCountBySegmentHandler: permission = Permission("fan_data_list", "view") def __init__( self, db: ReportingDB, artist_access_service: ArtistAccessService, artist_cache: ArtistCache, ) -> None: self.db = db self.artist_access_service = artist_access_service self.artist_cache = artist_cache def handle( self, request: GetArtistFansCountBySegmentRequest ) -> list[FansSegmentValue]: artist_access = self.artist_access_service.check_artist_access( request.identity_id, request.global_participant_id, request.account, permission=self.permission, ) segments = self._get_segments( request.global_participant_id, vendor_id=request.vendor_id, subaccount_id=request.subaccount_id, countries=request.countries, identity_id=request.identity_id, is_global=artist_access.is_global, ) if max(segment.value for segment in segments) == 0: return [] return segments @cached_artist_data("segments") def _get_segments( self, global_participant_id: str, vendor_id: int | None, subaccount_id: int | None, countries: list[str] | None, identity_id: str, is_global: bool, ) -> list[FansSegmentValue]: template_name = self._select_query_template_name(countries) query = self.db.query_from_template( template_name, context={ "vendor_id": vendor_id, "subaccount_id": subaccount_id, "global_participant_id": global_participant_id, "fan_segment_enum": FanSegment, "identity_id": identity_id, "countries": countries, "is_global": is_global, }, ) return FanSegmentValueListValidator.validate_python( self.db.session.execute(query).mappings() ) @staticmethod def _select_query_template_name(countries: list[str] | None) -> str: if countries: return "artist/get-artist-fans-count-by-segment-country.sql" return "artist/get-artist-fans-count-by-segment.sql"