[FIX] project_long_term: Fix yaml tests, specify resourceusers and
[odoo/odoo.git] / addons / project_long_term / wizard / project_schedule_tasks.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import datetime
23 from resource.faces import *
24 from new import classobj
25 import operator
26
27 from tools.translate import _
28 from osv import osv, fields
29
30 import working_calendar as wkcal
31
32 class project_schedule_task(osv.osv_memory):
33
34     _name = "project.schedule.tasks"
35     _description = 'project.schedule.tasks'
36     _columns = {
37         'msg': fields.char('Message', size=64)
38     }
39     _defaults = {
40          'msg': 'Task Scheduling Completed Successfully'
41     }
42
43     def default_get(self, cr, uid, fields_list, context=None):
44         if context is None:
45             context = {}
46         res = super(project_schedule_task, self).default_get(cr, uid, fields_list, context)
47         self.compute_date(cr, uid, context=context)
48         return res
49
50     def create_resources(self, cr, uid, phase, context=None):
51         """
52         Return a list of  Resource Class objects for the resources allocated to the phase.
53         """
54         resource_objs = []
55
56         if context is None:
57             context = {}
58
59         for resource in phase.resource_ids:
60             res = resource.resource_id
61             leaves = []
62             resource_eff = res.time_efficiency
63             resource_cal = res.calendar_id.id
64             if resource_cal:
65                 cal_id  = phase.project_id.resource_calendar_id and phase.project_id.resource_calendar_id.id or False
66                 leaves = wkcal.compute_leaves(cr, uid, cal_id, res.id, resource_cal, context=context)
67             resource_objs.append(classobj(res.user_id.name.encode('utf8'), (Resource,),{
68                                              '__doc__': res.user_id.name,
69                                              '__name__': res.user_id.name,
70                                              'vacation': tuple(leaves),
71                                              'efficiency': resource_eff,
72                                           }))
73         return resource_objs
74
75     def compute_date(self, cr, uid, context=None):
76         """
77         Schedule the tasks according to resource available and priority.
78         """
79
80         phase_obj = self.pool.get('project.phase')
81         task_obj = self.pool.get('project.task')
82         user_obj = self.pool.get('res.users')
83
84         if context is None:
85             # It makes no sense to continue on empty context
86             return { 'warning': _("You must select some project phase to compute on")}
87
88         if not 'active_id' in context:
89             return {}
90         phase = phase_obj.browse(cr, uid, context['active_id'], context=context)
91         task_ids = map(lambda x : x.id, (filter(lambda x : x.state in ['open', 'draft', 'pending'] , phase.task_ids)))
92         if task_ids:
93             task_ids.sort()
94             tasks = task_obj.browse(cr, uid, task_ids, context=context)
95             start_date = str(phase.date_start)
96             if not phase.date_start:
97                 if not phase.project_id.date_start:
98                     start_date = datetime.datetime.now().strftime("%Y-%m-%d")
99                 else:
100                     start_date = phase.project_id.date_start
101             date_start = datetime.datetime.strftime(datetime.datetime.strptime(start_date, "%Y-%m-%d"), "%Y-%m-%d %H:%M")
102             calendar_id = phase.project_id.resource_calendar_id.id
103             resources = self.create_resources(cr, uid, phase)
104             priority_dict = {'0': 1000, '1': 800, '2': 500, '3': 300, '4': 100}
105             # Create dynamic no of tasks with the resource specified
106             def create_tasks(j, eff, priorty=500, obj=False):
107                 def task():
108                     """
109                     task is a dynamic method!
110                     """
111                     effort = eff
112                     if obj:
113                         resource = obj
114                     priority = priorty
115                 task.__doc__ = "TaskNO%d" %j
116                 task.__name__ = "task%d" %j
117                 return task
118
119             # Create a 'Faces' project with all the tasks and resources
120             def Project():
121                 title = "Project"
122                 start = date_start
123                 try:
124                     resource = reduce(operator.or_, resources)
125                 except:
126                     raise osv.except_osv(_('Error'), _('Phase must have resources assigned !'))
127                 minimum_time_unit = 1
128                 if calendar_id:            # If project has working calendar
129                     working_days = wkcal.compute_working_calendar(cr, uid, calendar_id)
130                     vacation = tuple(wkcal.compute_leaves(cr, uid, calendar_id))
131                 # Dynamic creation of tasks
132                 i = 0
133                 for each_task in tasks:
134                     hours = str(each_task.planned_hours )+ 'H'
135                     if each_task.priority in priority_dict.keys():
136                         priorty = priority_dict[each_task.priority]
137                     resc = False
138                     if each_task.user_id:
139                         for resrce in resources:
140                             if resrce.__name__ == each_task.user_id.name:
141                                 resc = resrce
142                                 break
143                     
144                     task = create_tasks(i, hours, priorty, resc)
145                     i += 1
146
147             project = BalancedProject(Project)
148           
149             loop_no = 0
150             # Write back the computed dates
151             for t in project:
152                 s_date = t.start.to_datetime()
153                 e_date = t.end.to_datetime()
154                 if loop_no > 0:
155                     ctx = context.copy()
156                     ctx.update({'scheduler': True})
157                     user_id = user_obj.search(cr, uid, [('name', '=', t.booked_resource[0].__name__)])
158                     task_obj.write(cr, uid, [tasks[loop_no-1].id], {
159                                                         'date_start': s_date.strftime('%Y-%m-%d %H:%M:%S'),
160                                                         'date_end': e_date.strftime('%Y-%m-%d %H:%M:%S'),
161                                                         'user_id': user_id[0]
162                                                     }, context=ctx)
163
164                 loop_no += 1
165         else:
166             return {"warning": _("No tasks to compute for this phase") }
167         return {}
168
169 project_schedule_task()
170
171 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: