Skip to content

Commit

Permalink
refactor: serialization for task_status and created project dashboard…
Browse files Browse the repository at this point in the history
… fields (#1076)

* fix: Convert task_status to string in TaskBase schema

* fix: Convert created date to string in ProjectDashboard schema

* fix: datetime type and task status type

* fix: use field_serializer where appropriate in models

* fix: remove validators for task_status & created fields

---------

Co-authored-by: sujanadh <sujanadh07@gmail.com>
Co-authored-by: spwoodcock <sam.woodcock@protonmail.com>
  • Loading branch information
3 people authored Jan 5, 2024
1 parent bf8d697 commit 7bde9b5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 31 deletions.
16 changes: 6 additions & 10 deletions src/backend/app/projects/project_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@

import uuid
from datetime import datetime
from dateutil import parser
from typing import List, Optional

from dateutil import parser
from geojson_pydantic import Feature as GeojsonFeature
from pydantic import BaseModel, field_validator
from pydantic import BaseModel

from app.db import db_models
from app.models.enums import ProjectPriority, ProjectStatus, TaskSplitType
Expand Down Expand Up @@ -142,6 +142,7 @@ class ProjectBase(BaseModel):
class ProjectOut(ProjectBase):
project_uuid: uuid.UUID = uuid.uuid4()


class ReadProject(ProjectBase):
project_uuid: uuid.UUID = uuid.uuid4()
location_str: str
Expand All @@ -162,11 +163,6 @@ class ProjectDashboard(BaseModel):
total_contributors: Optional[int] = None
last_active: Optional[str] = None

@field_validator("created", mode="before")
def get_created(cls, value, values):
date = value.strftime("%d %b %Y")
return date

@field_validator("last_active", mode="before")
def get_last_active(cls, value, values):
if value is None:
Expand All @@ -180,10 +176,10 @@ def get_last_active(cls, value, values):
days_difference = time_difference.days

if days_difference == 0:
return 'today'
return "today"
elif days_difference == 1:
return 'yesterday'
return "yesterday"
elif days_difference < 7:
return f'{days_difference} day{"s" if days_difference > 1 else ""} ago'
else:
return last_active.strftime("%d %b %Y")
return last_active.strftime("%d %b %Y")
32 changes: 11 additions & 21 deletions src/backend/app/tasks/tasks_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from geojson_pydantic import Feature
from loguru import logger as log
from pydantic import BaseModel, ConfigDict, Field, ValidationInfo
from pydantic.functional_serializers import field_serializer
from pydantic.functional_validators import field_validator

from app.db.postgis_utils import geometry_to_geojson, get_centroid
Expand All @@ -41,6 +42,7 @@ class TaskHistoryBase(BaseModel):

class TaskHistoryOut(TaskHistoryBase):
"""Task mapping history display."""

status: str
username: str
profile_img: Optional[str]
Expand Down Expand Up @@ -71,20 +73,9 @@ class TaskBase(BaseModel):
locked_by_username: Optional[str] = None
task_history: Optional[List[TaskHistoryBase]] = None

@field_validator("task_status", mode="before")
def get_enum_name(cls, value, values):
if isinstance(value, int):
try:
return TaskStatus(value).name
except ValueError as e:
raise ValueError(
f"Invalid integer value for task_status: {value}"
) from e
return value

@field_validator("outline_geojson", mode="before")
@classmethod
def get_geojson_from_outline(cls, v: Any, info: ValidationInfo) -> str:
def get_geojson_from_outline(cls, value: Any, info: ValidationInfo) -> str:
"""Get outline_geojson from Shapely geom."""
if outline := info.data.get("outline"):
properties = {
Expand All @@ -98,7 +89,7 @@ def get_geojson_from_outline(cls, v: Any, info: ValidationInfo) -> str:

@field_validator("outline_centroid", mode="before")
@classmethod
def get_centroid_from_outline(cls, v: Any, info: ValidationInfo) -> str:
def get_centroid_from_outline(cls, value: Any, info: ValidationInfo) -> str:
"""Get outline_centroid from Shapely geom."""
if outline := info.data.get("outline"):
properties = {
Expand All @@ -110,17 +101,15 @@ def get_centroid_from_outline(cls, v: Any, info: ValidationInfo) -> str:
return get_centroid(outline, properties, info.data.get("id"))
return None

@field_validator("locked_by_uid", mode="before")
@classmethod
def get_lock_uid(cls, v: int, info: ValidationInfo) -> str:
@field_serializer("locked_by_uid")
def get_lock_uid(self, value: int, info: ValidationInfo) -> str:
"""Get lock uid from lock_holder details."""
if lock_holder := info.data.get("lock_holder"):
return lock_holder.id
return None

@field_validator("locked_by_username", mode="before")
@classmethod
def get_lock_username(cls, v: str, info: ValidationInfo) -> str:
@field_serializer("locked_by_username")
def get_lock_username(self, value: str, info: ValidationInfo) -> str:
"""Get lock username from lock_holder details."""
if lock_holder := info.data.get("lock_holder"):
return lock_holder.username
Expand All @@ -134,7 +123,7 @@ class Task(TaskBase):

@field_validator("qr_code_base64", mode="before")
@classmethod
def get_qrcode_base64(cls, v: Any, info: ValidationInfo) -> str:
def get_qrcode_base64(cls, value: Any, info: ValidationInfo) -> str:
"""Get base64 encoded qrcode."""
if qr_code := info.data.get("qr_code"):
log.debug(
Expand All @@ -146,7 +135,8 @@ def get_qrcode_base64(cls, v: Any, info: ValidationInfo) -> str:
log.warning(f"No QR code found for task ID {info.data.get('id')}")
return ""


class ReadTask(Task):
"""Task details plus updated task history."""

task_history: Optional[List[TaskHistoryOut]] = None
task_history: Optional[List[TaskHistoryOut]] = None

0 comments on commit 7bde9b5

Please sign in to comment.