from collections.abc import Sequence from anydi import singleton from dmp.google.dtos import AssignGoogleUserAdAccountLabelData from dmp.google.models import GoogleUserAdAccount from dmp.google.repositories import GoogleUserAdAccountRepository @singleton class GoogleUserAdAccountService: def __init__( self, user_ad_account_repository: GoogleUserAdAccountRepository, ) -> None: self.user_ad_account_repository = user_ad_account_repository def create_or_update_user_ad_accounts_for_user( self, assignments: list[AssignGoogleUserAdAccountLabelData], identity_id: str ) -> list[GoogleUserAdAccount]: existing_user_ad_accounts = ( self.user_ad_account_repository.find_by_ad_accounts_ids_and_identity_id( ad_accounts_ids=[ assignment.ad_account_id for assignment in assignments ], identity_id=identity_id, ) ) existing_user_ad_accounts_by_id = { existing_user_ad_account.ad_account_id: existing_user_ad_account for existing_user_ad_account in existing_user_ad_accounts } user_ad_accounts = [] for update_assignment in assignments: if ( update_assignment.ad_account_id in existing_user_ad_accounts_by_id.keys() ): existing_user_ad_account = existing_user_ad_accounts_by_id[ update_assignment.ad_account_id ] existing_user_ad_account.vendor_id = update_assignment.vendor_id existing_user_ad_account.subaccount_id = update_assignment.subaccount_id user_ad_accounts.append(existing_user_ad_account) else: new_user_ad_account = GoogleUserAdAccount( ad_account_id=update_assignment.ad_account_id, identity_id=identity_id, vendor_id=update_assignment.vendor_id, subaccount_id=update_assignment.subaccount_id, ) user_ad_accounts.append(new_user_ad_account) self.user_ad_account_repository.add_all(user_ad_accounts) return user_ad_accounts def get_labels_ad_accounts( self, vendor_ids: list[int], subaccount_ids: list[int] ) -> Sequence[GoogleUserAdAccount]: return self.user_ad_account_repository.find_by_vendor_and_subaccount_ids( vendor_ids=vendor_ids, subaccount_ids=subaccount_ids ) def get_ad_accounts( self, ad_accounts_ids: set[str] ) -> Sequence[GoogleUserAdAccount]: return self.user_ad_account_repository.find_by_ad_accounts_external_ids( ad_accounts_ids=ad_accounts_ids )