# app/repositories/health_repository.py """ HealthSync AI 건강 데이터 리포지토리 (쿼리 분리) """ from typing import Dict, Any, Optional, List from app.repositories.queries import HealthQueries, UserQueries import logging logger = logging.getLogger(__name__) class HealthRepository: """건강 데이터 DB 조회 리포지토리""" @staticmethod def _get_db(): """simple_db를 lazy import로 가져오기 (순환 import 방지)""" from app.utils.database_utils import simple_db return simple_db @staticmethod async def get_latest_health_checkup_by_user_id(user_id: int) -> Optional[Dict[str, Any]]: """사용자 ID로 최신 건강검진 데이터 조회""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_query( HealthQueries.GET_LATEST_HEALTH_CHECKUP, {"user_id": user_id} ) if result and len(result) > 0: return result[0] return None except Exception as e: logger.error(f"건강검진 데이터 조회 실패 - user_id: {user_id}, error: {str(e)}") raise Exception(f"건강검진 데이터 조회 실패: {str(e)}") @staticmethod async def get_user_basic_info_by_id(user_id: int) -> Optional[Dict[str, Any]]: """사용자 ID로 기본 정보 조회""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_query( UserQueries.GET_USER_BASIC_INFO, {"user_id": user_id} ) if result and len(result) > 0: return result[0] return None except Exception as e: logger.error(f"사용자 기본정보 조회 실패 - user_id: {user_id}, error: {str(e)}") raise Exception(f"사용자 기본정보 조회 실패: {str(e)}") @staticmethod async def get_health_history_by_user_id(user_id: int, limit: int = 5) -> List[Dict[str, Any]]: """사용자 건강검진 이력 조회""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_query( HealthQueries.GET_HEALTH_HISTORY, {"user_id": user_id, "limit": limit} ) return result if result else [] except Exception as e: logger.error(f"건강검진 이력 조회 실패 - user_id: {user_id}, error: {str(e)}") raise Exception(f"건강검진 이력 조회 실패: {str(e)}") @staticmethod async def get_normal_ranges_by_gender(gender_code: int = 0) -> List[Dict[str, Any]]: """성별에 따른 정상치 기준 조회""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_query( HealthQueries.GET_NORMAL_RANGES, {"gender_code": gender_code} ) return result if result else [] except Exception as e: logger.error(f"정상치 기준 조회 실패 - gender_code: {gender_code}, error: {str(e)}") raise Exception(f"정상치 기준 조회 실패: {str(e)}") @staticmethod async def check_user_exists(user_id: int) -> bool: """사용자 존재 여부 확인""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_query( UserQueries.CHECK_USER_EXISTS, {"user_id": user_id} ) if result and len(result) > 0: return result[0]["user_count"] > 0 return False except Exception as e: logger.error(f"사용자 존재 확인 실패 - user_id: {user_id}, error: {str(e)}") return False @staticmethod async def get_user_by_google_id(google_id: str) -> Optional[Dict[str, Any]]: """Google ID로 사용자 조회""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_query( UserQueries.GET_USER_BY_GOOGLE_ID, {"google_id": google_id} ) if result and len(result) > 0: return result[0] return None except Exception as e: logger.error(f"Google ID 사용자 조회 실패 - google_id: {google_id}, error: {str(e)}") raise Exception(f"Google ID 사용자 조회 실패: {str(e)}") @staticmethod async def insert_health_checkup(health_data: Dict[str, Any]) -> int: """건강검진 데이터 삽입""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_insert_update( HealthQueries.INSERT_HEALTH_CHECKUP, health_data ) return result except Exception as e: logger.error(f"건강검진 데이터 삽입 실패 - error: {str(e)}") raise Exception(f"건강검진 데이터 삽입 실패: {str(e)}") @staticmethod async def update_health_checkup(checkup_id: int, update_data: Dict[str, Any]) -> int: """건강검진 데이터 업데이트""" try: simple_db = HealthRepository._get_db() update_data["checkup_id"] = checkup_id result = await simple_db.execute_insert_update( HealthQueries.UPDATE_HEALTH_CHECKUP, update_data ) return result except Exception as e: logger.error(f"건강검진 데이터 업데이트 실패 - checkup_id: {checkup_id}, error: {str(e)}") raise Exception(f"건강검진 데이터 업데이트 실패: {str(e)}") @staticmethod async def insert_user(user_data: Dict[str, Any]) -> int: """사용자 생성""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_insert_update( UserQueries.INSERT_USER, user_data ) return result except Exception as e: logger.error(f"사용자 생성 실패 - error: {str(e)}") raise Exception(f"사용자 생성 실패: {str(e)}") @staticmethod async def update_user_info(member_serial_number: int, user_data: Dict[str, Any]) -> int: """사용자 정보 업데이트""" try: simple_db = HealthRepository._get_db() user_data["member_serial_number"] = member_serial_number result = await simple_db.execute_insert_update( UserQueries.UPDATE_USER_INFO, user_data ) return result except Exception as e: logger.error(f"사용자 정보 업데이트 실패 - member_serial_number: {member_serial_number}, error: {str(e)}") raise Exception(f"사용자 정보 업데이트 실패: {str(e)}") @staticmethod async def update_last_login(member_serial_number: int, last_login_at: str) -> int: """최근 로그인 시간 업데이트""" try: simple_db = HealthRepository._get_db() result = await simple_db.execute_insert_update( UserQueries.UPDATE_LAST_LOGIN, {"member_serial_number": member_serial_number, "last_login_at": last_login_at} ) return result except Exception as e: logger.error(f"로그인 시간 업데이트 실패 - member_serial_number: {member_serial_number}, error: {str(e)}") raise Exception(f"로그인 시간 업데이트 실패: {str(e)}")