Coverage for src/kwai/modules/club/repositories/member_importer.py: 100%
29 statements
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2024-01-01 00:00 +0000
1"""Module for defining an abstract class for importing member entities."""
3from abc import ABC, abstractmethod
4from dataclasses import dataclass
5from typing import AsyncGenerator
7from async_lru import alru_cache
9from kwai.core.domain.value_objects.owner import Owner
10from kwai.modules.club.domain.country import CountryEntity
11from kwai.modules.club.domain.file_upload import FileUploadEntity
12from kwai.modules.club.domain.member import MemberEntity
13from kwai.modules.club.repositories.country_repository import CountryRepository
16@dataclass(kw_only=True, frozen=True, slots=True)
17class Result:
18 """Base dataclass for a result of a member import."""
20 row: int
23@dataclass(kw_only=True, frozen=True, slots=True)
24class OkResult(Result):
25 """Dataclass for a successful member import."""
27 member: MemberEntity
30@dataclass(kw_only=True, frozen=True, slots=True)
31class FailureResult(Result):
32 """Dataclass for a failed member import."""
34 message: str
37class MemberImporter(ABC):
38 """Abstract class for importing member entities from a file."""
40 def __init__(self, filename: str, owner: Owner, country_repo: CountryRepository):
41 """Initialize the importer.
43 Args:
44 filename: The name of the csv file.
45 owner: The user that started the upload.
46 country_repo: A repository to get the nationality of a member.
47 """
48 self._filename = filename
49 self._owner = owner
50 self._country_repo = country_repo
52 @abstractmethod
53 def import_(self) -> AsyncGenerator[Result, None]:
54 """Import member entities.
56 For each imported (or failed import) of a member, a result will be yielded.
57 """
59 def create_file_upload_entity(self, preview: bool) -> FileUploadEntity:
60 """Create a file upload entity."""
61 return FileUploadEntity(
62 filename=self._filename, owner=self._owner, preview=preview
63 )
65 @staticmethod
66 @alru_cache
67 async def _get_country(
68 country_repo: CountryRepository, iso_2: str
69 ) -> CountryEntity:
70 """Gets the country from the repository.
72 The value is cached. When the country does not exist, a CountryNotFoundException
73 is raised.
75 Note: to avoid memory leaks, this method is a static method.
76 """
77 return await country_repo.get_by_iso_2(iso_2)