[IMP] Project: Clean code and improvements on project related modules
[odoo/odoo.git] / addons / project_timesheet / project_timesheet.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 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 import time
22 import datetime
23
24 from osv import fields, osv
25 import pooler
26 import tools
27 from tools.translate import _
28
29 class project_work(osv.osv):
30     _inherit = "project.task.work"
31
32     def get_user_related_details(self, cr, uid, user_id):
33         res = {}
34         emp_obj = self.pool.get('hr.employee')
35         emp_id = emp_obj.search(cr, uid, [('user_id', '=', user_id)])
36         if not emp_id:
37             user_name = self.pool.get('res.users').read(cr, uid, [user_id], ['name'])[0]['name']
38             raise osv.except_osv(_('Bad Configuration !'),
39                  _('No employee defined for user "%s". You must create one.')% (user_name,))
40         emp = self.pool.get('hr.employee').browse(cr, uid, emp_id[0])
41         if not emp.product_id:
42             raise osv.except_osv(_('Bad Configuration !'),
43                  _('No product defined on the related employee.\nFill in the timesheet tab of the employee form.'))
44
45         if not emp.journal_id:
46             raise osv.except_osv(_('Bad Configuration !'),
47                  _('No journal defined on the related employee.\nFill in the timesheet tab of the employee form.'))
48
49         a =  emp.product_id.product_tmpl_id.property_account_expense.id
50         if not a:
51             a = emp.product_id.categ_id.property_account_expense_categ.id
52             if not a:
53                 raise osv.except_osv(_('Bad Configuration !'),
54                         _('No product and product category property account defined on the related employee.\nFill in the timesheet tab of the employee form.'))
55         res['product_id'] = emp.product_id.id
56         res['journal_id'] = emp.journal_id.id
57         res['general_account_id'] = a
58         res['product_uom_id'] = emp.product_id.uom_id.id
59         return res
60
61     def create(self, cr, uid, vals, *args, **kwargs):
62         obj_timesheet = self.pool.get('hr.analytic.timesheet')
63         project_obj = self.pool.get('project.project')
64         task_obj = self.pool.get('project.task')
65         uom_obj = self.pool.get('product.uom')
66         
67         vals_line = {}
68         context = kwargs.get('context', {})
69         obj_task = task_obj.browse(cr, uid, vals['task_id'])
70         result = self.get_user_related_details(cr, uid, vals.get('user_id', uid))
71         vals_line['name'] = '%s: %s' % (tools.ustr(obj_task.name), tools.ustr(vals['name']) or '/')
72         vals_line['user_id'] = vals['user_id']
73         vals_line['product_id'] = result['product_id']
74         vals_line['date'] = vals['date'][:10]
75         
76         #calculate quantity based on employee's product's uom 
77         vals_line['unit_amount'] = vals['hours']
78         user_uom, default_uom = project_obj._get_user_and_default_uom_ids(cr, uid)
79         if result['product_uom_id'] != default_uom:
80             vals_line['unit_amount'] = uom_obj._compute_qty(cr, uid, default_uom, vals['hours'], result['product_uom_id'])
81         acc_id = obj_task.project_id.analytic_account_id.id
82         vals_line['account_id'] = acc_id
83         res = obj_timesheet.on_change_account_id(cr, uid, False, acc_id)
84         if res.get('value'):
85             vals_line.update(res['value'])
86         vals_line['general_account_id'] = result['general_account_id']
87         vals_line['journal_id'] = result['journal_id']
88         vals_line['amount'] = 0.0
89         vals_line['product_uom_id'] = result['product_uom_id']
90         amount = vals_line['unit_amount']
91         prod_id = vals_line['product_id']
92         unit = False
93         timeline_id = obj_timesheet.create(cr, uid, vals=vals_line, context=context)
94
95         # Compute based on pricetype
96         amount_unit = obj_timesheet.on_change_unit_amount(cr, uid, timeline_id,
97             prod_id, amount, unit, context=context)
98         if amount_unit and 'amount' in amount_unit.get('value',{}):
99             updv = { 'amount': amount_unit['value']['amount'] }
100             obj_timesheet.write(cr, uid, [timeline_id], updv, context=context)
101         vals['hr_analytic_timesheet_id'] = timeline_id
102         return super(project_work,self).create(cr, uid, vals, *args, **kwargs)
103
104     def write(self, cr, uid, ids, vals, context=None):
105         if context is None:
106             context = {}
107         obj = self.pool.get('hr.analytic.timesheet')
108         timesheet_obj = self.pool.get('hr.analytic.timesheet')
109         project_obj = self.pool.get('project.project')
110         uom_obj = self.pool.get('product.uom')
111         
112         if isinstance(ids, (long, int)):
113             ids = [ids,]
114
115         for task in self.browse(cr, uid, ids, context=context):
116             line_id = task.hr_analytic_timesheet_id
117             if not line_id:
118                 # if a record is deleted from timesheet, the line_id will become
119                 # null because of the foreign key on-delete=set null
120                 continue
121             vals_line = {}
122             if 'name' in vals:
123                 vals_line['name'] = '%s: %s' % (tools.ustr(task.task_id.name), tools.ustr(vals['name']) or '/')
124             if 'user_id' in vals:
125                 vals_line['user_id'] = vals['user_id']
126                 result = self.get_user_related_details(cr, uid, vals['user_id'])
127                 for fld in ('product_id', 'general_account_id', 'journal_id', 'product_uom_id'):
128                     if result.get(fld, False):
129                         vals_line[fld] = result[fld]
130                         
131             if 'date' in vals:
132                 vals_line['date'] = vals['date'][:10]
133             if 'hours' in vals:
134                 user_uom, default_uom = project_obj._get_user_and_default_uom_ids(cr, uid)
135                 vals_line['unit_amount'] = vals['hours']
136                 prod_id = vals_line.get('product_id', line_id.product_id.id) # False may be set
137
138                 if result['product_uom_id'] and (not result['product_uom_id'] == default_uom):
139                     vals_line['unit_amount'] = uom_obj._compute_qty(cr, uid, default_uom, vals['hours'], result['product_uom_id'])
140                     
141                 # Compute based on pricetype
142                 amount_unit = obj.on_change_unit_amount(cr, uid, line_id.id,
143                     prod_id=prod_id,
144                     unit_amount=vals_line['unit_amount'], unit=False, context=context)
145
146                 if amount_unit and 'amount' in amount_unit.get('value',{}):
147                     vals_line['amount'] = amount_unit['value']['amount']
148
149             obj.write(cr, uid, [line_id.id], vals_line, context=context)
150             
151         return super(project_work,self).write(cr, uid, ids, vals, context)
152
153     def unlink(self, cr, uid, ids, *args, **kwargs):
154         hat_obj = self.pool.get('hr.analytic.timesheet')
155         hat_ids = []
156         for task in self.browse(cr, uid, ids):
157             if task.hr_analytic_timesheet_id:
158                 hat_ids.append(task.hr_analytic_timesheet_id.id)
159 #            delete entry from timesheet too while deleting entry to task.
160         if hat_ids:
161             hat_obj.unlink(cr, uid, hat_ids, *args, **kwargs)
162         return super(project_work,self).unlink(cr, uid, ids, *args, **kwargs)
163
164     _columns={
165         'hr_analytic_timesheet_id':fields.many2one('hr.analytic.timesheet','Related Timeline Id', ondelete='set null'),
166     }
167
168 project_work()
169
170 class task(osv.osv):
171     _inherit = "project.task"
172
173     def unlink(self, cr, uid, ids, *args, **kwargs):
174         for task_obj in self.browse(cr, uid, ids, *args, **kwargs):
175             if task_obj.work_ids:
176                 work_ids = [x.id for x in task_obj.work_ids]
177                 self.pool.get('project.task.work').unlink(cr, uid, work_ids, *args, **kwargs)
178
179         return super(task,self).unlink(cr, uid, ids, *args, **kwargs)
180
181     def write(self, cr, uid, ids,vals,context=None):
182         if context is None:
183             context = {}
184         if vals.get('project_id',False) or vals.get('name',False):
185             vals_line = {}
186             hr_anlytic_timesheet = self.pool.get('hr.analytic.timesheet')
187             task_obj_l = self.browse(cr, uid, ids, context)
188             if vals.get('project_id',False):
189                 project_obj = self.pool.get('project.project').browse(cr, uid, vals['project_id'])
190                 acc_id = project_obj.analytic_account_id.id
191
192             for task_obj in task_obj_l:
193                 if len(task_obj.work_ids):
194                     for task_work in task_obj.work_ids:
195                         line_id = task_work.hr_analytic_timesheet_id.id
196                         if vals.get('project_id',False):
197                             vals_line['account_id'] = acc_id
198                         if vals.get('name',False):
199                             vals_line['name'] = '%s: %s' % (tools.ustr(vals['name']), tools.ustr(task_work.name) or '/')
200                         hr_anlytic_timesheet.write(cr, uid, [line_id], vals_line, {})
201         return super(task,self).write(cr, uid, ids, vals, context)
202
203 task()
204
205 class project_project(osv.osv):
206     _inherit = "project.project"
207
208     def name_get(self, cr, user, ids, context=None):
209         if context is None:
210             context = {}
211         result = []
212         if ids and not isinstance(ids, list):
213             ids = [ids]
214         for project in self.browse(cr, user, ids, context):
215             name = "[%s] %s" % (project.analytic_account_id and project.analytic_account_id.code or '?', project.name)
216             result.append((project.id, name))
217         return result
218
219 project_project()
220
221 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: