Files
chat/services/calendar_service/mobile_endpoint.py
Andrew K. Choi 76d0d86211
All checks were successful
continuous-integration/drone/push Build is passing
calendar events
2025-09-26 15:57:50 +09:00

83 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import date
from enum import Enum
from typing import Optional, Dict, Any, List, Union
from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel, Field, root_validator
from sqlalchemy.ext.asyncio import AsyncSession
from .schemas import (
EntryType, FlowIntensity, MoodType, CalendarEntryCreate, CalendarEntryResponse
)
from .schemas_mobile import (
MobileFlowIntensity, MobileMood, convert_mobile_app_format_to_server
)
from services.calendar_service.models import CalendarEntry
from shared.auth import get_current_user_from_token as get_current_user
from shared.database import get_db
class MobileCalendarEntryCreate(BaseModel):
"""Схема для создания записей в календаре из мобильного приложения"""
date: date
type: str # Тип записи (MENSTRUATION, OVULATION и т.д.)
flow_intensity: Optional[int] = None # Шкала 1-5
symptoms: Optional[List[str]] = None # Массив строк с симптомами
mood: Optional[str] = None # Настроение как строка (NORMAL, HAPPY и т.д.)
notes: Optional[str] = None
async def mobile_create_calendar_entry(
mobile_entry: MobileCalendarEntryCreate,
current_user: Dict = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Создать новую запись в календаре из мобильного приложения"""
# Преобразуем симптомы из списка в строку
symptoms_str = ""
if mobile_entry.symptoms:
symptoms_str = ", ".join(mobile_entry.symptoms)
# Преобразуем формат мобильного приложения в формат сервера
server_entry = CalendarEntryCreate(
entry_date=mobile_entry.date,
entry_type=EntryType.PERIOD if mobile_entry.type == "MENSTRUATION" else
EntryType.OVULATION if mobile_entry.type == "OVULATION" else
EntryType.SYMPTOMS,
flow_intensity=FlowIntensity.from_int(mobile_entry.flow_intensity) if mobile_entry.flow_intensity else None,
mood=MoodType.from_mobile_mood(mobile_entry.mood) if mobile_entry.mood else None,
symptoms=symptoms_str,
notes=mobile_entry.notes,
# Значения по умолчанию для обязательных полей сервера
period_symptoms="",
energy_level=1, # Минимальное значение должно быть 1
sleep_hours=0,
medications="",
)
# Создаем новую запись в календаре
new_entry = CalendarEntry(
user_id=current_user["user_id"],
entry_date=server_entry.entry_date,
entry_type=server_entry.entry_type.value,
flow_intensity=server_entry.flow_intensity.value if server_entry.flow_intensity else None,
period_symptoms=server_entry.period_symptoms,
mood=server_entry.mood.value if server_entry.mood else None,
energy_level=server_entry.energy_level,
sleep_hours=server_entry.sleep_hours,
symptoms=server_entry.symptoms,
medications=server_entry.medications,
notes=server_entry.notes,
)
db.add(new_entry)
await db.commit()
await db.refresh(new_entry)
# Если это запись о менструации, обновляем данные цикла
if server_entry.entry_type == EntryType.PERIOD:
from .main import update_cycle_data
await update_cycle_data(current_user["user_id"], server_entry.entry_date, db)
return CalendarEntryResponse.model_validate(new_entry)