diff options
| author | stephanchrst <stephanchrst@gmail.com> | 2022-05-10 21:51:50 +0700 |
|---|---|---|
| committer | stephanchrst <stephanchrst@gmail.com> | 2022-05-10 21:51:50 +0700 |
| commit | 3751379f1e9a4c215fb6eb898b4ccc67659b9ace (patch) | |
| tree | a44932296ef4a9b71d5f010906253d8c53727726 /addons/hr_attendance/models | |
| parent | 0a15094050bfde69a06d6eff798e9a8ddf2b8c21 (diff) | |
initial commit 2
Diffstat (limited to 'addons/hr_attendance/models')
| -rw-r--r-- | addons/hr_attendance/models/__init__.py | 6 | ||||
| -rw-r--r-- | addons/hr_attendance/models/hr_attendance.py | 104 | ||||
| -rw-r--r-- | addons/hr_attendance/models/hr_employee.py | 174 | ||||
| -rw-r--r-- | addons/hr_attendance/models/res_config_settings.py | 11 | ||||
| -rw-r--r-- | addons/hr_attendance/models/res_users.py | 30 |
5 files changed, 325 insertions, 0 deletions
diff --git a/addons/hr_attendance/models/__init__.py b/addons/hr_attendance/models/__init__.py new file mode 100644 index 00000000..724d7ee2 --- /dev/null +++ b/addons/hr_attendance/models/__init__.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- + +from . import res_config_settings +from . import hr_attendance +from . import hr_employee +from . import res_users diff --git a/addons/hr_attendance/models/hr_attendance.py b/addons/hr_attendance/models/hr_attendance.py new file mode 100644 index 00000000..5e91d90b --- /dev/null +++ b/addons/hr_attendance/models/hr_attendance.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +from odoo import models, fields, api, exceptions, _ +from odoo.tools import format_datetime + + +class HrAttendance(models.Model): + _name = "hr.attendance" + _description = "Attendance" + _order = "check_in desc" + + def _default_employee(self): + return self.env.user.employee_id + + employee_id = fields.Many2one('hr.employee', string="Employee", default=_default_employee, required=True, ondelete='cascade', index=True) + department_id = fields.Many2one('hr.department', string="Department", related="employee_id.department_id", + readonly=True) + check_in = fields.Datetime(string="Check In", default=fields.Datetime.now, required=True) + check_out = fields.Datetime(string="Check Out") + worked_hours = fields.Float(string='Worked Hours', compute='_compute_worked_hours', store=True, readonly=True) + + def name_get(self): + result = [] + for attendance in self: + if not attendance.check_out: + result.append((attendance.id, _("%(empl_name)s from %(check_in)s") % { + 'empl_name': attendance.employee_id.name, + 'check_in': format_datetime(self.env, attendance.check_in, dt_format=False), + })) + else: + result.append((attendance.id, _("%(empl_name)s from %(check_in)s to %(check_out)s") % { + 'empl_name': attendance.employee_id.name, + 'check_in': format_datetime(self.env, attendance.check_in, dt_format=False), + 'check_out': format_datetime(self.env, attendance.check_out, dt_format=False), + })) + return result + + @api.depends('check_in', 'check_out') + def _compute_worked_hours(self): + for attendance in self: + if attendance.check_out and attendance.check_in: + delta = attendance.check_out - attendance.check_in + attendance.worked_hours = delta.total_seconds() / 3600.0 + else: + attendance.worked_hours = False + + @api.constrains('check_in', 'check_out') + def _check_validity_check_in_check_out(self): + """ verifies if check_in is earlier than check_out. """ + for attendance in self: + if attendance.check_in and attendance.check_out: + if attendance.check_out < attendance.check_in: + raise exceptions.ValidationError(_('"Check Out" time cannot be earlier than "Check In" time.')) + + @api.constrains('check_in', 'check_out', 'employee_id') + def _check_validity(self): + """ Verifies the validity of the attendance record compared to the others from the same employee. + For the same employee we must have : + * maximum 1 "open" attendance record (without check_out) + * no overlapping time slices with previous employee records + """ + for attendance in self: + # we take the latest attendance before our check_in time and check it doesn't overlap with ours + last_attendance_before_check_in = self.env['hr.attendance'].search([ + ('employee_id', '=', attendance.employee_id.id), + ('check_in', '<=', attendance.check_in), + ('id', '!=', attendance.id), + ], order='check_in desc', limit=1) + if last_attendance_before_check_in and last_attendance_before_check_in.check_out and last_attendance_before_check_in.check_out > attendance.check_in: + raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % { + 'empl_name': attendance.employee_id.name, + 'datetime': format_datetime(self.env, attendance.check_in, dt_format=False), + }) + + if not attendance.check_out: + # if our attendance is "open" (no check_out), we verify there is no other "open" attendance + no_check_out_attendances = self.env['hr.attendance'].search([ + ('employee_id', '=', attendance.employee_id.id), + ('check_out', '=', False), + ('id', '!=', attendance.id), + ], order='check_in desc', limit=1) + if no_check_out_attendances: + raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee hasn't checked out since %(datetime)s") % { + 'empl_name': attendance.employee_id.name, + 'datetime': format_datetime(self.env, no_check_out_attendances.check_in, dt_format=False), + }) + else: + # we verify that the latest attendance with check_in time before our check_out time + # is the same as the one before our check_in time computed before, otherwise it overlaps + last_attendance_before_check_out = self.env['hr.attendance'].search([ + ('employee_id', '=', attendance.employee_id.id), + ('check_in', '<', attendance.check_out), + ('id', '!=', attendance.id), + ], order='check_in desc', limit=1) + if last_attendance_before_check_out and last_attendance_before_check_in != last_attendance_before_check_out: + raise exceptions.ValidationError(_("Cannot create new attendance record for %(empl_name)s, the employee was already checked in on %(datetime)s") % { + 'empl_name': attendance.employee_id.name, + 'datetime': format_datetime(self.env, last_attendance_before_check_out.check_in, dt_format=False), + }) + + @api.returns('self', lambda value: value.id) + def copy(self): + raise exceptions.UserError(_('You cannot duplicate an attendance.')) diff --git a/addons/hr_attendance/models/hr_employee.py b/addons/hr_attendance/models/hr_employee.py new file mode 100644 index 00000000..0f65f372 --- /dev/null +++ b/addons/hr_attendance/models/hr_employee.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +import pytz +from datetime import datetime +from dateutil.relativedelta import relativedelta + +from odoo import models, fields, api, exceptions, _, SUPERUSER_ID + + +class HrEmployeeBase(models.AbstractModel): + _inherit = "hr.employee.base" + + attendance_ids = fields.One2many('hr.attendance', 'employee_id', help='list of attendances for the employee') + last_attendance_id = fields.Many2one('hr.attendance', compute='_compute_last_attendance_id', store=True) + last_check_in = fields.Datetime(related='last_attendance_id.check_in', store=True) + last_check_out = fields.Datetime(related='last_attendance_id.check_out', store=True) + attendance_state = fields.Selection(string="Attendance Status", compute='_compute_attendance_state', selection=[('checked_out', "Checked out"), ('checked_in', "Checked in")]) + hours_last_month = fields.Float(compute='_compute_hours_last_month') + hours_today = fields.Float(compute='_compute_hours_today') + hours_last_month_display = fields.Char(compute='_compute_hours_last_month') + + @api.depends('user_id.im_status', 'attendance_state') + def _compute_presence_state(self): + """ + Override to include checkin/checkout in the presence state + Attendance has the second highest priority after login + """ + super()._compute_presence_state() + employees = self.filtered(lambda e: e.hr_presence_state != 'present') + employee_to_check_working = self.filtered(lambda e: e.attendance_state == 'checked_out' + and e.hr_presence_state == 'to_define') + working_now_list = employee_to_check_working._get_employee_working_now() + for employee in employees: + if employee.attendance_state == 'checked_out' and employee.hr_presence_state == 'to_define' and \ + employee.id not in working_now_list: + employee.hr_presence_state = 'absent' + elif employee.attendance_state == 'checked_in': + employee.hr_presence_state = 'present' + + def _compute_hours_last_month(self): + now = fields.Datetime.now() + now_utc = pytz.utc.localize(now) + for employee in self: + tz = pytz.timezone(employee.tz or 'UTC') + now_tz = now_utc.astimezone(tz) + start_tz = now_tz + relativedelta(months=-1, day=1, hour=0, minute=0, second=0, microsecond=0) + start_naive = start_tz.astimezone(pytz.utc).replace(tzinfo=None) + end_tz = now_tz + relativedelta(day=1, hour=0, minute=0, second=0, microsecond=0) + end_naive = end_tz.astimezone(pytz.utc).replace(tzinfo=None) + + attendances = self.env['hr.attendance'].search([ + ('employee_id', '=', employee.id), + '&', + ('check_in', '<=', end_naive), + ('check_out', '>=', start_naive), + ]) + + hours = 0 + for attendance in attendances: + check_in = max(attendance.check_in, start_naive) + check_out = min(attendance.check_out, end_naive) + hours += (check_out - check_in).total_seconds() / 3600.0 + + employee.hours_last_month = round(hours, 2) + employee.hours_last_month_display = "%g" % employee.hours_last_month + + def _compute_hours_today(self): + now = fields.Datetime.now() + now_utc = pytz.utc.localize(now) + for employee in self: + # start of day in the employee's timezone might be the previous day in utc + tz = pytz.timezone(employee.tz) + now_tz = now_utc.astimezone(tz) + start_tz = now_tz + relativedelta(hour=0, minute=0) # day start in the employee's timezone + start_naive = start_tz.astimezone(pytz.utc).replace(tzinfo=None) + + attendances = self.env['hr.attendance'].search([ + ('employee_id', '=', employee.id), + ('check_in', '<=', now), + '|', ('check_out', '>=', start_naive), ('check_out', '=', False), + ]) + + worked_hours = 0 + for attendance in attendances: + delta = (attendance.check_out or now) - max(attendance.check_in, start_naive) + worked_hours += delta.total_seconds() / 3600.0 + employee.hours_today = worked_hours + + @api.depends('attendance_ids') + def _compute_last_attendance_id(self): + for employee in self: + employee.last_attendance_id = self.env['hr.attendance'].search([ + ('employee_id', '=', employee.id), + ], limit=1) + + @api.depends('last_attendance_id.check_in', 'last_attendance_id.check_out', 'last_attendance_id') + def _compute_attendance_state(self): + for employee in self: + att = employee.last_attendance_id.sudo() + employee.attendance_state = att and not att.check_out and 'checked_in' or 'checked_out' + + @api.model + def attendance_scan(self, barcode): + """ Receive a barcode scanned from the Kiosk Mode and change the attendances of corresponding employee. + Returns either an action or a warning. + """ + employee = self.sudo().search([('barcode', '=', barcode)], limit=1) + if employee: + return employee._attendance_action('hr_attendance.hr_attendance_action_kiosk_mode') + return {'warning': _("No employee corresponding to Badge ID '%(barcode)s.'") % {'barcode': barcode}} + + def attendance_manual(self, next_action, entered_pin=None): + self.ensure_one() + can_check_without_pin = not self.env.user.has_group('hr_attendance.group_hr_attendance_use_pin') or (self.user_id == self.env.user and entered_pin is None) + if can_check_without_pin or entered_pin is not None and entered_pin == self.sudo().pin: + return self._attendance_action(next_action) + return {'warning': _('Wrong PIN')} + + def _attendance_action(self, next_action): + """ Changes the attendance of the employee. + Returns an action to the check in/out message, + next_action defines which menu the check in/out message should return to. ("My Attendances" or "Kiosk Mode") + """ + self.ensure_one() + employee = self.sudo() + action_message = self.env["ir.actions.actions"]._for_xml_id("hr_attendance.hr_attendance_action_greeting_message") + action_message['previous_attendance_change_date'] = employee.last_attendance_id and (employee.last_attendance_id.check_out or employee.last_attendance_id.check_in) or False + action_message['employee_name'] = employee.name + action_message['barcode'] = employee.barcode + action_message['next_action'] = next_action + action_message['hours_today'] = employee.hours_today + + if employee.user_id: + modified_attendance = employee.with_user(employee.user_id)._attendance_action_change() + else: + modified_attendance = employee._attendance_action_change() + action_message['attendance'] = modified_attendance.read()[0] + return {'action': action_message} + + def _attendance_action_change(self): + """ Check In/Check Out action + Check In: create a new attendance record + Check Out: modify check_out field of appropriate attendance record + """ + self.ensure_one() + action_date = fields.Datetime.now() + + if self.attendance_state != 'checked_in': + vals = { + 'employee_id': self.id, + 'check_in': action_date, + } + return self.env['hr.attendance'].create(vals) + attendance = self.env['hr.attendance'].search([('employee_id', '=', self.id), ('check_out', '=', False)], limit=1) + if attendance: + attendance.check_out = action_date + else: + raise exceptions.UserError(_('Cannot perform check out on %(empl_name)s, could not find corresponding check in. ' + 'Your attendances have probably been modified manually by human resources.') % {'empl_name': self.sudo().name, }) + return attendance + + @api.model + def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True): + if 'pin' in groupby or 'pin' in self.env.context.get('group_by', '') or self.env.context.get('no_group_by'): + raise exceptions.UserError(_('Such grouping is not allowed.')) + return super(HrEmployeeBase, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy) + + def _compute_presence_icon(self): + res = super()._compute_presence_icon() + # All employee must chek in or check out. Everybody must have an icon + employee_to_define = self.filtered(lambda e: e.hr_icon_display == 'presence_undetermined') + employee_to_define.hr_icon_display = 'presence_to_define' + return res diff --git a/addons/hr_attendance/models/res_config_settings.py b/addons/hr_attendance/models/res_config_settings.py new file mode 100644 index 00000000..5e67d2e5 --- /dev/null +++ b/addons/hr_attendance/models/res_config_settings.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +from odoo import fields, models + + +class ResConfigSettings(models.TransientModel): + _inherit = 'res.config.settings' + + group_attendance_use_pin = fields.Boolean(string='Employee PIN', + implied_group="hr_attendance.group_hr_attendance_use_pin") diff --git a/addons/hr_attendance/models/res_users.py b/addons/hr_attendance/models/res_users.py new file mode 100644 index 00000000..23dcb496 --- /dev/null +++ b/addons/hr_attendance/models/res_users.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Part of Odoo. See LICENSE file for full copyright and licensing details. + +from odoo import models, fields + + +class User(models.Model): + _inherit = ['res.users'] + + hours_last_month = fields.Float(related='employee_id.hours_last_month') + hours_last_month_display = fields.Char(related='employee_id.hours_last_month_display') + attendance_state = fields.Selection(related='employee_id.attendance_state') + last_check_in = fields.Datetime(related='employee_id.last_attendance_id.check_in') + last_check_out = fields.Datetime(related='employee_id.last_attendance_id.check_out') + + def __init__(self, pool, cr): + """ Override of __init__ to add access rights. + Access rights are disabled by default, but allowed + on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS. + """ + attendance_readable_fields = [ + 'hours_last_month', + 'hours_last_month_display', + 'attendance_state', + 'last_check_in', + 'last_check_out' + ] + super(User, self).__init__(pool, cr) + # duplicate list to avoid modifying the original reference + type(self).SELF_READABLE_FIELDS = type(self).SELF_READABLE_FIELDS + attendance_readable_fields |
