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 email_campaigns.adapters.db import Repository from email_campaigns.adapters.stripo import AutomatedStripoClientV2 from email_campaigns.automated.handlers.get_automated_email_status import ( AutomatedEmailStatusResponse, ) from email_campaigns.automated.models import AutomatedEmail from email_campaigns.emails.cache import EmailPublicPreviewCache from email_campaigns.emails.exceptions import EmailNotFoundError @dataclass(kw_only=True) class ApplyAutomatedEmailChangesRequest(AuthRequest): email_id: str @singleton class ApplyAutomatedEmailChangesHandler: # TODO: ---> Permission("automated_email", "edit") permission = Permission("email_campaign", "edit") def __init__( self, auth_service: AuthService, email_repository: Repository[AutomatedEmail], preview_cache: EmailPublicPreviewCache, stripo_v2_client: AutomatedStripoClientV2, ) -> None: self.auth_service = auth_service self.email_repository = email_repository self.preview_cache = preview_cache self.stripo_v2_client = stripo_v2_client def handle( self, request: ApplyAutomatedEmailChangesRequest ) -> AutomatedEmailStatusResponse: email = self.email_repository.get(request.email_id) if email is None: raise EmailNotFoundError self.auth_service.authorize_account( request.identity_id, account=email.account, permission=self.permission, ) if email.has_unapplied_changes: response = self.stripo_v2_client.get_html_css( email_id=email.id, user_id=request.identity_id, ) email.html_content = response.html email.css_content = response.css if email.is_automated: email.compressed_content = self.stripo_v2_client.compress( response.html, response.css ) email.has_unapplied_changes = False email.updated_by = request.identity_id self.email_repository.save(email) self.preview_cache.delete(email.id, email.email_type) return AutomatedEmailStatusResponse( has_unapplied_changes=email.has_unapplied_changes, is_automated=email.is_automated, )