Metadata-Version: 2.4
Name: aipm-backend
Version: 0.2.0
Summary: AI Project Manager Server - REST API backend for project and task management with notification support
Author: AIPM Team
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.104.0
Requires-Dist: uvicorn[standard]>=0.24.0
Requires-Dist: sqlalchemy>=2.0.23
Requires-Dist: pydantic>=2.5.0
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: apscheduler>=3.10.4
Requires-Dist: python-dateutil>=2.8.2
Requires-Dist: requests>=2.28.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: httpx>=0.25.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"

# AIPM - AI Project Manager

> 版本：0.1.0 (Phase 1 MVP)
> 描述：基于 FastAPI + SQLite 的项目管理后台 REST API

---

## 功能概述

AIPM 是一个完全独立的项目管理后台系统，提供：

- **项目管理**：创建、查询、更新项目
- **任务管理**：添加、查询、更新任务进展
- **进展收集**：定时启动进展收集，发送提醒
- **预警检查**：自动检查即将逾期的任务
- **周报生成**：自动生成项目周报
- **定时任务**：内置 APScheduler，支持三种定时任务

### 架构设计

```
┌──────────────────────────────────────────┐
│  aipm Backend（完全独立）                │
│  ├── REST API                            │
│  ├── Scheduler（定时任务）               │
│  ├── SQLite 数据库                       │
│  └── Business Logic                      │
└──────────────────────────────────────────┘
```

**关键原则**：
- Backend 完全独立，不绑定任何客户端
- 通知只返回内容，不负责发送
- 任何支持 HTTP 的客户端都能调用

---

## 快速开始

### 安装

```bash
# 从源码安装
pip install -e .

# 或从 git 安装
pip install git+https://github.com/yourname/aipm.git
```

### 启动

```bash
# 默认启动（端口 8000）
aipm

# 指定端口
aipm --port 9000

# 网络访问
aipm --host 0.0.0.0

# 使用自定义数据库
aipm --db sqlite:///custom.db

# 禁用定时任务
aipm --no-scheduler

# 开发模式（自动重载）
aipm --reload
```

### 访问 API 文档

启动后访问：
- Swagger UI：`http://localhost:8000/docs`
- ReDoc：`http://localhost:8000/redoc`

---

## API 接口

### 项目管理

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/projects` | POST | 创建项目 |
| `/api/v1/projects/{id}` | GET | 查询项目详情 |
| `/api/v1/projects` | GET | 查询项目列表 |
| `/api/v1/projects/{id}` | PATCH | 更新项目 |
| `/api/v1/projects/{id}` | DELETE | 删除项目 |

### 任务管理

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/tasks` | POST | 添加任务 |
| `/api/v1/tasks` | GET | 查询任务列表 |
| `/api/v1/tasks/{id}` | GET | 查询任务详情 |
| `/api/v1/tasks/{id}/progress` | PATCH | 更新进展 |
| `/api/v1/tasks/{id}` | DELETE | 删除任务 |

### 进展收集

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/collection/start` | POST | 启动进展收集 |
| `/api/v1/collection/check` | POST | 检查并发送提醒 |
| `/api/v1/collection/status/{session_id}` | GET | 查看收集状态 |
| `/api/v1/collection/feedback/chat` | POST | 群聊反馈 |
| `/api/v1/collection/feedback/form/{session_id}/{task_id}` | POST | 表单提交 |

### 报表与预警

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/reports` | POST | 生成报表 |
| `/api/v1/reports/overdue` | GET | 查询预警任务 |

### 定时任务

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/scheduled/check-overdue` | POST | 执行预警检查 |
| `/api/v1/scheduled/weekly-report` | POST | 生成周报 |
| `/api/v1/scheduled/collect-progress` | POST | 启动进展收集 |
| `/api/v1/scheduled/config` | GET | 查看定时任务配置 |
| `/api/v1/scheduled/config/{task_id}` | PATCH | 修改定时任务配置 |

---

## 数据库表

### 核心表

| 表名 | 描述 |
|------|------|
| `users` | 用户表 |
| `user_channels` | 用户渠道绑定表 |
| `projects` | 项目表 |
| `tasks` | 任务表 |
| `progress_history` | 进展历史表 |
| `progress_collect_sessions` | 收集会话表 |
| `progress_collect_details` | 收集明细表 |

### 辅助表

| 表名 | 描述 |
|------|------|
| `scheduled_task_configs` | 定时任务配置表 |

---

## 定时任务

### 三种定时任务

| 任务 ID | 名称 | 默认触发时间 |
|---------|------|--------------|
| `daily_check` | 每日预警检查 | 周一至周五 09:00 |
| `progress_collect` | 进展收集 | 周三 09:00 |
| `weekly_report` | 周报生成 | 周五 17:00 |

### 配置修改

通过 API 修改定时任务配置：

```bash
# 修改预警检查时间
curl -X PATCH http://localhost:8000/api/v1/scheduled/config/daily_check \
  -H "Content-Type: application/json" \
  -d '{"trigger_time": "08:00", "params": {"days_threshold": 5}}'

# 禁用定时任务
curl -X PATCH http://localhost:8000/api/v1/scheduled/config/weekly_report \
  -H "Content-Type: application/json" \
  -d '{"enabled": false}'
```

---

## 使用示例

### 创建项目

```bash
curl -X POST http://localhost:8000/api/v1/projects \
  -H "Content-Type: application/json" \
  -d '{
    "name": "智慧城市项目",
    "channel": "wecom",
    "group_id": "group_001",
    "webhook_url": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx",
    "background": "打造智慧城市管理平台",
    "objective": "完成一期建设",
    "deadline": "2026-06-30"
  }'
```

### 添加任务

```bash
curl -X POST http://localhost:8000/api/v1/tasks \
  -H "Content-Type: application/json" \
  -d '{
    "project_id": "proj_xxx",
    "title": "数据采集模块",
    "assignee": "user_001",
    "deadline": "2026-04-20",
    "priority": "high"
  }'
```

### 启动进展收集

```bash
curl -X POST http://localhost:8000/api/v1/collection/start \
  -H "Content-Type: application/json" \
  -d '{"project_id": "proj_xxx"}'

# 返回：
{
  "session_id": "session_xxx",
  "tasks_count": 5,
  "notifications": [
    {
      "target": "user",
      "channel": "wecom",
      "user_id": "user_001",
      "message": "请更新进展..."
    }
  ]
}
```

### 更新进展

```bash
curl -X PATCH http://localhost:8000/api/v1/tasks/task_xxx/progress \
  -H "Content-Type: application/json" \
  -d '{
    "progress": 60,
    "note": "已完成数据采集框架",
    "user_id": "user_001",
    "feedback_method": "chat"
  }'
```

### 生成周报

```bash
curl -X POST http://localhost:8000/api/v1/reports \
  -H "Content-Type: application/json" \
  -d '{
    "project_id": "proj_xxx",
    "report_type": "weekly"
  }'
```

## 通知系统（2026-04-15 新增）

### 核心功能

| 功能 | 说明 |
|------|------|
| **用户系统** | User + UserChannel 表，支持多渠道 |
| **Webhook @ 人** | 通过群机器人 webhook + mentioned_list 实现 |
| **消息推送** | 定时推送 + 实时推送，都通过 webhook 发送 |

**重要**：webhook_url 是必填参数，创建项目时必须提供。

### 用户管理 API

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/users` | POST | 创建用户 |
| `/api/v1/users` | GET | 查询用户列表 |
| `/api/v1/users/channels` | POST | 绑定 userid |
| `/api/v1/users/{id}/channels` | GET | 查询用户渠道绑定 |

### 通知发送 API

| 接口 | 方法 | 描述 |
|------|------|------|
| `/api/v1/notifications/notify` | POST | **实时发送通知**（人工/AI 触发） |

**架构说明**：

| 场景 | 发送方式 |
|------|----------|
| **定时推送** | Backend APScheduler → 直接 webhook |
| **实时推送** | 用户/AI 触发 `/notify` → 直接 webhook |

**依赖**：所有消息推送都依赖 webhook_url，创建项目时必须配置。

### 消息格式

**主动发送通知（POST /notifications/notify）：**

```json
{
  "target_name": "通哥",    // 可选，不填则不 @ 人
  "project_id": "proj_xxx", // 必填
  "message": "消息内容",    // 必填
  "channel": "wecom"        // 可选，默认企业微信
}
```

**消息显示格式：**

```
有 target_name:
To: 通哥
内容: 今天记得跑步

无 target_name:
大家好，这是群消息
```

**特殊值：target_name = "ALL"**

```
To: ALL
内容: 全体成员请注意
```
（不 @ 人，仅显示全员消息格式）

### 数据表扩展

**Project 表新增字段：**

| 字段 | 类型 | 说明 |
|------|------|------|
| `webhook_url` | VARCHAR | 群机器人 webhook URL（必填） |

**重要**：webhook_url 是必填参数，创建项目时必须提供。

### 消息发送流程

```
Backend APScheduler（定时推送）
  每天 09:00 → 检测逾期任务 → 直接 webhook 发送

实时推送（人工/AI 触发）
  用户/AI → /notifications/notify → 直接 webhook 发送
```

**重要**：webhook_url 是必填参数，创建项目时必须提供，否则无法发送消息。

### Webhook 消息格式

```json
{
  "msgtype": "text",
  "text": {
    "content": "⚠️ 【张三】任务即将逾期！...",
    "mentioned_list": ["HuangMingTong"]
  }
}
```

### 消息模板

**逾期预警：**

```
⚠️ 【张三】任务即将逾期！

📌 任务：完成 5 公里跑步
👤 责任人：张三
📁 项目：通哥家庭生活和学习任务跟踪项目
⏰ 剩余：0天
📊 进度：0%

🔥 请尽快处理！
```

**任务预警：**

```
⏰ 【通哥】任务预警

📌 任务：完成作业
👤 责任人：通哥
📁 项目：xxx
⏰ 剩余：3天
📊 进度：50%

💡 请注意进度！
```

---

### 环境变量

所有配置可通过环境变量设置，格式为 `AIPM_<section>__<key>`：

```bash
# 数据库配置
export AIPM_DATABASE__DATABASE_URL="sqlite:///./aipm.db"

# 定时任务配置
export AIPM_SCHEDULER__SCHEDULER_ENABLED="true"
export AIPM_SCHEDULER__SCHEDULER_TIMEZONE="Asia/Shanghai"

# API 配置
export AIPM_API_PREFIX="/api/v1"
```

### 配置文件

配置文件可选，默认使用内置配置：

```bash
# ~/.aipm/config.json（未来支持）
{
  "database": {
    "database_url": "sqlite:///./aipm.db"
  },
  "scheduler": {
    "scheduler_enabled": true,
    "scheduler_timezone": "Asia/Shanghai"
  }
}
```

---

## 技术栈

| 组件 | 技术 | 版本 |
|------|------|------|
| Web 框架 | FastAPI | ≥0.104.0 |
| 数据库 | SQLite | 默认 |
| ORM | SQLAlchemy | ≥2.0.23 |
| 数据验证 | Pydantic | ≥2.5.0 |
| 定时任务 | APScheduler | ≥3.10.4 |
| ASGI 服务器 | Uvicorn | ≥0.24.0 |

---

## 项目结构

```
code/
├── src/aipm/
│   ├── __init__.py           # 包入口
│   ├── config.py             # 配置管理
│   ├── database.py           # 数据库连接
│   ├── models.py             # 数据模型
│   ├── schemas.py            # API schemas
│   ├── scheduler.py          # 定时任务
│   ├── main.py               # FastAPI 应用
│   ├── cli.py                # CLI 入口
│   ├── api/                  # API 路由
│   │   ├── __init__.py
│   │   ├── projects.py
│   │   ├── tasks.py
│   │   ├── collection.py
│   │   ├── reports.py
│   │   └── scheduled.py
│   └── services/             # 业务逻辑
│       ├── __init__.py
│       ├── project_service.py
│       ├── task_service.py
│       ├── collection_service.py
│       └── report_service.py
├── pyproject.toml            # 项目配置
├── requirements.txt          # 依赖列表
└── README.md                 # 本文档
```

---

## Phase 1 MVP 验收

✅ **已完成功能**：

- [x] aipm Python package 结构（可 pip install）
- [x] FastAPI 后台 + SQLite 数据库
- [x] 项目管理 API（5个接口）
- [x] 任务管理 API（6个接口）
- [x] 进展收集功能（5个接口）
- [x] 预警检查 API
- [x] 周报生成 API
- [x] 定时任务（APScheduler）
- [x] 三种定时任务可配置
- [x] CLI 启动命令
- [x] **用户系统（User + UserChannel）**（2026-04-15）
- [x] **Webhook @ 人功能**（2026-04-15）
- [x] **webhook_url 必填参数**（2026-04-15）
- [x] **消息推送架构**（定时推送 + 实时推送都通过 webhook）

📋 **后续 Phase 2**：

- [ ] 认证机制（API token）
- [ ] 多用户支持
- [ ] PostgreSQL 迁移
- [ ] OpenClaw Skill
- [ ] 云服务器部署
- [ ] PyPI 发布

---

## 开发指南

### 本地开发

```bash
# 安装开发依赖
pip install -e ".[dev]"

# 启动开发服务器
aipm --reload

# 运行测试（未来添加）
pytest
```

### 代码结构

- **models.py**：数据库模型定义
- **schemas.py**：Pydantic 数据验证模型
- **services/**：业务逻辑层，与数据库交互
- **api/**：API 路由层，处理 HTTP 请求响应
- **scheduler.py**：定时任务调度器

### API 设计原则

1. RESTful 风格
2. 清晰的请求/响应模型
3. 错误处理统一
4. 通知只返回内容，不发送

---

## License

MIT License

---

**文档位置**：`/Users/hmt/.openclaw/workspace/pm/shared/aipm/code/README.md`
