[MIG] hr_holidays : migration to new api

This commit is contained in:
Ravi Gohil
2016-06-07 16:34:54 +02:00
committed by Jérome Maes
parent 3c1725da8c
commit 46ccb7036f
20 changed files with 868 additions and 772 deletions
+13 -7
View File
@@ -1,9 +1,9 @@
<?xml version="1.0"?>
<openerp>
<odoo>
<data noupdate="1">
<!-- notify all employees of module installation -->
<record model="mail.message" id="module_install_notification">
<record id="module_install_notification" model="mail.message">
<field name="model">mail.channel</field>
<field name="res_id" ref="mail.channel_all_employees"/>
<field name="message_type">notification</field>
@@ -15,28 +15,28 @@
<!-- Casual leave -->
<record model="hr.holidays.status" id="holiday_status_cl">
<record id="holiday_status_cl" model="hr.holidays.status">
<field name="name" eval="'Legal Leaves '+time.strftime('%Y')"/>
<field name="limit" eval="False"/>
<field name="color_name">black</field>
</record>
<!-- Sick leave -->
<record model="hr.holidays.status" id="holiday_status_sl">
<record id="holiday_status_sl" model="hr.holidays.status">
<field name="name">Sick Leaves</field>
<field name="limit" eval="True"/>
<field name="color_name">red</field>
</record>
<!-- Compensatory Days -->
<record model="hr.holidays.status" id="holiday_status_comp">
<record id="holiday_status_comp" model="hr.holidays.status">
<field name="name">Compensatory Days</field>
<field name="limit" eval="False"/>
<field name="color_name">lavender</field>
</record>
<!--Unpaid Leave -->
<record model="hr.holidays.status" id="holiday_status_unpaid">
<record id="holiday_status_unpaid" model="hr.holidays.status">
<field name="name">Unpaid</field>
<field name="limit" eval="True"/>
<field name="color_name">brown</field>
@@ -48,17 +48,20 @@
<field name="res_model">hr.holidays</field>
<field name="description">Request created and waiting confirmation</field>
</record>
<record id="mt_holidays_first_validated" model="mail.message.subtype">
<field name="name">Waiting Second Validation</field>
<field name="res_model">hr.holidays</field>
<field name="default" eval="False"/>
<field name="description">Request validated, waiting second validation</field>
</record>
<record id="mt_holidays_approved" model="mail.message.subtype">
<field name="name">Approved</field>
<field name="res_model">hr.holidays</field>
<field name="description">Request approved</field>
</record>
<record id="mt_holidays_refused" model="mail.message.subtype">
<field name="name">Refused</field>
<field name="res_model">hr.holidays</field>
@@ -75,6 +78,7 @@
<field name="relation_field">department_id</field>
<field name="sequence" eval="6"/>
</record>
<record id="mt_department_holidays_first_validated" model="mail.message.subtype">
<field name="name">Leaves/Allocations First Approval</field>
<field name="res_model">hr.department</field>
@@ -83,6 +87,7 @@
<field name="relation_field">department_id</field>
<field name="sequence" eval="7"/>
</record>
<record id="mt_department_holidays_approved" model="mail.message.subtype">
<field name="name">Leaves/Allocation Approved</field>
<field name="res_model">hr.department</field>
@@ -91,6 +96,7 @@
<field name="relation_field">department_id</field>
<field name="sequence" eval="8"/>
</record>
<record id="mt_department_holidays_refused" model="mail.message.subtype">
<field name="name">Leaves/Allocation Refused</field>
<field name="res_model">hr.department</field>
@@ -101,4 +107,4 @@
</record>
</data>
</openerp>
</odoo>
+7 -7
View File
@@ -1,8 +1,8 @@
<?xml version="1.0"?>
<openerp>
<odoo>
<data noupdate="1">
<record model="hr.holidays" id="hr_holidays_employee1_allocation_cl">
<record id="hr_holidays_employee1_allocation_cl" model="hr.holidays">
<field name="name">Legal Leaves for Peter Parker</field>
<field name="holiday_status_id" ref="holiday_status_cl"/>
<field name="type">add</field>
@@ -10,7 +10,7 @@
<field name="employee_id" ref="hr.employee_fp"/>
</record>
<record model="hr.holidays" id="hr_holidays_employee1_int_tour">
<record id="hr_holidays_employee1_int_tour" model="hr.holidays">
<field name="name">International Tour</field>
<field name="holiday_status_id" ref="holiday_status_comp"/>
<field eval="time.strftime('%Y-%m-26')" name="date_from"/>
@@ -20,7 +20,7 @@
<field name="employee_id" ref="hr.employee_fp"/>
</record>
<record model="hr.holidays" id="hr_holidays_employee1_vc">
<record id="hr_holidays_employee1_vc" model="hr.holidays">
<field name="name">Summer Vacation</field>
<field name="holiday_status_id" ref="holiday_status_unpaid"/>
<field eval="time.strftime('%Y-%m-23')" name="date_from"/>
@@ -34,7 +34,7 @@
<workflow action="validate" model="hr.holidays" ref="hr_holidays_employee1_allocation_cl"/>
<workflow action="validate" model="hr.holidays" ref="hr_holidays_employee1_int_tour"/>
<record model="hr.holidays" id="hr_holidays_employee1_cl">
<record id="hr_holidays_employee1_cl" model="hr.holidays">
<field name="name">Trip with Family</field>
<field name="holiday_status_id" ref="holiday_status_comp"/>
<field eval="time.strftime('%Y-%m-01')" name="date_from"/>
@@ -44,7 +44,7 @@
<field name="employee_id" ref="hr.employee_fp"/>
</record>
<record model="hr.holidays" id="hr_holidays_employee1_sl">
<record id="hr_holidays_employee1_sl" model="hr.holidays">
<field name="name">Doctor Appointment</field>
<field name="holiday_status_id" ref="holiday_status_sl"/>
<field eval="time.strftime('%Y-%m-20')" name="date_from"/>
@@ -58,4 +58,4 @@
<workflow action="validate" model="hr.holidays" ref="hr_holidays_employee1_sl"/>
</data>
</openerp>
</odoo>
@@ -1,5 +1,5 @@
<?xml version="1.0" ?>
<openerp>
<odoo>
<data>
<!-- Workflow definition
@@ -14,13 +14,14 @@
5. refuse -> draft (reset signal) if can_reset
-->
<record model="workflow" id="wkf_holidays">
<record id="wkf_holidays" model="workflow">
<field name="name">hr.wkf.holidays</field>
<field name="osv">hr.holidays</field>
<field name="on_create">True</field>
</record>
<record model="workflow.activity" id="act_draft"> <!-- draft -->
<!-- draft -->
<record id="act_draft" model="workflow.activity">
<field name="wkf_id" ref="wkf_holidays" />
<field name="name">draft</field>
<field name="flow_start" eval="False"/>
@@ -28,7 +29,8 @@
<field name="action">holidays_reset()</field>
</record>
<record model="workflow.activity" id="act_confirm"> <!-- submitted -->
<!-- submitted -->
<record id="act_confirm" model="workflow.activity">
<field name="wkf_id" ref="wkf_holidays" />
<field name="name">confirm</field>
<field name="flow_start" eval="True"/>
@@ -37,14 +39,16 @@
<field name="split_mode">OR</field>
</record>
<record model="workflow.activity" id="act_validate"> <!-- accepted -->
<!-- accepted -->
<record id="act_validate" model="workflow.activity">
<field name="wkf_id" ref="wkf_holidays" />
<field name="name">validate</field>
<field name="kind">function</field>
<field name="action">holidays_validate()</field>
</record>
<record model="workflow.activity" id="act_validate1"> <!-- first_accepted -->
<!-- first_accepted -->
<record id="act_validate1" model="workflow.activity">
<field name="wkf_id" ref="wkf_holidays" />
<field name="name">first_validate</field>
<field name="kind">function</field>
@@ -52,8 +56,9 @@
<field name="split_mode">OR</field>
</record>
<record model="workflow.activity" id="act_refuse"> <!-- refused -->
<field name="wkf_id" ref="wkf_holidays" />
<!-- refused -->
<record id="act_refuse" model="workflow.activity">
<field name="wkf_id" ref="wkf_holidays"/>
<field name="name">refuse</field>
<field name="flow_stop" eval="False"/>
<field name="kind">function</field>
@@ -64,7 +69,8 @@
workflow transition
-->
<record model="workflow.transition" id="holiday_draft2confirm"> <!-- 1. draft->submitted (confirm signal) -->
<!-- 1. draft->submitted (confirm signal) -->
<record id="holiday_draft2confirm" model="workflow.transition">
<field name="act_from" ref="act_draft" />
<field name="act_to" ref="act_confirm" />
<field name="signal">confirm</field>
@@ -72,7 +78,8 @@
<field name="group_id" ref="base.group_user"/>
</record>
<record model="workflow.transition" id="holiday_confirm2draft"> <!-- 2. submitted->draft (reset signal) -->
<!-- 2. submitted->draft (reset signal) -->
<record id="holiday_confirm2draft" model="workflow.transition">
<field name="act_from" ref="act_confirm" />
<field name="act_to" ref="act_draft" />
<field name="signal">reset</field>
@@ -80,7 +87,8 @@
<field name="group_id" ref="base.group_user"/>
</record>
<record model="workflow.transition" id="holiday_confirm2validate"> <!-- 2. submitted->accepted (validate signal) if not double_validation-->
<!-- 2. submitted->accepted (validate signal) if not double_validation -->
<record id="holiday_confirm2validate" model="workflow.transition">
<field name="act_from" ref="act_confirm" />
<field name="act_to" ref="act_validate" />
<field name="signal">validate</field>
@@ -88,7 +96,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_confirm2validate1"> <!-- 2. submitted -> first_accepted (validate signal) if double_validation-->
<!-- 2. submitted -> first_accepted (validate signal) if double_validation -->
<record id="holiday_confirm2validate1" model="workflow.transition">
<field name="act_from" ref="act_confirm" />
<field name="act_to" ref="act_validate1" />
<field name="signal">validate</field>
@@ -96,7 +105,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_confirm2refuse"> <!-- 2. submitted->refused (refuse signal) -->
<!-- 2. submitted->refused (refuse signal) -->
<record id="holiday_confirm2refuse" model="workflow.transition">
<field name="act_from" ref="act_confirm" />
<field name="act_to" ref="act_refuse" />
<field name="signal">refuse</field>
@@ -104,7 +114,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_validate2refuse"> <!-- 3. accepted->refused (refuse signal) -->
<!-- 3. accepted->refused (refuse signal) -->
<record id="holiday_validate2refuse" model="workflow.transition">
<field name="act_from" ref="act_validate" />
<field name="act_to" ref="act_refuse" />
<field name="signal">refuse</field>
@@ -112,7 +123,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_validate2refuse"> <!-- 3. accepted->refused (refuse signal) -->
<!-- 3. accepted->refused (refuse signal) -->
<record id="holiday_validate2refuse" model="workflow.transition">
<field name="act_from" ref="act_validate" />
<field name="act_to" ref="act_refuse" />
<field name="signal">refuse</field>
@@ -120,7 +132,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_validate1_validate"> <!-- 4. first_accepted -> accepted (second_validate signal) -->
<!-- 4. first_accepted -> accepted (second_validate signal) -->
<record id="holiday_validate1_validate" model="workflow.transition">
<field name="act_from" ref="act_validate1" />
<field name="act_to" ref="act_validate" />
<field name="condition">True</field>
@@ -128,7 +141,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_validate1_refuse"> <!-- 4. first_accepted->refused (refuse signal) -->
<!-- 4. first_accepted->refused (refuse signal) -->
<record id="holiday_validate1_refuse" model="workflow.transition">
<field name="act_from" ref="act_validate1" />
<field name="act_to" ref="act_refuse" />
<field name="signal">refuse</field>
@@ -136,7 +150,8 @@
<field name="group_id" ref="base.group_hr_user"/>
</record>
<record model="workflow.transition" id="holiday_refuse2draft"> <!-- 5. refused->draft (reset signal) -->
<!-- 5. refused->draft (reset signal) -->
<record id="holiday_refuse2draft" model="workflow.transition">
<field name="act_from" ref="act_refuse" />
<field name="act_to" ref="act_draft" />
<field name="signal">reset</field>
@@ -145,4 +160,4 @@
</record>
</data>
</openerp>
</odoo>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<odoo>
<data>
<record id="paperformat_hrsummary" model="report.paperformat">
<field name="name">Holidays Summary</field>
@@ -17,4 +17,4 @@
<field name="dpi">90</field>
</record>
</data>
</openerp>
</odoo>
+157 -126
View File
@@ -1,25 +1,32 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
import time
from dateutil.relativedelta import relativedelta
from openerp import api, fields, models
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
import openerp
from openerp.osv import osv
from openerp import SUPERUSER_ID, tools
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class hr_department(models.Model):
class Department(models.Model):
_inherit = 'hr.department'
absence_of_today = fields.Integer(
compute='_compute_leave_count', string='Absence by Today')
leave_to_approve_count = fields.Integer(
compute='_compute_leave_count', string='Leave to Approve')
allocation_to_approve_count = fields.Integer(
compute='_compute_leave_count', string='Allocation to Approve')
total_employee = fields.Integer(
compute='_compute_total_employee', string='Total Employee')
@api.multi
def _compute_leave_count(self):
Holiday = self.env['hr.holidays']
today_date = datetime.datetime.utcnow().date()
today_start = today_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT) # get the midnight of the current utc day
today_end = (today_date + relativedelta(hours=23, minutes=59, seconds=59)).strftime(DEFAULT_SERVER_DATETIME_FORMAT)
today_start = fields.Datetime.to_string(today_date) # get the midnight of the current utc day
today_end = fields.Datetime.to_string(today_date + relativedelta(hours=23, minutes=59, seconds=59))
leave_data = Holiday.read_group(
[('department_id', 'in', self.ids),
@@ -43,7 +50,6 @@ class hr_department(models.Model):
department.allocation_to_approve_count = res_allocation.get(department.id, 0)
department.absence_of_today = res_absence.get(department.id, 0)
@api.multi
def _compute_total_employee(self):
emp_data = self.env['hr.employee'].read_group([('department_id', 'in', self.ids)], ['department_id'], ['department_id'])
@@ -51,135 +57,160 @@ class hr_department(models.Model):
for department in self:
department.total_employee = result.get(department.id, 0)
absence_of_today = fields.Integer(
compute='_compute_leave_count', string='Absence by Today')
leave_to_approve_count = fields.Integer(
compute='_compute_leave_count', string='Leave to Approve')
allocation_to_approve_count = fields.Integer(
compute='_compute_leave_count', string='Allocation to Approve')
total_employee = fields.Integer(
compute='_compute_total_employee', string='Total Employee')
class Employee(models.Model):
class hr_employee(osv.Model):
_inherit = "hr.employee"
def _set_remaining_days(self, cr, uid, empl_id, name, value, arg, context=None):
if value:
employee = self.browse(cr, uid, empl_id, context=context)
diff = value - employee.remaining_leaves
type_obj = self.pool.get('hr.holidays.status')
holiday_obj = self.pool.get('hr.holidays')
# Find for holidays status
status_ids = type_obj.search(cr, uid, [('limit', '=', False)], context=context)
if len(status_ids) != 1 :
raise osv.except_osv(_('Warning!'),_("The feature behind the field 'Remaining Legal Leaves' can only be used when there is only one leave type with the option 'Allow to Override Limit' unchecked. (%s Found). Otherwise, the update is ambiguous as we cannot decide on which leave type the update has to be done. \nYou may prefer to use the classic menus 'Leave Requests' and 'Allocation Requests' located in 'Human Resources \ Leaves' to manage the leave days of the employees if the configuration does not allow to use this field.") % (len(status_ids)))
status_id = status_ids and status_ids[0] or False
if not status_id:
return False
if diff > 0:
leave_id = holiday_obj.create(cr, uid, {'name': _('Allocation for %s') % employee.name, 'employee_id': employee.id, 'holiday_status_id': status_id, 'type': 'add', 'holiday_type': 'employee', 'number_of_days_temp': diff}, context=context)
elif diff < 0:
raise osv.except_osv(_('Warning!'), _('You cannot reduce validated allocation requests'))
else:
return False
for sig in ('confirm', 'validate', 'second_validate'):
holiday_obj.signal_workflow(cr, uid, [leave_id], sig)
return True
return False
remaining_leaves = fields.Float(compute='_compute_remaining_leaves', string='Remaining Legal Leaves', inverse='_inverse_remaining_leaves',
help='Total number of legal leaves allocated to this employee, change this value to create allocation/leave request. '
'Total based on all the leave types without overriding limit.')
current_leave_state = fields.Selection(compute='_compute_leave_status', string="Current Leave Status",
selection=[
('draft', 'New'),
('confirm', 'Waiting Approval'),
('refuse', 'Refused'),
('validate1', 'Waiting Second Approval'),
('validate', 'Approved'),
('cancel', 'Cancelled')
])
current_leave_id = fields.Many2one('hr.holidays.status', compute='_compute_leave_status', string="Current Leave Type")
leave_date_from = fields.Date('From Date', compute='_compute_leave_status')
leave_date_to = fields.Date('To Date', compute='_compute_leave_status')
leaves_count = fields.Integer('Number of Leaves', compute='_compute_leaves_count')
show_leaves = fields.Boolean('Able to see Remaining Leaves', compute='_compute_show_leaves')
is_absent_totay = fields.Boolean('Absent Today', compute='_compute_absent_employee', search='_search_absent_employee')
def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
cr.execute("""SELECT
sum(h.number_of_days) as days,
def _get_remaining_leaves(self):
""" Helper to compute the remaining leaves for the current employees
:returns dict where the key is the employee id, and the value is the remain leaves
"""
self._cr.execute("""
SELECT
sum(h.number_of_days) AS days,
h.employee_id
from
FROM
hr_holidays h
join hr_holidays_status s on (s.id=h.holiday_status_id)
where
h.state='validate' and
s.limit=False and
join hr_holidays_status s ON (s.id=h.holiday_status_id)
WHERE
h.state='validate' AND
s.limit=False AND
h.employee_id in %s
group by h.employee_id""", (tuple(ids),))
res = cr.dictfetchall()
remaining = {}
for r in res:
remaining[r['employee_id']] = r['days']
for employee_id in ids:
if not remaining.get(employee_id):
remaining[employee_id] = 0.0
return remaining
GROUP BY h.employee_id""", (tuple(self.ids),))
return dict((row['employee_id'], row['days']) for row in self._cr.dictfetchall())
def _get_leave_status(self, cr, uid, ids, name, args, context=None):
holidays_obj = self.pool.get('hr.holidays')
#Used SUPERUSER_ID to forcefully get status of other user's leave, to bypass record rule
holidays_id = holidays_obj.search(cr, SUPERUSER_ID,
[('employee_id', 'in', ids), ('date_from','<=',time.strftime('%Y-%m-%d %H:%M:%S')),
('date_to','>=',time.strftime('%Y-%m-%d %H:%M:%S')),('type','=','remove'),('state','not in',('cancel','refuse'))],
context=context)
result = {}
for id in ids:
result[id] = {
'current_leave_state': False,
'current_leave_id': False,
'leave_date_from':False,
'leave_date_to':False,
}
for holiday in self.pool.get('hr.holidays').browse(cr, SUPERUSER_ID, holidays_id, context=context):
result[holiday.employee_id.id]['leave_date_from'] = holiday.date_from
result[holiday.employee_id.id]['leave_date_to'] = holiday.date_to
result[holiday.employee_id.id]['current_leave_state'] = holiday.state
result[holiday.employee_id.id]['current_leave_id'] = holiday.holiday_status_id.id
return result
@api.multi
def _compute_remaining_leaves(self):
remaining = self._get_remaining_leaves()
for employee in self:
employee.remaining_leaves = remaining.get(employee.id, 0.0)
def _leaves_count(self, cr, uid, ids, field_name, arg, context=None):
res = {}
leaves = self.pool['hr.holidays'].read_group(cr, uid, [
('employee_id', 'in', ids),
('holiday_status_id.limit', '=', False), ('state', '=', 'validate')], fields=['number_of_days', 'employee_id'], groupby=['employee_id'])
res.update(dict([(leave['employee_id'][0], leave['number_of_days']) for leave in leaves ]))
return res
@api.multi
def _inverse_remaining_leaves(self):
status_list = self.env['hr.holidays.status'].search([('limit', '=', False)])
# Create leaves (adding remaining leaves) or raise (reducing remaining leaves)
actual_remaining = self._get_remaining_leaves()
for employee in self.filtered(lambda employee: employee.remaining_leaves):
# check the status list. This is done here and not before the loop to avoid raising
# exception on employee creation (since we are in a computed field).
if len(status_list) != 1:
raise UserError(_("The feature behind the field 'Remaining Legal Leaves' can only be used when there is only one "
"leave type with the option 'Allow to Override Limit' unchecked. (%s Found). "
"Otherwise, the update is ambiguous as we cannot decide on which leave type the update has to be done. "
"\n You may prefer to use the classic menus 'Leave Requests' and 'Allocation Requests' located in 'Human Resources > Leaves' "
"to manage the leave days of the employees if the configuration does not allow to use this field.") % (len(status_list)))
status = status_list[0] if status_list else None
if not status:
continue
# if a status is found, then compute remaing leave for current employee
difference = employee.remaining_leaves - actual_remaining.get(employee.id, 0)
if difference > 0:
leave = self.env['hr.holidays'].create({
'name': _('Allocation for %s') % employee.name,
'employee_id': employee.id,
'holiday_status_id': status.id,
'type': 'add',
'holiday_type': 'employee',
'number_of_days_temp': difference
})
for signal in ('confirm', 'validate', 'second_validate'):
leave.signal_workflow(signal)
elif difference < 0:
raise UserError(_('You cannot reduce validated allocation requests'))
def _show_approved_remaining_leave(self, cr, uid, ids, name, args, context=None):
if self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'):
return dict([(employee_id, True) for employee_id in ids])
return dict([(employee.id, True) for employee in self.browse(cr, uid, ids, context=context) if employee.user_id.id == uid])
@api.multi
def _compute_leave_status(self):
# Used SUPERUSER_ID to forcefully get status of other user's leave, to bypass record rule
holidays = self.env['hr.holidays'].sudo().search([
('employee_id', 'in', self.ids),
('date_from', '<=', fields.Datetime.now()),
('date_to', '>=', fields.Datetime.now()),
('type', '=', 'remove'),
('state', 'not in', ('cancel', 'refuse'))
])
leave_data = {}
for holiday in holidays:
leave_data[holiday.employee_id.id] = {}
leave_data[holiday.employee_id.id]['leave_date_from'] = holiday.date_from
leave_data[holiday.employee_id.id]['leave_date_to'] = holiday.date_to
leave_data[holiday.employee_id.id]['current_leave_state'] = holiday.state
leave_data[holiday.employee_id.id]['current_leave_id'] = holiday.holiday_status_id.id
def _absent_employee(self, cr, uid, ids, field_name, arg, context=None):
today_date = datetime.datetime.utcnow().date()
today_start = today_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT) # get the midnight of the current utc day
today_end = (today_date + relativedelta(hours=23, minutes=59, seconds=59)).strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
data = self.pool['hr.holidays'].read_group(cr, uid,
[('employee_id', 'in', ids), ('state', 'not in', ['cancel', 'refuse']),
('date_from', '<=', today_end), ('date_to', '>=', today_start), ('type', '=', 'remove')],
['employee_id'], ['employee_id'], context=context)
result = dict.fromkeys(ids, False)
for d in data:
if d['employee_id_count'] >= 1:
result[d['employee_id'][0]] = True
return result
for employee in self:
employee.leave_date_from = leave_data.get(employee.id, {}).get('leave_date_from')
employee.leave_date_to = leave_data.get(employee.id, {}).get('leave_date_to')
employee.current_leave_state = leave_data.get(employee.id, {}).get('current_leave_state')
employee.current_leave_id = leave_data.get(employee.id, {}).get('current_leave_id')
def _search_absent_employee(self, cr, uid, obj, name, args, context=None):
today_date = datetime.datetime.utcnow().date()
today_start = today_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT) # get the midnight of the current utc day
today_end = (today_date + relativedelta(hours=23, minutes=59, seconds=59)).strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)
holiday_ids = self.pool['hr.holidays'].search_read(cr, uid, [
@api.multi
def _compute_leaves_count(self):
leaves = self.env['hr.holidays'].read_group([
('employee_id', 'in', self.ids),
('holiday_status_id.limit', '=', False),
('state', '=', 'validate')
], fields=['number_of_days', 'employee_id'], groupby=['employee_id'])
mapping = dict([(leave['employee_id'][0], leave['number_of_days']) for leave in leaves])
for employee in self:
employee.leaves_count = mapping.get(employee.id)
@api.multi
def _compute_show_leaves(self):
show_leaves = self.env['res.users'].has_group('base.group_hr_user')
for employee in self:
if show_leaves or employee.user_id == self.env.user:
employee.show_leaves = True
else:
employee.show_leaves = False
@api.multi
def _compute_absent_employee(self):
today_date = datetime.utcnow().date()
today_start = fields.Datetime.to_string(today_date) # get the midnight of the current utc day
today_end = fields.Datetime.to_string(today_date + relativedelta(hours=23, minutes=59, seconds=59))
data = self.env['hr.holidays'].read_group([
('employee_id', 'in', self.ids),
('state', 'not in', ['cancel', 'refuse']),
('date_from', '<=', today_end),
('date_to', '>=', today_start),
('type', '=', 'remove')], ['employee_id'], context=context)
absent_employee_ids = [holiday['employee_id'][0] for holiday in holiday_ids if holiday['employee_id']]
return [('id', 'in', absent_employee_ids)]
('type', '=', 'remove')
], ['employee_id'], ['employee_id'])
result = dict.fromkeys(self.ids, False)
for item in data:
if item['employee_id_count'] >= 1:
result[item['employee_id'][0]] = True
for employee in self:
employee.is_absent_totay = result.get(employee.id)
_columns = {
'remaining_leaves': openerp.osv.fields.function(_get_remaining_days, string='Remaining Legal Leaves', fnct_inv=_set_remaining_days, type="float", help='Total number of legal leaves allocated to this employee, change this value to create allocation/leave request. Total based on all the leave types without overriding limit.'),
'current_leave_state': openerp.osv.fields.function(
_get_leave_status, multi="leave_status", string="Current Leave Status", type="selection",
selection=[('draft', 'New'), ('confirm', 'Waiting Approval'), ('refuse', 'Refused'),
('validate1', 'Waiting Second Approval'), ('validate', 'Approved'), ('cancel', 'Cancelled')]),
'current_leave_id': openerp.osv.fields.function(_get_leave_status, multi="leave_status", string="Current Leave Type", type='many2one', relation='hr.holidays.status'),
'leave_date_from': openerp.osv.fields.function(_get_leave_status, multi='leave_status', type='date', string='From Date'),
'leave_date_to': openerp.osv.fields.function(_get_leave_status, multi='leave_status', type='date', string='To Date'),
'leaves_count': openerp.osv.fields.function(_leaves_count, type='integer', string='Number of Leaves'),
'show_leaves': openerp.osv.fields.function(_show_approved_remaining_leave, type='boolean', string="Able to see Remaining Leaves"),
'is_absent_totay': openerp.osv.fields.function(_absent_employee, fnct_search=_search_absent_employee, type="boolean", string="Absent Today", default=False)
}
@api.multi
def _search_absent_employee(self, operator, value):
today_date = datetime.utcnow().date()
today_start = fields.Datetime.to_string(today_date) # get the midnight of the current utc day
today_end = fields.Datetime.to_string(today_date + relativedelta(hours=23, minutes=59, seconds=59))
holiday_values = self.env['hr.holidays'].search_read([
('state', 'not in', ['cancel', 'refuse']),
('date_from', '<=', today_end),
('date_to', '>=', today_start),
('type', '=', 'remove')
], ['employee_id'])
absent_employee_ids = [holiday['employee_id'][0] for holiday in holiday_values if holiday['employee_id']]
return [('id', 'in', absent_employee_ids)]
+401 -405
View File
@@ -3,38 +3,76 @@
# Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com)
import calendar
import datetime
from datetime import date
import logging
import math
import time
from operator import attrgetter
from datetime import timedelta
from werkzeug import url_encode
from dateutil.relativedelta import relativedelta
from openerp.exceptions import UserError, AccessError
from openerp import tools, SUPERUSER_ID
from openerp.osv import fields, osv
from openerp.tools.translate import _
from odoo import api, fields, models
from odoo.exceptions import UserError, AccessError, ValidationError
from odoo.tools.translate import _
_logger = logging.getLogger(__name__)
class hr_holidays_status(osv.osv):
class HolidaysType(models.Model):
_name = "hr.holidays.status"
_description = "Leave Type"
def get_days(self, cr, uid, ids, employee_id, context=None):
result = dict((id, dict(max_leaves=0, leaves_taken=0, remaining_leaves=0,
virtual_remaining_leaves=0)) for id in ids)
holiday_ids = self.pool['hr.holidays'].search(cr, uid, [('employee_id', '=', employee_id),
('state', 'in', ['confirm', 'validate1', 'validate']),
('holiday_status_id', 'in', ids)
], context=context)
for holiday in self.pool['hr.holidays'].browse(cr, uid, holiday_ids, context=context):
name = fields.Char('Leave Type', required=True, translate=True)
categ_id = fields.Many2one('calendar.event.type', string='Meeting Type',
help='Once a leave is validated, Odoo will create a corresponding meeting of this type in the calendar.')
color_name = fields.Selection([
('red', 'Red'),
('blue', 'Blue'),
('lightgreen', 'Light Green'),
('lightblue', 'Light Blue'),
('lightyellow', 'Light Yellow'),
('magenta', 'Magenta'),
('lightcyan', 'Light Cyan'),
('black', 'Black'),
('lightpink', 'Light Pink'),
('brown', 'Brown'),
('violet', 'Violet'),
('lightcoral', 'Light Coral'),
('lightsalmon', 'Light Salmon'),
('lavender', 'Lavender'),
('wheat', 'Wheat'),
('ivory', 'Ivory')], string='Color in Report', required=True, default='red',
help='This color will be used in the leaves summary located in Reporting > Leaves by Department.')
limit = fields.Boolean('Allow to Override Limit',
help='If you select this check box, the system allows the employees to take more leaves '
'than the available ones for this type and will not take them into account for the '
'"Remaining Legal Leaves" defined on the employee form.')
active = fields.Boolean('Active', default=True,
help="If the active field is set to false, it will allow you to hide the leave type without removing it.")
max_leaves = fields.Float(compute='_compute_leaves', string='Maximum Allowed',
help='This value is given by the sum of all holidays requests with a positive value.')
leaves_taken = fields.Float(compute='_compute_leaves', string='Leaves Already Taken',
help='This value is given by the sum of all holidays requests with a negative value.')
remaining_leaves = fields.Float(compute='_compute_leaves', string='Remaining Leaves',
help='Maximum Leaves Allowed - Leaves Already Taken')
virtual_remaining_leaves = fields.Float(compute='_compute_leaves', string='Virtual Remaining Leaves',
help='Maximum Leaves Allowed - Leaves Already Taken - Leaves Waiting Approval')
double_validation = fields.Boolean(string='Apply Double Validation',
help="When selected, the Allocation/Leave Requests for this type require a second validation to be approved.")
company_id = fields.Many2one('res.company', string='Company')
@api.multi
def get_days(self, employee_id):
# need to use `dict` constructor to create a dict per id
result = dict((id, dict(max_leaves=0, leaves_taken=0, remaining_leaves=0, virtual_remaining_leaves=0)) for id in self.ids)
holidays = self.env['hr.holidays'].search([
('employee_id', '=', employee_id),
('state', 'in', ['confirm', 'validate1', 'validate']),
('holiday_status_id', 'in', self.ids)
])
for holiday in holidays:
status_dict = result[holiday.holiday_status_id.id]
if holiday.type == 'add':
if holiday.state == 'validate':
@@ -51,54 +89,39 @@ class hr_holidays_status(osv.osv):
status_dict['remaining_leaves'] -= holiday.number_of_days_temp
return result
def _user_left_days(self, cr, uid, ids, name, args, context=None):
@api.multi
def _compute_leaves(self):
employee_id = False
if context and 'employee_id' in context:
employee_id = context['employee_id']
if 'employee_id' in self._context:
employee_id = self._context['employee_id']
else:
employee_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
if employee_ids:
employee_id = employee_ids[0]
employee = self.env['hr.employee'].search([('user_id', '=', self.env.user.id)], limit=1)
employee_id = employee.id if employee else False
if employee_id:
res = self.get_days(cr, uid, ids, employee_id, context=context)
else:
res = dict((res_id, {'leaves_taken': 0, 'remaining_leaves': 0, 'max_leaves': 0}) for res_id in ids)
return res
data_days = self.get_days(employee_id)
_columns = {
'name': fields.char('Leave Type', size=64, required=True, translate=True),
'categ_id': fields.many2one('calendar.event.type', 'Meeting Type',
help='Once a leave is validated, Odoo will create a corresponding meeting of this type in the calendar.'),
'color_name': fields.selection([('red', 'Red'),('blue','Blue'), ('lightgreen', 'Light Green'), ('lightblue','Light Blue'), ('lightyellow', 'Light Yellow'), ('magenta', 'Magenta'),('lightcyan', 'Light Cyan'),('black', 'Black'),('lightpink', 'Light Pink'),('brown', 'Brown'),('violet', 'Violet'),('lightcoral', 'Light Coral'),('lightsalmon', 'Light Salmon'),('lavender', 'Lavender'),('wheat', 'Wheat'),('ivory', 'Ivory')],'Color in Report', required=True, help='This color will be used in the leaves summary located in Reporting\Leaves by Department.'),
'limit': fields.boolean('Allow to Override Limit', help='If you select this check box, the system allows the employees to take more leaves than the available ones for this type and will not take them into account for the "Remaining Legal Leaves" defined on the employee form.'),
'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the leave type without removing it."),
'max_leaves': fields.function(_user_left_days, string='Maximum Allowed', help='This value is given by the sum of all holidays requests with a positive value.', multi='user_left_days'),
'leaves_taken': fields.function(_user_left_days, string='Leaves Already Taken', help='This value is given by the sum of all holidays requests with a negative value.', multi='user_left_days'),
'remaining_leaves': fields.function(_user_left_days, string='Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken', multi='user_left_days'),
'virtual_remaining_leaves': fields.function(_user_left_days, string='Virtual Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken - Leaves Waiting Approval', multi='user_left_days'),
'double_validation': fields.boolean('Apply Double Validation', help="When selected, the Allocation/Leave Requests for this type require a second validation to be approved."),
'company_id': fields.many2one('res.company', 'Company'),
}
_defaults = {
'color_name': 'red',
'active': True,
}
for holiday_status in self:
result = data_days.get(holiday_status.id, {})
holiday_status.max_leaves = result.get('max_leaves', 0)
holiday_status.leaves_taken = result.get('leaves_taken', 0)
holiday_status.remaining_leaves = result.get('remaining_leaves', 0)
holiday_status.virtual_remaining_leaves = result.get('virtual_remaining_leaves', 0)
def name_get(self, cr, uid, ids, context=None):
if context is None:
context = {}
if not context.get('employee_id'):
@api.multi
def name_get(self):
if not self._context.get('employee_id'):
# leave counts is based on employee_id, would be inaccurate if not based on correct employee
return super(hr_holidays_status, self).name_get(cr, uid, ids, context=context)
return super(HolidaysType, self).name_get()
res = []
for record in self.browse(cr, uid, ids, context=context):
for record in self:
name = record.name
if not record.limit:
name = name + (' (%g remaining out of %g)' % (record.virtual_remaining_leaves or 0.0, record.max_leaves or 0.0))
res.append((record.id, name))
return res
def _search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
""" Override _search to order the results, according to some employee.
The order is the following
@@ -108,56 +131,104 @@ class hr_holidays_status(osv.osv):
This override is necessary because those fields are not stored and depends
on an employee_id given in context. This sort will be done when there
is an employee_id in context and that no other order has been given
to the method. """
if context is None:
context = {}
ids = super(hr_holidays_status, self)._search(cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count, access_rights_uid=access_rights_uid)
if not count and not order and context.get('employee_id'):
leaves = self.browse(cr, uid, ids, context=context)
to the method.
"""
leave_ids = super(HolidaysType, self)._search(args, offset=offset, limit=limit, order=order, count=count, access_rights_uid=access_rights_uid)
if not count and not order and self._context.get('employee_id'):
leaves = self.browse(leave_ids)
sort_key = lambda l: (not l.limit, l.virtual_remaining_leaves)
return map(int, leaves.sorted(key=sort_key, reverse=True))
return ids
return leave_ids
class hr_holidays(osv.osv):
class Holidays(models.Model):
_name = "hr.holidays"
_description = "Leave"
_order = "type desc, date_from desc"
_inherit = ['mail.thread', 'ir.needaction_mixin']
def _employee_get(self, cr, uid, context=None):
emp_id = context.get('default_employee_id', False)
if emp_id:
return emp_id
ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context)
if ids:
return ids[0]
return False
def _default_employee(self):
return self.env.context.get('default_employee_id') or self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
def _compute_number_of_days(self, cr, uid, ids, name, args, context=None):
result = {}
for hol in self.browse(cr, uid, ids, context=context):
if hol.type=='remove':
result[hol.id] = -hol.number_of_days_temp
name = fields.Char('Description')
state = fields.Selection([
('draft', 'To Submit'),
('cancel', 'Cancelled'),
('confirm', 'To Approve'),
('refuse', 'Refused'),
('validate1', 'Second Approval'),
('validate', 'Approved')
], string='Status', readonly=True, track_visibility='onchange', copy=False, default='confirm',
help="The status is set to 'To Submit', when a holiday request is created.\
\nThe status is 'To Approve', when holiday request is confirmed by user.\
\nThe status is 'Refused', when holiday request is refused by manager.\
\nThe status is 'Approved', when holiday request is approved by manager.")
payslip_status = fields.Boolean('Reported in last payslips',
help='Green this button when the leave has been taken into account in the payslip.')
report_note = fields.Text('HR Comments')
user_id = fields.Many2one('res.users', string='User', related='employee_id.user_id', related_sudo=True, store=True, default=lambda self: self.env.uid, readonly=True)
date_from = fields.Datetime('Start Date', readonly=True, index=True, copy=False,
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
date_to = fields.Datetime('End Date', readonly=True, copy=False,
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
holiday_status_id = fields.Many2one("hr.holidays.status", string="Leave Type", required=True, readonly=True,
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
employee_id = fields.Many2one('hr.employee', string='Employee', index=True, readonly=True,
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, default=_default_employee)
manager_id = fields.Many2one('hr.employee', string='First Approval', readonly=True, copy=False,
help='This area is automatically filled by the user who validate the leave')
notes = fields.Text('Reasons', readonly=True, states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
number_of_days_temp = fields.Float('Allocation', readonly=True, copy=False,
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]})
number_of_days = fields.Float('Number of Days', compute='_compute_number_of_days', store=True)
meeting_id = fields.Many2one('calendar.event', string='Meeting')
type = fields.Selection([
('remove', 'Leave Request'),
('add', 'Allocation Request')
], string='Request Type', required=True, readonly=True, index=True, default='remove',
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]},
help="Choose 'Leave Request' if someone wants to take an off-day. "
"\nChoose 'Allocation Request' if you want to increase the number of leaves available for someone")
parent_id = fields.Many2one('hr.holidays', string='Parent')
linked_request_ids = fields.One2many('hr.holidays', 'parent_id', string='Linked Requests')
department_id = fields.Many2one('hr.department', related='employee_id.department_id', string='Department', readonly=True, store=True)
category_id = fields.Many2one('hr.employee.category', string='Employee Tag', readonly=True,
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]}, help='Category of Employee')
holiday_type = fields.Selection([
('employee', 'By Employee'),
('category', 'By Employee Tag')
], string='Allocation Mode', readonly=True, required=True, default='employee',
states={'draft': [('readonly', False)], 'confirm': [('readonly', False)]},
help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category')
manager_id2 = fields.Many2one('hr.employee', string='Second Approval', readonly=True, copy=False,
help='This area is automaticly filled by the user who validate the leave with second level (If Leave type need second validation)')
double_validation = fields.Boolean('Apply Double Validation', related='holiday_status_id.double_validation')
can_reset = fields.Boolean('Can reset', compute='_compute_can_reset')
@api.multi
@api.depends('number_of_days_temp', 'type')
def _compute_number_of_days(self):
for holiday in self:
if holiday.type == 'remove':
holiday.number_of_days = -holiday.number_of_days_temp
else:
result[hol.id] = hol.number_of_days_temp
return result
holiday.number_of_days = holiday.number_of_days_temp
def _get_can_reset(self, cr, uid, ids, name, arg, context=None):
"""User can reset a leave request if it is its own leave request or if
he is an Hr Manager. """
user = self.pool['res.users'].browse(cr, uid, uid, context=context)
group_hr_manager_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_hr_manager')[1]
if group_hr_manager_id in [g.id for g in user.groups_id]:
return dict.fromkeys(ids, True)
result = dict.fromkeys(ids, False)
for holiday in self.browse(cr, uid, ids, context=context):
if holiday.employee_id and holiday.employee_id.user_id and holiday.employee_id.user_id.id == uid:
result[holiday.id] = True
return result
@api.multi
def _compute_can_reset(self):
""" User can reset a leave request if it is its own leave request
or if he is an Hr Manager.
"""
user = self.env.user
group_hr_manager = self.env.ref('base.group_hr_manager')
for holiday in self:
if group_hr_manager in user.groups_id or holiday.employee_id and holiday.employee_id.user_id == user:
holiday.can_reset = True
def _check_date(self, cr, uid, ids, context=None):
for holiday in self.browse(cr, uid, ids, context=context):
@api.constrains('date_from', 'date_to')
def _check_date(self):
for holiday in self:
domain = [
('date_from', '<=', holiday.date_to),
('date_to', '>=', holiday.date_from),
@@ -165,61 +236,19 @@ class hr_holidays(osv.osv):
('id', '!=', holiday.id),
('state', 'not in', ['cancel', 'refuse']),
]
nholidays = self.search_count(cr, uid, domain, context=context)
nholidays = self.search_count(domain)
if nholidays:
return False
return True
raise ValidationError(_('You can not have 2 leaves that overlaps on same day!'))
_check_holidays = lambda self, cr, uid, ids, context=None: self.check_holidays(cr, uid, ids, context=context)
_columns = {
'name': fields.char('Description', size=64),
'state': fields.selection([('draft', 'To Submit'), ('cancel', 'Cancelled'),('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved')],
'Status', readonly=True, track_visibility='onchange', copy=False,
help='The status is set to \'To Submit\', when a holiday request is created.\
\nThe status is \'To Approve\', when holiday request is confirmed by user.\
\nThe status is \'Refused\', when holiday request is refused by manager.\
\nThe status is \'Approved\', when holiday request is approved by manager.'),
'payslip_status': fields.boolean(string='Reported in last payslips',
help='Green this button when the leave has been taken into account in the payslip.'),
'report_note': fields.text('HR Comments'),
'user_id':fields.related('employee_id', 'user_id', type='many2one', relation='res.users', string='User', store=True),
'date_from': fields.datetime('Start Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, select=True, copy=False),
'date_to': fields.datetime('End Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False),
'holiday_status_id': fields.many2one("hr.holidays.status", "Leave Type", required=True,readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
'employee_id': fields.many2one('hr.employee', "Employee", select=True, invisible=False, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
'manager_id': fields.many2one('hr.employee', 'First Approval', invisible=False, readonly=True, copy=False,
help='This area is automatically filled by the user who validate the leave'),
'notes': fields.text('Reasons',readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
'number_of_days_temp': fields.float('Allocation', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False),
'number_of_days': fields.function(_compute_number_of_days, string='Number of Days', store=True),
'meeting_id': fields.many2one('calendar.event', 'Meeting'),
'type': fields.selection([('remove','Leave Request'),('add','Allocation Request')], 'Request Type', required=True, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help="Choose 'Leave Request' if someone wants to take an off-day. \nChoose 'Allocation Request' if you want to increase the number of leaves available for someone", select=True),
'parent_id': fields.many2one('hr.holidays', 'Parent'),
'linked_request_ids': fields.one2many('hr.holidays', 'parent_id', 'Linked Requests',),
'department_id':fields.related('employee_id', 'department_id', string='Department', type='many2one', relation='hr.department', readonly=True, store=True),
'category_id': fields.many2one('hr.employee.category', "Employee Tag", help='Category of Employee', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}),
'holiday_type': fields.selection([('employee','By Employee'),('category','By Employee Tag')], 'Allocation Mode', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category', required=True),
'manager_id2': fields.many2one('hr.employee', 'Second Approval', readonly=True, copy=False,
help='This area is automaticly filled by the user who validate the leave with second level (If Leave type need second validation)'),
'double_validation': fields.related('holiday_status_id', 'double_validation', type='boolean', relation='hr.holidays.status', string='Apply Double Validation'),
'can_reset': fields.function(
_get_can_reset, string="Can reset",
type='boolean'),
}
_defaults = {
'employee_id': _employee_get,
'state': 'confirm',
'type': 'remove',
'user_id': lambda obj, cr, uid, context: uid,
'holiday_type': 'employee',
'payslip_status': False,
}
_constraints = [
(_check_date, 'You can not have 2 leaves that overlaps on same day!', ['date_from', 'date_to']),
(_check_holidays, 'The number of remaining leaves is not sufficient for this leave type.\n'
'Please verify also the leaves waiting for validation.', ['state', 'number_of_days_temp'])
]
@api.constrains('state', 'number_of_days_temp')
def _check_holidays(self):
for holiday in self:
if holiday.holiday_type != 'employee' or holiday.type != 'remove' or not holiday.employee_id or holiday.holiday_status_id.limit:
continue
leave_days = holiday.holiday_status_id.get_days(holiday.employee_id.id)[holiday.holiday_status_id.id]
if leave_days['remaining_leaves'] < 0 or leave_days['virtual_remaining_leaves'] < 0:
raise ValidationError(_('The number of remaining leaves is not sufficient for this leave type.\n'
'Please verify also the leaves waiting for validation.'))
_sql_constraints = [
('type_value', "CHECK( (holiday_type='employee' AND employee_id IS NOT NULL) or (holiday_type='category' AND category_id IS NOT NULL))",
@@ -228,330 +257,297 @@ class hr_holidays(osv.osv):
('date_check', "CHECK ( number_of_days_temp >= 0 )", "The number of days must be greater than 0."),
]
def name_get(self, cr, uid, ids, context=None):
@api.onchange('holiday_type')
def _onchange_type(self):
if self.holiday_type == 'employee' and not self.employee_id:
self.employee_id = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
elif self.holiday_type != 'employee':
self.employee_id = None
@api.onchange('employee_id')
def _onchange_employee(self):
self.department_id = self.employee_id.department_id
def _get_number_of_days(self, date_from, date_to, employee_id):
""" Returns a float equals to the timedelta between two dates given as string."""
from_dt = fields.Datetime.from_string(date_from)
to_dt = fields.Datetime.from_string(date_to)
if employee_id:
employee = self.env['hr.employee'].browse(employee_id)
resource = self.env['resource.resource'].sudo().search([('user_id', '=', employee.user_id.id)], limit=1)
if resource and resource.calendar_id:
hours = resource.calendar_id.get_working_hours(from_dt, to_dt, resource_id=resource.id, compute_leaves=True)
uom_hour = resource.calendar_id.uom_id
uom_day = self.env.ref('product.product_uom_day')
if uom_hour and uom_day:
return self.env['product.uom']._compute_qty_obj(uom_hour, hours[0], uom_day)
time_delta = to_dt - from_dt
return math.ceil(time_delta.days + float(time_delta.seconds) / 86400)
@api.onchange('date_from')
def _onchange_date_from(self):
""" If there are no date set for date_to, automatically set one 8 hours later than
the date_from. Also update the number_of_days.
"""
date_from = self.date_from
date_to = self.date_to
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
raise UserError(_('The start date must be anterior to the end date.'))
# No date_to set so far: automatically compute one 8 hours later
if date_from and not date_to:
date_to_with_delta = fields.Datetime.from_string(date_from) + timedelta(hours=8)
self.date_to = str(date_to_with_delta)
# Compute and update the number of days
if (date_to and date_from) and (date_from <= date_to):
self.number_of_days_temp = self._get_number_of_days(date_from, date_to, self.employee_id.id)
else:
self.number_of_days_temp = 0
@api.onchange('date_to')
def _onchange_date_to(self):
""" Update the number_of_days. """
date_from = self.date_from
date_to = self.date_to
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
raise UserError(_('The start date must be anterior to the end date.'))
# Compute and update the number of days
if (date_to and date_from) and (date_from <= date_to):
self.number_of_days_temp = self._get_number_of_days(date_from, date_to, self.employee_id.id)
else:
self.number_of_days_temp = 0
####################################################
# ORM Overrides methods
####################################################
@api.multi
def name_get(self):
res = []
for leave in self.browse(cr, uid, ids, context=context):
for leave in self:
res.append((leave.id, _("%s on %s : %.2f day(s)") % (leave.employee_id.name, leave.holiday_status_id.name, leave.number_of_days_temp)))
return res
def _create_resource_leave(self, cr, uid, leaves, context=None):
'''This method will create entry in resource calendar leave object at the time of holidays validated '''
obj_res_leave = self.pool.get('resource.calendar.leaves')
for leave in leaves:
vals = {
def _check_state_access_right(self, vals):
if vals.get('state') and vals['state'] not in ['draft', 'confirm', 'cancel'] and not self.env['res.users'].has_group('base.group_hr_user'):
return False
return True
@api.multi
def add_follower(self, employee_id):
employee = self.env['hr.employee'].browse(employee_id)
if employee.user_id:
self.message_subscribe_users(user_ids=employee.user_id.ids)
@api.model
def create(self, values):
""" Override to avoid automatic logging of creation """
employee_id = values.get('employee_id', False)
if not self._check_state_access_right(values):
raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state'))
holiday = super(Holidays, self.with_context(mail_create_nolog=True, mail_create_nosubscribe=True)).create(values)
holiday.add_follower(employee_id)
return holiday
@api.multi
def write(self, values):
employee_id = values.get('employee_id', False)
if not self._check_state_access_right(values):
raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state'))
result = super(Holidays, self).write(values)
self.add_follower(employee_id)
return result
@api.multi
def unlink(self):
for holiday in self.filtered(lambda holiday: holiday.state not in ['draft', 'cancel', 'confirm']):
raise UserError(_('You cannot delete a leave which is in %s state.') % (holiday.state,))
return super(Holidays, self).unlink()
####################################################
# Business methods
####################################################
@api.multi
def _create_resource_leave(self):
""" This method will create entry in resource calendar leave object at the time of holidays validated """
for leave in self:
self.env['resource.calendar.leaves'].create({
'name': leave.name,
'date_from': leave.date_from,
'holiday_id': leave.id,
'date_to': leave.date_to,
'resource_id': leave.employee_id.resource_id.id,
'calendar_id': leave.employee_id.resource_id.calendar_id.id
}
obj_res_leave.create(cr, uid, vals, context=context)
})
return True
def _remove_resource_leave(self, cr, uid, ids, context=None):
'''This method will create entry in resource calendar leave object at the time of holidays cancel/removed'''
obj_res_leave = self.pool.get('resource.calendar.leaves')
leave_ids = obj_res_leave.search(cr, uid, [('holiday_id', 'in', ids)], context=context)
return obj_res_leave.unlink(cr, uid, leave_ids, context=context)
@api.multi
def _remove_resource_leave(self):
""" This method will create entry in resource calendar leave object at the time of holidays cancel/removed """
return self.env['resource.calendar.leaves'].search([('holiday_id', 'in', self.ids)]).unlink()
def onchange_type(self, cr, uid, ids, holiday_type, employee_id=False, context=None):
result = {}
if holiday_type == 'employee' and not employee_id:
ids_employee = self.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)])
if ids_employee:
result['value'] = {
'employee_id': ids_employee[0]
}
elif holiday_type != 'employee':
result['value'] = {
'employee_id': False
}
return result
def onchange_employee(self, cr, uid, ids, employee_id):
result = {'value': {'department_id': False}}
if employee_id:
employee = self.pool.get('hr.employee').browse(cr, uid, employee_id)
result['value'] = {'department_id': employee.department_id.id}
return result
def _get_number_of_days(self, cr, uid, date_from, date_to, employee_id, context=None):
"""Returns a float equals to the timedelta between two dates given as string."""
resource_obj = self.pool['resource.resource']
employee_obj = self.pool['hr.employee']
model_data_obj = self.pool['ir.model.data']
uom_obj = self.pool['product.uom']
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
from_dt = datetime.datetime.strptime(date_from, DATETIME_FORMAT)
to_dt = datetime.datetime.strptime(date_to, DATETIME_FORMAT)
if employee_id:
employee = employee_obj.browse(cr, uid, [employee_id], context=context)
resource_ids = resource_obj.search(cr, SUPERUSER_ID, [('user_id', '=', employee.user_id.id)], limit=1, context=context)
resource = resource_obj.browse(cr, SUPERUSER_ID, resource_ids, context=context)
if resource and resource.calendar_id:
hours = resource.calendar_id.get_working_hours(from_dt, to_dt, resource_id=resource.id, compute_leaves=True)
uom_hour = resource.calendar_id.uom_id
uom_day = model_data_obj.xmlid_to_object(cr, uid, 'product.product_uom_day')
if uom_hour and uom_day:
return uom_obj._compute_qty_obj(cr, uid, uom_hour, hours[0], uom_day, context=context)
timedelta = to_dt - from_dt
return math.ceil(timedelta.days + float(timedelta.seconds) / 86400)
def unlink(self, cr, uid, ids, context=None):
for rec in self.browse(cr, uid, ids, context=context):
if rec.state not in ['draft', 'cancel', 'confirm']:
raise UserError(_('You cannot delete a leave which is in %s state.') % (rec.state,))
return super(hr_holidays, self).unlink(cr, uid, ids, context)
def onchange_date_from(self, cr, uid, ids, date_to, date_from, employee_id, context=None):
"""
If there are no date set for date_to, automatically set one 8 hours later than
the date_from.
Also update the number_of_days.
"""
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
raise UserError(_('The start date must be anterior to the end date.'))
result = {'value': {}}
# No date_to set so far: automatically compute one 8 hours later
if date_from and not date_to:
date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8)
result['value']['date_to'] = str(date_to_with_delta)
# Compute and update the number of days
if (date_to and date_from) and (date_from <= date_to):
diff_day = self._get_number_of_days(cr, uid, date_from, date_to, employee_id, context=context)
result['value']['number_of_days_temp'] = diff_day
else:
result['value']['number_of_days_temp'] = 0
return result
def onchange_date_to(self, cr, uid, ids, date_to, date_from, employee_id, context=None):
"""
Update the number_of_days.
"""
# date_to has to be greater than date_from
if (date_from and date_to) and (date_from > date_to):
raise UserError(_('The start date must be anterior to the end date.'))
result = {'value': {}}
# Compute and update the number of days
if (date_to and date_from) and (date_from <= date_to):
diff_day = self._get_number_of_days(cr, uid, date_from, date_to, employee_id, context=context)
result['value']['number_of_days_temp'] = diff_day
else:
result['value']['number_of_days_temp'] = 0
return result
def _check_state_access_right(self, cr, uid, vals, context=None):
if vals.get('state') and vals['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'):
return False
return True
def add_follower(self, cr, uid, ids, employee_id, context=None):
employee = self.pool.get('hr.employee').browse(cr, uid, employee_id, context=context)
if employee and employee.user_id:
self.message_subscribe_users(cr, uid, ids, user_ids=[employee.user_id.id], context=context)
def create(self, cr, uid, values, context=None):
""" Override to avoid automatic logging of creation """
if context is None:
context = {}
employee_id = values.get('employee_id', False)
context = dict(context, mail_create_nolog=True, mail_create_nosubscribe=True)
if not self._check_state_access_right(cr, uid, values, context):
raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state'))
hr_holiday_id = super(hr_holidays, self).create(cr, uid, values, context=context)
self.add_follower(cr, uid, [hr_holiday_id], employee_id, context=context)
return hr_holiday_id
def write(self, cr, uid, ids, vals, context=None):
employee_id = vals.get('employee_id', False)
if not self._check_state_access_right(cr, uid, vals, context):
raise AccessError(_('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % vals.get('state'))
hr_holiday_id = super(hr_holidays, self).write(cr, uid, ids, vals, context=context)
self.add_follower(cr, uid, ids, employee_id, context=context)
return hr_holiday_id
def holidays_reset(self, cr, uid, ids, context=None):
self.write(cr, uid, ids, {
@api.multi
def holidays_reset(self):
self.write({
'state': 'draft',
'manager_id': False,
'manager_id2': False,
})
to_unlink = []
for record in self.browse(cr, uid, ids, context=context):
for record2 in record.linked_request_ids:
self.holidays_reset(cr, uid, [record2.id], context=context)
to_unlink.append(record2.id)
if to_unlink:
self.unlink(cr, uid, to_unlink, context=context)
linked_requests = self.mapped('linked_request_ids')
for linked_request in linked_requests:
linked_request.holidays_reset()
linked_requests.unlink()
return True
def holidays_first_validate(self, cr, uid, ids, context=None):
obj_emp = self.pool.get('hr.employee')
ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
manager = ids2 and ids2[0] or False
return self.write(cr, uid, ids, {'state': 'validate1', 'manager_id': manager}, context=context)
@api.multi
def holidays_first_validate(self):
manager = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
return self.write({'state': 'validate1', 'manager_id': manager.id if manager else False})
def holidays_validate(self, cr, uid, ids, context=None):
obj_emp = self.pool.get('hr.employee')
ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
manager = ids2 and ids2[0] or False
self.write(cr, uid, ids, {'state': 'validate'}, context=context)
data_holiday = self.browse(cr, uid, ids)
for record in data_holiday:
if record.double_validation:
self.write(cr, uid, [record.id], {'manager_id2': manager})
@api.multi
def holidays_validate(self):
manager = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
self.write({'state': 'validate'})
for holiday in self:
if holiday.double_validation:
holiday.write({'manager_id2': manager.id})
else:
self.write(cr, uid, [record.id], {'manager_id': manager})
if record.holiday_type == 'employee' and record.type == 'remove':
meeting_obj = self.pool.get('calendar.event')
meeting_vals = {
'name': record.display_name,
'categ_ids': record.holiday_status_id.categ_id and [(6,0,[record.holiday_status_id.categ_id.id])] or [],
'duration': record.number_of_days_temp * 8,
'description': record.notes,
'user_id': record.user_id.id,
'start': record.date_from,
'stop': record.date_to,
holiday.write({'manager_id': manager.id})
if holiday.holiday_type == 'employee' and holiday.type == 'remove':
meeting_values = {
'name': holiday.display_name,
'categ_ids': [(6, 0, [holiday.holiday_status_id.categ_id.id])] if holiday.holiday_status_id.categ_id else [],
'duration': holiday.number_of_days_temp * 8,
'description': holiday.notes,
'user_id': holiday.user_id.id,
'start': holiday.date_from,
'stop': holiday.date_to,
'allday': False,
'state': 'open', # to block that meeting date in the calendar
'class': 'confidential'
}
#Add the partner_id (if exist) as an attendee
if record.user_id and record.user_id.partner_id:
meeting_vals['partner_ids'] = [(4,record.user_id.partner_id.id)]
if holiday.user_id and holiday.user_id.partner_id:
meeting_values['partner_ids'] = [(4, holiday.user_id.partner_id.id)]
ctx_no_email = dict(context or {}, no_email=True)
meeting_id = meeting_obj.create(cr, uid, meeting_vals, context=ctx_no_email)
self._create_resource_leave(cr, uid, [record], context=context)
self.write(cr, uid, ids, {'meeting_id': meeting_id})
elif record.holiday_type == 'category':
emp_ids = record.category_id.employee_ids.ids
leave_ids = []
batch_context = dict(context, mail_notify_force_send=False)
for emp in obj_emp.browse(cr, uid, emp_ids, context=context):
vals = {
'name': record.name,
'type': record.type,
meeting = self.env['calendar.event'].with_context(no_email=True).create(meeting_values)
holiday._create_resource_leave()
holiday.write({'meeting_id': meeting.id})
elif holiday.holiday_type == 'category':
leaves = self.env['hr.holidays']
for employee in holiday.category_id.employee_ids:
values = {
'name': holiday.name,
'type': holiday.type,
'holiday_type': 'employee',
'holiday_status_id': record.holiday_status_id.id,
'date_from': record.date_from,
'date_to': record.date_to,
'notes': record.notes,
'number_of_days_temp': record.number_of_days_temp,
'parent_id': record.id,
'employee_id': emp.id
'holiday_status_id': holiday.holiday_status_id.id,
'date_from': holiday.date_from,
'date_to': holiday.date_to,
'notes': holiday.notes,
'number_of_days_temp': holiday.number_of_days_temp,
'parent_id': holiday.id,
'employee_id': employee.id
}
leave_ids.append(self.create(cr, uid, vals, context=batch_context))
for leave_id in leave_ids:
# TODO is it necessary to interleave the calls?
for sig in ('confirm', 'validate', 'second_validate'):
self.signal_workflow(cr, uid, [leave_id], sig)
leaves += self.with_context(mail_notify_force_send=False).create(values)
# TODO is it necessary to interleave the calls?
for signal in ('confirm', 'validate', 'second_validate'):
leaves.signal_workflow(signal)
return True
def holidays_confirm(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
if record.department_id:
@api.multi
def holidays_confirm(self):
for holiday in self:
if holiday.department_id:
# Subscribe the followers of the department following the `confirmed` subtype
# It's done manually because `message_auto_subscribe` only works on fields for which
# the value is passed to the `create` or `write` methods,
# it doesn't work for related/computed fields
# This can be removed as soon as `department_id` on `hr.holidays` becomes a regular
# fields or as soon as `message_auto_subscribe` works with related/computed fields.
confirmed_subtype = self.pool['ir.model.data'].xmlid_to_object(cr, uid, 'hr_holidays.mt_department_holidays_confirmed', context=context)
self.message_subscribe(cr, uid, [record.id], [
follower.partner_id.id for follower in record.department_id.message_follower_ids
if confirmed_subtype in follower.subtype_ids
], context=context)
return self.write(cr, uid, ids, {'state': 'confirm'})
confirmed_subtype = self.env.ref('hr_holidays.mt_department_holidays_confirmed')
partner_ids = [follower.partner_id.id for follower in holiday.department_id.message_follower_ids if confirmed_subtype in follower.subtype_ids]
holiday.message_subscribe(partner_ids)
return self.write({'state': 'confirm'})
def holidays_refuse(self, cr, uid, ids, context=None):
obj_emp = self.pool.get('hr.employee')
ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)])
manager = ids2 and ids2[0] or False
for holiday in self.browse(cr, uid, ids, context=context):
@api.multi
def holidays_refuse(self):
manager = self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
for holiday in self:
if holiday.state == 'validate1':
self.write(cr, uid, [holiday.id], {'state': 'refuse', 'manager_id': manager})
holiday.write({'state': 'refuse', 'manager_id': manager.id})
else:
self.write(cr, uid, [holiday.id], {'state': 'refuse', 'manager_id2': manager})
self.holidays_cancel(cr, uid, ids, context=context)
holiday.write({'state': 'refuse', 'manager_id2': manager.id})
self.holidays_cancel()
return True
def holidays_cancel(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
@api.multi
def holidays_cancel(self):
for holiday in self:
# Delete the meeting
if record.meeting_id:
record.meeting_id.unlink()
if holiday.meeting_id:
holiday.meeting_id.unlink()
# If a category that created several holidays, cancel all related
self.signal_workflow(cr, uid, map(attrgetter('id'), record.linked_request_ids or []), 'refuse')
self._remove_resource_leave(cr, uid, ids, context=context)
holiday.linked_request_ids.signal_workflow('refuse')
self._remove_resource_leave()
return True
def check_holidays(self, cr, uid, ids, context=None):
for record in self.browse(cr, uid, ids, context=context):
if record.holiday_type != 'employee' or record.type != 'remove' or not record.employee_id or record.holiday_status_id.limit:
continue
leave_days = self.pool.get('hr.holidays.status').get_days(cr, uid, [record.holiday_status_id.id], record.employee_id.id, context=context)[record.holiday_status_id.id]
if leave_days['remaining_leaves'] < 0 or leave_days['virtual_remaining_leaves'] < 0:
return False
return True
@api.multi
def toggle_payslip_status(self):
record_to_set_true = self.search([('id', 'in', self.ids), ('payslip_status', '=', False)])
record_to_set_false = self - record_to_set_true
return record_to_set_true.write({'payslip_status': True}) and record_to_set_false.write({'payslip_status': False})
def toggle_payslip_status(self, cr, uid, ids, context=None):
ids_to_set_true = self.search(cr, uid, [('id', 'in', ids), ('payslip_status', '=', False)], context=context)
ids_to_set_false = list(set(ids) - set(ids_to_set_true))
return self.write(cr, uid, ids_to_set_true, {'payslip_status': True}, context=context) and self.write(cr, uid, ids_to_set_false, {'payslip_status': False}, context=context)
def _track_subtype(self, cr, uid, ids, init_values, context=None):
record = self.browse(cr, uid, ids[0], context=context)
if 'state' in init_values and record.state == 'validate':
####################################################
# Messaging methods
####################################################
@api.multi
def _track_subtype(self, init_values):
if 'state' in init_values and self.state == 'validate':
return 'hr_holidays.mt_holidays_approved'
elif 'state' in init_values and record.state == 'validate1':
elif 'state' in init_values and self.state == 'validate1':
return 'hr_holidays.mt_holidays_first_validated'
elif 'state' in init_values and record.state == 'confirm':
elif 'state' in init_values and self.state == 'confirm':
return 'hr_holidays.mt_holidays_confirmed'
elif 'state' in init_values and record.state == 'refuse':
elif 'state' in init_values and self.state == 'refuse':
return 'hr_holidays.mt_holidays_refused'
return super(hr_holidays, self)._track_subtype(cr, uid, ids, init_values, context=context)
return super(Holidays, self)._track_subtype(init_values)
def _notification_group_recipients(self, cr, uid, ids, message, recipients, done_ids, group_data, context=None):
def _notification_group_recipients(self, message, recipients, done_ids, group_data):
""" Override the mail.thread method to handle HR users and officers
recipients. Indeed those will have specific action in their notification
emails. """
group_hr_user = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'base.group_hr_user')
recipients. Indeed those will have specific action in their notification
emails.
"""
group_hr_user = self.env.ref('base.group_hr_user')
for recipient in recipients:
if recipient.id in done_ids:
continue
if recipient.user_ids and group_hr_user in recipient.user_ids[0].groups_id.ids:
group_data['group_hr_user'] |= recipient
done_ids.add(recipient.id)
return super(hr_holidays, self)._notification_group_recipients(cr, uid, ids, message, recipients, done_ids, group_data, context=context)
return super(Holidays, self)._notification_group_recipients(message, recipients, done_ids, group_data)
def _notification_get_recipient_groups(self, cr, uid, ids, message, recipients, context=None):
res = super(hr_holidays, self)._notification_get_recipient_groups(cr, uid, ids, message, recipients, context=context)
@api.multi
def _notification_get_recipient_groups(self, message, recipients):
result = super(Holidays, self)._notification_get_recipient_groups(message, recipients)
app_action = '/mail/workflow?%s' % url_encode({'model': self._name, 'res_id': ids[0], 'signal': 'validate'})
ref_action = '/mail/workflow?%s' % url_encode({'model': self._name, 'res_id': ids[0], 'signal': 'refuse'})
app_action = '/mail/workflow?%s' % url_encode({'model': self._name, 'res_id': self.id, 'signal': 'validate'})
ref_action = '/mail/workflow?%s' % url_encode({'model': self._name, 'res_id': self.id, 'signal': 'refuse'})
holiday = self.browse(cr, uid, ids[0], context=context)
actions = []
if holiday.state == 'confirm':
if self.state == 'confirm':
actions.append({'url': app_action, 'title': 'Approve'})
if holiday.state in ['confirm', 'validate', 'validate1']:
if self.state in ['confirm', 'validate', 'validate1']:
actions.append({'url': ref_action, 'title': 'Refuse'})
res['group_hr_user'] = {
result['group_hr_user'] = {
'actions': actions
}
return res
return result
+14 -18
View File
@@ -1,29 +1,25 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import openerp
from openerp.osv import osv, fields
from odoo import api, fields, models
class resource_calendar(osv.osv):
class Calendar(models.Model):
_inherit = "resource.calendar"
_columns = {
'uom_id': fields.many2one("product.uom", "Hours per Day", required=True,
help="""Average hours of work per day.
It is used in an employee leave request to compute the number of days consumed based on the resource calendar.
It can be used to handle various contract types, e.g.:
- 38 Hours/Week, 5 Days/Week: 1 Day = 7.6 Hours
- 45 Hours/Week, 5 Days/Week: 1 Day = 9.0 Hours"""),
}
_defaults = {
'uom_id': lambda self, cr, uid, c: self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'product.product_uom_hour')
}
uom_id = fields.Many2one("product.uom", string="Hours per Day", required=True,
default=lambda self: self.env.ref('product.product_uom_hour'),
help="""Average hours of work per day.
It is used in an employee leave request to compute the number of days consumed based on the resource calendar.
It can be used to handle various contract types, e.g.:
- 38 Hours/Week, 5 Days/Week: 1 Day = 7.6 Hours
- 45 Hours/Week, 5 Days/Week: 1 Day = 9.0 Hours""")
class resource_calendar_leaves(osv.osv):
class CalendarLeaves(models.Model):
_inherit = "resource.calendar.leaves"
_description = "Leave Detail"
_columns = {
'holiday_id': fields.many2one("hr.holidays", "Leave Request"),
}
holiday_id = fields.Many2one("hr.holidays", string='Leave Request')
@@ -1,25 +1,25 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime, timedelta
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT
from odoo import api, fields, models
class HrHolidaySummaryReport(osv.AbstractModel):
class HrHolidaySummaryReport(models.AbstractModel):
_name = 'report.hr_holidays.report_holidayssummary'
def _get_header_info(self, start_date, holiday_type):
st_date = fields.Date.from_string(start_date)
return {
'start_date': datetime.strptime(start_date, DEFAULT_SERVER_DATE_FORMAT).strftime('%Y-%m-%d'),
'end_date': (datetime.strptime(start_date, DEFAULT_SERVER_DATE_FORMAT) + relativedelta(days=59)).strftime('%Y-%m-%d'),
'start_date': fields.Date.to_string(st_date),
'end_date': fields.Date.to_string(st_date + relativedelta(days=59)),
'holiday_type': 'Confirmed and Approved' if holiday_type == 'both' else holiday_type
}
def _get_day(self, start_date):
res = []
start_date = datetime.strptime(start_date, DEFAULT_SERVER_DATE_FORMAT)
start_date = fields.Date.from_string(start_date)
for x in range(0, 60):
color = '#ababab' if start_date.strftime('%a') == 'Sat' or start_date.strftime('%a') == 'Sun' else ''
res.append({'day_str': start_date.strftime('%a'), 'day': start_date.day , 'color': color})
@@ -29,7 +29,7 @@ class HrHolidaySummaryReport(osv.AbstractModel):
def _get_months(self, start_date):
# it works for geting month name between two dates.
res = []
start_date = datetime.strptime(start_date, DEFAULT_SERVER_DATE_FORMAT)
start_date = fields.Date.from_string(start_date)
end_date = start_date + relativedelta(days=59)
while start_date <= end_date:
last_date = start_date + relativedelta(day=1, months=+1, days=-1)
@@ -40,10 +40,10 @@ class HrHolidaySummaryReport(osv.AbstractModel):
start_date += relativedelta(day=1, months=+1)
return res
def _get_leaves_summary(self, cr, uid, ids, start_date, empid, holiday_type, context=None):
def _get_leaves_summary(self, start_date, empid, holiday_type):
res = []
count = 0
start_date = datetime.strptime(start_date, DEFAULT_SERVER_DATE_FORMAT)
start_date = fields.Date.from_string(start_date)
end_date = start_date + relativedelta(days=59)
for index in range(0, 60):
current = start_date + timedelta(index)
@@ -51,12 +51,15 @@ class HrHolidaySummaryReport(osv.AbstractModel):
if current.strftime('%a') == 'Sat' or current.strftime('%a') == 'Sun':
res[index]['color'] = '#ababab'
# count and get leave summary details.
holidays_obj = self.pool['hr.holidays']
holiday_type = ['confirm','validate'] if holiday_type == 'both' else ['confirm'] if holiday_type == 'Confirmed' else ['validate']
holidays_ids = holidays_obj.search(cr, uid, [('employee_id', '=', empid), ('state', 'in', holiday_type), ('type', '=', 'remove'), ('date_from', '<=', str(end_date)), ('date_to', '>=', str(start_date))], context=context)
for holiday in holidays_obj.browse(cr, uid, holidays_ids, context=context):
date_from = datetime.strptime(holiday.date_from, DEFAULT_SERVER_DATETIME_FORMAT)
date_to = datetime.strptime(holiday.date_to, DEFAULT_SERVER_DATETIME_FORMAT)
holidays = self.env['hr.holidays'].search([
('employee_id', '=', empid), ('state', 'in', holiday_type),
('type', '=', 'remove'), ('date_from', '<=', str(end_date)),
('date_to', '>=', str(start_date))
])
for holiday in holidays:
date_from = fields.Date.from_string(holiday.date_from)
date_to = fields.Date.from_string(holiday.date_to)
for index in range(0, ((date_to - date_from).days + 1)):
if date_from >= start_date and date_from <= end_date:
res[(date_from-start_date).days]['color'] = holiday.holiday_status_id.color_name
@@ -65,53 +68,47 @@ class HrHolidaySummaryReport(osv.AbstractModel):
self.sum = count
return res
def _get_data_from_report(self, cr, uid, ids, data, context=None):
def _get_data_from_report(self, data):
res = []
emp_obj = self.pool['hr.employee']
department_obj = self.pool['hr.department']
Employee = self.env['hr.employee']
if 'depts' in data:
for department in department_obj.browse(cr, uid, data['depts'], context=context):
for department in self.env['hr.department'].browse(data['depts']):
res.append({'dept' : department.name, 'data': [], 'color': self._get_day(data['date_from'])})
employee_ids = emp_obj.search(cr, uid, [('department_id', '=', department.id)], context=context)
employees = emp_obj.browse(cr, uid, employee_ids, context=context)
for emp in employees:
for emp in Employee.search([('department_id', '=', department.id)]):
res[len(res)-1]['data'].append({
'emp': emp.name,
'display': self._get_leaves_summary(cr, uid, ids, data['date_from'], emp.id, data['holiday_type'], context=context),
'display': self._get_leaves_summary(data['date_from'], emp.id, data['holiday_type']),
'sum': self.sum
})
elif 'emp' in data:
employees = emp_obj.browse(cr, uid, data['emp'], context=context)
res.append({'data':[]})
for emp in employees:
for emp in Employee.browse(data['emp']):
res[0]['data'].append({
'emp': emp.name,
'display': self._get_leaves_summary(cr, uid, ids, data['date_from'], emp.id, data['holiday_type'], context=context),
'display': self._get_leaves_summary(data['date_from'], emp.id, data['holiday_type']),
'sum': self.sum
})
return res
def _get_holidays_status(self, cr, uid, ids, context=None):
def _get_holidays_status(self):
res = []
holiday_obj = self.pool['hr.holidays.status']
holiday_ids = holiday_obj.search(cr, uid, [], context=context)
holiday_datas = holiday_obj.browse(cr, uid, holiday_ids, context=context)
for holiday in holiday_datas:
for holiday in self.env['hr.holidays.status'].search([]):
res.append({'color': holiday.color_name, 'name': holiday.name})
return res
def render_html(self, cr, uid, ids, data=None, context=None):
report_obj = self.pool['report']
holidays_report = report_obj._get_report_from_name(cr, uid, 'hr_holidays.report_holidayssummary')
selected_records = self.pool['hr.holidays'].browse(cr, uid, ids, context=context)
@api.multi
def render_html(self, data=None):
Report = self.env['report']
holidays_report = Report._get_report_from_name('hr_holidays.report_holidayssummary')
holidays = self.env['hr.holidays'].browse(self.ids)
docargs = {
'doc_ids': ids,
'doc_ids': self.ids,
'doc_model': holidays_report.model,
'docs': selected_records,
'docs': holidays,
'get_header_info': self._get_header_info(data['form']['date_from'], data['form']['holiday_type']),
'get_day': self._get_day(data['form']['date_from']),
'get_months': self._get_months(data['form']['date_from']),
'get_data_from_report': self._get_data_from_report(cr, uid, ids, data['form'], context=context),
'get_holidays_status': self._get_holidays_status(cr, uid, ids, context=context),
'get_data_from_report': self._get_data_from_report(data['form']),
'get_holidays_status': self._get_holidays_status(),
}
return report_obj.render(cr, uid, ids, 'hr_holidays.report_holidayssummary', docargs, context=context)
return Report.render('hr_holidays.report_holidayssummary', docargs)
@@ -1,23 +1,23 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import tools
from openerp.osv import fields,osv
from odoo import fields, models, tools
class HrHolidaysRemainingLeavesUser(models.Model):
class hr_holidays_remaining_leaves_user(osv.osv):
_name = "hr.holidays.remaining.leaves.user"
_description = "Total holidays by type"
_auto = False
_columns = {
'name': fields.char('Employee'),
'no_of_leaves': fields.integer('Remaining leaves'),
'user_id': fields.many2one('res.users', 'User'),
'leave_type': fields.char('Leave Type'),
}
def init(self, cr):
tools.drop_view_if_exists(cr, 'hr_holidays_remaining_leaves_user')
cr.execute("""
name = fields.Char('Employee', readonly=True)
no_of_leaves = fields.Integer('Remaining leaves', readonly=True)
user_id = fields.Many2one('res.users', string='User', readonly=True)
leave_type = fields.Char('Leave Type', readonly=True)
def init(self):
tools.drop_view_if_exists(self._cr, 'hr_holidays_remaining_leaves_user')
self._cr.execute("""
CREATE or REPLACE view hr_holidays_remaining_leaves_user as (
SELECT
min(hrs.id) as id,
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<odoo>
<record id="view_hr_holidays_remaining_leaves_user_tree" model="ir.ui.view">
<field name="name">hr.holidays.remaining.leaves.user.tree</field>
@@ -26,5 +25,4 @@
</field>
</record>
</data>
</openerp>
</odoo>
@@ -1,6 +1,5 @@
<?xml version="1.0"?>
<openerp>
<data>
<odoo>
<report
id="report_holidays_summary"
@@ -15,5 +14,4 @@
<field name="paperformat_id" ref="hr_holidays.paperformat_hrsummary"/>
</record>
</data>
</openerp>
</odoo>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<odoo>
<template id="report_holidayssummary">
<t t-call="report.html_container">
<t t-call="report.internal_layout">
@@ -78,5 +78,5 @@
</t>
</t>
</template>
</data>
</openerp>
</odoo>
+12 -16
View File
@@ -1,8 +1,6 @@
<?xml version="1.0"?>
<openerp>
<data>
<record model="ir.ui.view" id="view_holiday_pivot">
<odoo>
<record id="view_holiday_pivot" model="ir.ui.view">
<field name="name">hr.holidays.report_pivot</field>
<field name="model">hr.holidays</field>
<field name="priority">20</field>
@@ -16,7 +14,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday_graph">
<record id="view_holiday_graph" model="ir.ui.view">
<field name="name">hr.holidays.report_graph</field>
<field name="model">hr.holidays</field>
<field name="priority">20</field>
@@ -29,7 +27,7 @@
</field>
</record>
<record model="ir.actions.act_window" id="action_hr_available_holidays_report">
<record id="action_hr_available_holidays_report" model="ir.actions.act_window">
<field name="name">Leaves Analysis</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -39,13 +37,14 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<record model="ir.actions.act_window.view" id="action_window_leave_pivot">
<record id="action_window_leave_pivot" model="ir.actions.act_window.view">
<field name="sequence" eval="2"/>
<field name="view_mode">pivot</field>
<field name="view_id" ref="view_holiday_pivot"/>
<field name="act_window_id" ref="action_hr_available_holidays_report"/>
</record>
<record model="ir.actions.act_window.view" id="action_window_leave_graph">
<record id="action_window_leave_graph" model="ir.actions.act_window.view">
<field name="sequence" eval="2"/>
<field name="view_mode">graph</field>
<field name="view_id" ref="view_holiday_graph"/>
@@ -53,12 +52,9 @@
</record>
<menuitem
name="Leaves"
id="menu_hr_available_holidays_report_tree"
action="action_hr_available_holidays_report"
parent="menu_hr_holidays_report" sequence="5" />
</data>
</openerp>
name="Leaves"
id="menu_hr_available_holidays_report_tree"
action="action_hr_available_holidays_report"
parent="menu_hr_holidays_report" sequence="5"/>
</odoo>
@@ -1,6 +1,5 @@
<?xml version="1.0"?>
<openerp>
<data>
<odoo>
<record id="property_rule_holidays_employee" model="ir.rule">
<field name="name">Employee Holidays</field>
<field name="model_id" ref="model_hr_holidays"/>
@@ -40,5 +39,4 @@
<field name="domain_force">['|',('company_id','=',False),('company_id','in',[user.company_id.id])]</field>
</record>
</data>
</openerp>
</odoo>
+115 -52
View File
@@ -1,6 +1,5 @@
<?xml version='1.0' encoding='UTF-8' ?>
<openerp>
<data>
<odoo>
<!-- Graph report -->
<record id="view_evaluation_report_graph" model="ir.ui.view">
@@ -75,7 +74,7 @@
</record>
<!-- Holidays: Allocation Request -->
<record model="ir.ui.view" id="edit_holiday_new">
<record id="edit_holiday_new" model="ir.ui.view">
<field name="name">Leave Request</field>
<field name="model">hr.holidays</field>
<field name="arch" type="xml">
@@ -102,9 +101,9 @@
<label for="number_of_days_temp" string="Duration"/>
<div>
<div attrs="{'invisible': [('type', '=', 'add')]}">
<field name="date_from" on_change="onchange_date_from(date_to, date_from, employee_id, context)" attrs="{'required':[('type', '=', 'remove')]}" class="oe_inline"/>
<field name="date_from" attrs="{'required':[('type', '=', 'remove')]}" class="oe_inline"/>
<label string="-" class="oe_inline"/>
<field name="date_to" on_change="onchange_date_to(date_to, date_from, employee_id, context)" attrs="{'required':[('type', '=', 'remove')]}" class="oe_inline"/>
<field name="date_to" attrs="{'required':[('type', '=', 'remove')]}" class="oe_inline"/>
</div>
<div>
<field name="number_of_days_temp" class="oe_inline"/> days
@@ -112,8 +111,8 @@
</div>
</group>
<group>
<field name="holiday_type" on_change="onchange_type(holiday_type)" attrs="{'readonly':[('type', '=', 'remove'),('state','!=','draft')]}" string="Mode" groups="base.group_hr_user" context="{'employee_id':employee_id}" />
<field name="employee_id" attrs="{'required':[('holiday_type','=','employee')],'invisible':[('holiday_type','=','category')]}" on_change="onchange_employee(employee_id)" groups="base.group_hr_user"/>
<field name="holiday_type" attrs="{'readonly':[('type', '=', 'remove'),('state','!=','draft')]}" string="Mode" groups="base.group_hr_user" context="{'employee_id':employee_id}" />
<field name="employee_id" attrs="{'required':[('holiday_type','=','employee')],'invisible':[('holiday_type','=','category')]}" groups="base.group_hr_user"/>
<field name="category_id" attrs="{'required':[('holiday_type','=','category')], 'readonly': [('type', '=', 'remove'),('state','!=','draft'), ('state','!=','confirm')], 'invisible':[('holiday_type','=','employee')]}"/>
<field name="department_id" groups="base.group_hr_user" attrs="{'readonly':['|','|' ,('type','=','add'),('holiday_type','=','category'),('state','=', 'validate')],'invisible':[('holiday_type','=','category')]}"/>
<field name="payslip_status" groups="base.group_hr_manager" attrs="{'invisible':[('type','=','add')]}" widget="toggle_button"/>
@@ -133,7 +132,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday_allocation_tree">
<record id="view_holiday_allocation_tree" model="ir.ui.view">
<field name="name">hr.holidays.allocation.tree</field>
<field name="model">hr.holidays</field>
<field name="arch" type="xml">
@@ -155,7 +154,8 @@
</tree>
</field>
</record>
<record model="ir.ui.view" id="view_holiday_allocation_tree_customize">
<record id="view_holiday_allocation_tree_customize" model="ir.ui.view">
<field name="name">hr.holidays.allocation.tree.customize</field>
<field name="model">hr.holidays</field>
<field name="arch" type="xml">
@@ -164,8 +164,8 @@
<field name="holiday_type"/>
<field name="holiday_status_id"/>
<field name="name" readonly="1"/>
<field name="date_from" required="1" on_change="onchange_date_from(date_to, date_from)"/>
<field name="date_to" required="1" on_change="onchange_date_to(date_to, date_from)"/>
<field name="date_from" required="1"/>
<field name="date_to" required="1"/>
<field name="number_of_days_temp" string="Allocated Days" sum="Remaining Days"/>
<field name="state"/>
<button name="toggle_payslip_status" field_name="payslip_status" type="object"
@@ -176,7 +176,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday_simple">
<record id="view_holiday_simple" model="ir.ui.view">
<field name="name">hr.holidays.report_tree</field>
<field name="model">hr.holidays</field>
<field name="priority">20</field>
@@ -198,7 +198,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday_employee">
<record id="view_holiday_employee" model="ir.ui.view">
<field name="name">hr.holidays.report_employee_tree</field>
<field name="model">hr.holidays</field>
<field name="priority">21</field>
@@ -220,7 +220,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday">
<record id="view_holiday" model="ir.ui.view">
<field name="name">hr.holidays.tree</field>
<field name="model">hr.holidays</field>
<field name="arch" type="xml">
@@ -246,7 +246,7 @@
</field>
</record>
<record model="ir.actions.act_window" id="action_hr_holidays_dashboard">
<record id="action_hr_holidays_dashboard" model="ir.actions.act_window">
<field name="name">All Leaves</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -256,13 +256,42 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<menuitem name="Leaves" id="menu_hr_holidays_root" sequence="95" web_icon="hr_holidays,static/description/icon.png" groups="base.group_user"/>
<menuitem name="Dashboard" id="menu_hr_holidays_dashboard" parent="menu_hr_holidays_root" sequence="1" action="action_hr_holidays_dashboard" groups="base.group_hr_manager"/>
<menuitem name="My Leaves" id="menu_hr_holidays_my_leaves" parent="menu_hr_holidays_root" sequence="2"/>
<menuitem name="Leaves to Approve" id="menu_hr_holidays_approvals" parent="menu_hr_holidays_root" sequence="3" groups="base.group_hr_manager,base.group_hr_user"/>
<menuitem name="Reports" id="menu_hr_holidays_report" parent="menu_hr_holidays_root" sequence="99" groups="base.group_hr_manager,base.group_hr_user"/>
<menuitem
name="Leaves"
id="menu_hr_holidays_root"
sequence="95"
web_icon="hr_holidays,static/description/icon.png"
groups="base.group_user"/>
<record model="ir.actions.act_window" id="open_ask_holidays">
<menuitem
id="menu_hr_holidays_dashboard"
name="Dashboard"
parent="menu_hr_holidays_root"
sequence="1"
action="action_hr_holidays_dashboard"
groups="base.group_hr_manager"/>
<menuitem
id="menu_hr_holidays_my_leaves"
name="My Leaves"
parent="menu_hr_holidays_root"
sequence="2"/>
<menuitem
id="menu_hr_holidays_approvals"
name="Leaves to Approve"
parent="menu_hr_holidays_root"
sequence="3"
groups="base.group_hr_manager,base.group_hr_user"/>
<menuitem
id="menu_hr_holidays_report"
name="Reports"
parent="menu_hr_holidays_root"
sequence="99"
groups="base.group_hr_manager,base.group_hr_user"/>
<record id="open_ask_holidays" model="ir.actions.act_window">
<field name="name">Leaves Request</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -288,28 +317,32 @@
</field>
</record>
<record model="ir.actions.act_window.view" id="action_open_ask_holidays_tree">
<record id="action_open_ask_holidays_tree" model="ir.actions.act_window.view">
<field name="sequence" eval="2"/>
<field name="view_mode">tree</field>
<field name="view_id" ref="view_holiday"/>
<field name="act_window_id" ref="open_ask_holidays"/>
</record>
<record model="ir.actions.act_window.view" id="action_open_ask_holidays_form">
<record id="action_open_ask_holidays_form" model="ir.actions.act_window.view">
<field name="sequence" eval="3"/>
<field name="view_mode">form</field>
<field name="view_id" ref="edit_holiday_new"/>
<field name="act_window_id" ref="open_ask_holidays"/>
</record>
<record model="ir.actions.act_window.view" id="action_open_ask_holidays_calendar">
<record id="action_open_ask_holidays_calendar" model="ir.actions.act_window.view">
<field name="sequence" eval="1"/>
<field name="view_mode">calendar</field>
<field name="view_id" ref="view_holiday_new_calendar"/>
<field name="act_window_id" ref="open_ask_holidays"/>
</record>
<menuitem parent="menu_hr_holidays_my_leaves" id="menu_open_ask_holidays_new" action="open_ask_holidays" sequence="22"/>
<menuitem
id="menu_open_ask_holidays_new"
parent="menu_hr_holidays_my_leaves"
action="open_ask_holidays"
sequence="22"/>
<record model="ir.actions.act_window" id="request_approve_holidays">
<field name="name">Requests to Approve</field>
@@ -330,21 +363,21 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<record model="ir.actions.act_window.view" id="action_request_approve_holidays_tree">
<record id="action_request_approve_holidays_tree" model="ir.actions.act_window.view">
<field name="sequence" eval="1"/>
<field name="view_mode">tree</field>
<field name="view_id" ref="view_holiday"/>
<field name="act_window_id" ref="request_approve_holidays"/>
</record>
<record model="ir.actions.act_window.view" id="action_request_approve_holidays_form">
<record id="action_request_approve_holidays_form" model="ir.actions.act_window.view">
<field name="sequence" eval="2"/>
<field name="view_mode">form</field>
<field name="view_id" ref="edit_holiday_new"/>
<field name="act_window_id" ref="request_approve_holidays"/>
</record>
<record model="ir.actions.act_window" id="open_allocation_holidays">
<record id="open_allocation_holidays" model="ir.actions.act_window">
<field name="name">Allocation Request</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -365,23 +398,27 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<record model="ir.actions.act_window.view" id="action_open_allocation_holidays_tree">
<record id="action_open_allocation_holidays_tree" model="ir.actions.act_window.view">
<field name="sequence" eval="1"/>
<field name="view_mode">tree</field>
<field name="view_id" ref="view_holiday_allocation_tree"/>
<field name="act_window_id" ref="open_allocation_holidays"/>
</record>
<record model="ir.actions.act_window.view" id="action_open_allocation_holidays_form">
<record id="action_open_allocation_holidays_form" model="ir.actions.act_window.view">
<field name="sequence" eval="2"/>
<field name="view_mode">form</field>
<field name="view_id" ref="edit_holiday_new"/>
<field name="act_window_id" ref="open_allocation_holidays"/>
</record>
<menuitem parent="menu_hr_holidays_my_leaves" id="menu_open_allocation_holidays" action="open_allocation_holidays" sequence="40"/>
<menuitem
id="menu_open_allocation_holidays"
parent="menu_hr_holidays_my_leaves"
action="open_allocation_holidays"
sequence="40"/>
<record model="ir.actions.act_window" id="request_approve_allocation">
<record id="request_approve_allocation" model="ir.actions.act_window">
<field name="name">Allocation Request</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -399,21 +436,21 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<record model="ir.actions.act_window.view" id="action_request_approve_allocation_tree">
<record id="action_request_approve_allocation_tree" model="ir.actions.act_window.view">
<field name="sequence" eval="1"/>
<field name="view_mode">tree</field>
<field name="view_id" ref="view_holiday_allocation_tree"/>
<field name="act_window_id" ref="request_approve_allocation"/>
</record>
<record model="ir.actions.act_window.view" id="action_request_approve_allocation_form">
<record id="action_request_approve_allocation_form" model="ir.actions.act_window.view">
<field name="sequence" eval="2"/>
<field name="view_mode">form</field>
<field name="view_id" ref="edit_holiday_new"/>
<field name="act_window_id" ref="request_approve_allocation"/>
</record>
<record model="ir.actions.act_window" id="open_company_allocation">
<record id="open_company_allocation" model="ir.actions.act_window">
<field name="name">Leaves Summary</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -439,9 +476,14 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<menuitem name="Leaves Summary" parent="menu_hr_holidays_my_leaves" id="menu_open_company_allocation" action="open_company_allocation" sequence="21"/>
<menuitem
id="menu_open_company_allocation"
name="Leaves Summary"
parent="menu_hr_holidays_my_leaves"
action="open_company_allocation"
sequence="21"/>
<record model="ir.actions.act_window" id="open_employee_leaves">
<record id="open_employee_leaves" model="ir.actions.act_window">
<field name="name">Leave Details</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -457,7 +499,7 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<record model="ir.actions.act_window" id="open_department_holidays_approve">
<record id="open_department_holidays_approve" model="ir.actions.act_window">
<field name="name">Department Leaves</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -472,9 +514,15 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<menuitem name="Leaves" parent="menu_hr_holidays_approvals" id="menu_open_department_leave_approve" groups="base.group_hr_manager,base.group_hr_user" action="open_department_holidays_approve" sequence="1"/>
<menuitem
id="menu_open_department_leave_approve"
name="Leaves"
parent="menu_hr_holidays_approvals"
groups="base.group_hr_manager,base.group_hr_user"
action="open_department_holidays_approve"
sequence="1"/>
<record model="ir.actions.act_window" id="open_department_holidays_allocation_approve">
<record id="open_department_holidays_allocation_approve" model="ir.actions.act_window">
<field name="name">Department Leaves Allocation</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -489,9 +537,20 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<menuitem name="Leaves Allocation" parent="menu_hr_holidays_approvals" id="menu_open_department_leave_allocation_approve" groups="base.group_hr_manager,base.group_hr_user" action="open_department_holidays_allocation_approve" sequence="2"/>
<menuitem
id="menu_open_department_leave_allocation_approve" groups="base.group_hr_manager,base.group_hr_user"
name="Leaves Allocation"
parent="menu_hr_holidays_approvals"
action="open_department_holidays_allocation_approve"
sequence="2"/>
<menuitem name="Leave Details" parent="menu_hr_holidays_report" id="menu_open_employee_leave" groups="base.group_hr_manager,base.group_hr_user" action="open_employee_leaves" sequence="4"/>
<menuitem
id="menu_open_employee_leave"
name="Leave Details"
parent="menu_hr_holidays_report"
groups="base.group_hr_manager,base.group_hr_user"
action="open_employee_leaves"
sequence="4"/>
<!-- Holidays status -->
<record id="view_holidays_status_filter" model="ir.ui.view">
@@ -505,7 +564,7 @@
</field>
</record>
<record model="ir.ui.view" id="edit_holiday_status_form">
<record id="edit_holiday_status_form" model="ir.ui.view">
<field name="name">hr.holidays.status.form</field>
<field name="model">hr.holidays.status</field>
<field name="arch" type="xml">
@@ -527,7 +586,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday_status_tree">
<record id="view_holiday_status_tree" model="ir.ui.view">
<field name="name">hr.holidays.status.tree</field>
<field name="model">hr.holidays.status</field>
<field name="arch" type="xml">
@@ -540,7 +599,7 @@
</field>
</record>
<record model="ir.ui.view" id="view_holiday_status_normal_tree">
<record id="view_holiday_status_normal_tree" model="ir.ui.view">
<field name="name">hr.holidays.status.normal.tree</field>
<field name="model">hr.holidays.status</field>
<field name="priority">35</field>
@@ -573,8 +632,13 @@
<field name="search_view_id" ref="view_hr_holidays_status_search"/>
</record>
<menuitem id="menu_hr_holidays_configuration" name="Configuration" parent="menu_hr_holidays_root"
sequence="100" groups="base.group_hr_manager" action="open_view_holiday_status"/>
<menuitem
id="menu_hr_holidays_configuration"
name="Configuration"
parent="menu_hr_holidays_root"
sequence="100"
groups="base.group_hr_manager"
action="open_view_holiday_status"/>
<!-- Shortcuts -->
<record id="act_hr_employee_holiday_request" model="ir.actions.act_window">
@@ -615,7 +679,7 @@
</field>
</record>
<record model="ir.actions.act_window" id="hr_holidays_leaves_assign_legal">
<record id="hr_holidays_leaves_assign_legal" model="ir.actions.act_window">
<field name="name">Allocate Leaves for Employees</field>
<field name="type">ir.actions.act_window</field>
<field name="res_model">hr.employee</field>
@@ -683,7 +747,7 @@
<field name="search_view_id" ref="hr.view_employee_filter"/>
</record>
<record model="ir.actions.act_window" id="action_hr_holidays_leaves_analysis">
<record id="action_hr_holidays_leaves_analysis" model="ir.actions.act_window">
<field name="name">Leaves Analysis</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -692,7 +756,7 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
<record model="ir.actions.act_window" id="action_hr_holidays_leaves_analysis_filtered">
<record id="action_hr_holidays_leaves_analysis_filtered" model="ir.actions.act_window">
<field name="name">Leaves Analysis</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
@@ -705,5 +769,4 @@
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
</data>
</openerp>
</odoo>
+3 -2
View File
@@ -1,3 +1,4 @@
<?xml version='1.0' encoding='UTF-8'?>
<odoo>
<!--Hr Department Inherit Kanban view-->
<record id="hr_department_view_kanban" model="ir.ui.view">
@@ -93,8 +94,8 @@
</field>
</record>
<record model="ir.ui.view" id="hr_kanban_view_employees_kanban">
<field name="name">HR - Employees Kanban with leave status</field>
<record id="hr_kanban_view_employees_kanban" model="ir.ui.view">
<field name="name">hr.employee.kanban.leaves.status</field>
<field name="model">hr.employee</field>
<field name="inherit_id" ref="hr.hr_kanban_view_employees"/>
<field name="arch" type="xml">
@@ -2,31 +2,33 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp.exceptions import UserError
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class HolidaysSummaryDept(models.TransientModel):
class hr_holidays_summary_dept(osv.osv_memory):
_name = 'hr.holidays.summary.dept'
_description = 'HR Leaves Summary Report By Department'
_columns = {
'date_from': fields.date('From', required=True),
'depts': fields.many2many('hr.department', 'summary_dept_rel', 'sum_id', 'dept_id', 'Department(s)'),
'holiday_type': fields.selection([('Approved','Approved'),('Confirmed','Confirmed'),('both','Both Approved and Confirmed')], 'Leave Type', required=True)
}
_defaults = {
'date_from': lambda *a: time.strftime('%Y-%m-01'),
'holiday_type': 'Approved'
}
date_from = fields.Date(string='From', required=True, default=time.strftime('%Y-%m-01'))
depts = fields.Many2many('hr.department', 'summary_dept_rel', 'sum_id', 'dept_id', string='Department(s)')
holiday_type = fields.Selection([
('Approved', 'Approved'),
('Confirmed', 'Confirmed'),
('both', 'Both Approved and Confirmed')
], string='Leave Type', required=True, default='Approved')
def print_report(self, cr, uid, ids, context=None):
data = self.read(cr, uid, ids, context=context)[0]
if not data['depts']:
@api.multi
def print_report(self):
self.ensure_one()
[data] = self.read()
if not data.get('depts'):
raise UserError(_('You have to select at least one Department. And try again.'))
departments = self.env['hr.department'].browse(data['depts'])
datas = {
'ids': [],
'model': 'hr.department',
'form': data
}
return self.pool['report'].get_action(cr, uid, data['depts'], 'hr_holidays.report_holidayssummary', data=datas, context=context)
'ids': [],
'model': 'hr.department',
'form': data
}
return self.env['report'].get_action(departments, 'hr_holidays.report_holidayssummary', data=datas)
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<odoo>
<record id="view_hr_holidays_summary_dept" model="ir.ui.view">
<field name="name">hr.holidays.summary.dept.form</field>
@@ -36,5 +35,4 @@
id="menu_account_central_journal"
icon="STOCK_PRINT"/>
</data>
</openerp>
</odoo>
@@ -2,28 +2,31 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from openerp.osv import fields, osv
from odoo import api, fields, models
class HolidaysSummaryEmployee(models.TransientModel):
class hr_holidays_summary_employee(osv.osv_memory):
_name = 'hr.holidays.summary.employee'
_description = 'HR Leaves Summary Report By Employee'
_columns = {
'date_from': fields.date('From', required=True),
'emp': fields.many2many('hr.employee', 'summary_emp_rel', 'sum_id', 'emp_id', 'Employee(s)'),
'holiday_type': fields.selection([('Approved','Approved'),('Confirmed','Confirmed'),('both','Both Approved and Confirmed')], 'Select Leave Type', required=True)
}
_defaults = {
'date_from': lambda *a: time.strftime('%Y-%m-01'),
'holiday_type': 'Approved',
}
date_from = fields.Date(string='From', required=True, default=time.strftime('%Y-%m-01'))
emp = fields.Many2many('hr.employee', 'summary_emp_rel', 'sum_id', 'emp_id', string='Employee(s)')
holiday_type = fields.Selection([
('Approved', 'Approved'),
('Confirmed', 'Confirmed'),
('both', 'Both Approved and Confirmed')
], string='Select Leave Type', required=True, default='Approved')
def print_report(self, cr, uid, ids, context=None):
data = self.read(cr, uid, ids, context=context)[0]
data['emp'] = context.get('active_ids',[])
@api.multi
def print_report(self):
self.ensure_one()
[data] = self.read()
data['emp'] = self.env.context.get('active_ids', [])
employees = self.env['hr.employee'].browse(data['emp'])
datas = {
'ids': [],
'model': 'hr.employee',
'form': data
}
return self.pool['report'].get_action(cr, uid, data['emp'], 'hr_holidays.report_holidayssummary', data=datas, context=context)
'ids': [],
'model': 'hr.employee',
'form': data
}
return self.env['report'].get_action(employees, 'hr_holidays.report_holidayssummary', data=datas)
@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<odoo>
<record id="view_hr_holidays_summary_employee" model="ir.ui.view">
<field name="name">hr.holidays.summary.employee.form</field>
@@ -31,7 +30,7 @@
<field name="target">new</field>
</record>
<record model="ir.values" id="hr_holidays_summary_employee_value">
<record id="hr_holidays_summary_employee_value" model="ir.values">
<field name="model_id" ref="hr.model_hr_employee" />
<field name="name">Leaves Summary</field>
<field name="key2">client_print_multi</field>
@@ -40,5 +39,4 @@
<field name="model">hr.employee</field>
</record>
</data>
</openerp>
</odoo>