Files
OSIT-AE-API-FastAPI/app/models/post_comment_models.py
Scott Idem 78f04bca50 fix(v3-vision): allow resolved integers to pass model validation during creation
Hardened root_validators in Event and Post Comment models to use Union[int, str] for Vision ID fields. This ensures that integer IDs resolved by sanitize_payload reach the database during POST/PATCH operations while maintaining clean string outputs for clients.
2026-02-05 20:30:44 -05:00

106 lines
4.6 KiB
Python

import datetime, pytz
from typing import Dict, List, Optional, Set, Union, ClassVar
from pydantic import BaseModel, EmailStr, Field, Json, PrivateAttr, ValidationError, validator, root_validator
from app.db_sql import redis_lookup_id_random
from app.lib_general import log, logging, secure_hash_string
from app.models.common_field_schema import base_fields, default_num_bytes
from app.models.person_models import Person_Base
from app.models.user_models import User_Base
# ### BEGIN ### API Post Comment Models ### Post_Comment_Base() ###
# Updated 2024-11-13
class Post_Comment_Base(BaseModel):
log.setLevel(logging.WARNING) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
# --- Standardized Vision IDs (Strings for API, Integers for DB) ---
# We use Union[int, str] to allow both public string IDs and resolved DB integers to pass validation.
id: Optional[Union[int, str]] = Field(None, **base_fields['post_comment_id_random'])
post_comment_id: Optional[Union[int, str]] = Field(None, **base_fields['post_comment_id_random'])
post_id: Optional[Union[int, str]] = Field(None, **base_fields['post_id_random'])
account_id: Optional[Union[int, str]] = Field(None, **base_fields['account_id_random'])
person_id: Optional[Union[int, str]] = Field(None, **base_fields['person_id_random'])
user_id: Optional[Union[int, str]] = Field(None, **base_fields['user_id_random'])
# --- Standardized Legacy / Internal IDs (Excluded) ---
id_random: Optional[str] = Field(None, alias='post_comment_id_random', exclude=True)
external_person_id: Optional[str] # Person ID generated by external system (should be stable and not change)
title: Optional[str]
content: Optional[str]
anonymous: Optional[bool]
full_name: Optional[str]
email: Optional[str]
notify: Optional[bool]
# timezone: Optional[str]
linked_li_json: Optional[Union[Json, None]]
# cfg_json: Optional[Union[Json, None]]
enable: Optional[bool]
hide: Optional[bool]
priority: Optional[bool]
sort: Optional[int]
group: Optional[str]
notes: Optional[str]
created_on: Optional[datetime.datetime] = None
updated_on: Optional[datetime.datetime] = None
# Including other related objects
person: Optional[Person_Base]
user: Optional[User_Base]
_processed_at: datetime.datetime = PrivateAttr(default_factory=datetime.datetime.now)
@root_validator(pre=True)
def map_v3_ids(cls, values):
"""
Vision Transformer:
Map DB keys to clean API keys and strip internal integers during READ operations.
During CREATE (POST) operations, we ensure resolved integers are preserved.
"""
# 1. Map Random Strings to Clean Names
rid = values.get('id_random') or values.get('post_comment_id_random')
if rid and isinstance(rid, str):
values['id'] = rid
values['post_comment_id'] = rid
if p_rid := values.get('post_id_random'): values['post_id'] = p_rid
if a_rid := values.get('account_id_random'): values['account_id'] = a_rid
if per_rid := values.get('person_id_random'): values['person_id'] = per_rid
if u_rid := values.get('user_id_random'): values['user_id'] = u_rid
# 2. Prevent "Collision Population" or leakage of integers during API responses
# WE MUST NOT DELETE these if they are already integers during a POST operation
# as they have been resolved by sanitize_payload.
# We only delete the integer if a string version was successfully mapped above.
for k in ['id', 'post_comment_id', 'post_id', 'account_id', 'person_id', 'user_id']:
val = values.get(k)
if val is not None and not isinstance(val, str):
# If we have a random ID counterpart in the source dict, we are in "Read Mode".
# In Read Mode, we prioritize the string ID for the client.
# In "Create Mode", the random ID field won't be in 'values' after sanitize_payload
# but the integer will be in 'k'.
if values.get(f'{k}_random') or (k=='id' and values.get('id_random')):
del values[k]
return values
# Fields that are part of the model (for reading) but should not be saved to the DB table.
# account_id is joined from the 'post' table in the v_post_comment view.
fields_to_exclude_from_db: ClassVar[list] = ['account_id']
class Config:
underscore_attrs_are_private = True
allow_population_by_field_name = False
fields = base_fields
# ### END ### API Post Comment Models ### Post_Comment_Base() ###