206 lines
7.0 KiB
Python
206 lines
7.0 KiB
Python
from __future__ import annotations
|
||
|
||
from datetime import date
|
||
from typing import Iterable
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException
|
||
from pydantic import BaseModel
|
||
from sqlalchemy import func
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import constants
|
||
from ..constants import parse_period_label
|
||
from ..db import get_db
|
||
from ..models import Period, Project, Update
|
||
|
||
router = APIRouter()
|
||
|
||
|
||
class PeriodCreate(BaseModel):
|
||
label: str | None = None
|
||
year: int | None = None
|
||
month: int | None = None
|
||
week: int | None = None
|
||
start_date: str | None = None
|
||
end_date: str | None = None
|
||
|
||
# 状态严重程度排序(越靠前越需要关注)
|
||
_SEVERITY = ["blocked", "at_risk", "paused", "not_started", "in_progress", "done"]
|
||
|
||
|
||
def worst_status(codes: Iterable[str]) -> str:
|
||
codes = [c for c in codes if c]
|
||
for c in _SEVERITY:
|
||
if c in codes:
|
||
return c
|
||
return "in_progress"
|
||
|
||
|
||
def resolve_period_ids(
|
||
db: Session,
|
||
period_id: int | None = None,
|
||
year: int | None = None,
|
||
month: int | None = None,
|
||
) -> list[int]:
|
||
"""把 (period_id) 或 (year+month) 解析为具体的周周期 id 列表。"""
|
||
if period_id:
|
||
p = db.get(Period, period_id)
|
||
return [p.id] if p else []
|
||
if year and month:
|
||
rows = (
|
||
db.query(Period.id)
|
||
.filter(Period.year == year, Period.month == month)
|
||
.order_by(Period.sort_key)
|
||
.all()
|
||
)
|
||
return [r[0] for r in rows]
|
||
latest = db.query(Period).order_by(Period.sort_key.desc()).first()
|
||
return [latest.id] if latest else []
|
||
|
||
|
||
# ---------------------------------------------------------------- 周期
|
||
@router.get("/periods")
|
||
def list_periods(db: Session = Depends(get_db)):
|
||
from ..models import CustomUpdate
|
||
from .focus import _week_period
|
||
|
||
# 周期按时间自动创建:确保「今天所在的这一周」一定存在,不再需要手动新建第几周。
|
||
# (_week_period 已用于「每周重点工作」,没有则补一条,口径与 week_of_date 一致)
|
||
_week_period(db, *constants.week_of_date(date.today()))
|
||
db.commit()
|
||
|
||
weeks = db.query(Period).order_by(Period.sort_key).all()
|
||
uc = dict(
|
||
db.query(Update.period_id, func.count(Update.id)).group_by(Update.period_id).all()
|
||
)
|
||
cc = dict(
|
||
db.query(CustomUpdate.period_id, func.count(CustomUpdate.id))
|
||
.group_by(CustomUpdate.period_id)
|
||
.all()
|
||
)
|
||
|
||
months: dict[tuple[int, int], dict] = {}
|
||
week_list = []
|
||
for p in weeks:
|
||
d = p.to_dict()
|
||
d["update_count"] = uc.get(p.id, 0)
|
||
d["custom_update_count"] = cc.get(p.id, 0)
|
||
# 该周的实际起止日期(口径见 constants.month_week1),供前端按「顶栏选中的周期」取数
|
||
d["first_day"] = constants.period_first_day(p.year, p.month, p.week)
|
||
d["last_day"] = constants.period_last_day(p.year, p.month, p.week)
|
||
week_list.append(d)
|
||
|
||
key = (p.year, p.month)
|
||
item = months.setdefault(
|
||
key,
|
||
{
|
||
"year": p.year,
|
||
"month": p.month,
|
||
"label": f"{p.year}年{p.month}月",
|
||
"sort_key": p.year * 10000 + p.month * 100,
|
||
"period_ids": [],
|
||
"week_count": 0,
|
||
},
|
||
)
|
||
item["period_ids"].append(p.id)
|
||
item["week_count"] += 1
|
||
# 月视图的日期范围 = 该月各周的并集,与 /weekly 的月口径一致
|
||
if "first_day" not in item or d["first_day"] < item["first_day"]:
|
||
item["first_day"] = d["first_day"]
|
||
if "last_day" not in item or d["last_day"] > item["last_day"]:
|
||
item["last_day"] = d["last_day"]
|
||
y, m, w = constants.week_of_date(date.today())
|
||
today_key = y * 10000 + m * 100 + w
|
||
return {
|
||
"weeks": week_list,
|
||
"months": sorted(months.values(), key=lambda x: x["sort_key"]),
|
||
# 周期表里可能已经预建了后面的周,今天所在的这一周单独给出去当默认值
|
||
"today_id": next((d["id"] for d in week_list if d["sort_key"] == today_key), None),
|
||
}
|
||
|
||
|
||
@router.post("/periods")
|
||
def create_period(payload: PeriodCreate, db: Session = Depends(get_db)):
|
||
"""新增一个周期。可直接给 label(如『9月第1周』),年份自动接续在最新周期之后。"""
|
||
latest = db.query(Period).order_by(Period.sort_key.desc()).first()
|
||
|
||
year, month, week = payload.year, payload.month, payload.week
|
||
if month is None:
|
||
if not payload.label:
|
||
raise HTTPException(400, "请提供 label(如『9月第1周』)或 month")
|
||
parsed = parse_period_label(payload.label, 0)
|
||
if not parsed:
|
||
raise HTTPException(400, "无法识别周期,请使用『9月第1周』这类格式")
|
||
label_year, month, week = parsed
|
||
if label_year: # 标签里显式写了年份
|
||
year = label_year
|
||
|
||
week = week or 0
|
||
if year is None:
|
||
if latest is None:
|
||
year = 2026
|
||
elif month < latest.month:
|
||
# 只按月份判断跨年:补录同年更早的周次(如已有9月第4周,再补9月第1周)应留在同一年
|
||
year = latest.year + 1
|
||
else:
|
||
year = latest.year
|
||
|
||
sort_key = year * 10000 + month * 100 + week
|
||
existed = db.query(Period).filter(Period.sort_key == sort_key).one_or_none()
|
||
if existed:
|
||
return {"period": existed.to_dict(), "created": False}
|
||
|
||
label = (payload.label or "").strip() or f"{month}月第{week}周"
|
||
p = Period(
|
||
label=label,
|
||
kind="week",
|
||
year=year,
|
||
month=month,
|
||
week=week,
|
||
start_date=payload.start_date,
|
||
end_date=payload.end_date,
|
||
sort_key=sort_key,
|
||
)
|
||
db.add(p)
|
||
db.commit()
|
||
db.refresh(p)
|
||
return {"period": p.to_dict(), "created": True}
|
||
|
||
|
||
@router.delete("/periods/{pid}")
|
||
def delete_period(pid: int, db: Session = Depends(get_db)):
|
||
"""删除周期。仅允许删除没有任何执行记录(通用 / 定制)的空周期。"""
|
||
from ..models import CustomUpdate
|
||
|
||
p = db.get(Period, pid)
|
||
if not p:
|
||
raise HTTPException(404, "周期不存在")
|
||
n1 = db.query(Update).filter(Update.period_id == pid).count()
|
||
n2 = db.query(CustomUpdate).filter(CustomUpdate.period_id == pid).count()
|
||
if n1 or n2:
|
||
raise HTTPException(400, f"该周期下已有 {n1 + n2} 条执行记录,请先删除记录再删周期")
|
||
db.delete(p)
|
||
db.commit()
|
||
return {"ok": True}
|
||
|
||
|
||
@router.get("/meta")
|
||
def meta(db: Session = Depends(get_db)):
|
||
from ..ai_parser import ai_enabled, get_ai_settings
|
||
|
||
s = get_ai_settings(db)
|
||
return {
|
||
"statuses": [
|
||
{"code": c, "name": n, "color": col} for c, n, col in constants.STATUSES
|
||
],
|
||
"priorities": [
|
||
{"code": c, "name": n, "color": col} for c, n, col in constants.PRIORITIES
|
||
],
|
||
"ai": {
|
||
"enabled": ai_enabled(db),
|
||
"model": s.get("ai_model"),
|
||
"api_base": s.get("ai_api_base"),
|
||
"has_key": bool((s.get("ai_api_key") or "").strip()),
|
||
},
|
||
}
|