Coverage for bc/kwai-bc-identity/src/kwai_bc_identity/mail_user_recovery.py: 93%
29 statements
« prev ^ index » next coverage.py v7.11.0, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.11.0, created at 2024-01-01 00:00 +0000
1"""Module that defines the use case for sending a recovery email."""
3from dataclasses import dataclass
5from kwai_core.domain.exceptions import UnprocessableException
6from kwai_core.domain.value_objects.unique_id import UniqueId
7from kwai_core.mail.mailer import Mailer
8from kwai_core.mail.recipient import Recipients
9from kwai_core.template.mail_template import MailTemplate
11from kwai_bc_identity.user_recoveries.user_recovery import UserRecoveryEntity
12from kwai_bc_identity.user_recoveries.user_recovery_mailer import (
13 UserRecoveryMailer,
14)
15from kwai_bc_identity.user_recoveries.user_recovery_repository import (
16 UserRecoveryRepository,
17)
20@dataclass(frozen=True, kw_only=True)
21class MailUserRecoveryCommand:
22 """Command for the use case MailUserRecovery.
24 Attributes:
25 uuid: The unique id of the user recovery.
26 """
28 uuid: str
31class MailUserRecovery:
32 """Use case for sending a recovery email."""
34 def __init__(
35 self,
36 user_recovery_repo: UserRecoveryRepository,
37 mailer: Mailer,
38 recipients: Recipients,
39 mail_template: MailTemplate,
40 ):
41 self._user_recovery_repo = user_recovery_repo
42 self._mailer = mailer
43 self._recipients = recipients
44 self._mail_template = mail_template
46 async def execute(self, command: MailUserRecoveryCommand) -> UserRecoveryEntity:
47 """Execute the use case.
49 Args:
50 command: The input for this use case.
52 Raises:
53 UserRecoveryNotFoundException: Raised when
54 the user recovery cannot be found.
55 UnprocessableException: Raised when the mail was already sent.
56 Raised when the user recovery was already confirmed.
57 """
58 user_recovery = await self._user_recovery_repo.get_by_uuid(
59 UniqueId.create_from_string(command.uuid)
60 )
62 if user_recovery.mailed:
63 raise UnprocessableException(
64 f"Mail already send for user recovery {command.uuid}"
65 )
67 if user_recovery.is_expired:
68 raise UnprocessableException(
69 f"User recovery {command.uuid} already expired"
70 )
72 if user_recovery.confirmed:
73 raise UnprocessableException(
74 f"User recovery {command.uuid} already confirmed"
75 )
77 UserRecoveryMailer(
78 self._mailer, self._recipients, self._mail_template, user_recovery
79 ).send()
81 user_recovery = user_recovery.mail_sent()
83 await self._user_recovery_repo.update(user_recovery)
85 return user_recovery