84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
from sqlalchemy import func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.deps import get_current_active_user, get_db
|
|
from app.models.correction import Correction
|
|
from app.models.spot import Spot
|
|
from app.models.user import User
|
|
from app.schemas.common import PageResponse
|
|
from app.schemas.correction import CorrectionCreate, CorrectionOut
|
|
|
|
router = APIRouter()
|
|
|
|
FIELD_LABELS = {
|
|
"title": "地点名称",
|
|
"city": "所在城市",
|
|
"description": "地点介绍",
|
|
"transport": "交通方式",
|
|
"best_time": "最佳拍摄时间",
|
|
"difficulty": "路径难度",
|
|
"price": "收费信息",
|
|
}
|
|
|
|
|
|
@router.post(
|
|
"/spots/{spot_id}/corrections",
|
|
response_model=CorrectionOut,
|
|
status_code=status.HTTP_201_CREATED,
|
|
)
|
|
async def create_correction(
|
|
spot_id: int,
|
|
payload: CorrectionCreate,
|
|
current_user: User = Depends(get_current_active_user),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
result = await db.execute(select(Spot).where(Spot.id == spot_id))
|
|
spot = result.scalar_one_or_none()
|
|
if not spot:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Spot not found")
|
|
|
|
if spot.creator_id == current_user.id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Cannot submit correction for your own spot",
|
|
)
|
|
|
|
correction = Correction(
|
|
spot_id=spot_id,
|
|
user_id=current_user.id,
|
|
field_name=payload.field_name,
|
|
suggested_value=payload.suggested_value,
|
|
reason=payload.reason,
|
|
)
|
|
db.add(correction)
|
|
await db.commit()
|
|
await db.refresh(correction)
|
|
return correction
|
|
|
|
|
|
@router.get(
|
|
"/spots/{spot_id}/corrections",
|
|
response_model=PageResponse[CorrectionOut],
|
|
)
|
|
async def list_corrections(
|
|
spot_id: int,
|
|
page: int = Query(default=1, ge=1),
|
|
page_size: int = Query(default=20, ge=1, le=100),
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
base = Correction.spot_id == spot_id
|
|
count_result = await db.execute(select(func.count(Correction.id)).where(base))
|
|
total = count_result.scalar() or 0
|
|
|
|
offset = (page - 1) * page_size
|
|
result = await db.execute(
|
|
select(Correction)
|
|
.where(base)
|
|
.order_by(Correction.created_at.desc())
|
|
.offset(offset)
|
|
.limit(page_size)
|
|
)
|
|
items = result.scalars().all()
|
|
return PageResponse(total=total, items=[CorrectionOut.model_validate(c) for c in items])
|