Files
goal-planner/backend/routes/plans.py
T
2026-11-02 15:45:49 +08:00

343 lines
13 KiB
Python

from datetime import date as date_type
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from database import get_db
from models.models import Plan, Task, User
from schemas.schemas import PlanResponse, TaskResponse, TaskUpdate, TaskCreate
from routes.deps import get_current_user_id
from utils import build_task_tree, find_in_tree, calculate_task_depths, collect_descendant_ids
router = APIRouter(prefix="/api/plans", tags=["plans"])
XP_BY_DEPTH = {0: 120, 1: 50, 2: 15}
XP_ALL_DONE_BONUS = 300
@router.get("/", response_model=List[PlanResponse])
def get_user_plans(user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
plans = db.query(Plan).filter(Plan.user_id == user_id).all()
plan_ids = [p.id for p in plans]
# Batch load all tasks for all plans at once
all_tasks = db.query(Task).filter(Task.plan_id.in_(plan_ids)).all() if plan_ids else []
tasks_by_plan = {}
for t in all_tasks:
tasks_by_plan.setdefault(t.plan_id, []).append(t)
result = []
for plan in plans:
result.append({
"id": plan.id,
"user_id": plan.user_id,
"goal": plan.goal,
"created_at": plan.created_at,
"tasks": build_task_tree(tasks_by_plan.get(plan.id, []))
})
return result
@router.get("/{plan_id}", response_model=PlanResponse)
def get_plan(plan_id: int, user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
plan = db.query(Plan).filter(Plan.id == plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=404, detail="Plan not found")
tasks = db.query(Task).filter(Task.plan_id == plan.id).all()
return {
"id": plan.id,
"user_id": plan.user_id,
"goal": plan.goal,
"created_at": plan.created_at,
"tasks": build_task_tree(tasks)
}
@router.delete("/{plan_id}")
def delete_plan(plan_id: int, user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
plan = db.query(Plan).filter(Plan.id == plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=404, detail="Plan not found")
db.query(Task).filter(Task.plan_id == plan_id).delete()
db.delete(plan)
db.commit()
return {"message": "Plan deleted successfully"}
@router.post("/{plan_id}/tasks", response_model=TaskResponse)
def create_task(plan_id: int, task_data: TaskCreate, user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
"""Create a new task under a plan. Optionally set parent_id for subtask."""
plan = db.query(Plan).filter(Plan.id == plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=404, detail="Plan not found")
# Validate parent_id if provided
parent_id = task_data.parent_id if task_data.parent_id else None
if parent_id is not None:
parent_task = db.query(Task).filter(Task.id == parent_id, Task.plan_id == plan_id).first()
if not parent_task:
raise HTTPException(status_code=404, detail="Parent task not found")
# Parse due_date
due_date_val = None
if task_data.due_date:
try:
due_date_val = date_type.fromisoformat(task_data.due_date)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid due_date format, use YYYY-MM-DD")
task = Task(
plan_id=plan_id,
parent_id=parent_id,
task_id=task_data.task_id,
title=task_data.title,
description=task_data.description,
dependencies=task_data.dependencies,
duration_in_hours=task_data.duration_in_hours,
priority=task_data.priority,
due_date=due_date_val,
status=task_data.status,
sort_order=task_data.sort_order,
)
db.add(task)
db.commit()
db.refresh(task)
# Build response with children
all_tasks = db.query(Task).filter(Task.plan_id == plan_id).all()
tree = build_task_tree(all_tasks)
result = find_in_tree(tree, task.id)
return result or task
@router.delete("/{plan_id}/tasks/{task_db_id}")
def delete_task(plan_id: int, task_db_id: int, user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
"""Delete a task and all its children (cascade). Also clean up dependency references."""
plan = db.query(Plan).filter(Plan.id == plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=404, detail="Plan not found")
task = db.query(Task).filter(Task.id == task_db_id, Task.plan_id == plan_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
# Load all plan tasks once for batch descendant collection
all_plan_tasks = db.query(Task).filter(Task.plan_id == plan_id).all()
# Collect all descendant IDs (no N+1)
deleted_ids = [task.id] + collect_descendant_ids(all_plan_tasks, task.id)
# Collect task_id strings for dependency cleanup
deleted_task_ids = set()
task_by_id = {t.id: t for t in all_plan_tasks}
for tid in deleted_ids:
t = task_by_id.get(tid)
if t:
deleted_task_ids.add(t.task_id)
# Remove dependency references to the deleted tasks in remaining tasks
for t in all_plan_tasks:
if t.id in deleted_ids:
continue
if t.dependencies:
cleaned = [d for d in t.dependencies if d not in deleted_task_ids]
if len(cleaned) != len(t.dependencies):
t.dependencies = cleaned
# Delete the task (cascade will handle children)
db.delete(task)
db.commit()
return {"message": "Task deleted successfully", "deleted_ids": deleted_ids}
@router.put("/{plan_id}/tasks/reorder")
def reorder_tasks(
plan_id: int,
task_orders: list[dict],
user_id: int = Depends(get_current_user_id),
db: Session = Depends(get_db),
):
"""Batch update sort_order for tasks within a plan."""
plan = db.query(Plan).filter(Plan.id == plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=404, detail="Plan not found")
for item in task_orders:
task_id = item.get("id")
sort_order = item.get("sort_order")
if task_id is None or sort_order is None:
continue
task = db.query(Task).filter(Task.id == task_id, Task.plan_id == plan_id).first()
if task:
task.sort_order = sort_order
db.commit()
return {"message": "Tasks reordered successfully"}
@router.put("/{plan_id}/tasks/{task_db_id}", response_model=TaskResponse)
def update_task(plan_id: int, task_db_id: int, task_data: TaskUpdate, user_id: int = Depends(get_current_user_id), db: Session = Depends(get_db)):
task = db.query(Task).filter(Task.id == task_db_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
plan = db.query(Plan).filter(Plan.id == task.plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=403, detail="Not authorized")
update_data = task_data.model_dump(exclude_unset=True)
# Handle due_date conversion
if "due_date" in update_data:
val = update_data.pop("due_date")
if val is not None:
try:
update_data["due_date"] = date_type.fromisoformat(val)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid due_date format, use YYYY-MM-DD")
else:
update_data["due_date"] = None
for key, value in update_data.items():
setattr(task, key, value)
db.commit()
db.refresh(task)
# Build response with children
all_tasks = db.query(Task).filter(Task.plan_id == task.plan_id).all()
tree = build_task_tree(all_tasks)
result = find_in_tree(tree, task.id)
return result or task
@router.put("/{plan_id}/tasks/{task_db_id}/status")
def update_task_status(
plan_id: int,
task_db_id: int,
status: str = Query(..., description="New status: todo, in_progress, or done"),
user_id: int = Depends(get_current_user_id),
db: Session = Depends(get_db),
):
# Validate status value
valid_statuses = {"todo", "in_progress", "done"}
if status not in valid_statuses:
raise HTTPException(status_code=400, detail=f"Invalid status. Must be one of: {', '.join(valid_statuses)}")
task = db.query(Task).filter(Task.id == task_db_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
plan = db.query(Plan).filter(Plan.id == task.plan_id, Plan.user_id == user_id).first()
if not plan:
raise HTTPException(status_code=403, detail="Not authorized")
# If trying to mark a parent task as done, check all children are done
if status == "done":
children = db.query(Task).filter(Task.parent_id == task.id).all()
if children and not all(c.status == "done" for c in children):
raise HTTPException(
status_code=400,
detail="Cannot mark this task as done until all subtasks are completed"
)
# Track all status changes for cascade
changes = [{"id": task.id, "status": status}]
task.status = status
# Cascade up: if all siblings are done, auto-complete parent; if uncompleting, auto-uncomplete parent
if task.parent_id is not None:
parent = db.query(Task).filter(Task.id == task.parent_id).first()
if parent:
siblings = db.query(Task).filter(Task.parent_id == parent.id).all()
if status == "done":
# All siblings done → auto-complete parent
if all(s.status == "done" for s in siblings):
if parent.status != "done":
parent.status = "done"
changes.append({"id": parent.id, "status": "done"})
_cascade_parent_completion(parent, db, changes)
elif status == "todo":
# Uncompleting a child → auto-uncomplete parent if it was done
if parent.status == "done":
parent.status = "todo"
changes.append({"id": parent.id, "status": "todo"})
_cascade_parent_uncompletion(parent, db, changes)
# === XP Reward System ===
# Batch calculate depths (no N+1)
all_plan_tasks = db.query(Task).filter(Task.plan_id == plan.id).all()
depth_map = calculate_task_depths(all_plan_tasks)
xp_change = 0
for change in changes:
depth = depth_map.get(change["id"], 0)
if change["status"] == "done":
xp_change += XP_BY_DEPTH.get(min(depth, 2), 15)
elif change["status"] == "todo":
# Only deduct XP if the task was previously "done"
xp_change -= XP_BY_DEPTH.get(min(depth, 2), 15)
# Check if all tasks in the plan are done (bonus XP)
# Fix: check regardless of xp_change sign (was only checking when xp_change > 0)
all_done_bonus = 0
all_currently_done = all(t.status == "done" for t in all_plan_tasks)
if all_currently_done and xp_change > 0:
# Only award bonus on the transition to all-done, not when uncompleting
all_done_bonus = XP_ALL_DONE_BONUS
xp_change += all_done_bonus
# Update user XP
user = db.query(User).filter(User.id == user_id).first()
old_level = min(100, int(((user.xp if user else 0) / 5) ** 0.5)) if user and user.xp > 0 else 0
if user and xp_change != 0:
user.xp = max(0, user.xp + xp_change)
new_level = min(100, int(((user.xp if user else 0) / 5) ** 0.5)) if user and user.xp > 0 else 0
db.commit()
user_xp = user.xp if user else 0
user_level = new_level
level_up = new_level > old_level
return {
"message": "Task status updated",
"changes": changes,
"xp_change": xp_change,
"all_done_bonus": all_done_bonus,
"user_xp": user_xp,
"user_level": user_level,
"level_up": level_up,
"old_level": old_level,
"new_level": new_level,
}
def _cascade_parent_completion(task: Task, db: Session, changes: list):
"""Recursively auto-complete parent if all its children are done."""
if task.parent_id is None:
return
parent = db.query(Task).filter(Task.id == task.parent_id).first()
if not parent:
return
siblings = db.query(Task).filter(Task.parent_id == parent.id).all()
if all(s.status == "done" for s in siblings):
if parent.status != "done":
parent.status = "done"
changes.append({"id": parent.id, "status": "done"})
_cascade_parent_completion(parent, db, changes)
def _cascade_parent_uncompletion(task: Task, db: Session, changes: list):
"""Recursively auto-uncomplete parent chain."""
if task.parent_id is None:
return
parent = db.query(Task).filter(Task.id == task.parent_id).first()
if not parent:
return
if parent.status == "done":
parent.status = "todo"
changes.append({"id": parent.id, "status": "todo"})
_cascade_parent_uncompletion(parent, db, changes)