from dataclasses import dataclass from typing import Any from anydi import singleton from fansifter_common.auth.services import AuthService from fansifter_common.auth.types import Permission from pydantic import TypeAdapter from dmp.adapters.db import DefaultDB from dmp.app_connections.enums import AppConnectionStatus from dmp.google.dtos import GoogleAdAccountOverview from dmp.google.enums import GoogleUserConnectionStatus from dmp.google.services import GoogleAdAccountService @dataclass(frozen=True) class GetGoogleAdAccountsRequest: identity_id: str GoogleAdAccountOverviewListValidator = TypeAdapter(list[GoogleAdAccountOverview]) @singleton class GetGoogleAdAccountsHandler: permission = Permission("ad_account", "view") def __init__( self, db: DefaultDB, auth_service: AuthService, ad_account_service: GoogleAdAccountService, ) -> None: self.db = db self.auth_service = auth_service self.ad_account_service = ad_account_service def handle( self, request: GetGoogleAdAccountsRequest ) -> list[GoogleAdAccountOverview]: account_access = self.auth_service.authorize_for_permission( request.identity_id, permission=self.permission ) return self._get_overview( identity_id=request.identity_id, vendor_ids=account_access.vendor_ids, subaccount_ids=account_access.subaccount_ids, ) def _get_overview( self, identity_id: str, vendor_ids: list[int], subaccount_ids: list[int], ) -> list[GoogleAdAccountOverview]: query_context: dict[str, Any] = { "vendor_ids": vendor_ids, "subaccount_ids": subaccount_ids, "identity_id": identity_id, "ordered_reporting_enum_type": AppConnectionStatus.ordered(), "ordered_sharing_enum_type": GoogleUserConnectionStatus.ordered(), } query = self.db.query_from_template( "google-ad-account/find-by-account.sql", context=query_context, ) ad_accounts = GoogleAdAccountOverviewListValidator.validate_python( self.db.session.execute(query).mappings(), ) return list(self.ad_account_service.fill_ad_account_empty_data(ad_accounts))