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