From 4553cba89f89ec9e89a11274e7d0227cf9edc454 Mon Sep 17 00:00:00 2001 From: ewandor Date: Sun, 22 Jan 2023 17:55:34 +0100 Subject: [PATCH] Auto generated labels for resource --- back/app/entity/models.py | 49 ++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/back/app/entity/models.py b/back/app/entity/models.py index 17cc5ab2..43a76af9 100644 --- a/back/app/entity/models.py +++ b/back/app/entity/models.py @@ -2,17 +2,17 @@ from enum import Enum from datetime import datetime, date from typing import List, Literal -from pydantic import Field, BaseModel +from pydantic import Field, BaseModel, validator from beanie import Document, Link -class EntityType(str, Enum): - individual = 'individual' - corporation = 'corporation' - institution = 'institution' +class EntityType(BaseModel): + @property + def label(self) -> str: + return self.title -class Individual(BaseModel): +class Individual(EntityType): type: Literal['individual'] = 'individual' firstname: str middlenames: List[str] = Field(default=[]) @@ -23,28 +23,55 @@ class Individual(BaseModel): employer: str -class Employee(BaseModel): + @property + def label(self) -> str: + if len(self.surnames) > 0: + return '{} "{}" {}'.format(self.firstname, self.surnames[0], self.lastname) + + return '{} {}'.format(self.firstname, self.lastname) + + @staticmethod + def get_label(data) -> str: + if len(data['surname']) > 0: + return '{} "{}" {}'.format(data['firstname'], data['surnames'][0], data['lastname']) + + return '{} {}'.format(data['firstname'], data['lastname']) + + +class Employee(EntityType): role: str entity_id: str = Field(foreignKey={ "reference": { "resource": "entity", - "fields": "_id" + "displayName": "_id", + "condition": "entity_data.type=individual" } }) -class Corporation(BaseModel): +class Corporation(EntityType): type: Literal['corporation'] = 'corporation' title: str activity: str employees: List[Employee] = Field(default=[]) +class Institution(BaseModel): + type: Literal['institution'] = 'institution' + title: str + activity: str + employees: List[Employee] = Field(default=[]) + + class Entity(Document): _id: str - name: str address: str - entity_data: Individual | Corporation = Field(..., discriminator='type') + entity_data: Individual | Corporation | Institution = Field(..., discriminator='type') + label: str = None + + @validator("label", always=True) + def generate_label(cls, v, values, **kwargs): + return values['entity_data'].label created_at: datetime = Field(default=datetime.utcnow(), nullable=False) updated_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)