[ADD] analytic_contract_hr_expense: split of features of account_analytic_analysis...
[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_project(osv.osv):
30     _inherit = 'project.project'
31
32     def _to_invoice(self, cr, uid, ids, field_name, arg, context=None):
33         account_analytic_line = self.pool.get("account.analytic.line")
34         res = {}
35         for project in self.browse(cr,uid,ids,context=context):
36             line_ids = account_analytic_line.search(cr, uid, [('account_id', '=', project.analytic_account_id.id), ('to_invoice','=',1), ('invoice_id','=',False)])
37             lines = account_analytic_line.browse(cr, uid, line_ids, context)
38             res[project.id] = {
39                 'amount_to_invoice': sum(line.amount for line in lines),
40                 'time_to_invoice': sum(line.unit_amount for line in lines),
41             }
42         return res
43
44     def _timesheet_count(self, cr, uid, ids, field_name, arg, context=None):
45         account_analytic_line = self.pool.get('account.analytic.line')
46         res = {}
47         for project in self.browse(cr, uid, ids, context):
48             line_ids = account_analytic_line.search(cr, uid, [('account_id', '=', project.analytic_account_id.id)])
49             res[project.id] = len(line_ids)
50         return res
51
52     _columns = {
53         'use_timesheets': fields.boolean('Timesheets', help="Check this field if this project manages timesheets"),
54         'amount_to_invoice': fields.function(_to_invoice, string="Amount to Invoice", multi="sums"),
55         'time_to_invoice': fields.function(_to_invoice, string="Time to Invoice", multi="sums"),
56         'timesheet_count': fields.function(_timesheet_count, type='integer', string="Issue"),
57     }
58     _defaults = {
59         'use_timesheets': True,
60     }
61
62     def onchange_partner_id(self, cr, uid, ids, part=False, context=None):
63         res = super(project_project, self).onchange_partner_id(cr, uid, ids, part, context)
64         if part and res and ('value' in res):
65             # set Invoice Task Work to 100%
66             data_obj = self.pool.get('ir.model.data')
67             data_id = data_obj._get_id(cr, uid, 'hr_timesheet_invoice', 'timesheet_invoice_factor1')
68             if data_id:
69                 factor_id = data_obj.browse(cr, uid, data_id).res_id
70                 res['value'].update({'to_invoice': factor_id})
71         return res
72     
73     def open_timesheets(self, cr, uid, ids, context=None):
74         """ open Timesheets view """
75         project = self.browse(cr, uid, ids[0], context)
76         try:
77             journal_id = self.pool.get('ir.model.data').get_object(cr, uid, 'hr_timesheet', 'analytic_journal').id
78         except ValueError:
79             journal_id = False
80         view_context = {
81             'search_default_account_id': [project.analytic_account_id.id],
82             'default_account_id': project.analytic_account_id.id,
83             'default_journal_id': journal_id,
84         }
85         return {
86             'type': 'ir.actions.act_window',
87             'name': _('Bill Tasks Works'),
88             'res_model': 'account.analytic.line',
89             'view_type': 'form',
90             'view_mode': 'tree,form',
91             'context': view_context,
92             'nodestroy': True,
93         }
94
95 project_project()
96
97 class project_work(osv.osv):
98     _inherit = "project.task.work"
99
100     def get_user_related_details(self, cr, uid, user_id):
101         res = {}
102         emp_obj = self.pool.get('hr.employee')
103         emp_id = emp_obj.search(cr, uid, [('user_id', '=', user_id)])
104         if not emp_id:
105             user_name = self.pool.get('res.users').read(cr, uid, [user_id], ['name'])[0]['name']
106             raise osv.except_osv(_('Bad Configuration !'),
107                  _('No employee defined for user "%s". You must create one.')% (user_name,))
108         emp = self.pool.get('hr.employee').browse(cr, uid, emp_id[0])
109         if not emp.product_id:
110             raise osv.except_osv(_('Bad Configuration !'),
111                  _('No product defined on the related employee.\nFill in the timesheet tab of the employee form.'))
112
113         if not emp.journal_id:
114             raise osv.except_osv(_('Bad Configuration !'),
115                  _('No journal defined on the related employee.\nFill in the timesheet tab of the employee form.'))
116
117         a = emp.product_id.product_tmpl_id.property_account_expense.id
118         if not a:
119             a = emp.product_id.categ_id.property_account_expense_categ.id
120             if not a:
121                 raise osv.except_osv(_('Bad Configuration !'),
122                         _('No product and product category property account defined on the related employee.\nFill in the timesheet tab of the employee form.'))
123         res['product_id'] = emp.product_id.id
124         res['journal_id'] = emp.journal_id.id
125         res['general_account_id'] = a
126         res['product_uom_id'] = emp.product_id.uom_id.id
127         return res
128
129     def create(self, cr, uid, vals, *args, **kwargs):
130         obj_timesheet = self.pool.get('hr.analytic.timesheet')
131         project_obj = self.pool.get('project.project')
132         task_obj = self.pool.get('project.task')
133         uom_obj = self.pool.get('product.uom')
134         
135         vals_line = {}
136         context = kwargs.get('context', {})
137         if not context.get('no_analytic_entry',False):
138             obj_task = task_obj.browse(cr, uid, vals['task_id'])
139             result = self.get_user_related_details(cr, uid, vals.get('user_id', uid))
140             vals_line['name'] = '%s: %s' % (tools.ustr(obj_task.name), tools.ustr(vals['name']) or '/')
141             vals_line['user_id'] = vals['user_id']
142             vals_line['product_id'] = result['product_id']
143             vals_line['date'] = vals['date'][:10]
144             
145             #calculate quantity based on employee's product's uom 
146             vals_line['unit_amount'] = vals['hours']
147
148             default_uom = self.pool.get('res.users').browse(cr, uid, uid).company_id.project_time_mode_id.id
149             if result['product_uom_id'] != default_uom:
150                 vals_line['unit_amount'] = uom_obj._compute_qty(cr, uid, default_uom, vals['hours'], result['product_uom_id'])
151             acc_id = obj_task.project_id and obj_task.project_id.analytic_account_id.id or False
152             if acc_id:
153                 vals_line['account_id'] = acc_id
154                 res = obj_timesheet.on_change_account_id(cr, uid, False, acc_id)
155                 if res.get('value'):
156                     vals_line.update(res['value'])
157                 vals_line['general_account_id'] = result['general_account_id']
158                 vals_line['journal_id'] = result['journal_id']
159                 vals_line['amount'] = 0.0
160                 vals_line['product_uom_id'] = result['product_uom_id']
161                 amount = vals_line['unit_amount']
162                 prod_id = vals_line['product_id']
163                 unit = False
164                 timeline_id = obj_timesheet.create(cr, uid, vals=vals_line, context=context)
165
166                 # Compute based on pricetype
167                 amount_unit = obj_timesheet.on_change_unit_amount(cr, uid, timeline_id,
168                     prod_id, amount, False, unit, vals_line['journal_id'], context=context)
169                 if amount_unit and 'amount' in amount_unit.get('value',{}):
170                     updv = { 'amount': amount_unit['value']['amount'] }
171                     obj_timesheet.write(cr, uid, [timeline_id], updv, context=context)
172                 vals['hr_analytic_timesheet_id'] = timeline_id
173         return super(project_work,self).create(cr, uid, vals, *args, **kwargs)
174
175     def write(self, cr, uid, ids, vals, context=None):
176         if context is None:
177             context = {}
178         timesheet_obj = self.pool.get('hr.analytic.timesheet')
179         project_obj = self.pool.get('project.project')
180         uom_obj = self.pool.get('product.uom')
181         result = {}
182         
183         if isinstance(ids, (long, int)):
184             ids = [ids,]
185
186         for task in self.browse(cr, uid, ids, context=context):
187             line_id = task.hr_analytic_timesheet_id
188             if not line_id:
189                 # if a record is deleted from timesheet, the line_id will become
190                 # null because of the foreign key on-delete=set null
191                 continue
192             vals_line = {}
193             if 'name' in vals:
194                 vals_line['name'] = '%s: %s' % (tools.ustr(task.task_id.name), tools.ustr(vals['name']) or '/')
195             if 'user_id' in vals:
196                 vals_line['user_id'] = vals['user_id']
197                 result = self.get_user_related_details(cr, uid, vals['user_id'])
198                 for fld in ('product_id', 'general_account_id', 'journal_id', 'product_uom_id'):
199                     if result.get(fld, False):
200                         vals_line[fld] = result[fld]
201                         
202             if 'date' in vals:
203                 vals_line['date'] = vals['date'][:10]
204             if 'hours' in vals:
205                 default_uom = self.pool.get('res.users').browse(cr, uid, uid).company_id.project_time_mode_id.id
206                 vals_line['unit_amount'] = vals['hours']
207                 prod_id = vals_line.get('product_id', line_id.product_id.id) # False may be set
208
209                 if result.get('product_uom_id',False) and (not result['product_uom_id'] == default_uom):
210                     vals_line['unit_amount'] = uom_obj._compute_qty(cr, uid, default_uom, vals['hours'], result['product_uom_id'])
211                     
212                 # Compute based on pricetype
213                 amount_unit = timesheet_obj.on_change_unit_amount(cr, uid, line_id.id,
214                     prod_id=prod_id, company_id=False,
215                     unit_amount=vals_line['unit_amount'], unit=False, journal_id=vals_line['journal_id'], context=context)
216
217                 if amount_unit and 'amount' in amount_unit.get('value',{}):
218                     vals_line['amount'] = amount_unit['value']['amount']
219
220             self.pool.get('hr.analytic.timesheet').write(cr, uid, [line_id.id], vals_line, context=context)
221             
222         return super(project_work,self).write(cr, uid, ids, vals, context)
223
224     def unlink(self, cr, uid, ids, *args, **kwargs):
225         hat_obj = self.pool.get('hr.analytic.timesheet')
226         hat_ids = []
227         for task in self.browse(cr, uid, ids):
228             if task.hr_analytic_timesheet_id:
229                 hat_ids.append(task.hr_analytic_timesheet_id.id)
230 #            delete entry from timesheet too while deleting entry to task.
231         if hat_ids:
232             hat_obj.unlink(cr, uid, hat_ids, *args, **kwargs)
233         return super(project_work,self).unlink(cr, uid, ids, *args, **kwargs)
234
235     _columns={
236         'hr_analytic_timesheet_id':fields.many2one('hr.analytic.timesheet','Related Timeline Id', ondelete='set null'),
237     }
238
239 project_work()
240
241 class task(osv.osv):
242     _inherit = "project.task"
243
244     def unlink(self, cr, uid, ids, *args, **kwargs):
245         for task_obj in self.browse(cr, uid, ids, *args, **kwargs):
246             if task_obj.work_ids:
247                 work_ids = [x.id for x in task_obj.work_ids]
248                 self.pool.get('project.task.work').unlink(cr, uid, work_ids, *args, **kwargs)
249
250         return super(task,self).unlink(cr, uid, ids, *args, **kwargs)
251
252     def write(self, cr, uid, ids,vals,context=None):
253         if context is None:
254             context = {}
255         if vals.get('project_id',False) or vals.get('name',False):
256             vals_line = {}
257             hr_anlytic_timesheet = self.pool.get('hr.analytic.timesheet')
258             task_obj_l = self.browse(cr, uid, ids, context=context)
259             if vals.get('project_id',False):
260                 project_obj = self.pool.get('project.project').browse(cr, uid, vals['project_id'], context=context)
261                 acc_id = project_obj.analytic_account_id.id
262
263             for task_obj in task_obj_l:
264                 if len(task_obj.work_ids):
265                     for task_work in task_obj.work_ids:
266                         if not task_work.hr_analytic_timesheet_id:
267                             continue
268                         line_id = task_work.hr_analytic_timesheet_id.id
269                         if vals.get('project_id',False):
270                             vals_line['account_id'] = acc_id
271                         if vals.get('name',False):
272                             vals_line['name'] = '%s: %s' % (tools.ustr(vals['name']), tools.ustr(task_work.name) or '/')
273                         hr_anlytic_timesheet.write(cr, uid, [line_id], vals_line, {})
274         return super(task,self).write(cr, uid, ids, vals, context)
275
276 task()
277
278 class res_partner(osv.osv):
279     _inherit = 'res.partner'
280     def unlink(self, cursor, user, ids, context=None):
281         parnter_id=self.pool.get('project.project').search(cursor, user, [('partner_id', 'in', ids)])
282         if parnter_id:
283             raise osv.except_osv(_('Invalid action !'), _('You cannot delete a partner which is assigned to project, we suggest you to uncheck the active box!'))
284         return super(res_partner,self).unlink(cursor, user, ids,
285                 context=context)
286 res_partner()
287
288 class account_analytic_line(osv.osv):
289    _inherit = "account.analytic.line"
290    def on_change_account_id(self, cr, uid, ids, account_id):
291        res = {}
292        if not account_id:
293            return res
294        res.setdefault('value',{})
295        acc = self.pool.get('account.analytic.account').browse(cr, uid, account_id)
296        st = acc.to_invoice.id
297        res['value']['to_invoice'] = st or False
298        if acc.state == 'close' or acc.state == 'cancelled':
299            raise osv.except_osv(_('Invalid Analytic Account !'), _('You cannot select a Analytic Account which is in Close or Cancelled state'))
300        return res  
301 account_analytic_line()
302 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: