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

28 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 contact.""" 

2 

3from typing import Annotated, Self 

4 

5from pydantic import BaseModel, Field 

6 

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

8 ContactResourceIdentifier, 

9) 

10from kwai.api.v1.resources import CountryResourceIdentifier 

11from kwai.api.v1.schemas import CountryDocument, CountryResource 

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

13from kwai.modules.club.domain.contact import ContactEntity 

14 

15 

16class ContactAttributes(BaseModel): 

17 """Attributes for the contact JSON:API resource.""" 

18 

19 emails: list[str] = Field(default_factory=list) 

20 tel: str 

21 mobile: str 

22 address: str 

23 postal_code: str 

24 city: str 

25 county: str 

26 remark: str 

27 

28 

29class ContactRelationships(BaseModel): 

30 """Relationships for the contact JSON:API resource.""" 

31 

32 country: Relationship[CountryResourceIdentifier] 

33 

34 

35class ContactResource( 

36 ContactResourceIdentifier, ResourceData[ContactAttributes, ContactRelationships] 

37): 

38 """A JSON:API resource for a contact.""" 

39 

40 

41ContactInclude = Annotated[CountryResource, Field(discriminator="type")] 

42 

43 

44class ContactDocument(Document[ContactResource, ContactInclude]): 

45 """A JSON:API document for one or more contact resources.""" 

46 

47 @classmethod 

48 def create(cls, contact: ContactEntity) -> Self: 

49 """Create a contact document from a contact entity.""" 

50 country_document = CountryDocument.create(contact.address.country) 

51 

52 contact_resource = ContactResource( 

53 id=str(contact.id), 

54 attributes=ContactAttributes( 

55 emails=[str(email) for email in contact.emails], 

56 tel=contact.tel, 

57 mobile=contact.mobile, 

58 address=contact.address.address, 

59 postal_code=contact.address.postal_code, 

60 city=contact.address.city, 

61 county=contact.address.county, 

62 remark=contact.remark, 

63 ), 

64 relationships=ContactRelationships( 

65 country=Relationship[CountryResourceIdentifier]( 

66 data=CountryResourceIdentifier(id=country_document.data.id) 

67 ) 

68 ), 

69 meta=ResourceMeta( 

70 created_at=str(contact.traceable_time.created_at), 

71 updated_at=str(contact.traceable_time.updated_at), 

72 ), 

73 ) 

74 

75 included: set[CountryResource] = set() 

76 included.add(country_document.data) 

77 

78 return cls(data=contact_resource, included=included)