Coverage for src/kwai/modules/portal/create_news_item.py: 88%

24 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2024-01-01 00:00 +0000

1"""Module for defining the use case "Create News Item".""" 

2 

3from kwai.core.domain.value_objects.owner import Owner 

4from kwai.core.domain.value_objects.period import Period 

5from kwai.core.domain.value_objects.text import DocumentFormat, Locale, LocaleText 

6from kwai.core.domain.value_objects.timestamp import Timestamp 

7from kwai.modules.portal.applications.application import ApplicationIdentifier 

8from kwai.modules.portal.applications.application_repository import ( 

9 ApplicationRepository, 

10) 

11from kwai.modules.portal.news.news_item import NewsItemEntity, Promotion 

12from kwai.modules.portal.news.news_item_repository import NewsItemRepository 

13from kwai.modules.portal.news_item_command import NewsItemCommand 

14 

15 

16CreateNewsItemCommand = NewsItemCommand 

17 

18 

19class CreateNewsItem: 

20 """Use case "Create News Item".""" 

21 

22 def __init__( 

23 self, 

24 repo: NewsItemRepository, 

25 application_repo: ApplicationRepository, 

26 owner: Owner, 

27 ): 

28 """Initialize the use case. 

29 

30 Args: 

31 repo: The repository to create the news item. 

32 application_repo: The repository to get the application entity. 

33 owner: The owner of the news item. 

34 """ 

35 self._repo = repo 

36 self._application_repo = application_repo 

37 self._owner = owner 

38 

39 async def execute(self, command: CreateNewsItemCommand) -> NewsItemEntity: 

40 """Execute the use case. 

41 

42 Args: 

43 command: The input for this use case. 

44 

45 Raises: 

46 ApplicationNotFoundException: raised when the application does not exist. 

47 """ 

48 application = await self._application_repo.get_by_id( 

49 ApplicationIdentifier(command.application) 

50 ) 

51 if command.promotion > 0: 

52 if command.promotion_end_datetime is None: 

53 promotion = Promotion(priority=command.promotion) 

54 else: 

55 promotion = Promotion( 

56 priority=command.promotion, 

57 end_date=Timestamp.create_from_string( 

58 command.promotion_end_datetime 

59 ), 

60 ) 

61 else: 

62 promotion = None 

63 news_item = NewsItemEntity( 

64 enabled=command.enabled, 

65 promotion=promotion, 

66 period=Period( 

67 start_date=Timestamp.create_from_string(command.publish_datetime), 

68 end_date=Timestamp.create_from_string(command.end_datetime), 

69 ), 

70 application=application, 

71 texts=[ 

72 LocaleText( 

73 locale=Locale(text.locale), 

74 format=DocumentFormat(text.format), 

75 title=text.title, 

76 content=text.content, 

77 summary=text.summary, 

78 author=self._owner, 

79 ) 

80 for text in command.texts 

81 ], 

82 remark=command.remark, 

83 ) 

84 

85 return await self._repo.create(news_item)