-
Notifications
You must be signed in to change notification settings - Fork 20
/
iteration.py
431 lines (372 loc) · 13.5 KB
/
iteration.py
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
# -*- coding: utf-8 -*-
"""
iteration
:copyright: (c) 2015 by Openlabs Technologies & Consulting (P) Limited
:license: see LICENSE for more details.
"""
from nereid import (
login_required, url_for, abort, request, route, jsonify, current_user
)
from flask_wtf import Form
from wtforms import IntegerField, SelectField, validators, StringField, \
DateField
from trytond.model import ModelSQL, ModelView, fields
from trytond.transaction import Transaction
from trytond.pyson import Eval
from trytond.pool import PoolMeta, Pool
from trytond.wizard import Wizard, StateView, Button, StateAction
from nereid.ctx import has_request_context
from nereid.contrib.pagination import Pagination
from task import PROGRESS_STATES
__all__ = [
'Iteration', 'IterationBacklog', 'CloseIterationAsk', 'CloseIteration'
]
__metaclass__ = PoolMeta
READONLY_IF_CLOSED = {
'readonly': Eval('state') == 'closed'
}
class IterationForm(Form):
"Iteration Form"
name = StringField('Name', [validators.DataRequired()])
start_date = DateField('Start Date', [validators.DataRequired()])
end_date = DateField('End Date', [validators.DataRequired()])
class IterationAddTaskForm(Form):
"Iteratino Update Form"
task_id = IntegerField('Task Id', [validators.DataRequired()])
action = SelectField(
'Action to perform', validators=[validators.DataRequired()], choices=[
('add', 'Add'),
('remove', 'Remove'),
]
)
class Iteration(ModelSQL, ModelView):
'Iteration'
__name__ = 'project.iteration'
name = fields.Char(
'Name', required=True, states=READONLY_IF_CLOSED,
depends=['state'],
)
company = fields.Many2One(
'company.company', 'Company', select=True, required=True,
states=READONLY_IF_CLOSED, depends=['state'],
)
start_date = fields.Date(
'Start Date', required=True, select=True,
states=READONLY_IF_CLOSED, depends=['state'],
)
end_date = fields.Date(
'End Date', required=True, select=True,
states=READONLY_IF_CLOSED, depends=['state'],
)
state = fields.Selection([
('opened', 'Opened'),
('closed', 'Closed'),
], 'State', select=True, readonly=True)
tasks = fields.One2Many(
'project.work', 'iteration', 'Tasks',
domain=[
('type', '!=', 'project'),
('company', '=', Eval('company')),
],
add_remove=[
('type', '!=', 'project'),
('state', '=', 'opened'),
('company', '=', Eval('company')),
],
states=READONLY_IF_CLOSED, depends=['company', 'state'],
)
backlog_tasks = fields.One2Many(
'project.iteration.backlog', 'iteration', 'Backlog Tasks',
readonly=True
)
url = fields.Function(fields.Char('URL'), 'get_url')
# Function fields to return status
count_tasks = fields.Function(fields.Integer("Total Tasks"), 'get_count')
count_backlog = fields.Function(
fields.Integer("Tasks in Backlog"), 'get_count'
)
count_planning = fields.Function(
fields.Integer("Tasks in Planning"), 'get_count'
)
count_in_progress = fields.Function(
fields.Integer("Tasks in Progress"), 'get_count'
)
count_review = fields.Function(
fields.Integer("Tasks in Review"), 'get_count'
)
count_done = fields.Function(
fields.Integer("Done Tasks"), 'get_count'
)
def get_count(self, name):
"""Get task count based on task state.
"""
def _get_count(state):
return len(
filter(lambda task: task.progress_state == state, self.tasks)
)
if name == 'count_backlog':
return _get_count('Backlog')
elif name == 'count_planning':
return _get_count('Planning')
elif name == 'count_in_progress':
return _get_count('In Progress')
elif name == 'count_review':
return _get_count('Review')
elif name == 'count_done':
return len(filter(lambda task: task.state == 'done', self.tasks))
elif name == 'count_tasks':
return len(self.tasks + self.backlog_tasks)
def get_url(self, name):
"""
Return the url if within an active request context or return None
:param name: name of field
"""
if has_request_context():
return url_for(
'project.iteration.render', active_id=self.id
)
return None
@staticmethod
def default_company():
return Transaction().context.get('company')
@staticmethod
def default_state():
return 'opened'
@classmethod
def __setup__(cls):
super(Iteration, cls).__setup__()
cls._order.insert(0, ('start_date', 'ASC'))
cls._error_messages.update({
'wrong_dates': 'End Date should be greater than Start Date or '
'Iteration period is overlaping',
})
@classmethod
def validate(cls, iterations):
"""
Validate iterations
"""
super(Iteration, cls).validate(iterations)
for iteration in iterations:
iteration.check_dates()
def serialize(self, purpose=None):
"""
Serialize Iteration
"""
res = {
'id': self.id,
'name': self.name,
'start_date': self.start_date.isoformat(),
'end_date': self.end_date.isoformat(),
'count_tasks': self.count_tasks,
'count_backlog': self.count_backlog,
'count_planning': self.count_planning,
'count_in_progress': self.count_in_progress,
'count_review': self.count_review,
'count_done': self.count_done,
}
if purpose == "full":
res.update({
'tasks': [task.serialize(purpose) for task in self.tasks]
})
return res
def check_dates(self):
"""
Checks End date should not be less than Start date and,
Non overlapping of dates for iterations.
"""
cursor = Transaction().cursor
table = self.__table__()
if self.start_date and self.end_date and \
self.start_date >= self.end_date:
return False
cursor.execute(*table.select(
table.id, where=(((
(table.start_date <= self.start_date) &
(table.end_date >= self.start_date)) |
((table.start_date <= self.end_date) &
(table.end_date >= self.end_date)) |
((table.start_date >= self.start_date) &
(table.end_date <= self.end_date))) &
(table.id != self.id)
)
))
return bool(cursor.fetchone())
@classmethod
@route("/iterations/", methods=["GET", "POST"])
@login_required
def render_list(cls):
"""
GET: Renders list of iterations.
POST: Create new iteration.
"""
if request.method == 'GET':
page = request.args.get('page', 1, int)
state = request.args.get('state')
filter_domain = []
if state:
filter_domain.append(('state', '=', state))
iterations = Pagination(cls, filter_domain, page, 10)
return jsonify(iterations.serialize())
if not current_user.has_permissions(['project.scrum_master']):
# Only get is allowed if user is not scrum_master.
abort(403)
create_form = IterationForm()
if create_form.validate_on_submit():
iteration, = cls.create([{
'name': create_form.name.data,
'start_date': create_form.start_date.data,
'end_date': create_form.end_date.data,
}])
return jsonify({
'url': iteration.url,
}), 201
@route(
"/iterations/<int:active_id>/stats/tasks_by_user", methods=["GET"]
)
@login_required
def tasks_by_user_stat(self):
'''
GET: Return tasks by user
'''
res = self.serialize('full')
tasks_by_user = {}
for task in res['tasks']:
tasks_by_user.setdefault(task['owner'], []).append(task)
del res['tasks']
res['tasks_by_user'] = tasks_by_user
return jsonify(res)
@route(
"/iterations/<int:active_id>/stats/tasks_by_project", methods=["GET"]
)
@login_required
def tasks_by_project_stat(self):
'''
GET: Return tasks by project
'''
res = self.serialize('full')
tasks_by_project = {}
for task in res['tasks']:
tasks_by_project.setdefault(task['project'], []).append(task)
del res['tasks']
res['tasks_by_project'] = tasks_by_project
return jsonify(res)
@route(
"/iterations/<int:active_id>", methods=["GET", "POST", "PUT", "DELETE"]
)
@login_required
def render(self):
'''
GET: Renders an Iteration.
POST: Add/remove item to Iteration.
PUT: Update Iteration.
DELETE: Deletes an Iteration.
'''
if request.method == 'GET':
if not current_user.has_permissions(['project.scrum_master']):
# TODO: Show render according to user's project permissions
abort(403)
return jsonify(self.serialize('full'))
if self.state != 'opened' or \
not current_user.has_permissions(['project.scrum_master']):
# Only 'GET' is allowed if user is not scrum_master or state
# is not opened
abort(400)
add_task_form = IterationAddTaskForm()
if request.method == 'POST' and add_task_form.validate():
# Add and remove task from iteration
if add_task_form.task_id.data \
and add_task_form.action.data == 'add':
self.write([self], {
'tasks': [('add', [add_task_form.task_id.data])]
})
return jsonify(message='Added successfully')
if add_task_form.task_id.data \
and add_task_form.action.data == 'remove':
self.write([self], {
'tasks': [('remove', [add_task_form.task_id.data])]
})
return '', 204 # Removed
else:
abort(400)
update_form = IterationForm(obj=self)
if request.method == 'PUT' and update_form.validate():
# Update Iteration
self.write([self], {
'name': update_form.name.data,
'start_date': update_form.start_date.data,
'end_date': update_form.end_date.data,
})
return jsonify(message="Updated successfully")
if request.method == 'DELETE':
self.delete([self])
return "", 204
# Bad request errors
if request.method == 'POST':
return jsonify(errors=add_task_form.errors), 400
if request.method == 'PUT':
return jsonify(errors=update_form.errors), 400
abort(400)
class CloseIterationAsk(ModelView):
"Close Iteration Ask"
__name__ = "project.iteration.close_iteration.ask"
iteration = fields.Many2One(
'project.iteration', 'Iteration', domain=[
('state', '=', 'opened'),
], help="Transfer opened to task this iteration"
)
class CloseIteration(Wizard):
"Close Iteration"
__name__ = "project.iteration.close_iteration"
start_state = 'ask'
ask = StateView(
'project.iteration.close_iteration.ask',
'nereid_project.close_iteration_ask_view_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('OK', 'close', 'tryton-ok', default=True),
]
)
close = StateAction('nereid_project.act_iteration_form')
def do_close(self, action):
Iteration = Pool().get('project.iteration')
IterationBacklog = Pool().get('project.iteration.backlog')
old_iteration = Iteration(Transaction().context['active_id'])
new_iteration = self.ask.iteration
old_iteration.backlog_tasks = []
new_iteration.tasks = list(new_iteration.tasks)
for task in filter(lambda t: t.state == 'opened', old_iteration.tasks):
backlog_task = IterationBacklog()
backlog_task.task = task
backlog_task.progress_state = task.progress_state
backlog_task.owner = task.owner
backlog_task.assigned_to = task.assigned_to
backlog_task.project = task.parent
old_iteration.backlog_tasks.append(backlog_task)
new_iteration.tasks.append(task)
old_iteration.state = 'closed'
old_iteration.save()
new_iteration.save()
action['views'].reverse()
return action, {'res_id': [self.ask.iteration.id]}
class IterationBacklog(ModelSQL, ModelView):
"Iteration Backlog"
__name__ = 'project.iteration.backlog'
iteration = fields.Many2One(
'project.iteration', 'Iteration', required=True, select=True
)
task = fields.Many2One(
'project.work', 'Task', required=True, select=True,
domain=[('type', '=', 'task')]
)
progress_state = fields.Selection(
PROGRESS_STATES, 'Progress State', select=True
)
owner = fields.Many2One(
'nereid.user', 'Task Owner', select=True
)
assigned_to = fields.Many2One(
'nereid.user', 'Assigned To', select=True
)
project = fields.Many2One(
'project.work', 'Project', select=True,
domain=[('type', '=', 'project')]
)