from dataclasses import dataclass from anydi import singleton from fansifter_common.identifiers.types import ProfileToken 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 UnsubscribeAllRequest: token: ProfileToken @singleton class UnsubscribeAllHandler: 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: UnsubscribeAllRequest) -> None: identifier = self.profile_service.decode_profile_identifier(request.token) profile = self.profile_service.get_profile_by_identifier_cached(identifier) 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 profile.updated_by = identifier.impersonated_by # Clear 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=identifier.origin_id, origin_type=identifier.origin_type, automated_email_trigger_id=identifier.automated_email_trigger_id, ) return None