65 lines
2.3 KiB
Python
65 lines
2.3 KiB
Python
from datetime import datetime, timezone, timedelta
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.dependencies import get_db, get_current_user
|
|
from app.models.contact_request import ContactRequest
|
|
from app.models.user import User
|
|
from app.schemas.contact import ContactRequestCreate
|
|
from app.utils.id_gen import generate_id
|
|
|
|
router = APIRouter(prefix="/contact", tags=["contact"])
|
|
|
|
|
|
@router.post("/request", summary="提交联系请求", status_code=status.HTTP_201_CREATED)
|
|
async def create_contact_request(
|
|
request: ContactRequestCreate,
|
|
db: AsyncSession = Depends(get_db),
|
|
user: User = Depends(get_current_user),
|
|
):
|
|
today_str = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
|
|
async with db.begin_nested():
|
|
user_result = await db.execute(
|
|
select(User).where(User.id == user.id).with_for_update().limit(1)
|
|
)
|
|
locked_user = user_result.scalar_one_or_none()
|
|
if not locked_user:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
|
|
|
|
existing = await db.execute(
|
|
select(ContactRequest.id)
|
|
.where(ContactRequest.user_id == user.id)
|
|
.where(ContactRequest.submit_date == today_str)
|
|
.limit(1)
|
|
)
|
|
if existing.scalar_one_or_none():
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="每个账号每天只能提交一次联系我们"
|
|
)
|
|
|
|
try:
|
|
contact_request = ContactRequest(
|
|
id=generate_id(),
|
|
user_id=user.id,
|
|
phone=request.phone,
|
|
company_name=request.company_name,
|
|
industry=request.industry,
|
|
name=request.name,
|
|
message=request.message,
|
|
submit_date=today_str,
|
|
)
|
|
db.add(contact_request)
|
|
await db.commit()
|
|
except IntegrityError:
|
|
await db.rollback()
|
|
raise HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="每个账号每天只能提交一次联系我们"
|
|
)
|
|
|
|
return {"message": "提交成功,我们会尽快与您联系"} |