first commit
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from models.models import User
|
||||
from schemas.schemas import UserCreate, UserLogin, UserResponse, Token
|
||||
from auth import get_password_hash, verify_password, create_access_token
|
||||
from routes.deps import get_current_user_id, get_current_user
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
@router.post("/register", response_model=UserResponse)
|
||||
def register(user_data: UserCreate, db: Session = Depends(get_db)):
|
||||
existing_user = db.query(User).filter(User.email == user_data.email).first()
|
||||
if existing_user:
|
||||
raise HTTPException(status_code=400, detail="Email already registered")
|
||||
|
||||
new_user = User(
|
||||
name=user_data.name,
|
||||
email=user_data.email,
|
||||
password_hash=get_password_hash(user_data.password)
|
||||
)
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
return new_user
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
def login(user_data: UserLogin, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.email == user_data.email).first()
|
||||
if not user or not verify_password(user_data.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid email or password")
|
||||
|
||||
access_token = create_access_token(data={"sub": str(user.id), "email": user.email, "name": user.name})
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
def get_me(user: User = Depends(get_current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,32 @@
|
||||
from fastapi import Depends, HTTPException, Security
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from models.models import User
|
||||
from auth import decode_access_token
|
||||
|
||||
security_scheme = HTTPBearer()
|
||||
|
||||
def get_current_user_id(
|
||||
credentials: HTTPAuthorizationCredentials = Security(security_scheme),
|
||||
) -> int:
|
||||
"""Extract and validate user ID from Authorization: Bearer <token> header."""
|
||||
token = credentials.credentials
|
||||
payload = decode_access_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="Invalid token payload")
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Get the full User object from the token. Can be used as a dependency."""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return user
|
||||
@@ -0,0 +1,288 @@
|
||||
import httpx
|
||||
import json
|
||||
import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from models.models import Plan, Task
|
||||
from config import OPENAI_API_KEY, OPENAI_API_URL, OPENAI_MODEL, ENABLE_SEARCH, LLM_PROVIDER
|
||||
from routes.deps import get_current_user_id
|
||||
from utils import build_task_tree
|
||||
|
||||
router = APIRouter(prefix="/api/generate", tags=["generate"])
|
||||
|
||||
|
||||
def flatten_tasks(tasks_data: list, plan_id: int, parent_id=None, level=0) -> list[dict]:
|
||||
"""Flatten nested task data from AI into a flat list with parent_id references."""
|
||||
result = []
|
||||
for task_data in tasks_data:
|
||||
if not isinstance(task_data, dict):
|
||||
continue
|
||||
result.append({
|
||||
"plan_id": plan_id,
|
||||
"parent_id": parent_id,
|
||||
"task_id": task_data.get("id", ""),
|
||||
"title": task_data.get("title", ""),
|
||||
"description": task_data.get("description", ""),
|
||||
"dependencies": task_data.get("dependencies", []),
|
||||
"duration_in_hours": task_data.get("durationInHours", 0),
|
||||
"status": "todo",
|
||||
"_children": task_data.get("children", []),
|
||||
"_level": level,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def build_llm_payload(system_prompt: str, prompt: str) -> dict:
|
||||
"""Build the API request payload based on the LLM provider."""
|
||||
payload = {
|
||||
"model": OPENAI_MODEL,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"temperature": 0.7,
|
||||
}
|
||||
|
||||
provider = LLM_PROVIDER
|
||||
|
||||
# response_format: only providers that support json_object mode
|
||||
if provider in ("dashscope", "openai", "deepseek", "moonshot"):
|
||||
payload["response_format"] = {"type": "json_object"}
|
||||
# For gemini and others: rely on prompt instruction for JSON output
|
||||
|
||||
# Web search integration by provider
|
||||
if ENABLE_SEARCH:
|
||||
if provider == "dashscope":
|
||||
# 阿里千问: top-level enable_search param
|
||||
payload["enable_search"] = True
|
||||
elif provider == "openai":
|
||||
# OpenAI: use web_search tool (requires supported model like gpt-4o)
|
||||
payload["tools"] = [{"type": "web_search_preview"}]
|
||||
elif provider == "gemini":
|
||||
# Gemini: use google_search_retrieval tool
|
||||
payload["tools"] = [{"google_search_retrieval": {}}]
|
||||
# deepseek / moonshot: no web search support, skip
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
def build_llm_headers() -> dict:
|
||||
"""Build HTTP headers based on the LLM provider."""
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
||||
}
|
||||
print(headers)
|
||||
# Gemini uses a different auth header via OpenAI-compatible endpoint
|
||||
# The OpenAI-compatible endpoint still uses Bearer token, so no change needed
|
||||
return headers
|
||||
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class GeneratePlanRequest(BaseModel):
|
||||
goal: str
|
||||
additional_info: str = ""
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def generate_plan(req: GeneratePlanRequest, user_id: int = Depends(get_current_user_id)):
|
||||
if not OPENAI_API_KEY:
|
||||
raise HTTPException(status_code=500, detail="OPENAI_API_KEY not configured")
|
||||
|
||||
goal = req.goal
|
||||
additional_info = req.additional_info
|
||||
has_additional = additional_info.strip() != ""
|
||||
|
||||
if has_additional:
|
||||
prompt = f'''You are an expert project manager. The user has provided a goal AND a detailed reference plan (in Markdown format). Your task is to convert this reference plan into a structured, multi-level task plan.
|
||||
|
||||
RULES:
|
||||
1. Carefully parse the user's reference plan. Preserve the original structure, task names, and descriptions as much as possible.
|
||||
2. Organize the content into top-level tasks (level 1) as the main phases, subtasks (level 2), and sub-subtasks (level 3) based on the Markdown headings and list hierarchy.
|
||||
3. Do NOT go deeper than 3 levels total.
|
||||
4. Each task needs: "id" (short URL-friendly slug, unique across the entire plan), "title", "description" (summarize the task based on the reference content), "durationInHours" (estimate based on the task complexity), "dependencies" (list of other task IDs that must complete first - only reference IDs at the SAME level), and optionally "children" (array of subtasks with the same structure).
|
||||
5. Ensure tasks are in a logical order consistent with the reference plan.
|
||||
6. The output MUST be valid JSON with a top-level "tasks" key containing the array.
|
||||
|
||||
EXAMPLE STRUCTURE:
|
||||
{{
|
||||
"tasks": [
|
||||
{{
|
||||
"id": "phase-1",
|
||||
"title": "Phase 1: Research & Planning",
|
||||
"description": "...",
|
||||
"durationInHours": 10,
|
||||
"dependencies": [],
|
||||
"children": [
|
||||
{{
|
||||
"id": "phase-1-research",
|
||||
"title": "Market Research",
|
||||
"description": "...",
|
||||
"durationInHours": 5,
|
||||
"dependencies": [],
|
||||
"children": [
|
||||
{{"id": "phase-1-research-survey", "title": "Create Survey", "description": "...", "durationInHours": 2, "dependencies": []}},
|
||||
{{"id": "phase-1-research-analyze", "title": "Analyze Results", "description": "...", "durationInHours": 3, "dependencies": ["phase-1-research-survey"]}}
|
||||
]
|
||||
}},
|
||||
{{"id": "phase-1-competitor", "title": "Competitor Analysis", "description": "...", "durationInHours": 5, "dependencies": []}}
|
||||
]
|
||||
}},
|
||||
{{"id": "phase-2", "title": "Phase 2: Development", "description": "...", "durationInHours": 20, "dependencies": ["phase-1"]}}
|
||||
]
|
||||
}}
|
||||
|
||||
Goal: "{goal}"
|
||||
|
||||
Reference Plan (Markdown):
|
||||
{additional_info.strip()}'''
|
||||
|
||||
else:
|
||||
prompt = f'''You are an expert project manager. Break down the following goal into a structured, multi-level task plan.
|
||||
|
||||
RULES:
|
||||
1. Create top-level tasks (level 1) as the main phases of the project.
|
||||
2. For each top-level task that needs more detail, add subtasks (level 2) as "children".
|
||||
3. If a level 2 subtask still needs more detail, add level 3 sub-subtasks as "children" of that subtask.
|
||||
4. Do NOT go deeper than 3 levels total.
|
||||
5. Only add children when a task genuinely benefits from being broken down further. Simple tasks can be left without children.
|
||||
6. Each task needs: "id" (short URL-friendly slug, unique across the entire plan), "title", "description", "durationInHours" (estimated hours), "dependencies" (list of other task IDs that must complete first - only reference IDs at the SAME level), and optionally "children" (array of subtasks with the same structure).
|
||||
7. Ensure tasks are in a logical order.
|
||||
8. The output MUST be valid JSON with a top-level "tasks" key containing the array.
|
||||
|
||||
EXAMPLE STRUCTURE:
|
||||
{{
|
||||
"tasks": [
|
||||
{{
|
||||
"id": "phase-1",
|
||||
"title": "Phase 1: Research & Planning",
|
||||
"description": "...",
|
||||
"durationInHours": 10,
|
||||
"dependencies": [],
|
||||
"children": [
|
||||
{{
|
||||
"id": "phase-1-research",
|
||||
"title": "Market Research",
|
||||
"description": "...",
|
||||
"durationInHours": 5,
|
||||
"dependencies": [],
|
||||
"children": [
|
||||
{{"id": "phase-1-research-survey", "title": "Create Survey", "description": "...", "durationInHours": 2, "dependencies": []}},
|
||||
{{"id": "phase-1-research-analyze", "title": "Analyze Results", "description": "...", "durationInHours": 3, "dependencies": ["phase-1-research-survey"]}}
|
||||
]
|
||||
}},
|
||||
{{"id": "phase-1-competitor", "title": "Competitor Analysis", "description": "...", "durationInHours": 5, "dependencies": []}}
|
||||
]
|
||||
}},
|
||||
{{"id": "phase-2", "title": "Phase 2: Development", "description": "...", "durationInHours": 20, "dependencies": ["phase-1"]}}
|
||||
]
|
||||
}}
|
||||
|
||||
Goal: "{goal}"'''
|
||||
|
||||
system_prompt = """You are an expert project manager. You always respond with valid JSON only, no additional text. Structure tasks with up to 3 levels of subtasks when it makes sense."""
|
||||
|
||||
async def event_stream():
|
||||
yield f"data: {json.dumps({'type': 'progress', 'step': 'analyzing', 'progress': 10, 'message': '正在分析你的目标...'})}\n\n"
|
||||
|
||||
openai_url = f"{OPENAI_API_URL}/chat/completions"
|
||||
openai_payload = build_llm_payload(system_prompt, prompt)
|
||||
headers = build_llm_headers()
|
||||
|
||||
yield f"data: {json.dumps({'type': 'progress', 'step': 'connecting', 'progress': 20, 'message': '正在连接 AI 模型...'})}\n\n"
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
yield f"data: {json.dumps({'type': 'progress', 'step': 'generating', 'progress': 35, 'message': 'AI 正在生成计划...'})}\n\n"
|
||||
|
||||
response = await client.post(openai_url, json=openai_payload, headers=headers, timeout=180.0)
|
||||
except httpx.ReadTimeout:
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': 'AI API 请求超时,请重试'})}\n\n"
|
||||
return
|
||||
except httpx.RequestError as e:
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': f'AI API 请求失败: {str(e)}'})}\n\n"
|
||||
return
|
||||
|
||||
yield f"data: {json.dumps({'type': 'progress', 'step': 'parsing', 'progress': 65, 'message': '正在解析 AI 响应...'})}\n\n"
|
||||
|
||||
if response.status_code != 200:
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': f'AI API 错误: {response.text}'})}\n\n"
|
||||
return
|
||||
|
||||
data = response.json()
|
||||
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
|
||||
if not content:
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': '无法解析 AI 响应'})}\n\n"
|
||||
return
|
||||
|
||||
try:
|
||||
tasks_data = json.loads(content)
|
||||
if isinstance(tasks_data, dict) and "tasks" in tasks_data:
|
||||
tasks_data = tasks_data["tasks"]
|
||||
if not isinstance(tasks_data, list):
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': 'AI 返回了意外的 JSON 结构'})}\n\n"
|
||||
return
|
||||
except json.JSONDecodeError:
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': 'AI 返回了无效的 JSON'})}\n\n"
|
||||
return
|
||||
|
||||
yield f"data: {json.dumps({'type': 'progress', 'step': 'saving', 'progress': 80, 'message': '正在保存计划...'})}\n\n"
|
||||
|
||||
from database import SessionLocal
|
||||
stream_db = SessionLocal()
|
||||
try:
|
||||
new_plan = Plan(user_id=user_id, goal=goal)
|
||||
stream_db.add(new_plan)
|
||||
stream_db.commit()
|
||||
stream_db.refresh(new_plan)
|
||||
|
||||
all_flat = flatten_tasks(tasks_data, new_plan.id)
|
||||
sort_idx = 0
|
||||
|
||||
def process_level(items: list[dict], parent_db_id=None):
|
||||
nonlocal sort_idx
|
||||
for item in items:
|
||||
children_data = item.pop("_children", [])
|
||||
item.pop("_level", None)
|
||||
item["parent_id"] = parent_db_id
|
||||
|
||||
task = Task(
|
||||
plan_id=item["plan_id"],
|
||||
parent_id=item["parent_id"],
|
||||
task_id=item["task_id"],
|
||||
title=item["title"],
|
||||
description=item["description"],
|
||||
dependencies=item.get("dependencies", []),
|
||||
duration_in_hours=item.get("durationInHours", 0),
|
||||
status="todo",
|
||||
sort_order=sort_idx,
|
||||
)
|
||||
sort_idx += 1
|
||||
stream_db.add(task)
|
||||
stream_db.flush()
|
||||
|
||||
if children_data:
|
||||
child_flat = flatten_tasks(children_data, new_plan.id, parent_id=task.id, level=0)
|
||||
process_level(child_flat, parent_db_id=task.id)
|
||||
|
||||
process_level(all_flat)
|
||||
stream_db.commit()
|
||||
|
||||
yield f"data: {json.dumps({'type': 'progress', 'step': 'building', 'progress': 95, 'message': '正在构建任务树...'})}\n\n"
|
||||
|
||||
all_tasks = stream_db.query(Task).filter(Task.plan_id == new_plan.id).all()
|
||||
result_tree = build_task_tree(all_tasks)
|
||||
|
||||
yield f"data: {json.dumps({'type': 'complete', 'progress': 100, 'message': '计划生成完成!', 'data': {'plan_id': new_plan.id, 'goal': new_plan.goal, 'created_at': new_plan.created_at.isoformat(), 'tasks': result_tree}})}\n\n"
|
||||
except Exception as e:
|
||||
stream_db.rollback()
|
||||
yield f"data: {json.dumps({'type': 'error', 'message': f'保存计划失败: {str(e)}'})}\n\n"
|
||||
finally:
|
||||
stream_db.close()
|
||||
|
||||
return StreamingResponse(event_stream(), media_type="text/event-stream")
|
||||
@@ -0,0 +1,342 @@
|
||||
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)
|
||||
Reference in New Issue
Block a user