Coverage for src/kwai/api/v1/club/schemas/member.py: 100%

29 statements  

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

1"""Module for defining the JSON:API resource for a member.""" 

2 

3from typing import Annotated, Self 

4 

5from pydantic import BaseModel, Field 

6 

7from kwai.api.v1.club.schemas.contact import ContactResource 

8from kwai.api.v1.club.schemas.person import ( 

9 PersonDocument, 

10 PersonResource, 

11) 

12from kwai.api.v1.club.schemas.resources import ( 

13 MemberResourceIdentifier, 

14 PersonResourceIdentifier, 

15) 

16from kwai.api.v1.schemas import CountryResource 

17from kwai.core.json_api import Document, Relationship, ResourceData, ResourceMeta 

18from kwai.modules.club.domain.member import MemberEntity 

19 

20 

21class MemberAttributes(BaseModel): 

22 """Attributes for the member JSON:API resource.""" 

23 

24 license_number: str 

25 license_end_date: str 

26 remark: str 

27 active: bool 

28 competition: bool 

29 

30 

31class MemberRelationships(BaseModel): 

32 """Relationships of a member JSON:API resource.""" 

33 

34 person: Relationship[PersonResourceIdentifier] 

35 

36 

37class MemberResource( 

38 MemberResourceIdentifier, ResourceData[MemberAttributes, MemberRelationships] 

39): 

40 """A JSON:API resource for a member.""" 

41 

42 

43MemberInclude = Annotated[ 

44 PersonResource | ContactResource | CountryResource, Field(discriminator="type") 

45] 

46 

47 

48class MemberDocument(Document[MemberResource, MemberInclude]): 

49 """A JSON:API document for one or more member resources.""" 

50 

51 @classmethod 

52 def create(cls, member: MemberEntity) -> Self: 

53 """Create a member document from a member entity.""" 

54 person_document = PersonDocument.create(member.person) 

55 

56 member_resource = MemberResource( 

57 id=str(member.uuid), 

58 attributes=MemberAttributes( 

59 license_number=member.license.number, 

60 license_end_date=str(member.license.end_date), 

61 remark=member.remark, 

62 active=member.is_active, 

63 competition=member.is_competitive, 

64 ), 

65 meta=ResourceMeta( 

66 created_at=str(member.traceable_time.created_at), 

67 updated_at=str(member.traceable_time.updated_at), 

68 ), 

69 ) 

70 member_resource.relationships = MemberRelationships( 

71 person=Relationship[PersonResourceIdentifier]( 

72 data=PersonResourceIdentifier(id=person_document.resource.id) 

73 ) 

74 ) 

75 included: set[MemberInclude] = set() 

76 included.add(person_document.resource) 

77 if person_document.included is not None: 

78 included = included.union(person_document.included) 

79 

80 return cls(data=member_resource, included=included)