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