from dataclasses import dataclass from anydi import singleton from fansifter_common.auth.requests import AuthRequest from fansifter_common.auth.services import AuthService from fansifter_common.auth.types import Permission from dmp.ad_reporting.dtos import AdReportingAdSet, AdReportingAdSetCriteria from dmp.ad_reporting.exceptions import AdReportingAdSetNotFoundError from dmp.ad_reporting.repositories import AdReportingAdSetRepository from dmp.ad_reporting.services import AdReportingAccountService @dataclass(kw_only=True) class GetAdReportingAdSetRequest(AuthRequest): ad_set_id: str @singleton class GetAdReportingAdSetHandler: permission = Permission("ad_campaign", "view") def __init__( self, auth_service: AuthService, ad_set_repository: AdReportingAdSetRepository, account_service: AdReportingAccountService, ) -> None: self.auth_service = auth_service self.ad_set_repository = ad_set_repository self.account_service = account_service def handle(self, request: GetAdReportingAdSetRequest) -> AdReportingAdSet: account_access = self.auth_service.authorize_for_permission( request.identity_id, permission=self.permission, ) ad_account_labels = self.account_service.get_allowed_ad_account_labels( account_access ) if not ad_account_labels: raise AdReportingAdSetNotFoundError ad_sets = self.ad_set_repository.find_by_criteria( AdReportingAdSetCriteria( ad_set_ids={request.ad_set_id}, account_ids=set(ad_account_labels.keys()), ), limit=1, ) try: ad_set = ad_sets[0] except IndexError as exc: raise AdReportingAdSetNotFoundError from exc # Prefetch label ad accounts ad_set.accounts = ad_account_labels.get(ad_set.account_id, set()) return ad_set