-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtasks.py
More file actions
775 lines (682 loc) · 28.4 KB
/
tasks.py
File metadata and controls
775 lines (682 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
from flask import Blueprint, request, jsonify
from models import db, User, ProjectGroup, Task, TaskFile, SharedFile, TaskAssignee
from auth import token_required
from sqlalchemy.exc import IntegrityError
from datetime import datetime
tasks_bp = Blueprint('tasks', __name__, url_prefix='/tasks')
def build_task_tree(tasks, parent_id=None):
"""构建任务树结构"""
tree = []
for task in tasks:
if task.parent_task_id == parent_id and not task.is_deleted:
task_dict = task.to_dict()
# 递归获取子任务
children = build_task_tree(tasks, task.id)
if children:
task_dict['children'] = children
tree.append(task_dict)
return tree
@tasks_bp.route('', methods=['GET'])
@token_required
def get_tasks(current_user):
"""获取任务列表接口"""
try:
# 获取查询参数
project_id = request.args.get('projectId')
user_id = request.args.get('userId')
query = Task.query.filter(Task.is_deleted == False)
if project_id:
project = ProjectGroup.query.filter_by(id=project_id).first()
if not project:
return jsonify({'success': False, 'message': 'Project not found'}), 404
if current_user not in project.members and project.leader_id != current_user.id:
return jsonify({'success': False, 'message': 'Permission denied: Not a member of this project'}), 403
query = query.filter(Task.project_id == project_id)
elif user_id:
if user_id != current_user.id:
return jsonify({'success': False, 'message': 'Permission denied'}), 403
query = query.filter(Task.user_id == user_id)
else:
query = query.filter(Task.user_id == current_user.id)
# 按月份筛选(用于月视图)
month = request.args.get('month') # YYYY-MM
if month:
# 计算该月范围
try:
from datetime import datetime as dt
start = dt.strptime(month + '-01', '%Y-%m-%d')
if start.month == 12:
end = start.replace(year=start.year + 1, month=1)
else:
end = start.replace(month=start.month + 1)
start_str = start.strftime('%Y-%m-%d')
end_str = end.strftime('%Y-%m-%d')
except ValueError:
return jsonify({'success': False, 'message': 'Invalid month format'}), 400
# 任务在月视图内的判定:仅使用 start_date/end_date 区间
tasks = query.order_by(Task.created_at.desc()).all()
def in_month(t):
sd = t.start_date or t.end_date
ed = t.end_date or t.start_date
if not sd and not ed:
return False
sd = sd or ed
ed = ed or sd
return not (ed < start_str or sd >= end_str)
tasks = [t for t in tasks if in_month(t)]
else:
tasks = query.order_by(Task.created_at.desc()).all()
return jsonify({
'success': True,
'message': 'Tasks retrieved successfully',
'tasks': [task.to_dict() for task in tasks]
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': f'Failed to retrieve tasks: {str(e)}'
}), 500
@tasks_bp.route('', methods=['POST'])
@token_required
def create_task(current_user):
"""创建任务接口"""
try:
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
title = data.get('title', '').strip()
if not title:
return jsonify({
'success': False,
'message': 'Title is required'
}), 400
# 验证项目ID(如果提供)
project_id = data.get('project_id')
if project_id:
project = ProjectGroup.query.filter_by(id=project_id).first()
if not project:
return jsonify({
'success': False,
'message': 'Project not found'
}), 404
if current_user not in project.members and project.leader_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied: Not a member of this project'
}), 403
# 验证父任务ID(如果提供)
parent_task_id = data.get('parent_task_id')
if parent_task_id:
parent_task = Task.query.filter_by(id=parent_task_id, is_deleted=False).first()
if not parent_task:
return jsonify({
'success': False,
'message': 'Parent task not found'
}), 404
if parent_task.user_id != current_user.id:
if parent_task.project_id:
project = ProjectGroup.query.filter_by(id=parent_task.project_id).first()
if not project or (current_user not in project.members and project.leader_id != current_user.id):
return jsonify({'success': False, 'message': 'Permission denied'}), 403
else:
return jsonify({'success': False, 'message': 'Permission denied'}), 403
# 处理日期
def parse_date(value):
if not value:
return None
try:
dt = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
return dt.strftime('%Y-%m-%d')
except ValueError:
return None
start_date = parse_date(data.get('start_date'))
end_date = parse_date(data.get('end_date'))
due_date = parse_date(data.get('due_date'))
if any(v is None and data.get(k) for k, v in [('start_date', start_date), ('end_date', end_date)]):
return jsonify({'success': False, 'message': 'Invalid date format, please use ISO format'}), 400
# 创建新任务
new_task = Task(
user_id=current_user.id,
title=title,
project_id=project_id,
parent_task_id=parent_task_id,
description=data.get('description'),
status=data.get('status', 'pending'),
priority=data.get('priority', 'medium'),
start_date=start_date,
end_date=end_date,
due_date=due_date,
assigned_to=data.get('assigned_to')
)
db.session.add(new_task)
db.session.commit()
return jsonify({
'success': True,
'message': 'Task created successfully',
'task': new_task.to_dict()
}), 201
except IntegrityError:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Database constraint error'
}), 409
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Failed to create task: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>', methods=['GET'])
@token_required
def get_task(current_user, task_id):
"""获取任务详情接口"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
# 检查权限
if task.user_id != current_user.id:
if task.project_id:
project = ProjectGroup.query.filter_by(id=task.project_id).first()
if not project or (current_user not in project.members and project.leader_id != current_user.id):
return jsonify({'success': False, 'message': 'Permission denied'}), 403
else:
return jsonify({'success': False, 'message': 'Permission denied'}), 403
return jsonify({
'success': True,
'message': 'Task retrieved successfully',
'task': task.to_dict()
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': f'Failed to retrieve task: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>', methods=['PUT', 'PATCH'])
@token_required
def update_task(current_user, task_id):
"""更新任务接口"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
if task.user_id != current_user.id:
if task.project_id:
project = ProjectGroup.query.filter_by(id=task.project_id).first()
if not project or (current_user not in project.members and project.leader_id != current_user.id):
return jsonify({'success': False, 'message': 'Permission denied'}), 403
else:
return jsonify({'success': False, 'message': 'Permission denied'}), 403
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
# 更新任务字段
if 'title' in data:
title = data['title'].strip()
if title:
task.title = title
if 'description' in data:
task.description = data['description']
if 'status' in data:
status = data['status']
if status in ['pending', 'in_progress', 'completed', 'cancelled']:
task.status = status
if status == 'completed' and not task.completed_at:
task.completed_at = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
elif status != 'completed':
task.completed_at = None
if 'priority' in data:
priority = data['priority']
if priority in ['low', 'medium', 'high', 'urgent']:
task.priority = priority
if 'assigned_to' in data:
task.assigned_to = data['assigned_to']
def parse_date(value, field):
if value is None:
return None
try:
dt = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
return dt.strftime('%Y-%m-%d')
except ValueError:
return jsonify({'success': False, 'message': f'Invalid {field} format, please use ISO format'}), 400
if 'start_date' in data:
v = data['start_date']
if v:
res = parse_date(v, 'start_date')
if isinstance(res, tuple):
return res
task.start_date = res
else:
task.start_date = None
if 'end_date' in data:
v = data['end_date']
if v:
res = parse_date(v, 'end_date')
if isinstance(res, tuple):
return res
task.end_date = res
else:
task.end_date = None
# 移除 due_date 更新逻辑
if 'project_id' in data:
project_id = data['project_id']
if project_id:
project = ProjectGroup.query.filter_by(id=project_id).first()
if not project:
return jsonify({
'success': False,
'message': 'Project not found'
}), 404
if current_user not in project.members and project.leader_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied: Not a member of this project'
}), 403
task.project_id = project_id
if 'parent_task_id' in data:
parent_task_id = data['parent_task_id']
if parent_task_id:
# 不能将任务设置为自己的子任务
if parent_task_id == task_id:
return jsonify({
'success': False,
'message': 'Cannot set task as its own parent'
}), 400
# 检查是否会产生循环引用
parent = Task.query.filter_by(id=parent_task_id, is_deleted=False).first()
if not parent:
return jsonify({
'success': False,
'message': 'Parent task not found'
}), 404
# 检查父任务是否在任务的后代中(防止循环)
def is_descendant(check_task_id, ancestor_id):
check_task = Task.query.filter_by(id=check_task_id, is_deleted=False).first()
if not check_task or not check_task.parent_task_id:
return False
if check_task.parent_task_id == ancestor_id:
return True
return is_descendant(check_task.parent_task_id, ancestor_id)
if is_descendant(parent_task_id, task_id):
return jsonify({
'success': False,
'message': 'Cannot create circular reference'
}), 400
if parent.user_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied: Cannot set parent to other user\'s task'
}), 403
task.parent_task_id = parent_task_id
task.updated_at = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
db.session.commit()
return jsonify({
'success': True,
'message': 'Task updated successfully',
'task': task.to_dict()
}), 200
except IntegrityError:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Database constraint error'
}), 409
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Failed to update task: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>', methods=['DELETE'])
@token_required
def delete_task(current_user, task_id):
"""删除任务接口(软删除)"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
# 检查权限
if task.user_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied'
}), 403
# 软删除:标记为已删除
task.is_deleted = True
task.updated_at = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
db.session.commit()
return jsonify({
'success': True,
'message': 'Task deleted successfully'
}), 200
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Failed to delete task: {str(e)}'
}), 500
@tasks_bp.route('/tree/<group_id>', methods=['GET'])
@token_required
def get_task_tree(current_user, group_id):
"""获取项目组的任务树接口"""
try:
# 验证项目组存在且用户有权限
project = ProjectGroup.query.filter_by(id=group_id).first()
if not project:
return jsonify({
'success': False,
'message': 'Project group not found'
}), 404
if current_user not in project.members and project.leader_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied: Not a member of this project'
}), 403
# 获取该项目组的所有任务(包括所有成员的任务)
tasks = Task.query.filter(
Task.project_id == group_id,
Task.is_deleted == False
).order_by(Task.position, Task.created_at).all()
# 构建任务树
task_tree = build_task_tree(tasks)
return jsonify({
'success': True,
'message': 'Task tree retrieved successfully',
'tree': task_tree
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': f'Failed to retrieve task tree: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>/move', methods=['PUT'])
@token_required
def move_task(current_user, task_id):
"""移动任务接口(更改父任务或项目)"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
# 检查权限
if task.user_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied'
}), 403
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
# 更新父任务
if 'parent_task_id' in data:
parent_task_id = data['parent_task_id'] # 可以是null
if parent_task_id:
# 不能将任务设置为自己的子任务
if parent_task_id == task_id:
return jsonify({
'success': False,
'message': 'Cannot set task as its own parent'
}), 400
parent = Task.query.filter_by(id=parent_task_id, is_deleted=False).first()
if not parent:
return jsonify({
'success': False,
'message': 'Parent task not found'
}), 404
# 检查是否会产生循环引用
def is_descendant(check_task_id, ancestor_id):
check_task = Task.query.filter_by(id=check_task_id, is_deleted=False).first()
if not check_task or not check_task.parent_task_id:
return False
if check_task.parent_task_id == ancestor_id:
return True
return is_descendant(check_task.parent_task_id, ancestor_id)
if is_descendant(parent_task_id, task_id):
return jsonify({
'success': False,
'message': 'Cannot create circular reference'
}), 400
task.parent_task_id = parent_task_id
# 更新项目
if 'project_id' in data:
project_id = data['project_id'] # 可以是null
if project_id:
project = ProjectGroup.query.filter_by(id=project_id).first()
if not project:
return jsonify({
'success': False,
'message': 'Project not found'
}), 404
if current_user not in project.members and project.leader_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied: Not a member of this project'
}), 403
task.project_id = project_id
# 更新位置(用于排序)
if 'position' in data:
position = data.get('position', 0)
task.position = position
task.updated_at = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
db.session.commit()
return jsonify({
'success': True,
'message': 'Task moved successfully',
'task': task.to_dict()
}), 200
except IntegrityError:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Database constraint error'
}), 409
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Failed to move task: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>/attachments', methods=['POST'])
@token_required
def add_task_attachment(current_user, task_id):
"""添加任务附件接口"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
# 检查权限
if task.user_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied'
}), 403
data = request.get_json()
if not data:
return jsonify({
'success': False,
'message': 'Invalid request data'
}), 400
file_id = data.get('file_id')
if not file_id:
return jsonify({
'success': False,
'message': 'File ID is required'
}), 400
# 验证文件存在
file = SharedFile.query.filter_by(id=file_id, is_deleted=False).first()
if not file:
return jsonify({
'success': False,
'message': 'File not found'
}), 404
# 检查文件是否已有权限访问(文件所有者或项目组成员)
if file.user_id != current_user.id:
# 如果是项目文件,检查用户是否是项目组成员
if file.group_id:
project = ProjectGroup.query.filter_by(id=file.group_id).first()
if not project or (current_user not in project.members and project.leader_id != current_user.id):
return jsonify({
'success': False,
'message': 'Permission denied: Cannot attach file you do not have access to'
}), 403
else:
return jsonify({
'success': False,
'message': 'Permission denied: Cannot attach file you do not have access to'
}), 403
# 检查是否已经关联
existing = TaskFile.query.filter_by(task_id=task_id, file_id=file_id).first()
if existing:
return jsonify({
'success': False,
'message': 'File is already attached to this task'
}), 409
# 创建任务文件关联
task_file = TaskFile(task_id=task_id, file_id=file_id)
db.session.add(task_file)
db.session.commit()
return jsonify({
'success': True,
'message': 'Attachment added successfully',
'attachment': task_file.to_dict()
}), 201
except IntegrityError:
db.session.rollback()
return jsonify({
'success': False,
'message': 'Database constraint error'
}), 409
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Failed to add attachment: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>/attachments', methods=['GET'])
@token_required
def get_task_attachments(current_user, task_id):
"""获取任务附件列表接口"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
# 检查权限
if task.user_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied'
}), 403
# 获取任务的所有附件
task_files = TaskFile.query.filter_by(task_id=task_id).all()
attachments = []
for task_file in task_files:
file = SharedFile.query.filter_by(id=task_file.file_id, is_deleted=False).first()
if file:
attachments.append(file.to_dict())
return jsonify({
'success': True,
'message': 'Attachments retrieved successfully',
'attachments': attachments
}), 200
except Exception as e:
return jsonify({
'success': False,
'message': f'Failed to retrieve attachments: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>/attachments/<file_id>', methods=['DELETE'])
@token_required
def delete_task_attachment(current_user, task_id, file_id):
"""删除任务附件接口"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({
'success': False,
'message': 'Task not found'
}), 404
# 检查权限
if task.user_id != current_user.id:
return jsonify({
'success': False,
'message': 'Permission denied'
}), 403
# 查找任务文件关联
task_file = TaskFile.query.filter_by(task_id=task_id, file_id=file_id).first()
if not task_file:
return jsonify({
'success': False,
'message': 'Attachment not found'
}), 404
# 删除关联(不删除文件本身)
db.session.delete(task_file)
db.session.commit()
return jsonify({
'success': True,
'message': 'Attachment removed successfully'
}), 200
except Exception as e:
db.session.rollback()
return jsonify({
'success': False,
'message': f'Failed to remove attachment: {str(e)}'
}), 500
@tasks_bp.route('/<task_id>/assign', methods=['POST'])
@token_required
def assign_task(current_user, task_id):
"""批量或单项指派任务给成员"""
try:
task = Task.query.filter_by(id=task_id, is_deleted=False).first()
if not task:
return jsonify({'success': False, 'message': 'Task not found'}), 404
# 只有任务所有者或项目负责人可指派
project = ProjectGroup.query.filter_by(id=task.project_id).first() if task.project_id else None
if not (task.user_id == current_user.id or (project and project.leader_id == current_user.id)):
return jsonify({'success': False, 'message': 'Permission denied'}), 403
data = request.get_json() or {}
assignees = data.get('assignees')
assigned_to = data.get('assigned_to')
updated = []
if assigned_to:
task.assigned_to = assigned_to
if isinstance(assignees, list):
for uid in assignees:
# 必须是项目成员
if project and (uid not in [m.id for m in project.members] and uid != project.leader_id):
continue
existing = TaskAssignee.query.filter_by(task_id=task_id, user_id=uid).first()
if not existing:
db.session.add(TaskAssignee(task_id=task_id, user_id=uid))
updated.append(uid)
task.updated_at = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
db.session.commit()
return jsonify({'success': True, 'message': 'Task assigned', 'assigned_to': task.assigned_to, 'assignees_added': updated, 'task': task.to_dict()}), 200
except Exception as e:
db.session.rollback()
return jsonify({'success': False, 'message': f'Failed to assign: {str(e)}'}), 500