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 AdReportingAd, AdReportingAdCriteria from dmp.ad_reporting.exceptions import AdReportingAdNotFoundError from dmp.ad_reporting.repositories import AdReportingAdRepository from dmp.ad_reporting.services import AdReportingAccountService @dataclass(kw_only=True) class GetAdReportingAdRequest(AuthRequest): ad_id: str @singleton class GetAdReportingAdHandler: permission = Permission("ad_campaign", "view") def __init__( self, auth_service: AuthService, ad_repository: AdReportingAdRepository, account_service: AdReportingAccountService, ) -> None: self.auth_service = auth_service self.ad_repository = ad_repository self.account_service = account_service def handle(self, request: GetAdReportingAdRequest) -> AdReportingAd: 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 AdReportingAdNotFoundError ads = self.ad_repository.find_by_criteria( AdReportingAdCriteria( ad_ids={request.ad_id}, account_ids=set(ad_account_labels.keys()), ), limit=1, ) try: ad = ads[0] except IndexError as exc: raise AdReportingAdNotFoundError from exc # Prefetch label ad accounts ad.accounts = ad_account_labels.get(ad.account_id, set()) return ad