commit 328b6917a395c70e410f0608c8ae3c016517aa00 Author: Dev Date: Mon Nov 2 15:45:49 2026 +0800 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a631403 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +# Virtualenv (uv, repo root) +/.venv/ +# Editor / OS +.idea/ +.vscode/ +.DS_Store +Thumbs.db +desktop.ini diff --git a/DEPLOY.md b/DEPLOY.md new file mode 100644 index 0000000..7c11848 --- /dev/null +++ b/DEPLOY.md @@ -0,0 +1,480 @@ +# Goal Planner Linux 部署指南 + +## 环境要求 + +### 服务器 +- Linux 服务器(Ubuntu 20.04+ / CentOS 7+) +- Python 3.11+(由 uv 管理,不依赖系统 Python) +- MySQL 5.7+ / 8.0(需提前安装) +- Nginx(需提前安装) +- [uv](https://docs.astral.sh/uv/)(Python 包管理工具) + +> **关于 Python 版本**:项目要求 Python ≥ 3.10。CentOS 7 系统自带 Python 2.7.5,无需升级或卸载,uv 会自动下载和管理独立的 Python 版本,不会与系统 Python 冲突。系统工具(如 yum)依赖的 Python 2.7.5 完全不受影响。**推荐使用 Python 3.11**,wheel 生态最成熟,所有依赖都有预编译 wheel,安装秒完成;Python 3.12/3.14 部分包(如 greenlet、pydantic-core)在 CentOS 7 上缺少兼容的预编译 wheel,需要从源码编译,而 CentOS 7 的 GCC 4.8.5 不支持 C++11,会导致编译失败。 + +### 本地(仅构建前端时需要) +- Node.js 18+ + +--- + +## 1. 安装 uv + +```bash +curl -LsSf https://astral.sh/uv/install.sh | sh +``` + +安装完成后,需要让 uv 命令生效(二选一): + +```bash +# 方式一:执行以下命令(推荐,立即生效) +source $HOME/.local/bin/env + +# 方式二:重新连接 SSH +``` + +验证安装: + +```bash +uv --version +``` + +--- + +## 2. 配置 MySQL + +```bash +# 登录 MySQL +sudo mysql -u root -p + +# 创建数据库和用户 +CREATE DATABASE goal_planner CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +CREATE USER 'goal_planner'@'localhost' IDENTIFIED BY '你的数据库密码'; +GRANT ALL PRIVILEGES ON goal_planner.* TO 'goal_planner'@'localhost'; +FLUSH PRIVILEGES; +EXIT; +``` + +> 首次启动后端时,SQLAlchemy 会自动创建表结构,无需手动导入。 + +--- + +## 3. 上传项目 + +将项目上传到服务器,部署目录为 `/home/wwwroot/goal-planner`: + +```bash +sudo mkdir -p /home/wwwroot/goal-planner +# 方式一:git clone +cd /home/wwwroot/goal-planner +git clone <你的仓库地址> . + +# 方式二:scp 上传 +# scp -r ./goal-planner/* user@server:/home/wwwroot/goal-planner/ +``` + +--- + +## 4. 后端部署 + +### 4.1 配置环境变量 + +```bash +cd /home/wwwroot/goal-planner/backend +cp .env.example .env +``` + +编辑 `.env` 文件: + +```bash +vi .env +``` + +填入实际配置: + +```env +MYSQL_HOST=localhost +MYSQL_PORT=3306 +MYSQL_USER=goal_planner +MYSQL_PASSWORD=你的数据库密码 +MYSQL_DATABASE=goal_planner +SECRET_KEY=替换为一个随机长字符串 +ACCESS_TOKEN_EXPIRE_MINUTES=1440 +LLM_PROVIDER=dashscope +OPENAI_API_KEY=你的API密钥 +OPENAI_API_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 +OPENAI_MODEL=qwen3-plus +ENABLE_SEARCH=true +``` + +> **重要**:`SECRET_KEY` 必须替换为随机字符串,可用 `openssl rand -hex 32` 生成。 + +### 4.2 使用 uv 创建虚拟环境并安装依赖 + +```bash +cd /home/wwwroot/goal-planner + +# 创建虚拟环境,uv 会自动下载 Python 3.11(不依赖系统 Python) +uv venv .venv --python 3.11 + +# 激活虚拟环境 +source .venv/bin/activate + +# 安装依赖(使用清华镜像加速,强制只安装预编译 wheel) +uv pip install -r backend/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --only-binary :all: +``` + +> **说明**:`uv venv --python 3.11` 会将 Python 3.11 下载到 `~/.local/share/uv/python/` 目录,仅 uv 使用,不会覆盖或修改系统自带的 Python 2.7.5。虚拟环境放在项目根目录 `/home/wwwroot/goal-planner/.venv`,与 backend 同级。`--only-binary :all:` 强制只安装预编译 wheel,避免在 CentOS 7 的旧 GCC 上从源码编译失败。 + +### 4.3 验证后端启动 + +```bash +cd /home/wwwroot/goal-planner/backend +source /home/wwwroot/goal-planner/.venv/bin/activate +uvicorn main:app --host 127.0.0.1 --port 8000 +``` + +看到 `Uvicorn running on http://127.0.0.1:8000` 即启动成功,`Ctrl+C` 停止。 + +### 4.4 后台运行 + +验证无误后,使用以下方式后台运行(推荐方式二): + +**方式一:nohup(简单快速)** + +```bash +cd /home/wwwroot/goal-planner/backend +source /home/wwwroot/goal-planner/.venv/bin/activate +nohup uvicorn main:app --host 127.0.0.1 --port 8000 > /home/wwwroot/goal-planner/backend/app.log 2>&1 & +``` + +常用操作: + +```bash +# 查看日志 +tail -f /home/wwwroot/goal-planner/backend/app.log + +# 查看进程 +ps aux | grep uvicorn + +# 停止服务 +kill $(ps aux | grep 'uvicorn main:app' | grep -v grep | awk '{print $2}') +``` + +**方式二:systemd 服务(推荐,开机自启 + 自动重启)** + +见第 7 章。 + +--- + +## 5. 前端构建与部署 + +### 5.1 修改 API 接口地址 + +前端 API 地址硬编码在 `frontend/services/apiService.ts` 中: + +```typescript +const API_BASE_URL = 'http://localhost:8000'; +``` + +**部署前必须修改为实际的后端地址**。根据你的部署方式选择: + +#### 方式一:使用 Nginx 反向代理(推荐) + +将 API 地址改为相对路径,由 Nginx 统一代理: + +```typescript +const API_BASE_URL = '/api-proxy'; +``` + +这样前端请求 `/api-proxy/api/generate/` 会被 Nginx 转发到后端 `http://127.0.0.1:8000/api/generate/`,无需暴露后端端口。 + +#### 方式二:直接指向后端地址 + +如果你的后端运行在独立域名或端口上: + +```typescript +const API_BASE_URL = 'http://你的服务器IP:8000'; +``` + +> **注意**:此方式需要后端开放 8000 端口,并在 `main.py` 的 CORS 配置中添加前端域名。 + +### 5.2 修改后端 CORS 配置(方式一不需要) + +如果使用方式二,需要修改 `backend/main.py` 中的 CORS 允许来源: + +```python +origins = [ + "http://你的域名", + "http://你的服务器IP", +] +``` + +### 5.3 本地构建前端 + +在本地开发机器上执行构建(不需要在服务器上安装 Node.js): + +```bash +cd frontend + +# 安装依赖 +npm install + +# 构建 +npm run build +``` + +构建产物在 `frontend/dist/` 目录中。 + +### 5.4 上传静态文件到服务器 + +将本地构建产物上传到服务器: + +```bash +# 在本地执行 +scp -r frontend/dist/* user@你的服务器IP:/var/www/goal-planner/ +``` + +或在服务器上从项目目录复制(如果已上传整个项目): + +```bash +sudo mkdir -p /var/www/goal-planner +sudo cp -r /home/wwwroot/goal-planner/frontend/dist/* /var/www/goal-planner/ +``` + +--- + +## 6. 配置 Nginx + +创建 Nginx 配置文件: + +```bash +sudo vi /etc/nginx/conf.d/goal-planner.conf +``` + +### 方式一:Nginx 反向代理(推荐) + +前后端统一通过 Nginx 访问,后端不对外暴露端口: + +```nginx +server { + listen 80; + server_name 你的域名或IP; + + # 前端静态文件 + root /var/www/goal-planner; + index index.html; + + # 前端路由 - SPA 应用所有路径都返回 index.html + location / { + try_files $uri $uri/ /index.html; + } + + # 后端 API 反向代理 + location /api-proxy/ { + rewrite ^/api-proxy/(.*) /$1 break; + proxy_pass http://127.0.0.1:8000; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # SSE 支持 - 关键配置 + proxy_buffering off; + proxy_cache off; + proxy_read_timeout 300s; + proxy_http_version 1.1; + proxy_set_header Connection ''; + } + + # 静态资源缓存 + location /assets/ { + expires 30d; + add_header Cache-Control "public, immutable"; + } + + # 禁止访问隐藏文件 + location ~ /\. { + deny all; + } +} +``` + +> **SSE 关键配置说明**: +> - `proxy_buffering off` — 禁用缓冲,确保 SSE 事件实时推送到客户端 +> - `proxy_cache off` — 禁用缓存 +> - `proxy_read_timeout 300s` — AI 生成可能耗时较长,增大超时时间 +> - `proxy_http_version 1.1` + `Connection ''` — 保持长连接 + +### 方式二:前后端分离部署 + +后端直接监听 8000 端口对外服务: + +```nginx +server { + listen 80; + server_name 你的域名或IP; + + root /var/www/goal-planner; + index index.html; + + location / { + try_files $uri $uri/ /index.html; + } + + location /assets/ { + expires 30d; + add_header Cache-Control "public, immutable"; + } +} +``` + +此方式下 `apiService.ts` 中的 `API_BASE_URL` 应设为 `http://你的域名或IP:8000`。 + +### 验证并重启 Nginx + +```bash +sudo nginx -t +sudo systemctl restart nginx +``` + +--- + +## 7. 使用 systemd 管理后端进程 + +创建 systemd 服务文件,实现开机自启和进程管理: + +```bash +sudo vi /etc/systemd/system/goal-planner.service +``` + +```ini +[Unit] +Description=Goal Planner Backend API +After=network.target mysql.service + +[Service] +Type=simple +User=root +WorkingDirectory=/home/wwwroot/goal-planner/backend +ExecStart=/home/wwwroot/goal-planner/.venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 +Restart=always +RestartSec=5 +Environment=PYTHONUNBUFFERED=1 + +[Install] +WantedBy=multi-user.target +``` + +> 如果使用方式二(前后端分离),将 `--host 127.0.0.1` 改为 `--host 0.0.0.0` 以允许外部访问。 + +启动并设置开机自启: + +```bash +sudo systemctl daemon-reload +sudo systemctl start goal-planner +sudo systemctl enable goal-planner +``` + +常用管理命令: + +```bash +sudo systemctl status goal-planner # 查看状态 +sudo systemctl restart goal-planner # 重启 +sudo systemctl stop goal-planner # 停止 +sudo journalctl -u goal-planner -f # 查看实时日志 +``` + +--- + +## 8. 验证部署 + +```bash +# 检查后端健康状态 +curl http://127.0.0.1:8000/api/health +# 预期返回: {"status":"ok"} + +# 检查 Nginx 代理(方式一) +curl http://你的域名或IP/api-proxy/api/health +# 预期返回: {"status":"ok"} + +# 浏览器访问 +# http://你的域名或IP +``` + +--- + +## 9. HTTPS 配置(可选但推荐) + +使用 Let's Encrypt 免费证书: + +```bash +sudo apt install certbot python3-certbot-nginx # Ubuntu +sudo yum install certbot python3-certbot-nginx # CentOS + +sudo certbot --nginx -d 你的域名 +``` + +Certbot 会自动修改 Nginx 配置并配置 SSL 证书自动续期。 + +--- + +## 10. 更新部署 + +当代码更新后,执行以下步骤: + +### 后端更新 + +```bash +# 服务器上拉取最新代码 +cd /home/wwwroot/goal-planner +git pull + +# 更新后端依赖(如有变动) +source /home/wwwroot/goal-planner/.venv/bin/activate +uv pip install -r backend/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --only-binary :all: + +# 重启后端 +sudo systemctl restart goal-planner +``` + +### 前端更新 + +```bash +# 本地构建 +cd frontend +npm install +npm run build + +# 上传到服务器 +scp -r dist/* user@你的服务器IP:/var/www/goal-planner/ +``` + +--- + +## 文件结构总览 + +``` +/home/wwwroot/goal-planner/ +├── .venv/ # uv 创建的 Python 虚拟环境(项目根目录) +├── backend/ +│ ├── .env # 环境变量配置(含数据库密码、API密钥) +│ ├── .env.example # 环境变量模板 +│ ├── main.py # FastAPI 入口 +│ ├── config.py # 配置读取 +│ ├── database.py # 数据库连接 +│ ├── requirements.txt # Python 依赖 +│ ├── models/ # 数据模型 +│ └── routes/ # API 路由 +│ ├── auth.py +│ ├── generate.py +│ └── plans.py +└── frontend/ + ├── dist/ # 构建产物 → 部署到 /var/www/goal-planner/ + ├── services/ + │ └── apiService.ts # API 地址配置(需修改 API_BASE_URL) + ├── package.json + └── vite.config.ts + +/var/www/goal-planner/ # Nginx 静态文件目录 +/etc/nginx/conf.d/goal-planner.conf # Nginx 配置 +/etc/systemd/system/goal-planner.service # 后端服务配置 +``` diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..88e8fd4 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,10 @@ +MYSQL_HOST=localhost +MYSQL_PORT=3306 +MYSQL_USER=root +MYSQL_PASSWORD=your_mysql_password +MYSQL_DATABASE=goal_planner +SECRET_KEY=your-secret-key-change-in-production +ACCESS_TOKEN_EXPIRE_MINUTES=1440 +OPENAI_API_KEY=your_openai_api_key +OPENAI_API_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 +OPENAI_MODEL=qwen3-plus diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..fbc71d9 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,13 @@ +__pycache__/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +# Secrets +.env +.env.* +!.env.example +*.pem +*.key + +# Logs +*.log \ No newline at end of file diff --git a/backend/__init__.py b/backend/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/auth.py b/backend/auth.py new file mode 100644 index 0000000..d01ab03 --- /dev/null +++ b/backend/auth.py @@ -0,0 +1,28 @@ +from datetime import datetime, timedelta +from typing import Optional +from jose import JWTError, jwt +import bcrypt +from config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES + +def verify_password(plain_password: str, hashed_password: str) -> bool: + return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8")) + +def get_password_hash(password: str) -> str: + return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + +def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str: + to_encode = data.copy() + if expires_delta: + expire = datetime.utcnow() + expires_delta + else: + expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) + to_encode.update({"exp": expire}) + encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) + return encoded_jwt + +def decode_access_token(token: str) -> Optional[dict]: + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + return payload + except JWTError: + return None diff --git a/backend/config.py b/backend/config.py new file mode 100644 index 0000000..35ceb78 --- /dev/null +++ b/backend/config.py @@ -0,0 +1,22 @@ +import os +from dotenv import load_dotenv, dotenv_values + +load_dotenv() +_dotenv = dotenv_values() + +MYSQL_HOST = os.getenv("MYSQL_HOST", "localhost") +MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306")) +MYSQL_USER = os.getenv("MYSQL_USER", "root") +MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD", "") +MYSQL_DATABASE = os.getenv("MYSQL_DATABASE", "goal_planner") +SECRET_KEY = os.getenv("SECRET_KEY", "your-secret-key-change-in-production") +ALGORITHM = "HS256" +ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "1440")) +OPENAI_API_KEY = _dotenv.get("OPENAI_API_KEY", "") +OPENAI_API_URL = _dotenv.get("OPENAI_API_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1") +OPENAI_MODEL = os.getenv("OPENAI_MODEL", "qwen3-plus") +ENABLE_SEARCH = os.getenv("ENABLE_SEARCH", "true").lower() == "true" +# Provider type: "dashscope" (阿里千问), "openai", "gemini", "deepseek" +LLM_PROVIDER = os.getenv("LLM_PROVIDER", "dashscope").lower() + +DATABASE_URL = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DATABASE}" diff --git a/backend/database.py b/backend/database.py new file mode 100644 index 0000000..d071026 --- /dev/null +++ b/backend/database.py @@ -0,0 +1,14 @@ +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker, declarative_base +from config import DATABASE_URL + +engine = create_engine(DATABASE_URL, pool_pre_ping=True, pool_recycle=3600) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) +Base = declarative_base() + +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() diff --git a/backend/main.py b/backend/main.py new file mode 100644 index 0000000..bb1952f --- /dev/null +++ b/backend/main.py @@ -0,0 +1,64 @@ +import sys +import os +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware +from database import engine +from models.models import Base +from routes import auth, plans, generate + +Base.metadata.create_all(bind=engine) + +# Migration helpers for existing databases - MySQL compatible +try: + import sqlalchemy + with engine.connect() as conn: + # Check existing columns in users table + result = conn.execute(sqlalchemy.text( + "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users'" + )) + columns = [row[0] for row in result] + if 'xp' not in columns: + conn.execute(sqlalchemy.text("ALTER TABLE users ADD COLUMN xp INTEGER NOT NULL DEFAULT 0")) + conn.commit() + + # Check existing columns in tasks table + result = conn.execute(sqlalchemy.text( + "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'tasks'" + )) + task_columns = [row[0] for row in result] + if 'priority' not in task_columns: + conn.execute(sqlalchemy.text("ALTER TABLE tasks ADD COLUMN priority VARCHAR(10) NOT NULL DEFAULT 'medium'")) + conn.commit() + if 'due_date' not in task_columns: + conn.execute(sqlalchemy.text("ALTER TABLE tasks ADD COLUMN due_date DATE NULL")) + conn.commit() + if 'sort_order' not in task_columns: + conn.execute(sqlalchemy.text("ALTER TABLE tasks ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0")) + conn.commit() +except Exception as e: + print(f"Migration warning (safe to ignore on first run): {e}") + +app = FastAPI(title="Goal Planner API", version="1.0.0") + +origins = [ + "http://localhost:3000", + "http://127.0.0.1:3000", +] + +app.add_middleware( + CORSMiddleware, + allow_origins=origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +app.include_router(auth.router) +app.include_router(plans.router) +app.include_router(generate.router) + +@app.get("/api/health") +def health_check(): + return {"status": "ok"} diff --git a/backend/models/__init__.py b/backend/models/__init__.py new file mode 100644 index 0000000..929d8ce --- /dev/null +++ b/backend/models/__init__.py @@ -0,0 +1 @@ +from .models import User, Plan, Task diff --git a/backend/models/models.py b/backend/models/models.py new file mode 100644 index 0000000..cfacb0b --- /dev/null +++ b/backend/models/models.py @@ -0,0 +1,60 @@ +from sqlalchemy import Column, Integer, String, Text, Float, DateTime, ForeignKey, JSON, Date, Enum +from sqlalchemy.orm import relationship +from datetime import datetime, timezone +from database import Base +import enum + + +class TaskStatus(str, enum.Enum): + todo = "todo" + in_progress = "in_progress" + done = "done" + + +class TaskPriority(str, enum.Enum): + low = "low" + medium = "medium" + high = "high" + + +class User(Base): + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + name = Column(String(100), nullable=False) + email = Column(String(191), unique=True, nullable=False, index=True) + password_hash = Column(String(255), nullable=False) + xp = Column(Integer, nullable=False, default=0) + created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + + plans = relationship("Plan", back_populates="user", cascade="all, delete-orphan") + +class Plan(Base): + __tablename__ = "plans" + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + user_id = Column(Integer, ForeignKey("users.id"), nullable=False) + goal = Column(Text, nullable=False) + created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc)) + + user = relationship("User", back_populates="plans") + tasks = relationship("Task", back_populates="plan", cascade="all, delete-orphan") + +class Task(Base): + __tablename__ = "tasks" + + id = Column(Integer, primary_key=True, index=True, autoincrement=True) + plan_id = Column(Integer, ForeignKey("plans.id"), nullable=False) + parent_id = Column(Integer, ForeignKey("tasks.id"), nullable=True, index=True) + task_id = Column(String(100), nullable=False, index=True) + title = Column(String(255), nullable=False) + description = Column(Text, nullable=False) + dependencies = Column(JSON, default=list) + duration_in_hours = Column(Float, nullable=False, default=0) + priority = Column(String(10), nullable=False, default="medium") + due_date = Column(Date, nullable=True) + status = Column(String(20), nullable=False, default="todo") + sort_order = Column(Integer, nullable=False, default=0) + + plan = relationship("Plan", back_populates="tasks") + children = relationship("Task", backref="parent", remote_side=[id], cascade="all, delete-orphan", single_parent=True) diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..be4ab99 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,10 @@ +fastapi==0.115.6 +uvicorn==0.34.0 +sqlalchemy==2.0.36 +pymysql==1.1.1 +cryptography==44.0.0 +python-jose[cryptography]==3.3.0 +passlib[bcrypt]==1.7.4 +python-dotenv==1.0.1 +httpx==0.28.1 +pydantic[email]==2.10.3 diff --git a/backend/routes/__init__.py b/backend/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/routes/auth.py b/backend/routes/auth.py new file mode 100644 index 0000000..d541fe5 --- /dev/null +++ b/backend/routes/auth.py @@ -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 diff --git a/backend/routes/deps.py b/backend/routes/deps.py new file mode 100644 index 0000000..9d5407c --- /dev/null +++ b/backend/routes/deps.py @@ -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 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 diff --git a/backend/routes/generate.py b/backend/routes/generate.py new file mode 100644 index 0000000..2a5ac7c --- /dev/null +++ b/backend/routes/generate.py @@ -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") diff --git a/backend/routes/plans.py b/backend/routes/plans.py new file mode 100644 index 0000000..80f0f73 --- /dev/null +++ b/backend/routes/plans.py @@ -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) diff --git a/backend/schemas/__init__.py b/backend/schemas/__init__.py new file mode 100644 index 0000000..19c382c --- /dev/null +++ b/backend/schemas/__init__.py @@ -0,0 +1,5 @@ +from .schemas import ( + UserCreate, UserLogin, UserResponse, Token, + TaskCreate, TaskUpdate, TaskResponse, + PlanCreate, PlanResponse +) diff --git a/backend/schemas/schemas.py b/backend/schemas/schemas.py new file mode 100644 index 0000000..8f7947f --- /dev/null +++ b/backend/schemas/schemas.py @@ -0,0 +1,82 @@ +from pydantic import BaseModel, EmailStr, Field +from typing import List, Optional +from datetime import datetime, date + + +class UserCreate(BaseModel): + name: str + email: EmailStr + password: str = Field(..., min_length=6) + + +class UserLogin(BaseModel): + email: EmailStr + password: str + + +class UserResponse(BaseModel): + id: int + name: str + email: str + xp: int = 0 + created_at: datetime + + class Config: + from_attributes = True + +class Token(BaseModel): + access_token: str + token_type: str + +class TaskCreate(BaseModel): + task_id: str + title: str + description: str + parent_id: Optional[int] = None + dependencies: List[str] = [] + duration_in_hours: float = 0 + priority: str = "medium" + due_date: Optional[str] = None # ISO date string YYYY-MM-DD + status: str = "todo" + sort_order: int = 0 + +class TaskUpdate(BaseModel): + title: Optional[str] = None + description: Optional[str] = None + dependencies: Optional[List[str]] = None + duration_in_hours: Optional[float] = None + priority: Optional[str] = None + due_date: Optional[str] = None # ISO date string YYYY-MM-DD or null + status: Optional[str] = None + sort_order: Optional[int] = None + +class TaskResponse(BaseModel): + id: int + plan_id: int + parent_id: Optional[int] = None + task_id: str + title: str + description: str + dependencies: List[str] = [] + duration_in_hours: float + priority: str = "medium" + due_date: Optional[str] = None + status: str + sort_order: int = 0 + children: List["TaskResponse"] = [] + + class Config: + from_attributes = True + +class PlanCreate(BaseModel): + goal: str + +class PlanResponse(BaseModel): + id: int + user_id: int + goal: str + created_at: datetime + tasks: List[TaskResponse] = [] + + class Config: + from_attributes = True diff --git a/backend/smart_task_planner.sql b/backend/smart_task_planner.sql new file mode 100644 index 0000000..bc6cbc5 --- /dev/null +++ b/backend/smart_task_planner.sql @@ -0,0 +1,200 @@ +/* + Navicat Premium Dump SQL + + Source Server : .local + Source Server Type : MySQL + Source Server Version : 50726 (5.7.26) + Source Host : localhost:3306 + Source Schema : goal_planner + + Target Server Type : MySQL + Target Server Version : 50726 (5.7.26) + File Encoding : 65001 + + Date: 24/04/2026 19:04:05 +*/ + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- Table structure for plans +-- ---------------------------- +DROP TABLE IF EXISTS `plans`; +CREATE TABLE `plans` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `user_id` int(11) NOT NULL, + `goal` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `created_at` datetime NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + INDEX `user_id`(`user_id`) USING BTREE, + INDEX `ix_plans_id`(`id`) USING BTREE +) ENGINE = MyISAM AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of plans +-- ---------------------------- +INSERT INTO `plans` VALUES (6, 1, '程序员如何实现靠副业年入百万', '2026-04-24 10:57:45'); +INSERT INTO `plans` VALUES (2, 1, '如何实现靠AI技术快速变现?', '2026-04-25 05:20:00'); +INSERT INTO `plans` VALUES (3, 1, '如何实现靠副业月入十万?', '2026-04-25 05:20:00'); +INSERT INTO `plans` VALUES (4, 1, '如何三个月学会可以与外国人正常交流的英语', '2026-04-24 07:59:28'); +INSERT INTO `plans` VALUES (5, 1, '程序员如何实现靠副业年入百万', '2026-04-24 09:12:28'); + +-- ---------------------------- +-- Table structure for tasks +-- ---------------------------- +DROP TABLE IF EXISTS `tasks`; +CREATE TABLE `tasks` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `plan_id` int(11) NOT NULL, + `parent_id` int(11) NULL DEFAULT NULL, + `task_id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `dependencies` json NULL, + `duration_in_hours` float NOT NULL, + `status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `priority` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'medium', + `due_date` date NULL DEFAULT NULL, + `sort_order` int(11) NOT NULL DEFAULT 0, + PRIMARY KEY (`id`) USING BTREE, + INDEX `plan_id`(`plan_id`) USING BTREE, + INDEX `ix_tasks_task_id`(`task_id`) USING BTREE, + INDEX `ix_tasks_id`(`id`) USING BTREE, + INDEX `ix_tasks_parent_id`(`parent_id`) USING BTREE +) ENGINE = MyISAM AUTO_INCREMENT = 116 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of tasks +-- ---------------------------- +INSERT INTO `tasks` VALUES (1, 2, NULL, 'phase-1-assessment', '第一阶段:自我评估与方向定位', '分析自身技术栈、可用时间及市场需求,确定能达到月入 10 万的高价值副业赛道。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (2, 2, 1, 'p1-audit-skills', '核心能力与时间盘点', '评估编程技能树、行业资源及每周可投入副业的精确小时数。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (3, 2, 1, 'p1-research-niches', '高价值赛道调研', '调研独立开发 SaaS、高端技术咨询、知识付费等高客单价方向的可行性。', '[\"p1-audit-skills\"]', 0.5, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (4, 2, 3, 'p1-research-saas', 'SaaS 产品机会分析', '分析海外及国内微型 SaaS 的盈利案例与切入点。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (5, 2, 3, 'p1-research-consulting', '高端咨询/培训分析', '评估企业级技术咨询或高阶课程开发的潜在收益。', '[\"p1-research-saas\"]', 2.5, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (6, 2, 1, 'p1-validate-idea', '初步想法验证', '通过落地页或预售方式验证选定方向的付费意愿。', '[\"p1-research-niches\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (7, 2, NULL, 'phase-2-branding', '第二阶段:个人品牌与信任构建', '打造专家人设,建立流量池,为高客单价产品提供信任背书。', '[\"phase-1-assessment\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (8, 2, 7, 'p2-content-strategy', '内容营销策略制定', '确定输出平台(知乎、推特、公众号)及内容主题规划。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (9, 2, 7, 'p2-channel-setup', '全渠道账号搭建', '完成各平台专业账号注册、简介优化及初始内容填充。', '[\"p2-content-strategy\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (10, 2, 7, 'p2-audience-grow', '种子用户获取', '通过免费资源或干货内容吸引首批 1000 名精准粉丝。', '[\"p2-channel-setup\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (11, 2, NULL, 'phase-3-product', '第三阶段:高价值产品开发', '开发可规模化销售的产品或服务,确保交付价值匹配高收入目标。', '[\"phase-2-branding\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (12, 2, 11, 'p3-mvp-dev', 'MVP 核心功能开发', '快速构建产品最小可行性版本,聚焦核心痛点解决。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (13, 2, 11, 'p3-payment-legal', '支付与合规设置', '配置收款渠道、签订合同模板及处理税务合规问题。', '[\"p3-mvp-dev\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (14, 2, 11, 'p3-pricing-model', '定价模型设计', '设计订阅制、一次性付费或分层服务定价以最大化收益。', '[\"p3-payment-legal\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (15, 2, NULL, 'phase-4-growth', '第四阶段:流量获取与销售转化', '通过多渠道引流并优化销售漏斗,实现收入快速增长。', '[\"phase-3-product\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (16, 2, 15, 'p4-sales-funnel', '销售漏斗搭建', '设计从流量到付费的自动化转化流程。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (17, 2, 15, 'p4-paid-ads', '付费投放测试', '在精准渠道进行小规模广告投放测试 ROI。', '[\"p4-sales-funnel\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (18, 2, 15, 'p4-partnership', '渠道合作与分销', '寻找行业 KOL 或平台进行联合推广或分销合作。', '[\"p4-paid-ads\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (19, 2, NULL, 'phase-5-scaling', '第五阶段:规模化运营与复利', '通过自动化、外包及产品矩阵实现收入稳定在月入 10 万及以上。', '[\"phase-4-growth\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (20, 2, 19, 'p5-automation', '业务流程自动化', '利用工具自动化客服、交付及营销流程以减少人力投入。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (21, 2, 19, 'p5-team-build', '虚拟团队组建', '外包非核心任务(如客服、内容编辑),聚焦核心战略。', '[\"p5-automation\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (22, 2, 19, 'p5-revenue-optimize', '收入模型迭代优化', '分析数据,拓展产品线或提高客单价以实现目标收入。', '[\"p5-team-build\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (23, 3, NULL, 'market-validation', '阶段一:市场定位与可行性验证', '确定高收益副业赛道,评估个人资源,并通过最小可行性产品验证市场需求。', '[]', 0, 'todo', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (24, 3, 23, 'niche-research', '高净值赛道调研', '分析当前市场中客单价高、需求大的副业领域,如咨询、高端服务、数字产品等。', '[]', 0.5, 'in_progress', 'medium', NULL, 1); +INSERT INTO `tasks` VALUES (25, 3, 23, 'resource-audit', '个人资源盘点', '评估自身技能、人脉、时间及资金资源,确定可切入的竞争优势。', '[]', 1.5, 'done', 'medium', NULL, 2); +INSERT INTO `tasks` VALUES (26, 3, 23, 'mvp-validation', '最小可行性测试', '推出简易版服务或产品,收集早期用户反馈,验证付费意愿。', '[\"niche-research\", \"resource-audit\"]', 2.5, 'in_progress', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (27, 3, NULL, 'product-development', '阶段二:核心产品与服务打磨', '基于验证结果,提升核心技能,设计标准化高客单价产品体系。', '[\"market-validation\"]', 3, 'done', 'medium', NULL, 2); +INSERT INTO `tasks` VALUES (28, 3, 27, 'skill-upgrade', '技能强化学习', '针对选定赛道进行深度学习,确保交付质量达到行业顶尖水平。', '[]', 1, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (29, 3, 27, 'product-design', '产品标准化设计', '将服务或产品流程化、标准化,确保可复制性和高质量交付。', '[\"skill-upgrade\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (30, 3, 27, 'pricing-strategy', '高客单价定价策略', '设计分层定价模型,确保单笔交易利润最大化,支撑月入十万目标。', '[\"product-design\"]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (31, 3, NULL, 'traffic-acquisition', '阶段三:全渠道流量体系搭建', '建立公域内容矩阵,沉淀私域流量,并测试付费投放以获得稳定客源。', '[\"product-development\"]', 0, 'todo', 'medium', NULL, 1); +INSERT INTO `tasks` VALUES (32, 3, 31, 'content-matrix', '公域内容矩阵建立', '在主流社交平台布局高质量内容,打造个人品牌影响力。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (33, 3, 31, 'private-domain', '私域转化路径设计', '将公域流量引导至私域池,设计信任培育与转化流程。', '[\"content-matrix\"]', 0, 'todo', 'medium', NULL, 2); +INSERT INTO `tasks` VALUES (34, 3, 31, 'paid-ads', '付费流量投放测试', '在模型验证成功后,通过付费广告放大流量规模。', '[\"private-domain\"]', 0, 'done', 'medium', NULL, 1); +INSERT INTO `tasks` VALUES (36, 3, NULL, 'sales-sop', '销售 SOP 流程制定', '编写标准销售话术与跟进流程,提高转化率至行业领先水平。', '[]', 0, 'todo', 'medium', NULL, 4); +INSERT INTO `tasks` VALUES (38, 3, NULL, 'revenue-tracking', '收入目标拆解与监控', '将月入十万目标拆解为每日关键指标,持续监控并优化。', '[\"team-building\"]', 0, 'todo', 'medium', NULL, 5); +INSERT INTO `tasks` VALUES (40, 3, NULL, 'tax-legal', '税务筹划与公司注册', '选择合适的主体形式,合规纳税,规避法律风险。', '[]', 0, 'todo', 'medium', NULL, 7); +INSERT INTO `tasks` VALUES (41, 3, NULL, 'risk-management', '现金流与合同风险管理', '建立财务预警机制,规范合同签署,保障资金安全。', '[\"tax-legal\"]', 0, 'todo', 'medium', NULL, 6); +INSERT INTO `tasks` VALUES (92, 6, NULL, 'phase-1-direction-validation', '阶段一:方向验证(第1–4周)', '找到能赚钱的细分领域,验证有人愿意付钱,确定项目定位。', '[]', 0, 'todo', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (46, 4, NULL, 'prep-phase', 'Phase 0: 准备与资源搭建', '收集学习材料,制定详细时间表,安装必要工具(词典、AI 口语工具),确立每日学习时段(如早晚黄金时段)。', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (47, 4, 46, 'prep-resources', '学习资源收集', '下载 BBC 慢速英语、新概念英语、英语儿歌等材料,订阅英语学习 APP。', '[]', 0, 'done', 'medium', NULL, 1); +INSERT INTO `tasks` VALUES (48, 4, 46, 'prep-schedule', '制定时间表', '规划每天 2-3 小时学习时间,分配听说读写比例,设定阶段性目标。', '[\"prep-resources\"]', 0, 'done', 'medium', NULL, 2); +INSERT INTO `tasks` VALUES (49, 4, NULL, 'month-1-foundation', '第一阶段:基础积累与模仿 (第 1 月)', '重点在于词汇积累、基础语法构建及听力输入,通过模仿朗读培养语感。', '[\"prep-phase\"]', 0, 'todo', 'medium', NULL, 3); +INSERT INTO `tasks` VALUES (50, 4, 49, 'm1-half-1-basics', '第 1-2 周:词汇与语法基础', '每日学习 20-25 个高频单词,掌握基本句型和时态,建立简单交流能力。', '[]', 0, 'todo', 'medium', NULL, 4); +INSERT INTO `tasks` VALUES (51, 4, 50, 'm1-h1-vocab', '高频词汇记忆', '使用四步法(听发音、造句、图像联想、应用)每日记忆 20 个生活常用词。', '[]', 1.5, 'todo', 'medium', NULL, 5); +INSERT INTO `tasks` VALUES (52, 4, 50, 'm1-h1-grammar', '基础语法学习', '学习五大简单句结构、基本时态,并完成配套练习题巩固。', '[\"m1-h1-vocab\"]', 0.5, 'todo', 'medium', NULL, 6); +INSERT INTO `tasks` VALUES (53, 4, 49, 'm1-half-2-listening', '第 3-4 周:听力输入与模仿', '增加听力材料难度,进行逐句模仿朗读,改善语音语调。', '[\"m1-half-1-basics\"]', 0, 'todo', 'medium', NULL, 7); +INSERT INTO `tasks` VALUES (54, 4, 53, 'm1-h2-input', '原声听力训练', '每日早晚各 30 分钟听英语新闻或对话,尝试复述大意。', '[]', 0, 'todo', 'medium', NULL, 8); +INSERT INTO `tasks` VALUES (55, 4, 53, 'm1-h2-imitation', '模仿朗读练习', '选取 1-2 分钟音频进行逐句模仿,重复 10-15 遍直至满意,尝试背诵短文。', '[\"m1-h2-input\"]', 0, 'todo', 'medium', NULL, 9); +INSERT INTO `tasks` VALUES (56, 4, NULL, 'month-2-expansion', '第二阶段:输出强化与拓展 (第 2 月)', '重点转向口语输出,利用影子跟读法提升流利度,并开始场景化练习。', '[\"month-1-foundation\"]', 0, 'todo', 'medium', NULL, 10); +INSERT INTO `tasks` VALUES (57, 4, 56, 'm2-half-1-speaking', '第 5-6 周:影子跟读与 AI 练习', '通过影子跟读法强化语音语调,利用 AI 工具纠正发音。', '[]', 0, 'todo', 'medium', NULL, 11); +INSERT INTO `tasks` VALUES (58, 4, 57, 'm2-h1-shadowing', '影子跟读训练', '延迟 0.5 秒模仿原声,每日 30 分钟,重点练习连读和语调。', '[]', 0, 'todo', 'medium', NULL, 12); +INSERT INTO `tasks` VALUES (59, 4, 57, 'm2-h1-ai-practice', 'AI 口语测评', '使用 AI 工具进行发音测评,针对弱项进行针对性修正练习。', '[\"m2-h1-shadowing\"]', 0, 'todo', 'medium', NULL, 13); +INSERT INTO `tasks` VALUES (60, 4, 56, 'm2-half-2-scenarios', '第 7-8 周:场景化对话练习', '针对餐饮、出行、购物等特定场景进行专题词汇和对话练习。', '[\"m2-half-1-speaking\"]', 0, 'todo', 'medium', NULL, 14); +INSERT INTO `tasks` VALUES (61, 4, 60, 'm2-h2-topic-practice', '场景词汇与句型', '学习特定场景下的高频短语和固定搭配,创设语境造句。', '[]', 0, 'todo', 'medium', NULL, 15); +INSERT INTO `tasks` VALUES (62, 4, 60, 'm2-h2-partner-talk', '模拟对话实践', '与语言伙伴或假想对象进行 15 分钟以上的情景对话练习。', '[\"m2-h2-topic-practice\"]', 0, 'todo', 'medium', NULL, 16); +INSERT INTO `tasks` VALUES (63, 4, NULL, 'month-3-application', '第三阶段:实际应用与流利度 (第 3 月)', '全面进入实战交流,接触真实外国人对话,巩固知识并提升反应速度。', '[\"month-2-expansion\"]', 0, 'todo', 'medium', NULL, 17); +INSERT INTO `tasks` VALUES (64, 4, 63, 'm3-half-1-real-world', '第 9-10 周:真实交流与媒体消费', '参与线上论坛讨论,观看无字幕美剧,尝试与外国人实际沟通。', '[]', 0, 'todo', 'medium', NULL, 18); +INSERT INTO `tasks` VALUES (65, 4, 64, 'm3-h1-foreigner-chat', '真人对话交流', '每周 3-4 次与母语者或外教对话,大胆表达日常见闻,避开私人话题。', '[]', 0, 'todo', 'medium', NULL, 19); +INSERT INTO `tasks` VALUES (66, 4, 64, 'm3-h1-media-consume', '无字幕媒体学习', '观看英文视频或听播客,尝试理解 60% 以上内容,记录新表达。', '[\"m3-h1-foreigner-chat\"]', 0, 'todo', 'medium', NULL, 20); +INSERT INTO `tasks` VALUES (67, 4, 63, 'm3-half-2-consolidation', '第 11-12 周:复盘与流利度提升', '录制口语复盘修正错误,总结三个月学习成果,确保能应对日常沟通。', '[\"m3-half-1-real-world\"]', 0, 'todo', 'medium', NULL, 21); +INSERT INTO `tasks` VALUES (68, 4, 67, 'm3-h2-review', '错误复盘与修正', '录制自己的口语内容,分析语法和发音错误,针对性改进。', '[]', 0, 'todo', 'medium', NULL, 22); +INSERT INTO `tasks` VALUES (69, 4, 67, 'm3-h2-final-test', '最终沟通测试', '进行一次完整的英文自我介绍及复杂话题讨论,评估是否达到交流目标。', '[\"m3-h2-review\"]', 0, 'todo', 'medium', NULL, 23); +INSERT INTO `tasks` VALUES (70, 5, NULL, 'phase-1-assessment', '阶段一:自我评估与方向定位', '分析个人技术栈与市场需求,确定高潜力的副业赛道', '[]', 0, 'done', 'medium', NULL, 0); +INSERT INTO `tasks` VALUES (71, 5, 70, 'phase-1-skill-audit', '核心技能盘点', '梳理编程技术栈、行业经验及可复用能力', '[]', 0, 'done', 'medium', NULL, 1); +INSERT INTO `tasks` VALUES (72, 5, 70, 'phase-1-market-research', '市场调研与分析', '研究当前副业市场趋势及盈利模式', '[\"phase-1-skill-audit\"]', 0, 'done', 'medium', NULL, 2); +INSERT INTO `tasks` VALUES (73, 5, 72, 'phase-1-market-comp', '竞品案例分析', '分析年入百万同行的产品结构与流量来源', '[]', 0, 'done', 'medium', NULL, 3); +INSERT INTO `tasks` VALUES (74, 5, 72, 'phase-1-market-user', '用户需求验证', '通过访谈或问卷验证目标用户付费意愿', '[\"phase-1-market-comp\"]', 0, 'done', 'medium', NULL, 4); +INSERT INTO `tasks` VALUES (75, 5, 70, 'phase-1-model-select', '副业模式选定', '确定是走知识付费、SaaS 工具还是高端咨询路线', '[\"phase-1-market-research\"]', 0, 'done', 'medium', NULL, 5); +INSERT INTO `tasks` VALUES (76, 5, NULL, 'phase-2-mvp-build', '阶段二:最小可行性产品开发', '快速构建核心产品或服务原型,完成首次交付闭环', '[\"phase-1-assessment\"]', 0, 'done', 'medium', NULL, 6); +INSERT INTO `tasks` VALUES (77, 5, 76, 'phase-2-prototype', '产品原型设计', '设计产品功能清单及用户交互流程', '[]', 0, 'done', 'medium', NULL, 7); +INSERT INTO `tasks` VALUES (78, 5, 76, 'phase-2-dev-core', '核心功能开发', '编码实现最关键的盈利功能模块', '[\"phase-2-prototype\"]', 0, 'done', 'medium', NULL, 8); +INSERT INTO `tasks` VALUES (79, 5, 76, 'phase-2-pricing', '定价策略制定', '设计阶梯价格体系以最大化生命周期价值', '[\"phase-2-dev-core\"]', 0, 'done', 'medium', NULL, 9); +INSERT INTO `tasks` VALUES (80, 5, NULL, 'phase-3-traffic-growth', '阶段三:流量获取与品牌建设', '建立多渠道内容矩阵,获取精准付费流量', '[\"phase-2-mvp-build\"]', 0, 'done', 'medium', NULL, 10); +INSERT INTO `tasks` VALUES (81, 5, 80, 'phase-3-content-matrix', '内容矩阵搭建', '布局博客、社交媒体及视频平台内容', '[]', 0, 'done', 'medium', NULL, 11); +INSERT INTO `tasks` VALUES (82, 5, 81, 'phase-3-content-blog', 'SEO 技术博客', '撰写高质量技术文章获取长尾搜索流量', '[]', 0, 'done', 'medium', NULL, 12); +INSERT INTO `tasks` VALUES (83, 5, 81, 'phase-3-content-social', '社交媒体运营', '在知乎、公众号或抖音建立个人 IP', '[\"phase-3-content-blog\"]', 0, 'done', 'medium', NULL, 13); +INSERT INTO `tasks` VALUES (84, 5, 80, 'phase-3-paid-ads', '付费投放测试', '小预算测试广告渠道以加速流量获取', '[\"phase-3-content-matrix\"]', 0, 'done', 'medium', NULL, 14); +INSERT INTO `tasks` VALUES (85, 5, NULL, 'phase-4-scaling', '阶段四:销售转化与规模化', '优化销售漏斗,引入自动化与外包以实现收入倍增', '[\"phase-3-traffic-growth\"]', 0, 'done', 'medium', NULL, 15); +INSERT INTO `tasks` VALUES (86, 5, 85, 'phase-4-automation', '自动化流程建立', '实现获客、交付、售后的全流程自动化', '[]', 0, 'done', 'medium', NULL, 16); +INSERT INTO `tasks` VALUES (87, 5, 85, 'phase-4-outsource', '团队外包协作', '将非核心业务外包,释放精力专注高价值环节', '[\"phase-4-automation\"]', 0, 'done', 'medium', NULL, 17); +INSERT INTO `tasks` VALUES (88, 5, 85, 'phase-4-expand', '产品线扩展', '基于现有用户群开发高客单价新产品', '[\"phase-4-outsource\"]', 0, 'done', 'medium', NULL, 18); +INSERT INTO `tasks` VALUES (89, 5, NULL, 'phase-5-finance', '阶段五:财务合规与风险控制', '确保税务合规,管理现金流,保障副业长期稳定', '[\"phase-4-scaling\"]', 0, 'done', 'medium', NULL, 19); +INSERT INTO `tasks` VALUES (90, 5, 89, 'phase-5-tax', '税务规划与合规', '注册个体户或公司,优化个人所得税结构', '[]', 0, 'done', 'medium', NULL, 20); +INSERT INTO `tasks` VALUES (91, 5, 89, 'phase-5-cashflow', '现金流管理', '建立财务模型,确保收入再投资与风险储备', '[\"phase-5-tax\"]', 0, 'done', 'medium', NULL, 21); +INSERT INTO `tasks` VALUES (93, 6, 92, 'phase-1-skill-inventory', '列出技能与经验', '梳理现有技术栈和行业经验,作为方向选择的基础。', '[]', 0, 'todo', 'medium', NULL, 1); +INSERT INTO `tasks` VALUES (94, 6, 92, 'phase-1-direction-selection', '选择潜在方向', '基于技能选出3个潜在方向(如AI工具、数据抓取、提效工具)。', '[\"phase-1-skill-inventory\"]', 0, 'todo', 'medium', NULL, 2); +INSERT INTO `tasks` VALUES (95, 6, 92, 'phase-1-competitor-research', '竞品调研', '每个方向找10个类似产品,重点分析收费模式。', '[\"phase-1-direction-selection\"]', 0, 'todo', 'medium', NULL, 3); +INSERT INTO `tasks` VALUES (96, 6, 92, 'phase-1-demand-validation', '需求验证', '在知乎/小红书/Reddit等平台搜索关键词,验证是否存在高频且付费意愿强的问题。', '[\"phase-1-competitor-research\"]', 0, 'todo', 'medium', NULL, 4); +INSERT INTO `tasks` VALUES (97, 6, 92, 'phase-1-final-positioning', '确定项目定位', '输出一句话项目定位,明确解决什么问题及目标用户。', '[\"phase-1-demand-validation\"]', 0, 'todo', 'medium', NULL, 5); +INSERT INTO `tasks` VALUES (98, 6, NULL, 'phase-2-mvp-development', '阶段二:最小产品(第2个月)', '2周内做出能收费的最小版本,核心是能收钱而非完美。', '[\"phase-1-direction-validation\"]', 0, 'todo', 'medium', NULL, 6); +INSERT INTO `tasks` VALUES (99, 6, 98, 'phase-2-core-function', '定义核心功能', '只保留1个核心功能,画简单用户流程(进来→付费→使用)。', '[]', 0, 'todo', 'medium', NULL, 7); +INSERT INTO `tasks` VALUES (100, 6, 98, 'phase-2-tech-implementation', '技术实现', '优先快速实现,后端Node/Python,前端简单页面,可用现成API。', '[\"phase-2-core-function\"]', 0, 'todo', 'medium', NULL, 8); +INSERT INTO `tasks` VALUES (101, 6, 98, 'phase-2-payment-integration', '接入支付', '集成Stripe或国内支付渠道,确保能收款。', '[\"phase-2-tech-implementation\"]', 0, 'todo', 'medium', NULL, 9); +INSERT INTO `tasks` VALUES (102, 6, 98, 'phase-2-landing-page', '制作落地页', '编写落地页,清楚说明解决的问题、好处及价格。', '[\"phase-2-core-function\"]', 0, 'todo', 'medium', NULL, 10); +INSERT INTO `tasks` VALUES (103, 6, NULL, 'phase-3-cold-start', '阶段三:冷启动赚钱(第3–4个月)', '赚到第一笔1000–10000元,通过内容分发和私聊获取早期用户。', '[\"phase-2-mvp-development\"]', 0, 'todo', 'medium', NULL, 11); +INSERT INTO `tasks` VALUES (104, 6, 103, 'phase-3-content-distribution', '内容分发', '在目标用户聚集地(小红书/知乎/B站)每天发布1条教方法或展示效果的内容。', '[]', 0, 'todo', 'medium', NULL, 12); +INSERT INTO `tasks` VALUES (105, 6, 103, 'phase-3-user-outreach', '私聊潜在用户', '直接询问潜在用户是否使用工具及愿意付多少钱,获取反馈。', '[\"phase-3-content-distribution\"]', 0, 'todo', 'medium', NULL, 13); +INSERT INTO `tasks` VALUES (106, 6, 103, 'phase-3-early-sales', '早期优惠销售', '提供早期优惠(如9.9/19.9),验证有人主动问、愿意掏钱及复购。', '[\"phase-3-user-outreach\"]', 0, 'todo', 'medium', NULL, 14); +INSERT INTO `tasks` VALUES (107, 6, NULL, 'phase-4-growth-scaling', '阶段四:放大(第5–8个月)', '目标月入3万–10万,优化产品、放大流量并建立转化链路。', '[\"phase-3-cold-start\"]', 0, 'todo', 'medium', NULL, 15); +INSERT INTO `tasks` VALUES (108, 6, 107, 'phase-4-product-optimization', '产品优化', '根据用户反馈迭代,增加高频功能,提升留存率。', '[]', 0, 'todo', 'medium', NULL, 16); +INSERT INTO `tasks` VALUES (109, 6, 107, 'phase-4-traffic-scaling', '流量放大', '选择1个平台重点做(小红书/YouTube/知乎),批量制作教方法或展示结果的内容。', '[\"phase-4-product-optimization\"]', 0, 'todo', 'medium', NULL, 17); +INSERT INTO `tasks` VALUES (110, 6, 107, 'phase-4-conversion-funnel', '建立转化链路', '完善免费内容引导到工具、工具引导收费、收费引导会员订阅的流程。', '[\"phase-4-traffic-scaling\"]', 0, 'todo', 'medium', NULL, 18); +INSERT INTO `tasks` VALUES (111, 6, NULL, 'phase-5-standardization', '阶段五:规模化(第9–12个月)', '逼近或达到年入百万,通过提价、矩阵化、自动化及外包实现规模化。', '[\"phase-4-growth-scaling\"]', 0, 'todo', 'medium', NULL, 19); +INSERT INTO `tasks` VALUES (112, 6, 111, 'phase-5-pricing-strategy', '提价策略', '逐步从9.9提价至299,推出年费套餐,提升客单价。', '[]', 0, 'todo', 'medium', NULL, 20); +INSERT INTO `tasks` VALUES (113, 6, 111, 'phase-5-product-matrix', '做产品矩阵', '复制同类工具3–5个或拓展功能模块,扩大收入来源。', '[\"phase-5-pricing-strategy\"]', 0, 'todo', 'medium', NULL, 21); +INSERT INTO `tasks` VALUES (114, 6, 111, 'phase-5-automation', '系统自动化', '实现自动获客(SEO/内容)、自动交付及自动收钱,减少人工干预。', '[\"phase-5-product-matrix\"]', 0, 'todo', 'medium', NULL, 22); +INSERT INTO `tasks` VALUES (115, 6, 111, 'phase-5-team-building', '外包与组队', '找人做客服和内容,创始人专注增长,实现团队化运作。', '[\"phase-5-automation\"]', 0, 'todo', 'medium', NULL, 23); + +-- ---------------------------- +-- Table structure for users +-- ---------------------------- +DROP TABLE IF EXISTS `users`; +CREATE TABLE `users` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `email` varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `password_hash` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, + `xp` int(11) NOT NULL, + `created_at` datetime NULL DEFAULT NULL, + PRIMARY KEY (`id`) USING BTREE, + UNIQUE INDEX `ix_users_email`(`email`) USING BTREE, + INDEX `ix_users_id`(`id`) USING BTREE +) ENGINE = MyISAM AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; + +-- ---------------------------- +-- Records of users +-- ---------------------------- +INSERT INTO `users` VALUES (1, 'admin', 'admin@qq.com', '$2b$12$ZYvZAqV3rd7zu/mWlgwgbuR8zXDvUlGdeS9rNJyED3O8aRmau6J7S', 4670, '2026-04-24 03:43:41'); + +SET FOREIGN_KEY_CHECKS = 1; diff --git a/backend/utils.py b/backend/utils.py new file mode 100644 index 0000000..3a6dd0b --- /dev/null +++ b/backend/utils.py @@ -0,0 +1,95 @@ +from models.models import Task + + +def build_task_tree(tasks: list[Task]) -> list[dict]: + """Build nested tree from flat DB task list.""" + task_map = {} + for t in tasks: + task_map[t.id] = { + "id": t.id, + "plan_id": t.plan_id, + "parent_id": t.parent_id, + "task_id": t.task_id, + "title": t.title, + "description": t.description, + "dependencies": t.dependencies or [], + "duration_in_hours": t.duration_in_hours, + "priority": t.priority, + "due_date": t.due_date.isoformat() if t.due_date else None, + "status": t.status, + "sort_order": t.sort_order, + "children": [], + } + + roots = [] + for t in tasks: + node = task_map[t.id] + if t.parent_id is None: + roots.append(node) + else: + parent = task_map.get(t.parent_id) + if parent: + parent["children"].append(node) + else: + roots.append(node) + + # Sort children by sort_order at every level + def sort_children(nodes: list[dict]) -> list[dict]: + nodes.sort(key=lambda n: n.get("sort_order", 0)) + for n in nodes: + if n["children"]: + sort_children(n["children"]) + return nodes + + sort_children(roots) + return roots + + +def find_in_tree(nodes: list[dict], task_id: int) -> dict | None: + """Find a task node in the tree by its DB id.""" + for n in nodes: + if n["id"] == task_id: + return n + found = find_in_tree(n["children"], task_id) + if found: + return found + return None + + +def calculate_task_depths(tasks: list[Task]) -> dict[int, int]: + """Calculate depth for all tasks in one pass using a parent_id -> id map. + Returns {task_id: depth}.""" + task_by_id = {t.id: t for t in tasks} + depth_cache: dict[int, int] = {} + + def _depth(task_id: int) -> int: + if task_id in depth_cache: + return depth_cache[task_id] + task = task_by_id.get(task_id) + if not task or task.parent_id is None: + depth_cache[task_id] = 0 + return 0 + d = _depth(task.parent_id) + 1 + depth_cache[task_id] = d + return d + + for t in tasks: + _depth(t.id) + + return depth_cache + + +def collect_descendant_ids(tasks: list[Task], parent_id: int) -> list[int]: + """Collect all descendant task IDs using a pre-loaded list (no N+1 queries).""" + children_map: dict[int, list[int]] = {} + for t in tasks: + if t.parent_id is not None: + children_map.setdefault(t.parent_id, []).append(t.id) + + result = [] + stack = children_map.get(parent_id, []) + while stack: + cid = stack.pop() + result.append(cid) + stack.extend(children_map.get(cid, [])) + return result diff --git a/frontend b/frontend new file mode 160000 index 0000000..98facaf --- /dev/null +++ b/frontend @@ -0,0 +1 @@ +Subproject commit 98facaf720f880740e68615fbc2938d7f99dcc35 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b412b35 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,8 @@ +[project] +name = "goal-planner" +version = "0.1.0" +description = "Add your description here" +requires-python = ">=3.10" +dependencies = [ + "python-dotenv>=1.2.2", +] diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..64c62b2 --- /dev/null +++ b/uv.lock @@ -0,0 +1,23 @@ +version = 1 +revision = 3 +requires-python = ">=3.10" + +[[package]] +name = "goal-planner" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "python-dotenv" }, +] + +[package.metadata] +requires-dist = [{ name = "python-dotenv", specifier = ">=1.2.2" }] + +[[package]] +name = "python-dotenv" +version = "1.2.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/82/ed/0301aeeac3e5353ef3d94b6ec08bbcabd04a72018415dcb29e588514bba8/python_dotenv-1.2.2.tar.gz", hash = "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3", size = 50135, upload-time = "2026-03-01T16:00:26.196Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101, upload-time = "2026-03-01T16:00:25.09Z" }, +]