107 lines
3.2 KiB
Markdown
107 lines
3.2 KiB
Markdown
# 互动之星任务跟踪集成计划
|
||
|
||
## Summary
|
||
在用户发表评论/帖子时,调用 `tasks.track` 接口更新"互动之星"任务进度。
|
||
|
||
## Current State Analysis
|
||
|
||
### 已有功能
|
||
- ✅ `TaskTrackAPIView` 已存在 - `POST /api/tasks/track/`
|
||
- ✅ "互动之星" 任务已在种子数据中定义(`action_type='post'`, `task_type='weekly'`, `target_count=5`)
|
||
- ✅ `action_type='post'` 已在 `TaskDefinition.ACTION_TYPE_CHOICES` 中定义
|
||
|
||
### 问题
|
||
- ❌ 文章创建 (`ArticleListCreateView.create`) 未调用任务跟踪
|
||
- ❌ 评论创建 (`ArticleCommentListCreateView.create`) 未调用任务跟踪
|
||
|
||
---
|
||
|
||
## Proposed Changes
|
||
|
||
### 1. 创建任务跟踪工具函数
|
||
**文件**: `user/utils/task_tracker.py` (新建)
|
||
|
||
```python
|
||
from django.utils import timezone
|
||
from user.models import TaskDefinition, UserTaskProgress
|
||
|
||
def track_task(user, action_type, count=1):
|
||
"""跟踪用户任务进度"""
|
||
now = timezone.localtime(timezone.now())
|
||
daily_period = now.strftime('%Y-%m-%d')
|
||
weekly_period = now.strftime('%Y-W%W')
|
||
|
||
tasks = TaskDefinition.objects.filter(
|
||
action_type=action_type,
|
||
is_active=True,
|
||
)
|
||
|
||
updated_tasks = []
|
||
for task in tasks:
|
||
if task.task_type == 'daily':
|
||
period_key = daily_period
|
||
elif task.task_type == 'weekly':
|
||
period_key = weekly_period
|
||
else:
|
||
period_key = 'permanent'
|
||
|
||
progress = get_or_create_progress(user, task, period_key)
|
||
|
||
if progress.is_completed and progress.is_claimed:
|
||
continue
|
||
|
||
progress.current_count = min(
|
||
progress.current_count + count,
|
||
task.target_count
|
||
)
|
||
|
||
if progress.current_count >= task.target_count and not progress.is_completed:
|
||
progress.is_completed = True
|
||
progress.completed_at = now
|
||
|
||
progress.save()
|
||
|
||
updated_tasks.append({
|
||
'id': task.id,
|
||
'name': task.name,
|
||
'current_count': progress.current_count,
|
||
'target_count': task.target_count,
|
||
'is_completed': progress.is_completed,
|
||
})
|
||
|
||
return updated_tasks
|
||
```
|
||
|
||
### 2. 修改文章创建视图
|
||
**文件**: `article/views.py`
|
||
|
||
在 `ArticleListCreateView.create` 方法中,文章创建成功后调用:
|
||
```python
|
||
from user.utils.task_tracker import track_task
|
||
track_task(request.user, 'post')
|
||
```
|
||
|
||
### 3. 修改评论创建视图
|
||
**文件**: `article/views.py`
|
||
|
||
在 `ArticleCommentListCreateView.create` 方法中,评论创建成功后调用:
|
||
```python
|
||
from user.utils.task_tracker import track_task
|
||
track_task(request.user, 'post')
|
||
```
|
||
|
||
---
|
||
|
||
## Assumptions & Decisions
|
||
|
||
1. **调用方式**: 使用同步调用(非异步),因为任务跟踪不应阻塞主流程,但需要确保数据一致性
|
||
2. **错误处理**: 任务跟踪失败不应影响主流程(文章/评论创建),使用 try-except 捕获异常
|
||
3. **action_type**: 使用 `'post'` 匹配"互动之星"任务定义
|
||
|
||
## Verification
|
||
|
||
- [ ] 创建文章后,任务中心"互动之星"进度 +1
|
||
- [ ] 发表评论后,任务中心"互动之星"进度 +1
|
||
- [ ] 达到目标次数(5次)后,任务标记为已完成
|
||
- [ ] 任务跟踪失败不影响文章/评论创建
|