sync from local backup
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
import logging
|
||||
from django.utils import timezone
|
||||
from .models import TaskDefinition, UserTaskProgress
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def get_or_create_progress(user, task, period_key):
|
||||
progress, created = UserTaskProgress.objects.get_or_create(
|
||||
user=user,
|
||||
task=task,
|
||||
period_key=period_key,
|
||||
defaults={'current_count': 0}
|
||||
)
|
||||
return progress
|
||||
|
||||
|
||||
def track_task(user, action_type, count=1):
|
||||
"""跟踪用户任务进度
|
||||
|
||||
Args:
|
||||
user: 用户实例
|
||||
action_type: 行为类型,如 'post', 'browse', 'learn' 等
|
||||
count: 行为次数,默认1
|
||||
|
||||
Returns:
|
||||
list: 更新的任务列表
|
||||
"""
|
||||
try:
|
||||
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
|
||||
except Exception as e:
|
||||
logger.error(f'任务跟踪失败: user={user.id}, action={action_type}, error={e}')
|
||||
return []
|
||||
Reference in New Issue
Block a user