Coverage for kwai/modules/identity/mail_user_invitation.py: 93%

30 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-09-05 17:55 +0000

1"""Module that defines the use case for sending a user invitation email.""" 

2from dataclasses import dataclass 

3 

4from kwai.core.domain.exceptions import UnprocessableException 

5from kwai.core.domain.value_objects.unique_id import UniqueId 

6from kwai.core.mail.mailer import Mailer 

7from kwai.core.mail.recipient import Recipients 

8from kwai.core.template.mail_template import MailTemplate 

9from kwai.modules.identity.user_invitations.user_invitation import UserInvitationEntity 

10from kwai.modules.identity.user_invitations.user_invitation_mailer import ( 

11 UserInvitationMailer, 

12) 

13from kwai.modules.identity.user_invitations.user_invitation_repository import ( 

14 UserInvitationRepository, 

15) 

16 

17 

18@dataclass(frozen=True, kw_only=True, slots=True) 

19class MailUserInvitationCommand: 

20 """Command for the use case MailUserInvitation. 

21 

22 Attributes: 

23 uuid: The unique id of the user invitation. 

24 """ 

25 

26 uuid: str 

27 

28 

29class MailUserInvitation: 

30 """Use case for sending a user invitation email.""" 

31 

32 def __init__( 

33 self, 

34 user_invitation_repo: UserInvitationRepository, 

35 mailer: Mailer, 

36 recipients: Recipients, 

37 mail_template: MailTemplate, 

38 ): 

39 self._user_invitation_repo = user_invitation_repo 

40 self._mailer = mailer 

41 self._recipients = recipients 

42 self._mail_template = mail_template 

43 

44 async def execute(self, command: MailUserInvitationCommand) -> UserInvitationEntity: 

45 """Execute the use case. 

46 

47 Args: 

48 command: the input for this use case. 

49 

50 Raises: 

51 UserInvitationNotFoundException: Raised when 

52 the user invitation cannot be found. 

53 UnprocessableException: Raised when the mail was already sent. 

54 Raised when the user recovery was already confirmed. 

55 """ 

56 user_invitation = await self._user_invitation_repo.get_invitation_by_uuid( 

57 UniqueId.create_from_string(command.uuid) 

58 ) 

59 if user_invitation.mailed: 

60 raise UnprocessableException( 

61 f"Mail already send for user invitation {command.uuid}" 

62 ) 

63 

64 if user_invitation.is_expired: 

65 raise UnprocessableException( 

66 f"User invitation {command.uuid} already expired" 

67 ) 

68 

69 if user_invitation.confirmed: 

70 raise UnprocessableException( 

71 f"User invitation {command.uuid} already confirmed" 

72 ) 

73 

74 UserInvitationMailer( 

75 self._mailer, 

76 self._recipients, 

77 self._mail_template, 

78 user_invitation, 

79 ).send() 

80 

81 user_invitation.mail_sent() 

82 await self._user_invitation_repo.update(user_invitation) 

83 

84 return user_invitation