66 行
2.6 KiB
Python
66 行
2.6 KiB
Python
from __future__ import annotations
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.database import get_db
|
|
from app.auth import get_current_user
|
|
from app.models.calendar import CalendarMonth
|
|
from app.schemas.calendar import CalendarMonthSchema, CalendarMonthResponse
|
|
|
|
router = APIRouter(prefix="/api/calendar", tags=["行程日历"], dependencies=[Depends(get_current_user)])
|
|
|
|
MONTH_NAMES = ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
|
|
|
|
|
|
@router.get("/", response_model=list[CalendarMonthResponse])
|
|
def list_calendar(
|
|
year: int = Query(..., description="年份,如 2025"),
|
|
db: Session = Depends(get_db),
|
|
):
|
|
items = db.query(CalendarMonth).filter(CalendarMonth.year == year).order_by(CalendarMonth.month).all()
|
|
# 如果该年份还没有数据,自动初始化12个月份
|
|
if not items:
|
|
for m in range(1, 13):
|
|
month_record = CalendarMonth(
|
|
year=year,
|
|
month=m,
|
|
title=MONTH_NAMES[m - 1],
|
|
highlights=[],
|
|
events=[],
|
|
is_available=False,
|
|
)
|
|
db.add(month_record)
|
|
db.commit()
|
|
items = db.query(CalendarMonth).filter(CalendarMonth.year == year).order_by(CalendarMonth.month).all()
|
|
return [CalendarMonthResponse.model_validate(item) for item in items]
|
|
|
|
|
|
@router.put("/{year}/{month}", response_model=CalendarMonthResponse)
|
|
def update_calendar_month(year: int, month: int, req: CalendarMonthSchema, db: Session = Depends(get_db)):
|
|
item = db.query(CalendarMonth).filter(CalendarMonth.year == year, CalendarMonth.month == month).first()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="日历月份不存在")
|
|
for key, val in req.model_dump().items():
|
|
setattr(item, key, val)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return CalendarMonthResponse.model_validate(item)
|
|
|
|
|
|
@router.post("/init")
|
|
def init_calendar_year(year: int = Query(..., description="要初始化的年份"), db: Session = Depends(get_db)):
|
|
existing = db.query(CalendarMonth).filter(CalendarMonth.year == year).count()
|
|
if existing > 0:
|
|
return {"message": f"{year}年日历已存在,共{existing}条记录"}
|
|
for m in range(1, 13):
|
|
db.add(CalendarMonth(
|
|
year=year,
|
|
month=m,
|
|
title=MONTH_NAMES[m - 1],
|
|
highlights=[],
|
|
events=[],
|
|
is_available=False,
|
|
))
|
|
db.commit()
|
|
return {"message": f"{year}年12个月份初始化成功"}
|