feat: add web interface for task management
Some checks failed
continuous-integration/drone/push Build is failing

- Added full-featured web UI with drag-and-drop task sorting
- Implemented CRUD API endpoints for task management
- Added task reordering endpoint with priority support
- Created responsive HTML interface with inline styles
- Updated Docker configuration for web service deployment
- Added requirements.txt for dependency management
- Enhanced README with web interface documentation
- Made Google Calendar integration optional
This commit is contained in:
Ching L 2025-09-11 16:04:17 +08:00
parent ef3a841812
commit cae33176af
8 changed files with 901 additions and 31 deletions

50
.dockerignore Normal file
View File

@ -0,0 +1,50 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
.venv
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# Git
.git/
.gitignore
# Documentation
README.md
*.md
# Docker
Dockerfile
docker-compose.yml
.dockerignore
# Environment
.env
.env.example
# Database (will be mounted as volume)
*.db
data/
# Credentials (will be mounted as volume)
credentials.json
# Temporary files
*.log
*.tmp
.DS_Store
# Test files
test_*
*_test.py

11
.env.example Normal file
View File

@ -0,0 +1,11 @@
# API Configuration
API_KEY=your-secure-api-key-here
# Google Calendar Configuration
CALENDAR_ID=primary
# Port Configuration (optional)
# PORT=5000
# Database Path (optional, defaults to /app/data/tasks.db in container)
# TASK_DB=/app/data/tasks.db

View File

@ -1,14 +1,25 @@
# 使用自定义 Docker Registry 中官方 Python 镜像作为基础镜像
# 使用自定义 Docker Registry 中已安装依赖的镜像
FROM git.tunpok.com/ching/python-env:latest
# 设置工作目录
WORKDIR /app
# 将当前目录下的所有文件复制到容器中
COPY . .
# 复制应用代码和模板
COPY app.py .
COPY templates/ templates/
# port number
# 创建数据目录
RUN mkdir -p /app/data
# 设置环境变量默认值
ENV PORT=5000
ENV API_KEY=change-me
ENV TASK_DB=/app/data/tasks.db
ENV GOOGLE_CREDENTIALS_FILE=/app/credentials.json
ENV CALENDAR_ID=primary
# 暴露端口
EXPOSE 5000
# run flask app
# 运行 Flask 应用
CMD ["python", "app.py"]

128
README.md
View File

@ -1,20 +1,37 @@
# Calendar Widget
一个基于 Flask 的任务管理系统,集成 Google Calendar 日程安排功能,并配套 iOS Scriptable 小组件展示。
一个功能完整的任务管理系统,提供 Web 界面、RESTful API、Google Calendar 集成,以及 iOS Scriptable 小组件支持。
## 快速开始
```bash
# 1. 克隆项目
git clone <repository-url>
cd calendar-widget
# 2. 启动服务
docker-compose up -d
# 3. 访问 Web 界面
open http://localhost:5000
```
## 功能特性
- 🌐 **Web 管理界面**: 美观的任务管理页面,支持增删改查和拖拽排序
- 📋 **任务管理**: 基于最小执行间隔的任务追踪系统
- 📅 **Google Calendar 集成**: 自动将任务同步到 Google 日历
- 🚦 **智能状态显示**: 根据任务执行时间自动显示红黄绿三色状态
- 📱 **iOS Widget 支持**: 通过 Scriptable 在 iOS 桌面显示任务状态
- 🔄 **自动刷新**: Widget 每分钟自动更新状态
- 💾 **离线缓存**: API 不可用时自动使用本地缓存
- 💾 **数据持久化**: SQLite 数据库存储,支持 Docker 卷挂载
- 🎯 **拖拽排序**: Web 界面支持任务拖拽重新排序
## 系统架构
### 后端 API (Flask)
- **app.py**: 主应用程序,提供 RESTful API
### 后端服务 (Flask)
- **app.py**: 主应用程序,提供 RESTful API 和 Web 界面
- **templates/**: HTML 模板目录,包含任务管理界面
- **数据库**: SQLite 存储任务信息
- **认证**: 基于 API Key 的请求认证
- **时区**: 使用亚洲/上海时区 (北京时间)
@ -29,6 +46,16 @@
- **CI/CD**: Drone CI 自动构建和部署
- **服务编排**: Docker Compose 管理服务
## 访问入口
### Web 管理界面
直接访问 `http://your-server:5000/` 即可使用完整的任务管理界面,功能包括:
- 创建新任务(设置名称和最小间隔天数)
- 编辑现有任务
- 删除任务
- 拖拽排序任务
- 执行任务(添加到 Google Calendar
## API 接口
### 获取任务列表
@ -43,11 +70,56 @@ Headers: X-API-Key: <your-api-key>
{
"id": 1,
"name": "任务名称",
"color": "green|yellow|red"
"color": "green|yellow|red",
"min_interval_days": 7,
"last_execution_time": "2025-01-01T12:00:00+08:00",
"priority": 1
}
]
```
### 创建任务
```
POST /tasks
Headers: X-API-Key: <your-api-key>
Content-Type: application/json
{
"name": "任务名称",
"min_interval_days": 7,
"priority": 0
}
```
### 更新任务
```
PUT /tasks/<task_id>
Headers: X-API-Key: <your-api-key>
Content-Type: application/json
{
"name": "新任务名称",
"min_interval_days": 5
}
```
### 删除任务
```
DELETE /tasks/<task_id>
Headers: X-API-Key: <your-api-key>
```
### 重新排序任务
```
POST /tasks/reorder
Headers: X-API-Key: <your-api-key>
Content-Type: application/json
{
"task_ids": [3, 1, 2] // 按优先级从高到低排列的任务ID
}
```
### 创建日程
```
POST /tasks/<task_id>/schedule
@ -68,16 +140,34 @@ Headers: X-API-Key: <your-api-key>
### Docker 部署
1. 使用 Docker Compose:
1. 克隆项目:
```bash
git clone <repository-url>
cd calendar-widget
```
2. 配置环境变量:
```bash
cp .env.example .env
# 编辑 .env 文件,设置 API_KEY
```
3. 使用 Docker Compose 启动:
```bash
docker-compose up -d
```
2. 配置要求:
- 挂载 SQLite 数据库文件: `./tasks.db:/app/tasks.db`
- 挂载 Google 凭证文件: `<path-to-credentials>:/app/credentials.json`
4. 数据持久化:
- 任务数据库自动保存到: `./data/tasks.db`
- Google 凭证文件(可选): `./credentials.json`
### Google Calendar 配置
5. 访问服务:
- Web 界面: `http://localhost:5000/`
- API 端点: `http://localhost:5000/tasks`
### Google Calendar 配置(可选)
如果需要将任务同步到 Google Calendar
1. 创建 Google Cloud 项目
2. 启用 Google Calendar API
@ -85,6 +175,8 @@ docker-compose up -d
4. 将凭证文件放置在项目目录,命名为 `credentials.json`
5. 将服务账号邮箱添加到目标日历的共享用户
注意:即使没有配置 Google Calendar任务管理功能仍可正常使用
### iOS Widget 配置
1. 在 iPhone 上安装 [Scriptable](https://scriptable.app/) 应用
@ -104,12 +196,13 @@ docker-compose up -d
## 技术栈
- **后端**: Python 3.9+, Flask, Peewee ORM
- **后端**: Python 3.10+, Flask, Peewee ORM
- **前端**: HTML5, CSS3, JavaScript (原生)
- **数据库**: SQLite
- **容器**: Docker
- **容器**: Docker, Docker Compose
- **CI/CD**: Drone CI
- **端**: JavaScript (Scriptable iOS)
- **集成**: Google Calendar API
- **移动端**: JavaScript (Scriptable iOS)
- **集成**: Google Calendar API (可选)
## 开发环境
@ -120,9 +213,16 @@ pip install flask peewee google-api-python-client google-auth google-auth-httpli
### 本地运行
```bash
# 设置环境变量
export API_KEY=your-api-key
export PORT=5000
# 运行应用
python app.py
```
然后访问 `http://localhost:5000/` 使用 Web 界面
## License
MIT

96
app.py
View File

@ -21,7 +21,7 @@ import datetime as dt
from functools import wraps
from zoneinfo import ZoneInfo # Python 3.9+ standard timezone database
from flask import Flask, jsonify, request, abort
from flask import Flask, jsonify, request, abort, render_template
from peewee import (
Model, SqliteDatabase, AutoField, CharField, IntegerField, DateTimeField,
)
@ -65,10 +65,14 @@ with db:
# ---------------------------------------------------------------------------
# Google Calendar client
# ---------------------------------------------------------------------------
creds = service_account.Credentials.from_service_account_file(
CREDENTIALS_FILE, scopes=SCOPES
)
calendar_service = build("calendar", "v3", credentials=creds, cache_discovery=False)
try:
creds = service_account.Credentials.from_service_account_file(
CREDENTIALS_FILE, scopes=SCOPES
)
calendar_service = build("calendar", "v3", credentials=creds, cache_discovery=False)
except FileNotFoundError:
print(f"Warning: Google credentials file '{CREDENTIALS_FILE}' not found. Calendar integration disabled.")
calendar_service = None
# ---------------------------------------------------------------------------
# Flask app + helpers
@ -117,6 +121,9 @@ def compute_color(task: Task, now: dt.datetime) -> str:
# ---------------------------------------------------------------------------
# Routes
# ---------------------------------------------------------------------------
@app.route("/")
def index():
return render_template("index.html", api_key=API_KEY)
@app.route("/tasks", methods=["GET"])
@require_api_key
def list_tasks():
@ -129,11 +136,87 @@ def list_tasks():
"id": t.id,
"name": t.name,
"color": compute_color(t, now),
"min_interval_days": t.min_interval_days,
"last_execution_time": _to_datetime(t.last_execution_time).isoformat() if t.last_execution_time else None,
"priority": t.priority,
}
for t in tasks
]
return jsonify(response)
@app.route("/tasks", methods=["POST"])
@require_api_key
def create_task():
data = request.json
if not data or "name" not in data:
abort(400, description="Task name is required")
task = Task.create(
name=data["name"],
min_interval_days=data.get("min_interval_days", 7),
priority=data.get("priority", 0)
)
return jsonify({
"id": task.id,
"name": task.name,
"min_interval_days": task.min_interval_days,
"priority": task.priority,
}), 201
@app.route("/tasks/<int:task_id>", methods=["PUT"])
@require_api_key
def update_task(task_id: int):
task = Task.get_or_none(Task.id == task_id)
if not task:
abort(404, description="Task not found")
data = request.json
if "name" in data:
task.name = data["name"]
if "min_interval_days" in data:
task.min_interval_days = data["min_interval_days"]
if "priority" in data:
task.priority = data["priority"]
task.save()
return jsonify({
"id": task.id,
"name": task.name,
"min_interval_days": task.min_interval_days,
"priority": task.priority,
})
@app.route("/tasks/<int:task_id>", methods=["DELETE"])
@require_api_key
def delete_task(task_id: int):
task = Task.get_or_none(Task.id == task_id)
if not task:
abort(404, description="Task not found")
task.delete_instance()
return jsonify({"success": True})
@app.route("/tasks/reorder", methods=["POST"])
@require_api_key
def reorder_tasks():
data = request.json
if not data or "task_ids" not in data:
abort(400, description="task_ids array is required")
task_ids = data["task_ids"]
priority = len(task_ids)
for task_id in task_ids:
task = Task.get_or_none(Task.id == task_id)
if task:
task.priority = priority
task.save()
priority -= 1
return jsonify({"success": True})
@app.route("/tasks/<int:task_id>/schedule", methods=["POST"])
@require_api_key
def schedule_task(task_id: int):
@ -141,6 +224,9 @@ def schedule_task(task_id: int):
if not task:
abort(404, description="Task not found")
if calendar_service is None:
abort(503, description="Calendar service not available")
# Event time is now (Asia/Shanghai)
start_dt = dt.datetime.now(TZ).replace(microsecond=0)
start_time = start_dt.isoformat()

View File

@ -1,14 +1,21 @@
version: '3.8'
services:
calendar-widget-api:
build: .
image: git.tunpok.com/ching/calendar-widget-api:latest
container_name: calendar-widget-api
restart: always
restart: unless-stopped
environment:
- API_KEY=change-me
- CALENDAR_ID=primary
- PORT=5000
- API_KEY=${API_KEY:-change-me}
- TASK_DB=/app/data/tasks.db
- GOOGLE_CREDENTIALS_FILE=/app/credentials.json
- CALENDAR_ID=${CALENDAR_ID:-primary}
ports:
- 5000:5000
- "5000:5000"
volumes:
- ./tasks.db:/app/tasks.db
- /Users/ching/Nutstore\ Files/我的坚果云/calendar-bot-tunpok-ade3b1a46d71.json:/app/credentials.json
# 数据持久化
- ./data:/app/data
# Google Calendar 凭证文件(可选,如果存在)
- ./credentials.json:/app/credentials.json:ro

6
requirements.txt Normal file
View File

@ -0,0 +1,6 @@
flask==3.0.0
peewee==3.17.0
google-api-python-client==2.111.0
google-auth==2.25.2
google-auth-httplib2==0.2.0
google-auth-oauthlib==1.2.0

599
templates/index.html Normal file
View File

@ -0,0 +1,599 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>任务管理</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 28px;
font-weight: 600;
margin-bottom: 10px;
}
.add-task-form {
padding: 20px 30px;
background: #f8f9fa;
border-bottom: 1px solid #e0e0e0;
}
.form-row {
display: flex;
gap: 10px;
margin-bottom: 10px;
}
.form-group {
flex: 1;
}
.form-group label {
display: block;
margin-bottom: 5px;
color: #555;
font-size: 14px;
}
.form-group input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.btn-danger {
background: #ff4757;
color: white;
}
.btn-danger:hover {
background: #ff3838;
}
.btn-success {
background: #00b894;
color: white;
}
.btn-success:hover {
background: #00a885;
}
.task-list {
padding: 20px 30px;
min-height: 300px;
}
.task-item {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 15px;
margin-bottom: 10px;
display: flex;
align-items: center;
gap: 15px;
transition: all 0.3s;
cursor: move;
}
.task-item:hover {
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
transform: translateY(-2px);
}
.task-item.dragging {
opacity: 0.5;
transform: rotate(5deg);
}
.task-item.drag-over {
border: 2px dashed #667eea;
background: #f5f5ff;
}
.drag-handle {
color: #999;
cursor: grab;
font-size: 20px;
}
.drag-handle:active {
cursor: grabbing;
}
.task-color {
width: 12px;
height: 12px;
border-radius: 50%;
flex-shrink: 0;
}
.task-color.green {
background: #00b894;
}
.task-color.yellow {
background: #fdcb6e;
}
.task-color.red {
background: #ff4757;
}
.task-info {
flex: 1;
}
.task-name {
font-size: 16px;
font-weight: 500;
margin-bottom: 5px;
}
.task-details {
font-size: 12px;
color: #666;
}
.task-actions {
display: flex;
gap: 5px;
}
.btn-small {
padding: 5px 10px;
font-size: 12px;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #999;
}
.empty-state svg {
width: 100px;
height: 100px;
margin-bottom: 20px;
opacity: 0.3;
}
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
animation: fadeIn 0.3s;
}
.modal.show {
display: flex;
align-items: center;
justify-content: center;
}
.modal-content {
background-color: white;
padding: 30px;
border-radius: 12px;
max-width: 500px;
width: 90%;
animation: slideIn 0.3s;
}
.modal-header {
margin-bottom: 20px;
}
.modal-header h2 {
font-size: 20px;
color: #333;
}
.modal-footer {
margin-top: 20px;
display: flex;
gap: 10px;
justify-content: flex-end;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideIn {
from {
transform: translateY(-50px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>📋 任务管理系统</h1>
<p>拖拽排序 · 实时同步 · 智能提醒</p>
</div>
<div class="add-task-form">
<h3 style="margin-bottom: 15px; color: #333;">新增任务</h3>
<form id="addTaskForm">
<div class="form-row">
<div class="form-group">
<label for="taskName">任务名称</label>
<input type="text" id="taskName" placeholder="输入任务名称" required>
</div>
<div class="form-group" style="max-width: 150px;">
<label for="minInterval">最少间隔天数</label>
<input type="number" id="minInterval" value="7" min="1" required>
</div>
</div>
<button type="submit" class="btn btn-primary">
<span> 添加任务</span>
</button>
</form>
</div>
<div class="task-list" id="taskList">
<div class="empty-state">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
<p>暂无任务,点击上方添加第一个任务</p>
</div>
</div>
</div>
<div id="editModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2>编辑任务</h2>
</div>
<form id="editTaskForm">
<input type="hidden" id="editTaskId">
<div class="form-group">
<label for="editTaskName">任务名称</label>
<input type="text" id="editTaskName" required>
</div>
<div class="form-group">
<label for="editMinInterval">最少间隔天数</label>
<input type="number" id="editMinInterval" min="1" required>
</div>
<div class="modal-footer">
<button type="button" class="btn" onclick="closeEditModal()">取消</button>
<button type="submit" class="btn btn-primary">保存</button>
</div>
</form>
</div>
</div>
<script>
const API_KEY = '{{ api_key }}';
const API_URL = '';
let tasks = [];
let draggedElement = null;
async function fetchTasks() {
try {
const response = await fetch(`${API_URL}/tasks`, {
headers: {
'X-API-Key': API_KEY
}
});
tasks = await response.json();
renderTasks();
} catch (error) {
console.error('获取任务失败:', error);
}
}
function renderTasks() {
const taskList = document.getElementById('taskList');
if (tasks.length === 0) {
taskList.innerHTML = `
<div class="empty-state">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
<p>暂无任务,点击上方添加第一个任务</p>
</div>
`;
return;
}
taskList.innerHTML = tasks.map(task => `
<div class="task-item" draggable="true" data-id="${task.id}">
<span class="drag-handle"></span>
<div class="task-color ${task.color}"></div>
<div class="task-info">
<div class="task-name">${task.name}</div>
<div class="task-details">
间隔: ${task.min_interval_days} 天
${task.last_execution_time ? ` | 上次执行: ${new Date(task.last_execution_time).toLocaleDateString('zh-CN')}` : ''}
</div>
</div>
<div class="task-actions">
<button class="btn btn-success btn-small" onclick="scheduleTask(${task.id})">📅 执行</button>
<button class="btn btn-primary btn-small" onclick="editTask(${task.id})">✏️ 编辑</button>
<button class="btn btn-danger btn-small" onclick="deleteTask(${task.id})">🗑️ 删除</button>
</div>
</div>
`).join('');
initDragAndDrop();
}
function initDragAndDrop() {
const taskItems = document.querySelectorAll('.task-item');
taskItems.forEach(item => {
item.addEventListener('dragstart', handleDragStart);
item.addEventListener('dragover', handleDragOver);
item.addEventListener('drop', handleDrop);
item.addEventListener('dragenter', handleDragEnter);
item.addEventListener('dragleave', handleDragLeave);
item.addEventListener('dragend', handleDragEnd);
});
}
function handleDragStart(e) {
draggedElement = this;
this.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
if (this !== draggedElement) {
this.classList.add('drag-over');
}
}
function handleDragLeave(e) {
this.classList.remove('drag-over');
}
function handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (draggedElement !== this) {
const taskList = document.getElementById('taskList');
const allItems = [...taskList.querySelectorAll('.task-item')];
const draggedIndex = allItems.indexOf(draggedElement);
const targetIndex = allItems.indexOf(this);
if (draggedIndex < targetIndex) {
this.parentNode.insertBefore(draggedElement, this.nextSibling);
} else {
this.parentNode.insertBefore(draggedElement, this);
}
updateTaskOrder();
}
return false;
}
function handleDragEnd(e) {
const taskItems = document.querySelectorAll('.task-item');
taskItems.forEach(item => {
item.classList.remove('dragging', 'drag-over');
});
}
async function updateTaskOrder() {
const taskItems = document.querySelectorAll('.task-item');
const taskIds = Array.from(taskItems).map(item => parseInt(item.dataset.id));
try {
await fetch(`${API_URL}/tasks/reorder`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
},
body: JSON.stringify({ task_ids: taskIds })
});
fetchTasks();
} catch (error) {
console.error('更新排序失败:', error);
}
}
async function addTask(event) {
event.preventDefault();
const name = document.getElementById('taskName').value;
const minInterval = document.getElementById('minInterval').value;
try {
await fetch(`${API_URL}/tasks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
},
body: JSON.stringify({
name: name,
min_interval_days: parseInt(minInterval)
})
});
document.getElementById('addTaskForm').reset();
fetchTasks();
} catch (error) {
console.error('添加任务失败:', error);
}
}
function editTask(taskId) {
const task = tasks.find(t => t.id === taskId);
if (task) {
document.getElementById('editTaskId').value = task.id;
document.getElementById('editTaskName').value = task.name;
document.getElementById('editMinInterval').value = task.min_interval_days;
document.getElementById('editModal').classList.add('show');
}
}
function closeEditModal() {
document.getElementById('editModal').classList.remove('show');
}
async function updateTask(event) {
event.preventDefault();
const taskId = document.getElementById('editTaskId').value;
const name = document.getElementById('editTaskName').value;
const minInterval = document.getElementById('editMinInterval').value;
try {
await fetch(`${API_URL}/tasks/${taskId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-API-Key': API_KEY
},
body: JSON.stringify({
name: name,
min_interval_days: parseInt(minInterval)
})
});
closeEditModal();
fetchTasks();
} catch (error) {
console.error('更新任务失败:', error);
}
}
async function deleteTask(taskId) {
if (confirm('确定要删除这个任务吗?')) {
try {
await fetch(`${API_URL}/tasks/${taskId}`, {
method: 'DELETE',
headers: {
'X-API-Key': API_KEY
}
});
fetchTasks();
} catch (error) {
console.error('删除任务失败:', error);
}
}
}
async function scheduleTask(taskId) {
try {
await fetch(`${API_URL}/tasks/${taskId}/schedule`, {
method: 'POST',
headers: {
'X-API-Key': API_KEY
}
});
alert('任务已添加到日历!');
fetchTasks();
} catch (error) {
console.error('安排任务失败:', error);
alert('安排任务失败,请检查日历配置');
}
}
document.getElementById('addTaskForm').addEventListener('submit', addTask);
document.getElementById('editTaskForm').addEventListener('submit', updateTask);
window.onclick = function(event) {
if (event.target === document.getElementById('editModal')) {
closeEditModal();
}
}
fetchTasks();
</script>
</body>
</html>