-
Notifications
You must be signed in to change notification settings - Fork 20
/
project.py
1875 lines (1637 loc) · 61.6 KB
/
project.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
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
project
Extend the project to allow users
:copyright: (c) 2012-2015 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
import os
import uuid
import re
import tempfile
import time
import dateutil.parser
import calendar
from collections import defaultdict
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from itertools import chain, cycle
from mimetypes import guess_type
from email.utils import parseaddr
import simplejson as json
from babel.dates import parse_date, format_date
from nereid import (
request, abort, render_template, login_required, url_for, redirect,
flash, jsonify, render_email, permissions_required, current_app, route,
current_user
)
from flask import send_file
from flask.helpers import send_from_directory
from nereid.ctx import has_request_context
from nereid.contrib.pagination import Pagination
from trytond.model import ModelView, ModelSQL, fields
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction
from trytond.pyson import Eval
from trytond.config import config
from trytond import backend
from utils import request_wants_json
import hashlib
import hmac
__all__ = [
'ProjectWorkMember', 'ProjectInvitation',
'ProjectWorkInvitation', 'Project', 'ProjectHistory', 'ProjectWorkCommit',
]
__metaclass__ = PoolMeta
calendar.setfirstweekday(calendar.SUNDAY)
PROGRESS_STATES = [
(None, ''),
('Backlog', 'Backlog'),
('Planning', 'Planning'),
('In Progress', 'In Progress'),
('Review', 'Review/QA'),
('Done', 'Done'),
]
#: Get the static folder. The static folder also
#: goes into the site packages
STATIC_FOLDER = os.path.join(
os.path.abspath(
os.path.dirname(__file__)
), 'static'
)
class ProjectWorkMember(ModelSQL, ModelView):
"Project Work Member"
__name__ = 'project.work.member'
user = fields.Many2One(
"nereid.user", "Nereid User", required=True, select=True
)
role = fields.Selection([
('admin', 'Admin'),
('member', 'Member'),
], "Role", required=True)
project = fields.Many2One(
"project.work", "Project", required=True, select=True
)
@classmethod
def __setup__(cls):
super(ProjectWorkMember, cls).__setup__()
cls._sql_constraints += [(
'check_user',
'UNIQUE(project, "user")',
'Users must be unique per project'
)]
@staticmethod
def default_role():
"""
Sets default role
"""
return 'member'
@classmethod
def __register__(cls, module_name):
'''
Register class and migrate data from old table(project_work-nereid_user)
to new table (project_work_user) only for porject participants
'''
cursor = Transaction().cursor
TableHandler = backend.get('TableHandler')
table_exist = TableHandler.table_exist(cursor, 'project_work_member')
super(ProjectWorkMember, cls).__register__(module_name)
if not table_exist:
ProjectUsers = Pool().get('project.work-nereid.user')
ProjectWork = Pool().get('project.work')
company_user = Pool().get('company.company-nereid.user')
# Migrate project participants from old user table to new member
# table
cursor.execute(
"INSERT INTO %s (project, \"user\", role) "
"SELECT old.task, old.user, 'member' from \"%s\" old "
"JOIN %s as p on old.task=p.id where p.type='project'"
% (
cls._table, ProjectUsers._table, ProjectWork._table
)
)
cursor.execute("SELECT id from project_work where type='project'")
for project in cursor.fetchall():
# Add project admins as admin member of all projects
cursor.execute(
"INSERT INTO %s (project, \"user\", role) "
"SELECT %d, a.user, 'admin' from \"%s\" a "
"WHERE NOT EXISTS "
"(select * from %s b where b.user=a.user and b.project=%d)"
% (
cls._table, project[0], company_user._table, cls._table,
project[0]
)
)
# If project admin is already member of project update the role as
# admin
cursor.execute(
"UPDATE \"%s\""
"SET role='admin' "
"WHERE \"user\" IN (select b.user from %s b) "
% (
cls._table, company_user._table
)
)
class ProjectInvitation(ModelSQL, ModelView):
"Project Invitation store"
__name__ = 'project.work.invitation'
email = fields.Char('Email', required=True, select=True)
invitation_code = fields.Char(
'Invitation Code', select=True
)
nereid_user = fields.Many2One('nereid.user', 'Nereid User')
project = fields.Many2One('project.work', 'Project')
joining_date = fields.Function(
fields.DateTime('Joining Date', depends=['nereid_user']),
'get_joining_date'
)
@classmethod
def __setup__(cls):
super(ProjectInvitation, cls).__setup__()
cls._sql_constraints += [
(
'invitation_code_unique',
'UNIQUE(invitation_code)',
'Invitation code cannot be same',
),
]
@staticmethod
def default_invitation_code():
"""
Sets the default invitation code as uuid everytime
"""
return unicode(uuid.uuid4())
def get_joining_date(self, name):
"""
Joining Date of User
"""
if self.nereid_user:
return self.nereid_user.create_date
@login_required
@route('/invitation-<int:active_id>/-remove', methods=['POST'])
def remove_invite(self):
"""
Remove the invite to a participant from project
"""
# Check if user is among the project admins
if not request.nereid_user.is_admin_of_project(self.project):
abort(403)
self.delete([self])
return jsonify({
"message": "Invitation to the user has been voided."
"The user can no longer join the project unless reinvited"
})
@login_required
@route('/invitation-<int:active_id>/-resend', methods=['GET', 'POST'])
def resend_invite(self):
"""Resend the invite to a participant
"""
EmailQueue = Pool().get('email.queue')
# Check if user is among the project admin members
if not request.nereid_user.is_admin_of_project(self.project):
flash(
"Sorry! You are not allowed to resend invites. "
"Contact your project admin for the same."
)
return redirect(request.referrer)
sender = config.get('email', 'from')
if request.method == 'POST':
subject = '[%s] You have been re-invited to join the project' \
% self.project.rec_name
email_message = render_email(
text_template='project/emails/invite_2_project_text.html',
subject=subject, to=self.email,
from_email=sender, project=self.project,
invitation=self
)
EmailQueue.queue_mail(
sender, self.email, email_message.as_string()
)
if request.is_xhr:
return jsonify({
'success': True,
})
flash("Invitation has been resent to %s." % self.email)
return redirect(request.referrer)
class ProjectWorkInvitation(ModelSQL):
"Project Work Invitation"
__name__ = 'project.work-project.invitation'
invitation = fields.Many2One(
'project.work.invitation', 'Invitation',
ondelete='CASCADE', select=1, required=True
)
project = fields.Many2One(
'project.work.invitation', 'Project',
ondelete='CASCADE', select=1, required=True
)
class Project:
"""
Tryton itself is very flexible in allowing multiple layers of Projects and
sub projects. But having this and implementing this seems to be too
convulted for everyday use. So nereid simplifies the process to:
- Project::Associated to a party
|
|-- Task (Type is task)
"""
__name__ = 'project.work'
history = fields.One2Many(
'project.work.history', 'project',
'History', readonly=True
)
members = fields.One2Many(
'project.work.member', 'project', 'Members',
states={'invisible': Eval('type') != 'project'},
depends=['type']
)
admins = fields.Function(
fields.One2Many('nereid.user', None, "Admins"), 'get_admins'
)
tags_for_projects = fields.One2Many(
'project.work.tag', 'project', 'Tags',
states={
'invisible': Eval('type') != 'project',
'readonly': Eval('type') != 'project',
}
)
created_by = fields.Many2One('nereid.user', 'Created by')
#: Get all the attachments on the object and return them
attachments = fields.Function(
fields.One2Many('ir.attachment', None, 'Attachments'),
'get_attachments'
)
repo_commits = fields.One2Many(
'project.work.commit', 'project', 'Repo Commits'
)
project = fields.Function(
fields.Many2One(
'project.work', 'Project', domain=[('type', '=', 'project')],
states={
'invisible': Eval('type') != 'project'
}
), 'get_parent_project'
)
iteration = fields.Many2One(
'project.iteration', 'Iteration',
)
backlog_iterations = fields.Many2Many(
'project.iteration-project.work', 'task', 'iteration',
'Backlog Iteration', readonly=True
)
subtype = fields.Selection([
('feature', 'Feature'),
('bug', 'Bug'),
('question', 'Question'),
('epic', 'Epic'),
], 'Subtype', select=True, states={
'invisible': Eval('type') != 'task',
'required': Eval('type') == 'task',
})
@staticmethod
def default_subtype():
return 'feature'
def get_parent_project(self, name):
"""
Gets the parent of this project
"""
# TODO: Make this function work even with highly nested tasks
if self.parent:
return self.parent.id
return self.id
@staticmethod
def default_created_by():
if has_request_context() and not current_user.is_anonymous():
return current_user.id
return None
def get_admins(self, name):
"""
Return all admin users of the project
"""
assert self.type == 'project'
return [
member.user.id for member in self.members
if member.role == 'admin'
]
@classmethod
@route('/projects/', methods=['GET', 'POST'])
@login_required
def home(cls):
"""
GET /projects/
POST /projects/
Param: name
"""
Activity = Pool().get('nereid.activity')
Work = Pool().get('timesheet.work')
if request.method == 'POST':
if not current_user.has_permissions(['project.admin']):
abort(403)
project, = cls.create([{
'work': Work.create([{
'name': request.values.get('name'),
'company': request.nereid_website.company.id,
}])[0].id,
'type': 'project',
'members': [
('create', [{
'user': request.nereid_user.id,
'role': 'admin',
}])
]
}])
Activity.create([{
'actor': request.nereid_user.id,
'object_': 'project.work, %d' % project.id,
'verb': 'created_project',
'project': project.id,
}])
return jsonify(message="Project successfully created"), 201
domain = [
('type', '=', 'project'),
('parent', '=', None),
]
if not current_user.has_permissions(['project.admin']):
# If not project admin, then the project only where user has
# a membership is shown
domain.append(('members.user', '=', request.nereid_user.id))
page = request.args.get('page', 1, int)
per_page = min(request.args.get('per_page', 50, int), 50)
projects = Pagination(cls, domain, page, per_page)
return jsonify(projects.serialize('listing'))
def serialize(self, purpose=None):
"""
Serialize a record, which could be a task or project
"""
assigned_to = None
if self.assigned_to:
assigned_to = self.assigned_to.serialize('listing')
value = {
'id': self.id,
'name': self.rec_name,
'type': self.type,
'parent': self.parent and self.parent.id or None,
# Task specific
'tags': map(lambda t: t.name, self.tags),
'assigned_to': assigned_to,
'attachments': len(self.attachments),
'progress_state': self.progress_state,
'comment': self.comment,
'create_date': self.create_date.isoformat(),
'owner': self.owner and self.owner.id,
'constraint_finish_time': (
self.constraint_finish_time and
self.constraint_finish_time.isoformat() or None
)
}
if self.type == 'task':
# Computing the effort for project is expensive
value['hours'] = self.hours
value['subtype'] = self.subtype
value['effort'] = self.effort
value['total_effort'] = self.total_effort,
value['project'] = self.project and {
'id': self.project.id,
'name': self.project.rec_name,
}
value['created_by'] = self.created_by and \
self.created_by.serialize('listing')
value['displayName'] = '#%d' % self.id
value['url'] = url_for(
'project.work.render_task', project_id=self.parent.id,
active_id=self.id,
)
elif purpose == 'activity_stream':
value['create_date'] = self.create_date.isoformat()
value['id'] = self.id
value['displayName'] = self.rec_name
value['type'] = self.type
value['objectType'] = self.__name__
elif self.type == 'project':
value['url'] = url_for(
'project.work.render_project', active_id=self.id
)
else:
value['all_participants'] = [
participant.serialize('listing') for participant in
self.all_participants
]
# TODO: Convert self.parent to self.project
value['url'] = url_for(
'project.work.render_task', project_id=self.parent.id,
active_id=self.id,
)
return value
@classmethod
@route('/rst-to-html', methods=['GET', 'POST'])
def rst_to_html(cls):
"""
Return the response as rst converted to html
"""
text = request.form['text']
return render_template('project/rst_to_html.jinja', text=text)
def get_attachments(self, name):
"""
Return all the attachments in the object
"""
Attachment = Pool().get('ir.attachment')
return map(
int, Attachment.search([
('resource', '=', '%s,%d' % (self.__name__, self.id))
])
)
def can_read(self, user, silent=False):
"""
Returns true if the given nereid user can read the project
:param user: The browse record of the current nereid user
"""
if user.has_permissions(['project.admin']):
return True
if user not in map(lambda member: member.user, self.members):
if silent:
return False
raise abort(403)
return True
def can_write(self, user, silent=False):
"""
Returns true if the given user can write to the project
:param user: The browse record of the current nereid user
"""
if user.has_permissions(['project.admin']):
return True
if user not in map(lambda member: member.user, self.members):
if silent:
return False
raise abort(403)
return True
@classmethod
def get_project(cls, project_id):
"""
Common base for fetching the project while validating if the user
can use it.
:param project_id: Project Id of project to fetch.
"""
projects = cls.search([
('id', '=', project_id),
('type', '=', 'project'),
])
if not projects:
raise abort(404)
if not projects[0].can_read(request.nereid_user, silent=True):
# If the user is not allowed to access this project then dont let
raise abort(403)
return projects[0]
@route('/projects/<int:active_id>/', methods=['GET', 'POST', 'DELETE'])
@login_required
def render_project(self):
"""
GET: Return serialized project
POST: edit project
DELETE: delete a project
"""
project = self.get_project(self.id)
if request.method == "POST":
# TODO: Not implemented yet
pass
elif request.method == "DELETE":
# TODO: Not implemented yet
pass
rv = project.serialize()
rv['participants'] = [
member.user.serialize('listing') for member in project.members
]
return jsonify(rv)
@classmethod
@route('/project-<int:project_id>/-permissions')
@login_required
def permissions(cls, project_id):
"""
Permissions for the project
:params project_id: project's id to check permission
"""
ProjectInvitation = Pool().get('project.work.invitation')
project = cls.get_project(project_id)
if not request.nereid_user.is_admin_of_project(project):
abort(404)
invitations = ProjectInvitation.search([
('project', '=', project.id),
('nereid_user', '=', None)
])
return render_template(
'project/permissions.jinja', project=project,
invitations=invitations, active_type_name='permissions'
)
@classmethod
@login_required
def projects_list(cls, page=1):
"""
Render a list of projects
"""
projects = cls.search([
('party', '=', request.nereid_user.party),
])
return render_template('project/projects.jinja', projects=projects)
@classmethod
@route('/project-<int:project_id>/-invite', methods=['POST'])
@login_required
def invite(cls, project_id):
"""Invite a user via email to the project
:param project_id: ID of Project
"""
NereidUser = Pool().get('nereid.user')
ProjectInvitation = Pool().get('project.work.invitation')
Activity = Pool().get('nereid.activity')
EmailQueue = Pool().get('email.queue')
project = cls.get_project(project_id)
if not request.nereid_user.is_admin_of_project(project):
flash(
"You are not allowed to invite users for this project"
)
return redirect(request.referrer)
if not request.method == 'POST':
return abort(404)
email = request.form['email']
existing_user = NereidUser.search([
('email', '=', email),
('company', '=', request.nereid_website.company.id),
], limit=1)
subject = '[%s] You have been invited to join the project' \
% project.rec_name
sender = config.get('email', 'from')
if existing_user:
# If participant already existed
if existing_user[0] in [m.user for m in project.members]:
flash("%s has been already added as a participant \
for the project" % existing_user[0].display_name)
return redirect(request.referrer)
email_message = render_email(
text_template="project/emails/"
"inform_addition_2_project_text.html",
subject=subject, to=email, from_email=sender,
project=project, user=existing_user[0]
)
cls.write(
[project], {
'members': [
('create', [{'user': existing_user[0].id}])
]
}
)
Activity.create([{
'actor': existing_user[0].id,
'object_': 'project.work, %d' % project.id,
'verb': 'joined_project',
'project': project.id,
}])
flash_message = "%s has been invited to the project" \
% existing_user[0].display_name
else:
new_invite, = ProjectInvitation.create([{
'email': email,
'project': project.id,
}])
email_message = render_email(
text_template='project/emails/invite_2_project_text.html',
subject=subject, to=email, from_email=sender,
project=project, invitation=new_invite
)
flash_message = "%s has been invited to the project" % email
EmailQueue.queue_mail(
sender, email, email_message.as_string()
)
if request.is_xhr:
return jsonify({
'success': True,
})
flash(flash_message)
return redirect(request.referrer)
@login_required
@route(
'/project-<int:active_id>/participant-<int:participant_id>/-remove',
methods=['POST']
)
def remove_participant(self, participant_id):
"""
Remove the participant from the project
"""
Activity = Pool().get('nereid.activity')
ProjectMember = Pool().get('project.work.member')
# Check if user is admin member of the project
if not request.nereid_user.is_admin_of_project(self):
abort(403)
task_ids_to_update = []
task_ids_to_update.extend([child.id for child in self.children])
# If this participant is assigned to any task in this project,
# that user cannot be removed as tryton's domain does not permit
# this.
# So removing assigned user from those tasks as well.
# TODO: Find a better way to do it, this is memory intensive
assigned_to_participant = self.search([
('id', 'in', task_ids_to_update),
('assigned_to', '=', participant_id)
])
self.write(assigned_to_participant, {
'assigned_to': None,
})
self.write(
map(
lambda rec_id: self.__class__(rec_id),
task_ids_to_update
), {'participants': [('remove', [participant_id])]}
)
project_member, = ProjectMember.search([
('project', '=', self.id),
('user', '=', participant_id),
])
self.write([self], {
'members': [('delete', [project_member.id])]
})
# FIXME: I think object_ in activity should be
# project.work-nereid.user models record.
object_ = 'nereid.user, %d' % participant_id
Activity.create([{
'actor': request.nereid_user.id,
'object_': object_,
'target': 'project.work, %d' % self.id,
'verb': 'removed_participant',
'project': self.id,
}])
return jsonify({
'success': True,
})
@classmethod
@route('/project-<int:project_id>/-files', methods=['GET', 'POST'])
@login_required
def render_files(cls, project_id):
project = cls.get_project(project_id)
other_attachments = chain.from_iterable(
[list(task.attachments) for task in project.children if
task.attachments]
)
return render_template(
'project/files.jinja', project=project,
active_type_name='files', guess_type=guess_type,
other_attachments=other_attachments
)
@classmethod
def _get_expected_date_range(cls):
"""Return the start and end date based on the GET arguments.
Also asjust for the full calendar asking for more information than
it actually must show
The last argument of the tuple returns a boolean to show if the
weekly table/aggregation should be displayed
"""
start = datetime.fromtimestamp(
request.args.get('start', type=int)
).date()
end = datetime.fromtimestamp(
request.args.get('end', type=int)
).date()
if (end - start).days < 20:
# this is not a month call, just some smaller range
return start, end
# This is a data call for a month, but fullcalendar tries to
# fill all the days in the first and last week from the prev
# and next month. So just return start and end date of the month
mid_date = start + relativedelta(days=((end - start).days / 2))
ignore, last_day = calendar.monthrange(mid_date.year, mid_date.month)
return (
date(year=mid_date.year, month=mid_date.month, day=1),
date(year=mid_date.year, month=mid_date.month, day=last_day),
)
@classmethod
def get_week(cls, day):
"""
Return the week for any given day
"""
if (day >= 1) and (day <= 7):
return '01-07'
elif (day >= 8) and (day <= 14):
return '08-14'
elif (day >= 15) and (day <= 21):
return '15-21'
else:
return '22-END'
@classmethod
def get_task_from_work(cls, work):
'''
Returns task from work
:param work: Instance of work
'''
with Transaction().set_context(active_test=False):
task, = cls.search([('work', '=', work.id)], limit=1)
return task
@classmethod
def get_calendar_data(cls, project=None):
"""
Returns the calendar data
"""
Timesheet = Pool().get('timesheet.line')
ProjectWork = Pool().get('project.work')
Employee = Pool().get('company.employee')
if request.args.get('timesheet_lines_of'):
# This request only expects timesheet lines and the request comes
# in the format date:employee_id:project_id
date, employee_id, project_id = request.args.get(
'timesheet_lines_of').split(':')
domain = [
('date', '=', datetime.strptime(date, '%Y-%m-%d').date()),
('employee', '=', int(employee_id))
]
if int(project_id):
project = ProjectWork(int(project_id))
domain.append(('work.parent', 'child_of', [project.work.id]))
lines = Timesheet.search(
domain, order=[('date', 'asc'), ('employee', 'asc')]
)
return jsonify(lines=[
unicode(render_template(
'project/timesheet-line.jinja', line=line,
related_task=cls.get_task_from_work(line.work)
))
for line in lines[::-1]
])
start, end = cls._get_expected_date_range()
day_totals = []
color_map = {}
colors = cycle([
'grey', 'RoyalBlue', 'CornflowerBlue', 'DarkSeaGreen',
'SeaGreen', 'Silver', 'MediumOrchid', 'Olive',
'maroon', 'PaleTurquoise'
])
query = '''SELECT
timesheet_line.employee,
timesheet_line.date,
'''
if project:
query += 'project_work.id AS project,'
else:
query += '0 AS project,'
query += '''SUM(timesheet_line.hours) AS sum
FROM timesheet_line
JOIN timesheet_work ON timesheet_work.id = timesheet_line.work \
AND timesheet_work.parent IS NOT NULL
JOIN project_work ON project_work.work = timesheet_work.parent
WHERE
timesheet_line.date >= %s AND
timesheet_line.date <= %s
'''
qargs = [start, end]
if project:
qargs.append(project.id)
query += 'AND project_work.id = %s'
if request.args.get('employee', None) and \
request.nereid_user.has_permissions(['project.admin']):
qargs.append(request.args.get('employee', None, int))
query += 'AND timesheet_line.employee = %s'
query += '''
GROUP BY
timesheet_line.employee,
timesheet_line.date
'''
if project:
query += ',project_work.id'
Transaction().cursor.execute(query, qargs)
raw_data = Transaction().cursor.fetchall()
hours_by_week_employee = defaultdict(lambda: defaultdict(float))
for employee_id, date, project_id, hours in raw_data:
employee = Employee(employee_id)
day_totals.append({
'id': '%s:%s:%s' % (date, employee.id, project_id),
'title': '%s (%dh %dm)' % (
employee.rec_name, hours, (hours * 60) % 60
),
'start': date.isoformat(),
'color': color_map.setdefault(employee, colors.next()),
})
hours_by_week_employee[cls.get_week(date.day)][employee] += hours
total_by_employee = defaultdict(float)
for employee_hours in hours_by_week_employee.values():
for employee, hours in employee_hours.iteritems():
total_by_employee[employee] += hours
work_week = render_template(
'project/work-week.jinja', data_by_week=hours_by_week_employee,
total_by_employee=total_by_employee
)
return jsonify(
day_totals=day_totals, lines=[],
work_week=unicode(work_week)
)
@classmethod
@route('/-project/-my-last-7-days')
@login_required
def get_7_day_performance(cls):
"""
Returns the hours worked in the last 7 days.
"""
Timesheet = Pool().get('timesheet.line')
Date_ = Pool().get('ir.date')
if not request.nereid_user.employee:
return jsonify({})
end_date = Date_.today()
start_date = end_date - relativedelta(days=7)
timesheet_lines = Timesheet.search([
('date', '>=', start_date),
('date', '<=', end_date),
('employee', '=', request.nereid_user.employee.id),
])
hours_by_day = {}
for line in timesheet_lines:
hours_by_day[line.date] = \
hours_by_day.setdefault(line.date, 0.0) + line.hours
days = hours_by_day.keys()
days.sort()
return jsonify({
'categories': map(lambda d: d.strftime('%d-%b'), days),
'series': ['%.2f' % hours_by_day[day] for day in days]
})
@classmethod
def get_comparison_data(cls):
"""
Compare the performance of people
"""
Date = Pool().get('ir.date')
Employee = Pool().get('company.employee')
employee_ids = request.args.getlist('employee', type=int)
if not employee_ids:
employees = Employee.search([])
employee_ids = map(lambda emp: emp.id, employees)
else:
employees = Employee.browse(employee_ids)
employees = dict(zip(employee_ids, employees))