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