Spaces:
Running
Running
| import uuid | |
| from fastapi import APIRouter, Depends, HTTPException | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy.future import select | |
| from pydantic import BaseModel | |
| from typing import Optional, List | |
| from apps.api.dependencies.auth import get_api_key | |
| from packages.core.database import get_db | |
| from packages.core.models import Subscription | |
| router = APIRouter(prefix="/subscription", tags=["Subscription"]) | |
| class SubscriptionRequest(BaseModel): | |
| user_email: str | |
| target_entity_id: Optional[str] = None | |
| target_hs_code: Optional[str] = None | |
| class SubscriptionResponse(BaseModel): | |
| id: str | |
| user_email: str | |
| target_entity_id: Optional[str] | |
| target_hs_code: Optional[str] | |
| async def create_subscription( | |
| req: SubscriptionRequest, | |
| api_key: str = Depends(get_api_key), | |
| db: AsyncSession = Depends(get_db) | |
| ): | |
| """ | |
| 创建动态监控与预警订阅。 | |
| 可以订阅特定企业或特定 HS Code。 | |
| """ | |
| if not req.target_entity_id and not req.target_hs_code: | |
| raise HTTPException(status_code=400, detail="Must provide target_entity_id or target_hs_code") | |
| sub_id = str(uuid.uuid4()) | |
| sub = Subscription( | |
| id=sub_id, | |
| user_email=req.user_email, | |
| target_entity_id=req.target_entity_id, | |
| target_hs_code=req.target_hs_code | |
| ) | |
| db.add(sub) | |
| await db.commit() | |
| return SubscriptionResponse( | |
| id=sub_id, | |
| user_email=sub.user_email, | |
| target_entity_id=sub.target_entity_id, | |
| target_hs_code=sub.target_hs_code | |
| ) | |
| async def list_subscriptions( | |
| user_email: str, | |
| api_key: str = Depends(get_api_key), | |
| db: AsyncSession = Depends(get_db) | |
| ): | |
| """ | |
| 获取指定用户的所有订阅 | |
| """ | |
| stmt = select(Subscription).where(Subscription.user_email == user_email) | |
| result = await db.execute(stmt) | |
| subs = result.scalars().all() | |
| return [ | |
| SubscriptionResponse( | |
| id=s.id, | |
| user_email=s.user_email, | |
| target_entity_id=s.target_entity_id, | |
| target_hs_code=s.target_hs_code | |
| ) for s in subs | |
| ] | |