[MERGE] forward port of branch 8.0 up to e883193
[odoo/odoo.git] / addons / hr_timesheet / hr_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
22 import time
23
24 from openerp.osv import fields
25 from openerp.osv import osv
26 from openerp.tools.translate import _
27 import openerp
28
29 class hr_employee(osv.osv):
30     _name = "hr.employee"
31     _inherit = "hr.employee"
32     _columns = {
33         'product_id': fields.many2one('product.product', 'Product', help="If you want to reinvoice working time of employees, link this employee to a service to determinate the cost price of the job."),
34         'journal_id': fields.many2one('account.analytic.journal', 'Analytic Journal'),
35         'uom_id': fields.related('product_id', 'uom_id', type='many2one', relation='product.uom', string='Unit of Measure', store=True, readonly=True)
36     }
37
38     def _getAnalyticJournal(self, cr, uid, context=None):
39         md = self.pool.get('ir.model.data')
40         try:
41             dummy, res_id = md.get_object_reference(cr, uid, 'hr_timesheet', 'analytic_journal')
42             #search on id found in result to check if current user has read access right
43             check_right = self.pool.get('account.analytic.journal').search(cr, uid, [('id', '=', res_id)], context=context)
44             if check_right:
45                 return res_id
46         except ValueError:
47             pass
48         return False
49
50     def _getEmployeeProduct(self, cr, uid, context=None):
51         md = self.pool.get('ir.model.data')
52         try:
53             dummy, res_id = md.get_object_reference(cr, uid, 'product', 'product_product_consultant')
54             #search on id found in result to check if current user has read access right
55             check_right = self.pool.get('product.template').search(cr, uid, [('id', '=', res_id)], context=context)
56             if check_right:
57                 return res_id
58         except ValueError:
59             pass
60         return False
61
62     _defaults = {
63         'journal_id': _getAnalyticJournal,
64         'product_id': _getEmployeeProduct
65     }
66
67
68 class hr_analytic_timesheet(osv.osv):
69     _name = "hr.analytic.timesheet"
70     _table = 'hr_analytic_timesheet'
71     _description = "Timesheet Line"
72     _inherits = {'account.analytic.line': 'line_id'}
73     _order = "id desc"
74     _columns = {
75         'line_id': fields.many2one('account.analytic.line', 'Analytic Line', ondelete='cascade', required=True),
76         'partner_id': fields.related('account_id', 'partner_id', type='many2one', string='Partner', relation='res.partner', store=True),
77     }
78
79     def unlink(self, cr, uid, ids, context=None):
80         toremove = {}
81         for obj in self.browse(cr, uid, ids, context=context):
82             toremove[obj.line_id.id] = True
83         super(hr_analytic_timesheet, self).unlink(cr, uid, ids, context=context)
84         self.pool.get('account.analytic.line').unlink(cr, uid, toremove.keys(), context=context)
85         return True
86
87
88     def on_change_unit_amount(self, cr, uid, id, prod_id, unit_amount, company_id, unit=False, journal_id=False, context=None):
89         res = {'value':{}}
90         if prod_id and unit_amount:
91             # find company
92             company_id = self.pool.get('res.company')._company_default_get(cr, uid, 'account.analytic.line', context=context)
93             r = self.pool.get('account.analytic.line').on_change_unit_amount(cr, uid, id, prod_id, unit_amount, company_id, unit, journal_id, context=context)
94             if r:
95                 res.update(r)
96         # update unit of measurement
97         if prod_id:
98             uom = self.pool.get('product.product').browse(cr, uid, prod_id, context=context)
99             if uom.uom_id:
100                 res['value'].update({'product_uom_id': uom.uom_id.id})
101         else:
102             res['value'].update({'product_uom_id': False})
103         return res
104
105     def _getEmployeeProduct(self, cr, uid, context=None):
106         if context is None:
107             context = {}
108         emp_obj = self.pool.get('hr.employee')
109         emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id') or uid)], context=context)
110         if emp_id:
111             emp = emp_obj.browse(cr, uid, emp_id[0], context=context)
112             if emp.product_id:
113                 return emp.product_id.id
114         return False
115
116     def _getEmployeeUnit(self, cr, uid, context=None):
117         emp_obj = self.pool.get('hr.employee')
118         if context is None:
119             context = {}
120         emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id') or uid)], context=context)
121         if emp_id:
122             emp = emp_obj.browse(cr, uid, emp_id[0], context=context)
123             if emp.product_id:
124                 return emp.product_id.uom_id.id
125         return False
126
127     def _getGeneralAccount(self, cr, uid, context=None):
128         emp_obj = self.pool.get('hr.employee')
129         if context is None:
130             context = {}
131         emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id') or uid)], context=context)
132         if emp_id:
133             emp = emp_obj.browse(cr, uid, emp_id[0], context=context)
134             if bool(emp.product_id):
135                 a = emp.product_id.property_account_expense.id
136                 if not a:
137                     a = emp.product_id.categ_id.property_account_expense_categ.id
138                 if a:
139                     return a
140         return False
141
142     def _getAnalyticJournal(self, cr, uid, context=None):
143         emp_obj = self.pool.get('hr.employee')
144         if context is None:
145             context = {}
146         if context.get('employee_id'):
147             emp_id = [context.get('employee_id')]
148         else:
149             emp_id = emp_obj.search(cr, uid, [('user_id','=',context.get('user_id') or uid)], limit=1, context=context)
150         if not emp_id:
151             model, action_id = self.pool['ir.model.data'].get_object_reference(cr, uid, 'hr', 'open_view_employee_list_my')
152             msg = _("Employee is not created for this user. Please create one from configuration panel.")
153             raise openerp.exceptions.RedirectWarning(msg, action_id, _('Go to the configuration panel'))
154         emp = emp_obj.browse(cr, uid, emp_id[0], context=context)
155         if emp.journal_id:
156             return emp.journal_id.id
157         else :
158             raise osv.except_osv(_('Warning!'), _('No analytic journal defined for \'%s\'.\nYou should assign an analytic journal on the employee form.')%(emp.name))
159
160
161     _defaults = {
162         'product_uom_id': _getEmployeeUnit,
163         'product_id': _getEmployeeProduct,
164         'general_account_id': _getGeneralAccount,
165         'journal_id': _getAnalyticJournal,
166         'date': lambda self, cr, uid, ctx: ctx.get('date', fields.date.context_today(self,cr,uid,context=ctx)),
167         'user_id': lambda obj, cr, uid, ctx: ctx.get('user_id') or uid,
168     }
169     def on_change_account_id(self, cr, uid, ids, account_id, context=None):
170         return {'value':{}}
171
172     def on_change_date(self, cr, uid, ids, date):
173         if ids:
174             new_date = self.read(cr, uid, ids[0], ['date'])['date']
175             if date != new_date:
176                 warning = {'title':_('User Alert!'),'message':_('Changing the date will let this entry appear in the timesheet of the new date.')}
177                 return {'value':{},'warning':warning}
178         return {'value':{}}
179
180     def create(self, cr, uid, vals, context=None):
181         if context is None:
182             context = {}
183         emp_obj = self.pool.get('hr.employee')
184         emp_id = emp_obj.search(cr, uid, [('user_id', '=', context.get('user_id') or uid)], context=context)
185         ename = ''
186         if emp_id:
187             ename = emp_obj.browse(cr, uid, emp_id[0], context=context).name
188         if not vals.get('journal_id',False):
189            raise osv.except_osv(_('Warning!'), _('No \'Analytic Journal\' is defined for employee %s \nDefine an employee for the selected user and assign an \'Analytic Journal\'!')%(ename,))
190         if not vals.get('account_id',False):
191            raise osv.except_osv(_('Warning!'), _('No analytic account is defined on the project.\nPlease set one or we cannot automatically fill the timesheet.'))
192         return super(hr_analytic_timesheet, self).create(cr, uid, vals, context=context)
193
194     def on_change_user_id(self, cr, uid, ids, user_id):
195         if not user_id:
196             return {}
197         context = {'user_id': user_id}
198         return {'value': {
199             'product_id': self. _getEmployeeProduct(cr, uid, context),
200             'product_uom_id': self._getEmployeeUnit(cr, uid, context),
201             'general_account_id': self._getGeneralAccount(cr, uid, context),
202             'journal_id': self._getAnalyticJournal(cr, uid, context),
203         }}
204
205 class account_analytic_account(osv.osv):
206
207     _inherit = 'account.analytic.account'
208     _description = 'Analytic Account'
209     _columns = {
210         'use_timesheets': fields.boolean('Timesheets', help="Check this field if this project manages timesheets", deprecated=True),
211         'invoice_on_timesheets': fields.boolean('Timesheets', help="Check this field if this project manages timesheets"),
212     }
213
214     def on_change_template(self, cr, uid, ids, template_id, date_start=False, context=None):
215         res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, date_start=date_start, context=context)
216         if template_id and 'value' in res:
217             template = self.browse(cr, uid, template_id, context=context)
218             res['value']['invoice_on_timesheets'] = template.invoice_on_timesheets
219         return res
220
221     def onchange_invoice_on_timesheets(self, cr, uid, ids, invoice_on_timesheets, context=None):
222         result = {}
223         if not invoice_on_timesheets:
224             return {'value': {'to_invoice': False}}
225         try:
226             to_invoice = self.pool.get('ir.model.data').xmlid_to_res_id(cr, uid, 'hr_timesheet_invoice.timesheet_invoice_factor1')
227             result['to_invoice'] = to_invoice
228         except ValueError:
229             pass
230         return result
231
232 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: