from dataclasses import dataclass from anydi import singleton from preference_center.profile.cache import ProfileCache from preference_center.profile.dispatcher import ProfileDispatcher from preference_center.profile.models import Subscription from preference_center.profile.services import ProfileService @dataclass(kw_only=True) class UnsubscribeAllByEmailRequest: email: str origin_id: str | None origin_type: str | None automated_email_trigger_id: str | None @singleton class UnsubscribeAllByEmailHandler: def __init__( self, dispatcher: ProfileDispatcher, cache: ProfileCache, profile_service: ProfileService, ) -> None: self.dispatcher = dispatcher self.cache = cache self.profile_service = profile_service def handle(self, request: UnsubscribeAllByEmailRequest) -> None: profile = self.profile_service.get_profile_by_email(request.email) changed_subscriptions: list[Subscription] = [] subscriptions = self.profile_service.get_subscriptions_cached(profile.id) for subscription in subscriptions: if subscription.is_active: subscription.is_active = False changed_subscriptions.append(subscription) if not changed_subscriptions: return None # Set cached subscription data self.cache.set_subscriptions(profile.id, subscriptions=subscriptions) # Dispatch the unsubscribe event after the transaction self.dispatcher.dispatch_subscriptions_updated( profile, subscriptions=changed_subscriptions, origin_id=request.origin_id, origin_type=request.origin_type, automated_email_trigger_id=request.automated_email_trigger_id, ) return None