刘涛 8c0a5f489d Initial commit: hulai admin API backend
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-22 22:01:23 +08:00

69 行
2.5 KiB
Python

from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import func as sqlfunc
from app.database import get_db
from app.auth import get_current_user
from app.models.contact import ContactChannel, ContactConfig
from app.schemas.contact import ContactChannelSchema, ContactChannelResponse, ContactConfigSchema
router = APIRouter(prefix="/api/contact", tags=["联系方式"], dependencies=[Depends(get_current_user)])
@router.get("/channels", response_model=list[ContactChannelResponse])
def list_channels(db: Session = Depends(get_db)):
channels = db.query(ContactChannel).order_by(ContactChannel.sort_order).all()
return [ContactChannelResponse.model_validate(c) for c in channels]
@router.post("/channels", response_model=ContactChannelResponse, status_code=201)
def create_channel(req: ContactChannelSchema, db: Session = Depends(get_db)):
max_order = db.query(sqlfunc.max(ContactChannel.sort_order)).scalar() or 0
ch = ContactChannel(**req.model_dump(), sort_order=max_order + 1)
db.add(ch)
db.commit()
db.refresh(ch)
return ContactChannelResponse.model_validate(ch)
@router.put("/channels/{ch_id}", response_model=ContactChannelResponse)
def update_channel(ch_id: int, req: ContactChannelSchema, db: Session = Depends(get_db)):
ch = db.query(ContactChannel).get(ch_id)
if not ch:
raise HTTPException(status_code=404, detail="联系方式不存在")
for key, val in req.model_dump().items():
setattr(ch, key, val)
db.commit()
db.refresh(ch)
return ContactChannelResponse.model_validate(ch)
@router.delete("/channels/{ch_id}")
def delete_channel(ch_id: int, db: Session = Depends(get_db)):
ch = db.query(ContactChannel).get(ch_id)
if not ch:
raise HTTPException(status_code=404, detail="联系方式不存在")
db.delete(ch)
db.commit()
return {"message": "删除成功"}
@router.get("/config", response_model=ContactConfigSchema)
def get_config(db: Session = Depends(get_db)):
config = db.query(ContactConfig).first()
if not config:
return ContactConfigSchema()
return ContactConfigSchema(security_notice=config.security_notice)
@router.put("/config")
def update_config(req: ContactConfigSchema, db: Session = Depends(get_db)):
config = db.query(ContactConfig).first()
if not config:
config = ContactConfig()
db.add(config)
config.security_notice = req.security_notice
db.commit()
return {"message": "更新成功"}