hr_employee.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import pytz
  4. from dateutil.relativedelta import relativedelta
  5. from odoo import models, fields, api, exceptions, _
  6. from odoo.tools import float_round
  7. class HrEmployee(models.Model):
  8. _inherit = "hr.employee"
  9. attendance_ids = fields.One2many(
  10. 'hr.attendance', 'employee_id', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user")
  11. last_attendance_id = fields.Many2one(
  12. 'hr.attendance', compute='_compute_last_attendance_id', store=True,
  13. groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user")
  14. last_check_in = fields.Datetime(
  15. related='last_attendance_id.check_in', store=True,
  16. groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user")
  17. last_check_out = fields.Datetime(
  18. related='last_attendance_id.check_out', store=True,
  19. groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user")
  20. attendance_state = fields.Selection(
  21. string="Attendance Status", compute='_compute_attendance_state',
  22. selection=[('checked_out', "Checked out"), ('checked_in', "Checked in")],
  23. groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user")
  24. hours_last_month = fields.Float(
  25. compute='_compute_hours_last_month', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user")
  26. hours_today = fields.Float(
  27. compute='_compute_hours_today',
  28. groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user")
  29. hours_last_month_display = fields.Char(
  30. compute='_compute_hours_last_month', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user")
  31. overtime_ids = fields.One2many(
  32. 'hr.attendance.overtime', 'employee_id', groups="hr_attendance.group_hr_attendance_user,hr.group_hr_user")
  33. total_overtime = fields.Float(
  34. compute='_compute_total_overtime', compute_sudo=True,
  35. groups="hr_attendance.group_hr_attendance_kiosk,hr_attendance.group_hr_attendance,hr.group_hr_user")
  36. @api.depends('overtime_ids.duration', 'attendance_ids')
  37. def _compute_total_overtime(self):
  38. for employee in self:
  39. if employee.company_id.hr_attendance_overtime:
  40. employee.total_overtime = float_round(sum(employee.overtime_ids.mapped('duration')), 2)
  41. else:
  42. employee.total_overtime = 0
  43. @api.depends('user_id.im_status', 'attendance_state')
  44. def _compute_presence_state(self):
  45. """
  46. Override to include checkin/checkout in the presence state
  47. Attendance has the second highest priority after login
  48. """
  49. super()._compute_presence_state()
  50. employees = self.filtered(lambda e: e.hr_presence_state != 'present')
  51. employee_to_check_working = self.filtered(lambda e: e.attendance_state == 'checked_out'
  52. and e.hr_presence_state == 'to_define')
  53. working_now_list = employee_to_check_working._get_employee_working_now()
  54. for employee in employees:
  55. if employee.attendance_state == 'checked_out' and employee.hr_presence_state == 'to_define' and \
  56. employee.id not in working_now_list:
  57. employee.hr_presence_state = 'absent'
  58. elif employee.attendance_state == 'checked_in':
  59. employee.hr_presence_state = 'present'
  60. def _compute_hours_last_month(self):
  61. now = fields.Datetime.now()
  62. now_utc = pytz.utc.localize(now)
  63. for employee in self:
  64. tz = pytz.timezone(employee.tz or 'UTC')
  65. now_tz = now_utc.astimezone(tz)
  66. start_tz = now_tz + relativedelta(months=-1, day=1, hour=0, minute=0, second=0, microsecond=0)
  67. start_naive = start_tz.astimezone(pytz.utc).replace(tzinfo=None)
  68. end_tz = now_tz + relativedelta(day=1, hour=0, minute=0, second=0, microsecond=0)
  69. end_naive = end_tz.astimezone(pytz.utc).replace(tzinfo=None)
  70. attendances = self.env['hr.attendance'].search([
  71. ('employee_id', '=', employee.id),
  72. '&',
  73. ('check_in', '<=', end_naive),
  74. ('check_out', '>=', start_naive),
  75. ])
  76. hours = 0
  77. for attendance in attendances:
  78. check_in = max(attendance.check_in, start_naive)
  79. check_out = min(attendance.check_out, end_naive)
  80. hours += (check_out - check_in).total_seconds() / 3600.0
  81. employee.hours_last_month = round(hours, 2)
  82. employee.hours_last_month_display = "%g" % employee.hours_last_month
  83. def _compute_hours_today(self):
  84. now = fields.Datetime.now()
  85. now_utc = pytz.utc.localize(now)
  86. for employee in self:
  87. # start of day in the employee's timezone might be the previous day in utc
  88. tz = pytz.timezone(employee.tz)
  89. now_tz = now_utc.astimezone(tz)
  90. start_tz = now_tz + relativedelta(hour=0, minute=0) # day start in the employee's timezone
  91. start_naive = start_tz.astimezone(pytz.utc).replace(tzinfo=None)
  92. attendances = self.env['hr.attendance'].search([
  93. ('employee_id', '=', employee.id),
  94. ('check_in', '<=', now),
  95. '|', ('check_out', '>=', start_naive), ('check_out', '=', False),
  96. ])
  97. worked_hours = 0
  98. for attendance in attendances:
  99. delta = (attendance.check_out or now) - max(attendance.check_in, start_naive)
  100. worked_hours += delta.total_seconds() / 3600.0
  101. employee.hours_today = worked_hours
  102. @api.depends('attendance_ids')
  103. def _compute_last_attendance_id(self):
  104. for employee in self:
  105. employee.last_attendance_id = self.env['hr.attendance'].search([
  106. ('employee_id', '=', employee.id),
  107. ], limit=1)
  108. @api.depends('last_attendance_id.check_in', 'last_attendance_id.check_out', 'last_attendance_id')
  109. def _compute_attendance_state(self):
  110. for employee in self:
  111. att = employee.last_attendance_id.sudo()
  112. employee.attendance_state = att and not att.check_out and 'checked_in' or 'checked_out'
  113. @api.model
  114. def attendance_scan(self, barcode):
  115. """ Receive a barcode scanned from the Kiosk Mode and change the attendances of corresponding employee.
  116. Returns either an action or a warning.
  117. """
  118. employee = self.sudo().search([('barcode', '=', barcode)], limit=1)
  119. if employee:
  120. return employee._attendance_action('hr_attendance.hr_attendance_action_kiosk_mode')
  121. return {'warning': _("No employee corresponding to Badge ID '%(barcode)s.'") % {'barcode': barcode}}
  122. def attendance_manual(self, next_action, entered_pin=None):
  123. self.ensure_one()
  124. attendance_user_and_no_pin = self.user_has_groups(
  125. 'hr_attendance.group_hr_attendance_user,'
  126. '!hr_attendance.group_hr_attendance_use_pin')
  127. can_check_without_pin = attendance_user_and_no_pin or (self.user_id == self.env.user and entered_pin is None)
  128. if can_check_without_pin or entered_pin is not None and entered_pin == self.sudo().pin:
  129. return self._attendance_action(next_action)
  130. if not self.user_has_groups('hr_attendance.group_hr_attendance_user'):
  131. return {'warning': _('To activate Kiosk mode without pin code, you must have access right as an Officer or above in the Attendance app. Please contact your administrator.')}
  132. return {'warning': _('Wrong PIN')}
  133. def _attendance_action(self, next_action):
  134. """ Changes the attendance of the employee.
  135. Returns an action to the check in/out message,
  136. next_action defines which menu the check in/out message should return to. ("My Attendances" or "Kiosk Mode")
  137. """
  138. self.ensure_one()
  139. employee = self.sudo()
  140. action_message = self.env["ir.actions.actions"]._for_xml_id("hr_attendance.hr_attendance_action_greeting_message")
  141. 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
  142. action_message['employee_name'] = employee.name
  143. action_message['barcode'] = employee.barcode
  144. action_message['next_action'] = next_action
  145. action_message['hours_today'] = employee.hours_today
  146. action_message['kiosk_delay'] = employee.company_id.attendance_kiosk_delay * 1000
  147. if employee.user_id:
  148. modified_attendance = employee.with_user(employee.user_id).sudo()._attendance_action_change()
  149. else:
  150. modified_attendance = employee._attendance_action_change()
  151. action_message['attendance'] = modified_attendance.read()[0]
  152. action_message['total_overtime'] = employee.total_overtime
  153. # Overtime have an unique constraint on the day, no need for limit=1
  154. action_message['overtime_today'] = self.env['hr.attendance.overtime'].sudo().search([
  155. ('employee_id', '=', employee.id), ('date', '=', fields.Date.context_today(self)), ('adjustment', '=', False)]).duration or 0
  156. return {'action': action_message}
  157. def _attendance_action_change(self):
  158. """ Check In/Check Out action
  159. Check In: create a new attendance record
  160. Check Out: modify check_out field of appropriate attendance record
  161. """
  162. self.ensure_one()
  163. action_date = fields.Datetime.now()
  164. if self.attendance_state != 'checked_in':
  165. vals = {
  166. 'employee_id': self.id,
  167. 'check_in': action_date,
  168. }
  169. return self.env['hr.attendance'].create(vals)
  170. attendance = self.env['hr.attendance'].search([('employee_id', '=', self.id), ('check_out', '=', False)], limit=1)
  171. if attendance:
  172. attendance.check_out = action_date
  173. else:
  174. raise exceptions.UserError(_('Cannot perform check out on %(empl_name)s, could not find corresponding check in. '
  175. 'Your attendances have probably been modified manually by human resources.') % {'empl_name': self.sudo().name, })
  176. return attendance
  177. @api.model
  178. def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
  179. if 'pin' in groupby or 'pin' in self.env.context.get('group_by', '') or self.env.context.get('no_group_by'):
  180. raise exceptions.UserError(_('Such grouping is not allowed.'))
  181. return super(HrEmployee, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
  182. def _compute_presence_icon(self):
  183. res = super()._compute_presence_icon()
  184. # All employee must chek in or check out. Everybody must have an icon
  185. self.filtered(lambda employee: not employee.show_hr_icon_display).show_hr_icon_display = True
  186. return res