diff --git a/addons/hr_holidays_attendance/models/hr_leave.py b/addons/hr_holidays_attendance/models/hr_leave.py index 6468917212a..26c67d0aa20 100644 --- a/addons/hr_holidays_attendance/models/hr_leave.py +++ b/addons/hr_holidays_attendance/models/hr_leave.py @@ -24,8 +24,30 @@ class HRLeave(models.Model): @api.model_create_multi def create(self, vals_list): res = super().create(vals_list) - today = fields.Date.today() - for leave in res: + self._check_overtime_deductible(res) + return res + + def write(self, vals): + res = super().write(vals) + fields_to_check = {'number_of_days', 'date_from', 'date_to', 'state', 'employee_id', 'holiday_status_id'} + if not any(field for field in fields_to_check if field in vals): + return res + if vals.get('holiday_status_id'): + self._check_overtime_deductible(self) + #User may not have access to overtime_id field + for leave in self.sudo().filtered('overtime_id'): + employee = leave.employee_id + duration = leave.number_of_hours_display + overtime_duration = leave.overtime_id.sudo().duration + if overtime_duration != duration: + if duration > employee.total_overtime - overtime_duration: + raise ValidationError(_('The employee does not have enough extra hours to extend this leave.')) + leave.overtime_id.sudo().duration = -1 * duration + return res + + def _check_overtime_deductible(self, leaves): + # If the type of leave is overtime deductible, we have to check that the employee has enough extra hours + for leave in leaves: if not leave.overtime_deductible: continue employee = leave.employee_id.sudo() @@ -37,27 +59,10 @@ class HRLeave(models.Model): if not leave.overtime_id: leave.sudo().overtime_id = self.env['hr.attendance.overtime'].sudo().create({ 'employee_id': employee.id, - 'date': today, + 'date': fields.Date.today(), 'adjustment': True, 'duration': -1 * duration, }) - return res - - def write(self, vals): - res = super().write(vals) - fields_to_check = {'number_of_days', 'date_from', 'date_to', 'state', 'employee_id'} - if not any(field for field in fields_to_check if field in vals): - return res - #User may not have access to overtime_id field - for leave in self.sudo().filtered('overtime_id'): - employee = leave.employee_id - duration = leave.number_of_hours_display - overtime_duration = leave.overtime_id.sudo().duration - if overtime_duration != duration: - if duration > employee.total_overtime - overtime_duration: - raise ValidationError(_('The employee does not have enough extra hours to extend this leave.')) - leave.overtime_id.sudo().duration = -1 * duration - return res def action_draft(self): overtime_leaves = self.filtered('overtime_deductible')