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