from datetime import timedelta from sqlalchemy.ext.asyncio import AsyncSession from app.core.db import utc_now from app.features.user import repo from app.features.user.models import User from app.features.user.schemas import ( TestSubscriptionResponse, UpdateUserProfileRequest, UserProfileResponse, ) def _user_to_profile(user: User) -> UserProfileResponse: return UserProfileResponse( id=user.id, phone=user.phone, email=user.email, nickname=user.nickname, avatar_url=user.avatar_url, subscription_type=user.subscription_type, created_at=user.created_at.isoformat(), birth_year=user.birth_year, birth_place=user.birth_place, grew_up_place=user.grew_up_place, occupation=user.occupation, ) class UserService: def __init__(self, db: AsyncSession): self._db = db async def update_profile( self, user_id: str, body: UpdateUserProfileRequest ) -> UserProfileResponse: user = await repo.get_user_by_id(user_id, self._db) if not user: raise ValueError("用户不存在") if body.birth_year is not None: user.birth_year = body.birth_year if body.birth_place is not None: user.birth_place = body.birth_place if body.grew_up_place is not None: user.grew_up_place = body.grew_up_place if body.occupation is not None: user.occupation = body.occupation await self._db.commit() await self._db.refresh(user) return _user_to_profile(user) async def toggle_test_subscription( self, user_id: str, action: str, plan_id: str ) -> TestSubscriptionResponse: user = await repo.get_user_by_id(user_id, self._db) if not user: raise ValueError("用户不存在") now = utc_now() if action == "activate": user.subscription_type = plan_id user.subscription_expires_at = now + timedelta(days=365) await self._db.commit() return TestSubscriptionResponse( success=True, message=f"已开启测试订阅:{plan_id}", subscription_type=plan_id, ) user.subscription_type = "free" user.subscription_expires_at = None await self._db.commit() return TestSubscriptionResponse( success=True, message="已关闭测试订阅,恢复免费体验版", subscription_type="free", )