367 lines
15 KiB
Python
367 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
|
# Copyright 2026 Nexa Systems Inc.
|
|
# License OPL-1 (Odoo Proprietary License v1.0)
|
|
|
|
import math
|
|
import logging
|
|
from datetime import datetime, timedelta
|
|
from odoo import http, fields, _
|
|
from odoo.http import request
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
|
|
def haversine_distance(lat1, lon1, lat2, lon2):
|
|
"""Calculate the great-circle distance between two points on Earth (in meters)."""
|
|
R = 6371000 # Earth radius in meters
|
|
phi1 = math.radians(lat1)
|
|
phi2 = math.radians(lat2)
|
|
delta_phi = math.radians(lat2 - lat1)
|
|
delta_lambda = math.radians(lon2 - lon1)
|
|
|
|
a = (math.sin(delta_phi / 2) ** 2
|
|
+ math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2)
|
|
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
|
|
return R * c
|
|
|
|
|
|
class FusionClockAPI(http.Controller):
|
|
"""JSON API endpoints for Fusion Clock operations."""
|
|
|
|
def _get_employee(self):
|
|
"""Get the current user's employee record."""
|
|
user = request.env.user
|
|
employee = request.env['hr.employee'].sudo().search([
|
|
('user_id', '=', user.id),
|
|
], limit=1)
|
|
return employee
|
|
|
|
def _get_locations_for_employee(self, employee):
|
|
"""Get all clock locations available to this employee."""
|
|
Location = request.env['fusion.clock.location'].sudo()
|
|
locations = Location.search([
|
|
('active', '=', True),
|
|
('company_id', '=', employee.company_id.id),
|
|
])
|
|
# Filter: all_employees OR employee in employee_ids
|
|
result = locations.filtered(
|
|
lambda loc: loc.all_employees or employee.id in loc.employee_ids.ids
|
|
)
|
|
return result
|
|
|
|
def _verify_location(self, latitude, longitude, employee):
|
|
"""Verify if GPS coordinates are within any allowed geofence.
|
|
|
|
Returns (location_record, distance, error_detail) tuple.
|
|
"""
|
|
locations = self._get_locations_for_employee(employee)
|
|
|
|
if not locations:
|
|
return False, 0, 'no_locations'
|
|
|
|
geocoded = locations.filtered(lambda l: l.latitude is not None and l.longitude is not None
|
|
and not (l.latitude == 0.0 and l.longitude == 0.0))
|
|
if not geocoded:
|
|
return False, 0, 'no_geocoded'
|
|
|
|
nearest_location = False
|
|
nearest_distance = float('inf')
|
|
|
|
for loc in geocoded:
|
|
dist = haversine_distance(latitude, longitude, loc.latitude, loc.longitude)
|
|
if dist <= loc.radius:
|
|
return loc, dist, None
|
|
if dist < nearest_distance:
|
|
nearest_distance = dist
|
|
nearest_location = loc
|
|
|
|
return False, nearest_distance, 'outside'
|
|
|
|
def _location_error_message(self, error_type, distance=0):
|
|
"""Return a user-friendly error message based on the location check result."""
|
|
if error_type == 'no_locations':
|
|
return 'No clock locations configured. Ask your manager to set up locations in Fusion Clock > Locations.'
|
|
elif error_type == 'no_geocoded':
|
|
return 'Clock locations exist but have no GPS coordinates. Ask your manager to geocode them.'
|
|
else:
|
|
dist_str = f"{int(distance)}m" if distance < 1000 else f"{distance/1000:.1f}km"
|
|
return f'You are {dist_str} away from the nearest clock location.'
|
|
|
|
def _get_scheduled_times(self, employee, date):
|
|
"""Get scheduled clock-in and clock-out datetime for an employee on a date."""
|
|
ICP = request.env['ir.config_parameter'].sudo()
|
|
clock_in_hour = float(ICP.get_param('fusion_clock.default_clock_in_time', '9.0'))
|
|
clock_out_hour = float(ICP.get_param('fusion_clock.default_clock_out_time', '17.0'))
|
|
|
|
# Convert float hours to time
|
|
in_h = int(clock_in_hour)
|
|
in_m = int((clock_in_hour - in_h) * 60)
|
|
out_h = int(clock_out_hour)
|
|
out_m = int((clock_out_hour - out_h) * 60)
|
|
|
|
scheduled_in = datetime.combine(date, datetime.min.time().replace(hour=in_h, minute=in_m))
|
|
scheduled_out = datetime.combine(date, datetime.min.time().replace(hour=out_h, minute=out_m))
|
|
|
|
return scheduled_in, scheduled_out
|
|
|
|
def _check_and_create_penalty(self, employee, attendance, penalty_type, scheduled_dt, actual_dt):
|
|
"""Check if a penalty should be created and create it if needed."""
|
|
ICP = request.env['ir.config_parameter'].sudo()
|
|
if ICP.get_param('fusion_clock.enable_penalties', 'True') != 'True':
|
|
return
|
|
|
|
grace = float(ICP.get_param('fusion_clock.penalty_grace_minutes', '5'))
|
|
diff_minutes = abs((actual_dt - scheduled_dt).total_seconds()) / 60.0
|
|
|
|
should_penalize = False
|
|
if penalty_type == 'late_in' and actual_dt > scheduled_dt:
|
|
should_penalize = diff_minutes > grace
|
|
elif penalty_type == 'early_out' and actual_dt < scheduled_dt:
|
|
should_penalize = diff_minutes > grace
|
|
|
|
if should_penalize:
|
|
request.env['fusion.clock.penalty'].sudo().create({
|
|
'attendance_id': attendance.id,
|
|
'employee_id': employee.id,
|
|
'penalty_type': penalty_type,
|
|
'scheduled_time': scheduled_dt,
|
|
'actual_time': actual_dt,
|
|
'date': actual_dt.date() if isinstance(actual_dt, datetime) else fields.Date.today(),
|
|
})
|
|
|
|
def _apply_break_deduction(self, attendance, employee):
|
|
"""Apply automatic break deduction if configured."""
|
|
ICP = request.env['ir.config_parameter'].sudo()
|
|
auto_deduct = ICP.get_param('fusion_clock.auto_deduct_break', 'True')
|
|
if auto_deduct != 'True':
|
|
return
|
|
|
|
threshold = float(ICP.get_param('fusion_clock.break_threshold_hours', '5.0'))
|
|
worked = attendance.worked_hours or 0.0
|
|
|
|
if worked >= threshold:
|
|
break_min = employee._get_fclk_break_minutes()
|
|
attendance.sudo().write({'x_fclk_break_minutes': break_min})
|
|
|
|
# -------------------------------------------------------------------------
|
|
# API Endpoints
|
|
# -------------------------------------------------------------------------
|
|
|
|
@http.route('/fusion_clock/verify_location', type='jsonrpc', auth='user', methods=['POST'])
|
|
def verify_location(self, latitude=0, longitude=0, accuracy=0, **kw):
|
|
"""Verify if the user's GPS position is within a valid geofence."""
|
|
employee = self._get_employee()
|
|
if not employee:
|
|
return {'error': 'No employee record found for current user.'}
|
|
|
|
location, distance, err = self._verify_location(latitude, longitude, employee)
|
|
|
|
if location:
|
|
return {
|
|
'allowed': True,
|
|
'location_id': location.id,
|
|
'location_name': location.name,
|
|
'location_address': location.address or '',
|
|
'distance': round(distance, 1),
|
|
'radius': location.radius,
|
|
}
|
|
else:
|
|
msg = self._location_error_message(err, distance)
|
|
return {
|
|
'allowed': False,
|
|
'nearest_distance': round(distance, 1) if distance != float('inf') else None,
|
|
'message': msg,
|
|
'error_type': err,
|
|
}
|
|
|
|
@http.route('/fusion_clock/clock_action', type='jsonrpc', auth='user', methods=['POST'])
|
|
def clock_action(self, latitude=0, longitude=0, accuracy=0, source='portal', **kw):
|
|
"""Perform clock-in or clock-out action."""
|
|
employee = self._get_employee()
|
|
if not employee:
|
|
return {'error': 'No employee record found for current user.'}
|
|
|
|
if not employee.x_fclk_enable_clock:
|
|
return {'error': 'Fusion Clock is not enabled for your account.'}
|
|
|
|
# Server-side location verification
|
|
location, distance, err = self._verify_location(latitude, longitude, employee)
|
|
if not location:
|
|
return {
|
|
'error': self._location_error_message(err, distance),
|
|
'allowed': False,
|
|
'error_type': err,
|
|
}
|
|
|
|
# Determine if clocking in or out
|
|
is_checked_in = employee.attendance_state == 'checked_in'
|
|
now = fields.Datetime.now()
|
|
today = now.date()
|
|
|
|
geo_info = {
|
|
'latitude': latitude,
|
|
'longitude': longitude,
|
|
'browser': kw.get('browser', ''),
|
|
'ip_address': kw.get('ip_address', ''),
|
|
}
|
|
|
|
try:
|
|
if not is_checked_in:
|
|
# CLOCK IN
|
|
attendance = employee.sudo()._attendance_action_change(geo_info)
|
|
attendance.sudo().write({
|
|
'x_fclk_location_id': location.id,
|
|
'x_fclk_in_distance': round(distance, 1),
|
|
'x_fclk_clock_source': source,
|
|
})
|
|
|
|
# Check for late clock-in penalty
|
|
scheduled_in, _ = self._get_scheduled_times(employee, today)
|
|
self._check_and_create_penalty(employee, attendance, 'late_in', scheduled_in, now)
|
|
|
|
return {
|
|
'success': True,
|
|
'action': 'clock_in',
|
|
'attendance_id': attendance.id,
|
|
'check_in': fields.Datetime.to_string(attendance.check_in),
|
|
'location_name': location.name,
|
|
'message': f'Clocked in at {location.name}',
|
|
}
|
|
|
|
else:
|
|
# CLOCK OUT
|
|
attendance = employee.sudo()._attendance_action_change(geo_info)
|
|
attendance.sudo().write({
|
|
'x_fclk_out_location_id': location.id,
|
|
'x_fclk_out_distance': round(distance, 1),
|
|
})
|
|
|
|
# Apply break deduction
|
|
self._apply_break_deduction(attendance, employee)
|
|
|
|
# Check for early clock-out penalty
|
|
_, scheduled_out = self._get_scheduled_times(employee, today)
|
|
self._check_and_create_penalty(employee, attendance, 'early_out', scheduled_out, now)
|
|
|
|
return {
|
|
'success': True,
|
|
'action': 'clock_out',
|
|
'attendance_id': attendance.id,
|
|
'check_in': fields.Datetime.to_string(attendance.check_in),
|
|
'check_out': fields.Datetime.to_string(attendance.check_out),
|
|
'worked_hours': round(attendance.worked_hours or 0, 2),
|
|
'net_hours': round(attendance.x_fclk_net_hours or 0, 2),
|
|
'break_minutes': attendance.x_fclk_break_minutes,
|
|
'location_name': location.name,
|
|
'message': f'Clocked out from {location.name}',
|
|
}
|
|
|
|
except Exception as e:
|
|
_logger.error("Fusion Clock error: %s", str(e))
|
|
return {'error': str(e)}
|
|
|
|
@http.route('/fusion_clock/get_status', type='jsonrpc', auth='user', methods=['POST'])
|
|
def get_status(self, **kw):
|
|
"""Get current clock status for the authenticated user."""
|
|
employee = self._get_employee()
|
|
if not employee:
|
|
return {'error': 'No employee record found for current user.'}
|
|
|
|
is_checked_in = employee.attendance_state == 'checked_in'
|
|
|
|
result = {
|
|
'is_checked_in': is_checked_in,
|
|
'employee_name': employee.name,
|
|
'enable_clock': employee.x_fclk_enable_clock,
|
|
}
|
|
|
|
if is_checked_in:
|
|
# Find the open attendance
|
|
att = request.env['hr.attendance'].sudo().search([
|
|
('employee_id', '=', employee.id),
|
|
('check_out', '=', False),
|
|
], limit=1)
|
|
if att:
|
|
result.update({
|
|
'attendance_id': att.id,
|
|
'check_in': fields.Datetime.to_string(att.check_in),
|
|
'location_name': att.x_fclk_location_id.name or '',
|
|
'location_id': att.x_fclk_location_id.id or False,
|
|
})
|
|
|
|
# Today's stats
|
|
today_start = fields.Datetime.to_string(
|
|
datetime.combine(fields.Date.today(), datetime.min.time())
|
|
)
|
|
today_atts = request.env['hr.attendance'].sudo().search([
|
|
('employee_id', '=', employee.id),
|
|
('check_in', '>=', today_start),
|
|
('check_out', '!=', False),
|
|
])
|
|
result['today_hours'] = round(sum(a.x_fclk_net_hours or 0 for a in today_atts), 2)
|
|
|
|
# This week stats
|
|
today = fields.Date.today()
|
|
week_start = today - timedelta(days=today.weekday())
|
|
week_start_dt = fields.Datetime.to_string(
|
|
datetime.combine(week_start, datetime.min.time())
|
|
)
|
|
week_atts = request.env['hr.attendance'].sudo().search([
|
|
('employee_id', '=', employee.id),
|
|
('check_in', '>=', week_start_dt),
|
|
('check_out', '!=', False),
|
|
])
|
|
result['week_hours'] = round(sum(a.x_fclk_net_hours or 0 for a in week_atts), 2)
|
|
|
|
# Recent activity (last 10)
|
|
recent = request.env['hr.attendance'].sudo().search([
|
|
('employee_id', '=', employee.id),
|
|
('check_out', '!=', False),
|
|
], order='check_in desc', limit=10)
|
|
result['recent_activity'] = [{
|
|
'id': a.id,
|
|
'check_in': fields.Datetime.to_string(a.check_in),
|
|
'check_out': fields.Datetime.to_string(a.check_out),
|
|
'worked_hours': round(a.worked_hours or 0, 2),
|
|
'net_hours': round(a.x_fclk_net_hours or 0, 2),
|
|
'location': a.x_fclk_location_id.name or '',
|
|
} for a in recent]
|
|
|
|
return result
|
|
|
|
@http.route('/fusion_clock/get_locations', type='jsonrpc', auth='user', methods=['POST'])
|
|
def get_locations(self, **kw):
|
|
"""Get all available clock locations for the current user."""
|
|
employee = self._get_employee()
|
|
if not employee:
|
|
return {'error': 'No employee record found for current user.'}
|
|
|
|
locations = self._get_locations_for_employee(employee)
|
|
default_id = employee.x_fclk_default_location_id.id if employee.x_fclk_default_location_id else False
|
|
|
|
return {
|
|
'locations': [{
|
|
'id': loc.id,
|
|
'name': loc.name,
|
|
'address': loc.address or '',
|
|
'latitude': loc.latitude,
|
|
'longitude': loc.longitude,
|
|
'radius': loc.radius,
|
|
'is_default': loc.id == default_id,
|
|
} for loc in locations],
|
|
'default_location_id': default_id,
|
|
}
|
|
|
|
@http.route('/fusion_clock/get_settings', type='jsonrpc', auth='user', methods=['POST'])
|
|
def get_settings(self, **kw):
|
|
"""Get Fusion Clock settings for the frontend."""
|
|
ICP = request.env['ir.config_parameter'].sudo()
|
|
return {
|
|
'enable_sounds': ICP.get_param('fusion_clock.enable_sounds', 'True') == 'True',
|
|
'google_maps_api_key': ICP.get_param('fusion_clock.google_maps_api_key', ''),
|
|
'default_clock_in': float(ICP.get_param('fusion_clock.default_clock_in_time', '9.0')),
|
|
'default_clock_out': float(ICP.get_param('fusion_clock.default_clock_out_time', '17.0')),
|
|
'target_daily_hours': 8.0,
|
|
'target_weekly_hours': 40.0,
|
|
}
|