[MERGE] forward port of branch 8.0 up to 591e329
[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 openerp.osv import fields, osv
25 from openerp import tools
26 from openerp.tools.translate import _
27
28 class project_project(osv.osv):
29     _inherit = 'project.project'
30
31     def onchange_partner_id(self, cr, uid, ids, part=False, context=None):
32         res = super(project_project, self).onchange_partner_id(cr, uid, ids, part, context)
33         if part and res and ('value' in res):
34             # set Invoice Task Work to 100%
35             data_obj = self.pool.get('ir.model.data')
36             data_id = data_obj._get_id(cr, uid, 'hr_timesheet_invoice', 'timesheet_invoice_factor1')
37             if data_id:
38                 factor_id = data_obj.browse(cr, uid, data_id).res_id
39                 res['value'].update({'to_invoice': factor_id})
40         return res
41         
42     _defaults = {
43         'invoice_on_timesheets': True,
44     }
45
46     def open_timesheets(self, cr, uid, ids, context=None):
47         """ open Timesheets view """
48         mod_obj = self.pool.get('ir.model.data')
49         act_obj = self.pool.get('ir.actions.act_window')
50
51         project = self.browse(cr, uid, ids[0], context)
52         view_context = {
53             'search_default_account_id': [project.analytic_account_id.id],
54             'default_account_id': project.analytic_account_id.id,
55         }
56         help = _("""<p class="oe_view_nocontent_create">Record your timesheets for the project '%s'.</p>""") % (project.name,)
57         try:
58             if project.to_invoice and project.partner_id:
59                 help+= _("""<p>Timesheets on this project may be invoiced to %s, according to the terms defined in the contract.</p>""" ) % (project.partner_id.name,)
60         except:
61             # if the user do not have access rights on the partner
62             pass
63
64         res = mod_obj.get_object_reference(cr, uid, 'hr_timesheet', 'act_hr_timesheet_line_evry1_all_form')
65         id = res and res[1] or False
66         result = act_obj.read(cr, uid, [id], context=context)[0]
67         result['name'] = _('Timesheets')
68         result['context'] = view_context
69         result['help'] = help
70         return result
71
72
73 class project_work(osv.osv):
74     _inherit = "project.task.work"
75
76     def get_user_related_details(self, cr, uid, user_id):
77         res = {}
78         emp_obj = self.pool.get('hr.employee')
79         emp_id = emp_obj.search(cr, uid, [('user_id', '=', user_id)])
80         if not emp_id:
81             user_name = self.pool.get('res.users').read(cr, uid, [user_id], ['name'])[0]['name']
82             raise osv.except_osv(_('Bad Configuration!'),
83                  _('Please define employee for user "%s". You must create one.')% (user_name,))
84         emp = emp_obj.browse(cr, uid, emp_id[0])
85         if not emp.product_id:
86             raise osv.except_osv(_('Bad Configuration!'),
87                  _('Please define product and product category property account on the related employee.\nFill in the HR Settings tab of the employee form.'))
88
89         if not emp.journal_id:
90             raise osv.except_osv(_('Bad Configuration!'),
91                  _('Please define journal on the related employee.\nFill in the timesheet tab of the employee form.'))
92
93         acc_id = emp.product_id.property_account_expense.id
94         if not acc_id:
95             acc_id = emp.product_id.categ_id.property_account_expense_categ.id
96             if not acc_id:
97                 raise osv.except_osv(_('Bad Configuration!'),
98                         _('Please define product and product category property account on the related employee.\nFill in the timesheet tab of the employee form.'))
99
100         res['product_id'] = emp.product_id.id
101         res['journal_id'] = emp.journal_id.id
102         res['general_account_id'] = acc_id
103         res['product_uom_id'] = emp.product_id.uom_id.id
104         return res
105
106     def _create_analytic_entries(self, cr, uid, vals, context):
107         """Create the hr analytic timesheet from project task work"""
108         timesheet_obj = self.pool['hr.analytic.timesheet']
109         task_obj = self.pool['project.task']
110
111         vals_line = {}
112         timeline_id = False
113         acc_id = False
114
115         task_obj = task_obj.browse(cr, uid, vals['task_id'], context=context)
116         result = self.get_user_related_details(cr, uid, vals.get('user_id', uid))
117         vals_line['name'] = '%s: %s' % (tools.ustr(task_obj.name), tools.ustr(vals['name'] or '/'))
118         vals_line['user_id'] = vals['user_id']
119         vals_line['product_id'] = result['product_id']
120         if vals.get('date'):
121             timestamp = datetime.datetime.strptime(vals['date'], tools.DEFAULT_SERVER_DATETIME_FORMAT)
122             ts = fields.datetime.context_timestamp(cr, uid, timestamp, context)
123             vals_line['date'] = ts.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
124
125         # Calculate quantity based on employee's product's uom
126         vals_line['unit_amount'] = vals['hours']
127
128         default_uom = self.pool['res.users'].browse(cr, uid, uid, context=context).company_id.project_time_mode_id.id
129         if result['product_uom_id'] != default_uom:
130             vals_line['unit_amount'] = self.pool['product.uom']._compute_qty(cr, uid, default_uom, vals['hours'], result['product_uom_id'])
131         acc_id = task_obj.project_id and task_obj.project_id.analytic_account_id.id or acc_id
132         if acc_id:
133             vals_line['account_id'] = acc_id
134             res = timesheet_obj.on_change_account_id(cr, uid, False, acc_id)
135             if res.get('value'):
136                 vals_line.update(res['value'])
137             vals_line['general_account_id'] = result['general_account_id']
138             vals_line['journal_id'] = result['journal_id']
139             vals_line['amount'] = 0.0
140             vals_line['product_uom_id'] = result['product_uom_id']
141             amount = vals_line['unit_amount']
142             prod_id = vals_line['product_id']
143             unit = False
144             timeline_id = timesheet_obj.create(cr, uid, vals=vals_line, context=context)
145
146             # Compute based on pricetype
147             amount_unit = timesheet_obj.on_change_unit_amount(cr, uid, timeline_id,
148                 prod_id, amount, False, unit, vals_line['journal_id'], context=context)
149             if amount_unit and 'amount' in amount_unit.get('value',{}):
150                 updv = { 'amount': amount_unit['value']['amount'] }
151                 timesheet_obj.write(cr, uid, [timeline_id], updv, context=context)
152
153         return timeline_id
154
155     def create(self, cr, uid, vals, *args, **kwargs):
156         context = kwargs.get('context', {})
157         if not context.get('no_analytic_entry',False):
158             vals['hr_analytic_timesheet_id'] = self._create_analytic_entries(cr, uid, vals, context=context)
159         return super(project_work,self).create(cr, uid, vals, *args, **kwargs)
160
161     def write(self, cr, uid, ids, vals, context=None):
162         """
163         When a project task work gets updated, handle its hr analytic timesheet.
164         """
165         if context is None:
166             context = {}
167         timesheet_obj = self.pool.get('hr.analytic.timesheet')
168         uom_obj = self.pool.get('product.uom')
169         result = {}
170
171         if isinstance(ids, (long, int)):
172             ids = [ids]
173
174         for task in self.browse(cr, uid, ids, context=context):
175             line_id = task.hr_analytic_timesheet_id
176             if not line_id:
177                 # if a record is deleted from timesheet, the line_id will become
178                 # null because of the foreign key on-delete=set null
179                 continue
180
181             vals_line = {}
182             if 'name' in vals:
183                 vals_line['name'] = '%s: %s' % (tools.ustr(task.task_id.name), tools.ustr(vals['name'] or '/'))
184             if 'user_id' in vals:
185                 vals_line['user_id'] = vals['user_id']
186             if 'date' in vals:
187                 vals_line['date'] = vals['date'][:10]
188             if 'hours' in vals:
189                 vals_line['unit_amount'] = vals['hours']
190                 prod_id = vals_line.get('product_id', line_id.product_id.id) # False may be set
191
192                 # Put user related details in analytic timesheet values
193                 details = self.get_user_related_details(cr, uid, vals.get('user_id', task.user_id.id))
194                 for field in ('product_id', 'general_account_id', 'journal_id', 'product_uom_id'):
195                     if details.get(field, False):
196                         vals_line[field] = details[field]
197
198                 # Check if user's default UOM differs from product's UOM
199                 user_default_uom_id = self.pool.get('res.users').browse(cr, uid, uid).company_id.project_time_mode_id.id
200                 if details.get('product_uom_id', False) and details['product_uom_id'] != user_default_uom_id:
201                     vals_line['unit_amount'] = uom_obj._compute_qty(cr, uid, user_default_uom_id, vals['hours'], details['product_uom_id'])
202
203                 # Compute based on pricetype
204                 amount_unit = timesheet_obj.on_change_unit_amount(cr, uid, line_id.id,
205                     prod_id=prod_id, company_id=False,
206                     unit_amount=vals_line['unit_amount'], unit=False, journal_id=vals_line['journal_id'], context=context)
207
208                 if amount_unit and 'amount' in amount_unit.get('value',{}):
209                     vals_line['amount'] = amount_unit['value']['amount']
210
211             if vals_line:
212                 self.pool.get('hr.analytic.timesheet').write(cr, uid, [line_id.id], vals_line, context=context)
213
214         return super(project_work,self).write(cr, uid, ids, vals, context)
215
216     def unlink(self, cr, uid, ids, *args, **kwargs):
217         hat_obj = self.pool.get('hr.analytic.timesheet')
218         hat_ids = []
219         for task in self.browse(cr, uid, ids):
220             if task.hr_analytic_timesheet_id:
221                 hat_ids.append(task.hr_analytic_timesheet_id.id)
222         # Delete entry from timesheet too while deleting entry to task.
223         if hat_ids:
224             hat_obj.unlink(cr, uid, hat_ids, *args, **kwargs)
225         return super(project_work,self).unlink(cr, uid, ids, *args, **kwargs)
226
227     _columns={
228         'hr_analytic_timesheet_id':fields.many2one('hr.analytic.timesheet','Related Timeline Id', ondelete='set null'),
229     }
230
231
232 class task(osv.osv):
233     _inherit = "project.task"
234
235     def unlink(self, cr, uid, ids, *args, **kwargs):
236         for task_obj in self.browse(cr, uid, ids, *args, **kwargs):
237             if task_obj.work_ids:
238                 work_ids = [x.id for x in task_obj.work_ids]
239                 self.pool.get('project.task.work').unlink(cr, uid, work_ids, *args, **kwargs)
240
241         return super(task,self).unlink(cr, uid, ids, *args, **kwargs)
242
243     def write(self, cr, uid, ids, vals, context=None):
244         if context is None:
245             context = {}
246         task_work_obj = self.pool['project.task.work']
247         acc_id = False
248         missing_analytic_entries = {}
249
250         if vals.get('project_id',False) or vals.get('name',False):
251             vals_line = {}
252             hr_anlytic_timesheet = self.pool.get('hr.analytic.timesheet')
253             if vals.get('project_id',False):
254                 project_obj = self.pool.get('project.project').browse(cr, uid, vals['project_id'], context=context)
255                 acc_id = project_obj.analytic_account_id.id
256
257             for task_obj in self.browse(cr, uid, ids, context=context):
258                 if len(task_obj.work_ids):
259                     for task_work in task_obj.work_ids:
260                         if not task_work.hr_analytic_timesheet_id:
261                             if acc_id :
262                                 # missing timesheet activities to generate
263                                 missing_analytic_entries[task_work.id] = {
264                                     'name' : task_work.name,
265                                     'user_id' : task_work.user_id.id,
266                                     'date' : task_work.date and task_work.date[:10] or False,
267                                     'account_id': acc_id,
268                                     'hours' : task_work.hours,
269                                     'task_id' : task_obj.id
270                                 }
271                             continue
272                         line_id = task_work.hr_analytic_timesheet_id.id
273                         if vals.get('project_id',False):
274                             vals_line['account_id'] = acc_id
275                         if vals.get('name',False):
276                             vals_line['name'] = '%s: %s' % (tools.ustr(vals['name']), tools.ustr(task_work.name) or '/')
277                         hr_anlytic_timesheet.write(cr, uid, [line_id], vals_line, {})
278
279         res = super(task,self).write(cr, uid, ids, vals, context)
280
281         for task_work_id, analytic_entry in missing_analytic_entries.items():
282             timeline_id = task_work_obj._create_analytic_entries(cr, uid, analytic_entry, context=context)
283             task_work_obj.write(cr, uid, task_work_id, {'hr_analytic_timesheet_id' : timeline_id}, context=context)
284
285         return res
286
287
288 class res_partner(osv.osv):
289     _inherit = 'res.partner'
290
291     def unlink(self, cursor, user, ids, context=None):
292         parnter_id=self.pool.get('project.project').search(cursor, user, [('partner_id', 'in', ids)])
293         if parnter_id:
294             raise osv.except_osv(_('Invalid Action!'), _('You cannot delete a partner which is assigned to project, but you can uncheck the active box.'))
295         return super(res_partner,self).unlink(cursor, user, ids,
296                 context=context)
297
298
299 class account_analytic_line(osv.osv):
300    _inherit = "account.analytic.line"
301
302    def get_product(self, cr, uid, context=None):
303         emp_obj = self.pool.get('hr.employee')
304         emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
305         if emp_ids:
306             employee = emp_obj.browse(cr, uid, emp_ids, context=context)[0]
307             if employee.product_id:return employee.product_id.id
308         return False
309    
310    _defaults = {'product_id': get_product,}
311    
312    def on_change_account_id(self, cr, uid, ids, account_id):
313        res = {}
314        if not account_id:
315            return res
316        res.setdefault('value',{})
317        acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
318        st = acc.to_invoice.id
319        res['value']['to_invoice'] = st or False
320        if acc.state == 'close' or acc.state == 'cancelled':
321            raise osv.except_osv(_('Invalid Analytic Account!'), _('You cannot select a Analytic Account which is in Close or Cancelled state.'))
322        return res
323
324
325 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: