[FIX-BUG] project_long_term - lp:701070
[odoo/odoo.git] / addons / project_long_term / project_long_term.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 from datetime import datetime, timedelta
23 from dateutil.relativedelta import relativedelta
24 from tools.translate import _
25 from osv import fields, osv
26 from resource.faces import task as Task 
27 import operator
28 from new import classobj
29 import types
30 import new
31
32 class project_phase(osv.osv):
33     _name = "project.phase"
34     _description = "Project Phase"
35
36     def _check_recursion(self, cr, uid, ids, context=None):
37          if context is None:
38             context = {}
39
40          data_phase = self.browse(cr, uid, ids[0], context=context)
41          prev_ids = data_phase.previous_phase_ids
42          next_ids = data_phase.next_phase_ids
43          # it should neither be in prev_ids nor in next_ids
44          if (data_phase in prev_ids) or (data_phase in next_ids):
45              return False
46          ids = [id for id in prev_ids if id in next_ids]
47          # both prev_ids and next_ids must be unique
48          if ids:
49              return False
50          # unrelated project
51          prev_ids = [rec.id for rec in prev_ids]
52          next_ids = [rec.id for rec in next_ids]
53          # iter prev_ids
54          while prev_ids:
55              cr.execute('SELECT distinct prv_phase_id FROM project_phase_rel WHERE next_phase_id IN %s', (tuple(prev_ids),))
56              prv_phase_ids = filter(None, map(lambda x: x[0], cr.fetchall()))
57              if data_phase.id in prv_phase_ids:
58                  return False
59              ids = [id for id in prv_phase_ids if id in next_ids]
60              if ids:
61                  return False
62              prev_ids = prv_phase_ids
63          # iter next_ids
64          while next_ids:
65              cr.execute('SELECT distinct next_phase_id FROM project_phase_rel WHERE prv_phase_id IN %s', (tuple(next_ids),))
66              next_phase_ids = filter(None, map(lambda x: x[0], cr.fetchall()))
67              if data_phase.id in next_phase_ids:
68                  return False
69              ids = [id for id in next_phase_ids if id in prev_ids]
70              if ids:
71                  return False
72              next_ids = next_phase_ids
73          return True
74
75     def _check_dates(self, cr, uid, ids, context=None):
76          for phase in self.read(cr, uid, ids, ['date_start', 'date_end'], context=context):
77              if phase['date_start'] and phase['date_end'] and phase['date_start'] > phase['date_end']:
78                  return False
79          return True
80
81     def _check_constraint_start(self, cr, uid, ids, context=None):
82          phase = self.read(cr, uid, ids[0], ['date_start', 'constraint_date_start'], context=context)
83          if phase['date_start'] and phase['constraint_date_start'] and phase['date_start'] < phase['constraint_date_start']:
84              return False
85          return True
86
87     def _check_constraint_end(self, cr, uid, ids, context=None):
88          phase = self.read(cr, uid, ids[0], ['date_end', 'constraint_date_end'], context=context)
89          if phase['date_end'] and phase['constraint_date_end'] and phase['date_end'] > phase['constraint_date_end']:
90              return False
91          return True
92
93     def _get_default_uom_id(self, cr, uid):
94        model_data_obj = self.pool.get('ir.model.data')
95        model_data_id = model_data_obj._get_id(cr, uid, 'product', 'uom_hour')
96        return model_data_obj.read(cr, uid, [model_data_id], ['res_id'])[0]['res_id']
97
98     def _compute(self, cr, uid, ids, field_name, arg, context=None):
99         res = {}
100         if not ids:
101             return res
102         for phase in self.browse(cr, uid, ids, context=context):
103             tot = 0.0
104             for task in phase.task_ids:
105                 tot += task.planned_hours
106             res[phase.id] = tot
107         return res
108
109     _columns = {
110         'name': fields.char("Name", size=64, required=True),
111         'date_start': fields.date('Start Date', help="It's computed by the scheduler according the project date or the end date of the previous phase.", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
112         'date_end': fields.date('End Date', help=" It's computed by the scheduler according to the start date and the duration.", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
113         'constraint_date_start': fields.date('Minimum Start Date', help='force the phase to start after this date', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
114         'constraint_date_end': fields.date('Deadline', help='force the phase to finish before this date', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
115         'project_id': fields.many2one('project.project', 'Project', required=True),
116         'next_phase_ids': fields.many2many('project.phase', 'project_phase_rel', 'prv_phase_id', 'next_phase_id', 'Next Phases', states={'cancelled':[('readonly',True)]}),
117         'previous_phase_ids': fields.many2many('project.phase', 'project_phase_rel', 'next_phase_id', 'prv_phase_id', 'Previous Phases', states={'cancelled':[('readonly',True)]}),
118         'sequence': fields.integer('Sequence', help="Gives the sequence order when displaying a list of phases."),
119         'duration': fields.float('Duration', required=True, help="By default in days", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
120         'product_uom': fields.many2one('product.uom', 'Duration UoM', required=True, help="UoM (Unit of Measure) is the unit of measurement for Duration", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
121         'task_ids': fields.one2many('project.task', 'phase_id', "Project Tasks", states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
122         'resource_ids': fields.one2many('project.resource.allocation', 'phase_id', "Project Resources",states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
123         'responsible_id': fields.many2one('res.users', 'Responsible', states={'done':[('readonly',True)], 'cancelled':[('readonly',True)]}),
124         'state': fields.selection([('draft', 'Draft'), ('open', 'In Progress'), ('pending', 'Pending'), ('cancelled', 'Cancelled'), ('done', 'Done')], 'State', readonly=True, required=True,
125                                   help='If the phase is created the state \'Draft\'.\n If the phase is started, the state becomes \'In Progress\'.\n If review is needed the phase is in \'Pending\' state.\
126                                   \n If the phase is over, the states is set to \'Done\'.'),
127         'total_hours': fields.function(_compute, method=True, string='Total Hours'),
128      }
129     _defaults = {
130         'responsible_id': lambda obj,cr,uid,context: uid,
131         'state': 'draft',
132         'sequence': 10,
133         'product_uom': lambda self,cr,uid,c: self.pool.get('product.uom').search(cr, uid, [('name', '=', _('Day'))], context=c)[0]
134     }
135     _order = "project_id, date_start, sequence, name"
136     _constraints = [
137         (_check_recursion,'Loops in phases not allowed',['next_phase_ids', 'previous_phase_ids']),
138         (_check_dates, 'Phase start-date must be lower than phase end-date.', ['date_start', 'date_end']),
139     ]
140
141     def onchange_project(self, cr, uid, ids, project, context=None):
142         result = {}
143         result['date_start'] = False
144         project_obj = self.pool.get('project.project')
145         if project:
146             project_id = project_obj.browse(cr, uid, project, context=context)
147             result['date_start'] = project_id.date_start
148         return {'value': result}
149
150
151     def _check_date_start(self, cr, uid, phase, date_end, context=None):
152        """
153        Check And Compute date_end of phase if change in date_start < older time.
154        """
155        uom_obj = self.pool.get('product.uom')
156        resource_obj = self.pool.get('resource.resource')
157        cal_obj = self.pool.get('resource.calendar')
158        calendar_id = phase.project_id.resource_calendar_id and phase.project_id.resource_calendar_id.id or False
159        resource_id = resource_obj.search(cr, uid, [('user_id', '=', phase.responsible_id.id)])
160        if resource_id:
161             res = resource_obj.read(cr, uid, resource_id, ['calendar_id'], context=context)[0]
162             cal_id = res.get('calendar_id', False) and res.get('calendar_id')[0] or False
163             if cal_id:
164                 calendar_id = cal_id
165        default_uom_id = self._get_default_uom_id(cr, uid)
166        avg_hours = uom_obj._compute_qty(cr, uid, phase.product_uom.id, phase.duration, default_uom_id)
167        work_times = cal_obj.interval_min_get(cr, uid, calendar_id, date_end, avg_hours or 0.0, resource_id and resource_id[0] or False)
168        dt_start = work_times[0][0].strftime('%Y-%m-%d')
169        self.write(cr, uid, [phase.id], {'date_start': dt_start, 'date_end': date_end.strftime('%Y-%m-%d')}, context=context)
170
171     def _check_date_end(self, cr, uid, phase, date_start, context=None):
172        """
173        Check And Compute date_end of phase if change in date_end > older time.
174        """
175        uom_obj = self.pool.get('product.uom')
176        resource_obj = self.pool.get('resource.resource')
177        cal_obj = self.pool.get('resource.calendar')
178        calendar_id = phase.project_id.resource_calendar_id and phase.project_id.resource_calendar_id.id or False
179        resource_id = resource_obj.search(cr, uid, [('user_id', '=', phase.responsible_id.id)], context=context)
180        if resource_id:
181             res = resource_obj.read(cr, uid, resource_id, ['calendar_id'], context=context)[0]
182             cal_id = res.get('calendar_id', False) and res.get('calendar_id')[0] or False
183             if cal_id:
184                 calendar_id = cal_id
185        default_uom_id = self._get_default_uom_id(cr, uid)
186        avg_hours = uom_obj._compute_qty(cr, uid, phase.product_uom.id, phase.duration, default_uom_id)
187        work_times = cal_obj.interval_get(cr, uid, calendar_id, date_start, avg_hours or 0.0, resource_id and resource_id[0] or False)
188        dt_end = work_times[-1][1].strftime('%Y-%m-%d')
189        self.write(cr, uid, [phase.id], {'date_start': date_start.strftime('%Y-%m-%d'), 'date_end': dt_end}, context=context)
190
191     def copy(self, cr, uid, id, default=None, context=None):
192         if default is None:
193             default = {}
194         if not default.get('name', False):
195             default['name'] = self.browse(cr, uid, id, context=context).name + _(' (copy)')
196         return super(project_phase, self).copy(cr, uid, id, default, context)
197
198     def set_draft(self, cr, uid, ids, *args):
199         self.write(cr, uid, ids, {'state': 'draft'})
200         return True
201
202     def set_open(self, cr, uid, ids, *args):
203         self.write(cr, uid, ids, {'state': 'open'})
204         return True
205
206     def set_pending(self, cr, uid, ids, *args):
207         self.write(cr, uid, ids, {'state': 'pending'})
208         return True
209
210     def set_cancel(self, cr, uid, ids, *args):
211         self.write(cr, uid, ids, {'state': 'cancelled'})
212         return True
213
214     def set_done(self, cr, uid, ids, *args):
215         self.write(cr, uid, ids, {'state': 'done'})
216         return True
217
218     def generate_phase(self, cr, uid, ids, f, parent=False, context=None):
219         if context is None:
220             context = {}
221         phase_ids = []
222         resource_pool = self.pool.get('resource.resource')
223         data_pool = self.pool.get('ir.model.data')
224         resource_allocation_pool = self.pool.get('project.resource.allocation')
225         uom_pool = self.pool.get('product.uom')
226         task_pool = self.pool.get('project.task')
227         data_model, day_uom_id = data_pool.get_object_reference(cr, uid, 'product', 'uom_day')
228         for phase in self.browse(cr, uid, ids, context=context):
229             avg_days = uom_pool._compute_qty(cr, uid, phase.product_uom.id, phase.duration, day_uom_id)
230             duration = str(avg_days) + 'd'
231             # Create a new project for each phase
232             str_resource = ('%s & '*len(phase.resource_ids))[:-2]
233             str_vals = str_resource % tuple(map(lambda x: 'Resource_%s'%x.resource_id.id, phase.resource_ids))
234
235             # Phases Defination for the Project
236             s = '''
237     def Phase_%s():
238         title = \"%s\"
239         effort = \'%s\'
240         resource = %s
241 '''%(phase.id, phase.name, duration, str_vals or False)
242
243             # Recalculate date_start and date_end
244             # according to constraints on date start and date end on phase
245             start_date = ''
246             end_date = ''
247             if phase.constraint_date_start:
248                 start_date = datetime.strptime(phase.constraint_date_start, '%Y-%m-%d')
249                 s += '''
250         start = \"%s\"
251 '''%(datetime.strftime(start_date, "%Y-%m-%d"))
252             else:
253                 if parent:
254                     start = 'up.Phase_%s.end' % (parent.id)
255                     s += '''
256         start = %s
257 '''%(start)
258                 else:
259                     start = phase.project_id.date_start or phase.date_start
260                     s += '''
261         start = \"%s\"
262 '''%(start)                
263                 
264             if phase.constraint_date_end :
265                 end_date= datetime.strptime(phase.constraint_date_end, '%Y-%m-%d')
266                 s += '''
267         end = \"%s\"
268 '''%(datetime.strftime(end_date, "%Y-%m-%d"))               
269
270
271                 #start = datetime.strftime((datetime.strptime(start, "%Y-%m-%d")), "%Y-%m-%d")
272
273             phase_ids.append(phase.id)
274             parent = False
275             task_ids = []
276             todo_task_ids = task_pool.search(cr, uid, [('id', 'in', map(lambda x : x.id, phase.task_ids)),
277                                               ('state', 'in', ['draft', 'open', 'pending'])
278                                               ], order='sequence')
279             if todo_task_ids :
280                 for task in task_pool.browse(cr, uid, todo_task_ids, context=context):
281                     s += task_pool.generate_task(cr, uid, task.id, parent=parent, flag=False, context=context)
282                     if not parent:
283                         parent = task
284                     task_ids.append(task.id)
285             
286             f += s + '\n'
287             # Recursive call till all the next phases scheduled
288             for next_phase in phase.next_phase_ids:
289                 if next_phase.state in ['draft', 'open', 'pending']:
290                     rf, rphase_ids = self.generate_phase(cr, uid, [next_phase.id], f = '', parent=phase, context=context)
291                     f += rf +'\n'
292                     phase_ids += rphase_ids
293                 else:   
294                     continue
295         return f, phase_ids
296
297     def schedule_tasks(self, cr, uid, ids, context=None):
298         """
299         Schedule tasks base on faces lib
300         """
301         if context is None:
302             context = {}
303         if type(ids) in (long, int,):
304             ids = [ids]
305         task_pool = self.pool.get('project.task')
306         resource_pool = self.pool.get('resource.resource')
307         data_pool = self.pool.get('ir.model.data')
308         resource_allocation_pool = self.pool.get('project.resource.allocation')
309
310         for phase in self.browse(cr, uid, ids, context=context):
311             project = phase.project_id
312             calendar_id = project.resource_calendar_id and project.resource_calendar_id.id or False
313             start_date = project.date_start
314             #Creating resources using the member of the Project
315             u_ids = [i.id for i in project.members]
316             resource_objs = resource_pool.generate_resources(cr, uid, u_ids, calendar_id, context=context)
317             start_date = datetime.strftime((datetime.strptime(start_date, "%Y-%m-%d")), "%Y-%m-%d")
318             func_str = ''
319             start = start_date
320             minimum_time_unit = 1
321             # default values
322             working_hours_per_day = 24
323             working_days_per_week = 7
324             working_days_per_month = 30
325             working_days_per_year = 365
326             
327             vacation = []
328             if calendar_id:
329                 working_hours_per_day = 8 #TODO: it should be come from calendars
330                 working_days_per_week = 5
331                 working_days_per_month = 20
332                 working_days_per_year = 200
333                 vacation = tuple(resource_pool.compute_vacation(cr, uid, calendar_id, context=context))
334
335             working_days = resource_pool.compute_working_calendar(cr, uid, calendar_id, context=context)
336             
337             cls_str = ''
338             # Creating Resources for the Project
339             for key, vals in resource_objs.items():
340                 cls_str +='''
341     class Resource_%s(Resource):
342         title = \"%s\"
343         vacation = %s
344         efficiency = %s
345 '''%(key,  vals.get('name',False), vals.get('vacation', False), vals.get('efficiency', False))
346     
347             # Create a new project for each phase
348             func_str += '''
349 def Phase_%d():
350     from resource.faces import Resource
351     title = \"%s\"
352     start = \'%s\'
353     minimum_time_unit = %s
354     working_hours_per_day = %s
355     working_days_per_week = %s
356     working_days_per_month = %s
357     working_days_per_year = %s
358     vacation = %s
359     working_days =  %s
360 '''%(phase.id, phase.name, start, minimum_time_unit, working_hours_per_day,  working_days_per_week, working_days_per_month, working_days_per_year, vacation, working_days )
361             
362             parent = False
363             task_ids = []
364             todo_task_ids = task_pool.search(cr, uid, [('id', 'in', map(lambda x : x.id, phase.task_ids)),
365                                               ('state', 'in', ['draft', 'open', 'pending'])
366                                               ], order='sequence')
367             for task in task_pool.browse(cr, uid, todo_task_ids, context=context):
368                 func_str += task_pool.generate_task(cr, uid, task.id, parent=parent, flag=True, context=context)
369                 if not parent:
370                     parent = task
371                 task_ids.append(task.id)
372             func_str += cls_str
373     
374             # Allocating Memory for the required Project and Pahses and Resources
375             exec(func_str)
376             Phase = eval('Phase_%d' % phase.id)
377             phase = Task.BalancedProject(Phase)
378         
379             for task_id in task_ids:
380                 task = eval("phase.Task_%d" % task_id)
381                 start_date = task.start.to_datetime()
382                 end_date = task.end.to_datetime()
383                 
384                 task_pool.write(cr, uid, [task_id], {
385                                       'date_start': start_date.strftime('%Y-%m-%d'),
386                                       'date_end': end_date.strftime('%Y-%m-%d')
387                                     }, context=context)
388         return True
389 project_phase()
390
391 class project_resource_allocation(osv.osv):
392     _name = 'project.resource.allocation'
393     _description = 'Project Resource Allocation'
394     _rec_name = 'resource_id'
395
396     def get_name(self, cr, uid, ids, field_name, arg, context=None):
397         res = {}
398         for allocation in self.browse(cr, uid, ids, context=context):
399             name = allocation.phase_id.name
400             name += ' (%s%%)' %(allocation.useability)
401             res[allocation.id] = name
402         return res
403     _columns = {
404         'name': fields.function(get_name, method=True, type='char', size=256),
405         'resource_id': fields.many2one('resource.resource', 'Resource', required=True),
406         'phase_id': fields.many2one('project.phase', 'Project Phase', ondelete='cascade', required=True),
407         'project_id': fields.related('phase_id', 'project_id', type='many2one', relation="project.project", string='Project', store=True),
408         'user_id': fields.related('resource_id', 'user_id', type='many2one', relation="res.users", string='User'),
409         'date_start': fields.date('Start Date', help="Starting Date"),
410         'date_end': fields.date('End Date', help="Ending Date"),
411         'useability': fields.float('Availability', help="Availability of this resource for this project phase in percentage (=50%)"),
412     }
413     _defaults = {
414         'useability': 100,
415     }
416
417 project_resource_allocation()
418
419 class project(osv.osv):
420     _inherit = "project.project"
421     _columns = {
422         'phase_ids': fields.one2many('project.phase', 'project_id', "Project Phases"),
423         'resource_calendar_id': fields.many2one('resource.calendar', 'Working Time', help="Timetable working hours to adjust the gantt diagram report", states={'close':[('readonly',True)]} ),
424     }
425     def generate_members(self, cr, uid, ids, context=None):
426         """
427         Return a list of  Resource Class objects for the resources allocated to the phase.
428         """
429         res = {}
430         resource_pool = self.pool.get('resource.resource')
431         for project in self.browse(cr, uid, ids, context=context):
432             user_ids = map(lambda x:x.id, project.members)
433             calendar_id  = project.resource_calendar_id and project.resource_calendar_id.id or False
434             resource_objs = resource_pool.generate_resources(cr, uid, user_ids, calendar_id, context=context)
435             res[project.id] = resource_objs
436         return res
437
438     def schedule_phases(self, cr, uid, ids, context=None):
439         """
440         Schedule phase base on faces lib
441         """
442         if context is None:
443             context = {}
444         if type(ids) in (long, int,):
445             ids = [ids]
446         phase_pool = self.pool.get('project.phase')
447         task_pool = self.pool.get('project.task')        
448         resource_pool = self.pool.get('resource.resource')
449         data_pool = self.pool.get('ir.model.data')
450         resource_allocation_pool = self.pool.get('project.resource.allocation')
451         uom_pool = self.pool.get('product.uom')
452         data_model, day_uom_id = data_pool.get_object_reference(cr, uid, 'product', 'uom_day')
453
454         for project in self.browse(cr, uid, ids, context=context):
455             root_phase_ids = phase_pool.search(cr, uid, [('project_id', '=', project.id),
456                                                   ('state', 'in', ['draft', 'open', 'pending']),
457                                                   ('previous_phase_ids', '=', False)
458                                                   ])
459             calendar_id = project.resource_calendar_id and project.resource_calendar_id.id or False
460             start_date = project.date_start
461             #if start_date:
462             #    start_date = datetime.strftime((datetime.strptime(start_date, "%Y-%m-%d")), "%Y-%m-%d")
463             #Creating resources using the member of the Project
464             u_ids = [i.id for i in project.members]
465             resource_objs = resource_pool.generate_resources(cr, uid, u_ids, calendar_id, context=context)
466             func_str = ''
467             start = start_date
468             minimum_time_unit = 1
469             # default values
470             working_hours_per_day = 24
471             working_days_per_week = 7
472             working_days_per_month = 30
473             working_days_per_year = 365
474             
475             vacation = []
476             if calendar_id:
477                 working_hours_per_day = 8 #TODO: it should be come from calendars
478                 working_days_per_week = 5
479                 working_days_per_month = 20
480                 working_days_per_year = 200
481                 vacation = tuple(resource_pool.compute_vacation(cr, uid, calendar_id, context=context))
482
483             working_days = resource_pool.compute_working_calendar(cr, uid, calendar_id, context=context)
484             
485             cls_str = ''
486             # Creating Resources for the Project
487             for key, vals in resource_objs.items():
488                 cls_str +='''
489     class Resource_%s(Resource):
490         title = \"%s\"
491         vacation = %s
492         efficiency = %s
493 '''%(key,  vals.get('name',False), vals.get('vacation', False), vals.get('efficiency', False))
494         
495             # Create a new project for each phase
496             func_str += '''
497 def Project_%d():
498     from resource.faces import Resource
499     title = \"%s\"
500     start = \'%s\'
501     minimum_time_unit = %s
502     working_hours_per_day = %s
503     working_days_per_week = %s
504     working_days_per_month = %s
505     working_days_per_year = %s
506     vacation = %s
507     working_days =  %s
508 '''%(project.id, project.name, start, minimum_time_unit, working_hours_per_day,  working_days_per_week, working_days_per_month, working_days_per_year, vacation, working_days )
509
510             func_str += cls_str
511             phase_ids = []
512             for root_phase in phase_pool.browse(cr, uid, root_phase_ids, context=context):
513                 phases, child_phase_ids = phase_pool.generate_phase(cr, uid, [root_phase.id], '', context=context)
514                 func_str += phases
515                 phase_ids += child_phase_ids
516         
517             # Allocating Memory for the required Project and Pahses and Resources
518             exec(func_str)
519             Project = eval('Project_%d' % project.id)
520             project = None
521             try:
522                 project = Task.BalancedProject(Project)
523             except :
524                 raise osv.except_osv(_('Error !'),_('Invalid resource allocation, Phase Scheduling is not possible.\nPlease check project member resource.'))
525             for phase_id in phase_ids:
526                 act_phase = phase_pool.browse(cr, uid, phase_id, context=context)
527                 resources = act_phase.resource_ids
528                 phase = eval("project.Phase_%d" % phase_id)
529                 start_date = phase.start.to_datetime()
530                 end_date = phase.end.to_datetime()
531                 
532                 if resources:
533                     for res in resources:
534                         vals = {}
535                         vals.update({'date_start' :  start_date })
536                         vals.update({'date_end' :  end_date})
537                         resource_allocation_pool.write(cr, uid, res.id, vals, context=context)
538                 if act_phase.task_ids:
539                     for task in act_phase.task_ids:
540                         vals = {}
541                         #Getting values of the Tasks
542                         temp = eval("phase.Task_%s"%task.id)
543                         if temp.booked_resource:
544                             res_name = temp.booked_resource[0].title
545                             res_id = resource_pool.search(cr, uid,[('name','=',res_name)], context = context)
546                             if res_id:
547                                 res = resource_pool.browse(cr, uid, res_id[0], context = context)
548                                 vals.update({'user_id' : res.user_id.id})
549                                                
550                         vals.update({'date_start' : temp.start.strftime('%Y-%m-%d %H:%M:%S')})
551                         vals.update({'date_end' : temp.end.strftime('%Y-%m-%d %H:%M:%S')})
552                         task_pool.write(cr, uid, task.id, vals, context=context)
553
554
555                 phase_pool.write(cr, uid, [phase_id], {
556                                       'date_start': start_date.strftime('%Y-%m-%d'),
557                                       'date_end': end_date.strftime('%Y-%m-%d')
558                                     }, context=context)
559         return True            
560
561     #TODO: DO Resource allocation and compute availability
562     def compute_allocation(self, rc, uid, ids, start_date, end_date, context=None):
563         if context ==  None:
564             contex = {}
565         allocation = {}
566         return allocation
567
568     def schedule_tasks(self, cr, uid, ids, context=None):
569         """
570         Schedule task base on faces lib
571         """
572         if context is None:
573             context = {}
574         if type(ids) in (long, int,):
575             ids = [ids]
576         task_pool = self.pool.get('project.task')
577         resource_pool = self.pool.get('resource.resource')
578         data_pool = self.pool.get('ir.model.data')
579         resource_allocation_pool = self.pool.get('project.resource.allocation')
580         uom_pool = self.pool.get('product.uom')
581         data_model, day_uom_id = data_pool.get_object_reference(cr, uid, 'product', 'uom_day')
582
583         for project in self.browse(cr, uid, ids, context=context):
584             calendar_id = project.resource_calendar_id and project.resource_calendar_id.id or False
585             start_date = project.date_start
586             #Creating resources using the member of the Project
587             u_ids = [i.id for i in project.members]
588             resource_objs = resource_pool.generate_resources(cr, uid, u_ids, calendar_id, context=context)
589             start_date = datetime.strftime((datetime.strptime(start_date, "%Y-%m-%d")), "%Y-%m-%d")
590             func_str = ''
591             start = start_date
592             minimum_time_unit = 1
593             # default values
594             working_hours_per_day = 24
595             working_days_per_week = 7
596             working_days_per_month = 30
597             working_days_per_year = 365
598             
599             vacation = []
600             if calendar_id:
601                 working_hours_per_day = 8 #TODO: it should be come from calendars
602                 working_days_per_week = 5
603                 working_days_per_month = 20
604                 working_days_per_year = 200
605                 vacation = tuple(resource_pool.compute_vacation(cr, uid, calendar_id, context=context))
606
607             working_days = resource_pool.compute_working_calendar(cr, uid, calendar_id, context=context)
608             
609             cls_str = ''
610             # Creating Resources for the Project
611             for key, vals in resource_objs.items():
612                 cls_str +='''
613     class Resource_%s(Resource):
614         title = \"%s\"
615         vacation = %s
616         efficiency = %s
617 '''%(key,  vals.get('name',False), vals.get('vacation', False), vals.get('efficiency', False))
618     
619             # Create a new project for each phase
620             func_str += '''
621 def Project_%d():
622     from resource.faces import Resource
623     title = \"%s\"
624     start = \'%s\'
625     minimum_time_unit = %s
626     working_hours_per_day = %s
627     working_days_per_week = %s
628     working_days_per_month = %s
629     working_days_per_year = %s
630     vacation = %s
631     working_days =  %s
632 '''%(project.id, project.name, start, minimum_time_unit, working_hours_per_day,  working_days_per_week, working_days_per_month, working_days_per_year, vacation, working_days )
633             
634             parent = False
635             task_ids = []
636             todo_task_ids = task_pool.search(cr, uid, [('project_id', '=', project.id),
637                                               ('state', 'in', ['draft', 'open', 'pending'])
638                                               ], order='sequence')
639             if todo_task_ids:
640                 for task in task_pool.browse(cr, uid, todo_task_ids, context=context):
641                     func_str += task_pool.generate_task(cr, uid, task.id, parent=parent, flag=True,context=context)
642                     if not parent:
643                         parent = task
644                     task_ids.append(task.id)
645             func_str += cls_str
646
647             # Allocating Memory for the required Project and Pahses and Resources
648             exec(func_str)
649             Project = eval('Project_%d' % project.id)
650             project = Task.BalancedProject(Project)
651             for task_id in task_ids:
652                 task = eval("project.Task_%d" % task_id)
653                 start_date = task.start.to_datetime()
654                 end_date = task.end.to_datetime()
655                 
656                 task_pool.write(cr, uid, [task_id], {
657                                       'date_start': start_date.strftime('%Y-%m-%d'),
658                                       'date_end': end_date.strftime('%Y-%m-%d')
659                                     }, context=context)
660         return True
661
662 project()
663
664 class resource_resource(osv.osv):
665     _inherit = "resource.resource"
666     def search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False):
667         if context is None:
668             context = {}
669         if context.get('project_id',False):
670             project_pool = self.pool.get('project.project')
671             project_rec = project_pool.browse(cr, uid, context['project_id'], context=context)
672             user_ids = [user_id.id for user_id in project_rec.members]
673             args.append(('user_id','in',user_ids))
674         return super(resource_resource, self).search(cr, uid, args, offset, limit, order, context, count)
675
676 resource_resource()
677
678 class project_task(osv.osv):
679     _inherit = "project.task"
680     _columns = {
681         'phase_id': fields.many2one('project.phase', 'Project Phase'),
682     }
683     _defaults = {
684         'user_id' : False
685     }
686
687     def generate_task(self, cr, uid, task_id, parent=False, flag=False, context=None):
688         if context is None:
689             context = {}
690         phase_pool = self.pool.get('project.phase')
691         resource_pool = self.pool.get('resource.resource')
692         resource_allocation_pool = self.pool.get('project.resource.allocation')
693         task = self.browse(cr, uid, task_id, context=context)
694         duration = str(task.planned_hours )+ 'H'
695         str_resource = False
696         if task.phase_id.resource_ids:
697             str_resource = ('%s | '*len(task.phase_id.resource_ids))[:-2]
698             str_resource = str_resource % tuple(map(lambda x: 'Resource_%s'%x.resource_id.id, task.phase_id.resource_ids))
699         # Task Defination for the Phase of the Project
700         if not flag:
701             s = '''
702         def Task_%s():
703             title = \"%s\"
704             effort = \'%s\'
705             resource = %s
706 '''%(task.id, task.name, duration, str_resource)
707             #start = datetime.strftime((datetime.strptime(start, "%Y-%m-%d")), "%Y-%m-%d")
708         else:
709             s = '''
710     def Task_%s():
711         title = \"%s\"
712         effort = \'%s\'
713         resource = %s
714 '''%(task.id, task.name, duration, str_resource)
715         s += '\n'
716         return s
717 project_task()
718 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: