[IMP] sale,purchase,invoice: make `Send by mail` action more robust to template/view...
[odoo/odoo.git] / addons / hr_timesheet / wizard / hr_timesheet_sign_in_out.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
23 from osv import osv, fields
24 from tools.translate import _
25
26 class hr_so_project(osv.osv_memory):
27     _name = 'hr.sign.out.project'
28     _description = 'Sign Out By Project'
29     _columns = {
30         'account_id': fields.many2one('account.analytic.account', 'Project / Analytic Account', domain=[('type','=','normal')]),
31         'info': fields.char('Work Description', size=256, required=True),
32         'date_start': fields.datetime('Starting Date', readonly=True),
33         'date': fields.datetime('Closing Date'),
34         'analytic_amount': fields.float('Minimum Analytic Amount'),
35         'name': fields.char('Employees name', size=32, required=True, readonly=True),
36         'state': fields.related('emp_id', 'state', string='Current state', type='char', required=True, readonly=True),
37         'server_date': fields.datetime('Current Date', required=True, readonly=True),
38         'emp_id': fields.many2one('hr.employee', 'Employee ID')
39                 }
40
41     def _get_empid(self, cr, uid, context=None):
42         emp_obj = self.pool.get('hr.employee')
43         emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
44         if emp_ids:
45             for employee in emp_obj.browse(cr, uid, emp_ids, context=context):
46                 return {'name': employee.name, 'state': employee.state, 'emp_id': emp_ids[0], 'server_date':time.strftime('%Y-%m-%d %H:%M:%S')}
47
48     def _get_empid2(self, cr, uid, context=None):
49         res = self._get_empid(cr, uid, context=context)
50         cr.execute('select name,action from hr_attendance where employee_id=%s order by name desc limit 1', (res['emp_id'],))
51
52         res['server_date'] = time.strftime('%Y-%m-%d %H:%M:%S')
53         date_start = cr.fetchone()
54
55         if date_start:
56             res['date_start'] = date_start[0]
57         return res
58
59     def default_get(self, cr, uid, fields_list, context=None):
60         res = super(hr_so_project, self).default_get(cr, uid, fields_list, context=context)
61         res.update(self._get_empid2(cr, uid, context=context))
62         return res
63
64     def _write(self, cr, uid, data, emp_id, context=None):
65         timesheet_obj = self.pool.get('hr.analytic.timesheet')
66         emp_obj = self.pool.get('hr.employee')
67         if context is None:
68             context = {}
69         hour = (time.mktime(time.strptime(data['date'] or time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) -
70             time.mktime(time.strptime(data['date_start'], '%Y-%m-%d %H:%M:%S'))) / 3600.0
71         minimum = data['analytic_amount']
72         if minimum:
73             hour = round(round((hour + minimum / 2) / minimum) * minimum, 2)
74         res = timesheet_obj.default_get(cr, uid, ['product_id','product_uom_id'], context=context)
75
76         if not res['product_uom_id']:
77             raise osv.except_osv(_('User Error!'), _('Please define cost unit for this employee.'))
78         up = timesheet_obj.on_change_unit_amount(cr, uid, False, res['product_id'], hour,False, res['product_uom_id'])['value']
79
80         res['name'] = data['info']
81         res['account_id'] = data['account_id'].id
82         res['unit_amount'] = hour
83         emp_journal = emp_obj.browse(cr, uid, emp_id, context=context).journal_id
84         res['journal_id'] = emp_journal and emp_journal.id or False
85         res.update(up)
86         up = timesheet_obj.on_change_account_id(cr, uid, [], res['account_id']).get('value', {})
87         res.update(up)
88         return timesheet_obj.create(cr, uid, res, context=context)
89
90     def sign_out_result_end(self, cr, uid, ids, context=None):
91         emp_obj = self.pool.get('hr.employee')
92         for data in self.browse(cr, uid, ids, context=context):
93             emp_id = data.emp_id.id
94             emp_obj.attendance_action_change(cr, uid, [emp_id], {'action':'sign_out', 'action_date':data.date})
95             self._write(cr, uid, data, emp_id, context=context)
96         return {'type': 'ir.actions.act_window_close'}
97
98     def sign_out_result(self, cr, uid, ids, context=None):
99         emp_obj = self.pool.get('hr.employee')
100         for data in self.browse(cr, uid, ids, context=context):
101             emp_id = data.emp_id.id
102             emp_obj.attendance_action_change(cr, uid, [emp_id], {'action':'action', 'action_date':data.date})
103             self._write(cr, uid, data, emp_id, context=context)
104         return {'type': 'ir.actions.act_window_close'}
105
106 hr_so_project()
107
108 class hr_si_project(osv.osv_memory):
109
110     _name = 'hr.sign.in.project'
111     _description = 'Sign In By Project'
112     _columns = {
113         'name': fields.char('Employees name', size=32,  readonly=True),
114         'state': fields.related('emp_id', 'state', string='Current state', type='char', required=True, readonly=True),
115         'date': fields.datetime('Starting Date'),
116         'server_date': fields.datetime('Current Date',  readonly=True),
117         'emp_id': fields.many2one('hr.employee', 'Employee ID')
118                 }
119
120     def view_init(self, cr, uid, fields, context=None):
121         """
122         This function checks for precondition before wizard executes
123         @param self: The object pointer
124         @param cr: the current row, from the database cursor,
125         @param uid: the current user’s ID for security checks,
126         @param fields: List of fields for default value
127         @param context: A standard dictionary for contextual values
128         """
129         emp_obj = self.pool.get('hr.employee')
130         emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
131         if not emp_id:
132             raise osv.except_osv(_('User Error!'), _('Please define employee for your user.'))
133         return False
134
135     def check_state(self, cr, uid, ids, context=None):
136         obj_model = self.pool.get('ir.model.data')
137         emp_id = self.default_get(cr, uid, context)['emp_id']
138         # get the latest action (sign_in or out) for this employee
139         cr.execute('select action from hr_attendance where employee_id=%s and action in (\'sign_in\',\'sign_out\') order by name desc limit 1', (emp_id,))
140         res = (cr.fetchone() or ('sign_out',))[0]
141         in_out = (res == 'sign_out') and 'in' or 'out'
142         #TODO: invert sign_in et sign_out
143         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','view_hr_timesheet_sign_%s' % in_out)], context=context)
144         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
145         return {
146             'name': 'Sign in / Sign out',
147             'view_type': 'form',
148             'view_mode': 'tree,form',
149             'res_model': 'hr.sign.%s.project' % in_out,
150             'views': [(False,'tree'), (resource_id,'form')],
151             'type': 'ir.actions.act_window',
152             'target': 'new'
153         }
154
155     def sign_in_result(self, cr, uid, ids, context=None):
156         emp_obj = self.pool.get('hr.employee')
157         for data in self.browse(cr, uid, ids, context=context):
158             emp_id = data.emp_id.id
159             emp_obj.attendance_action_change(cr, uid, [emp_id], {'action':'sign_in', 'action_date':data.date})
160         return {'type': 'ir.actions.act_window_close'}
161
162     def default_get(self, cr, uid, fields_list, context=None):
163         res = super(hr_si_project, self).default_get(cr, uid, fields_list, context=context)
164         emp_obj = self.pool.get('hr.employee')
165         emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
166         if emp_id:
167             for employee in emp_obj.browse(cr, uid, emp_id, context=context):
168                 res.update({'name': employee.name, 'state': employee.state, 'emp_id': emp_id[0], 'server_date':time.strftime('%Y-%m-%d %H:%M:%S')})
169         return res
170
171 hr_si_project()
172
173 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: