Initial commit

This commit is contained in:
gsinghpal
2026-02-22 01:22:18 -05:00
commit 5200d5baf0
2394 changed files with 386834 additions and 0 deletions

View File

@@ -0,0 +1,4 @@
# -*- coding: utf-8 -*-
from . import portal_clock
from . import clock_api

View File

@@ -0,0 +1,366 @@
# -*- 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,
}

View File

@@ -0,0 +1,263 @@
# -*- coding: utf-8 -*-
# Copyright 2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)
import base64
import json
import logging
from datetime import datetime, timedelta
from odoo import http, fields, _
from odoo.http import request
from odoo.addons.portal.controllers.portal import CustomerPortal
_logger = logging.getLogger(__name__)
class FusionClockPortal(CustomerPortal):
"""Portal controller for Fusion Clock pages."""
def _prepare_portal_layout_values(self):
"""Inject clock FAB data into every portal page context."""
values = super()._prepare_portal_layout_values()
employee = self._get_portal_employee()
if employee and employee.x_fclk_enable_clock:
is_checked_in = employee.attendance_state == 'checked_in'
check_in_time = ''
location_name = ''
if is_checked_in:
att = request.env['hr.attendance'].sudo().search([
('employee_id', '=', employee.id),
('check_out', '=', False),
], limit=1)
if att:
check_in_time = att.check_in.isoformat() if att.check_in else ''
location_name = att.x_fclk_location_id.name if att.x_fclk_location_id else ''
values.update({
'fclk_employee': employee,
'fclk_checked_in': is_checked_in,
'fclk_check_in_time': check_in_time,
'fclk_location_name': location_name,
})
else:
values['fclk_employee'] = False
return values
def _prepare_home_portal_values(self, counters):
"""Add clock counters to the portal home page."""
values = super()._prepare_home_portal_values(counters)
if 'clock_count' in counters:
employee = self._get_portal_employee()
if employee:
today_start = datetime.combine(fields.Date.today(), datetime.min.time())
count = request.env['hr.attendance'].sudo().search_count([
('employee_id', '=', employee.id),
('check_in', '>=', today_start),
])
values['clock_count'] = count
return values
def _get_portal_employee(self):
"""Get the employee record for the current portal/internal user."""
user = request.env.user
employee = request.env['hr.employee'].sudo().search([
('user_id', '=', user.id),
], limit=1)
return employee
# =========================================================================
# Clock Page
# =========================================================================
@http.route('/my/clock', type='http', auth='user', website=True)
def portal_clock(self, **kw):
"""Main clock-in/out portal page."""
employee = self._get_portal_employee()
if not employee:
return request.redirect('/my')
ICP = request.env['ir.config_parameter'].sudo()
google_maps_key = ICP.get_param('fusion_clock.google_maps_api_key', '')
enable_sounds = ICP.get_param('fusion_clock.enable_sounds', 'True') == 'True'
# Get locations
Location = request.env['fusion.clock.location'].sudo()
locations = Location.search([
('active', '=', True),
('company_id', '=', employee.company_id.id),
])
locations = locations.filtered(
lambda loc: loc.all_employees or employee.id in loc.employee_ids.ids
)
# Current attendance status
is_checked_in = employee.attendance_state == 'checked_in'
current_attendance = False
if is_checked_in:
current_attendance = request.env['hr.attendance'].sudo().search([
('employee_id', '=', employee.id),
('check_out', '=', False),
], limit=1)
# Today stats
today_start = 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),
])
today_hours = sum(a.x_fclk_net_hours or 0 for a in today_atts)
# Week stats
today = fields.Date.today()
week_start = today - timedelta(days=today.weekday())
week_start_dt = 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),
])
week_hours = sum(a.x_fclk_net_hours or 0 for a in week_atts)
# Recent activity
recent = request.env['hr.attendance'].sudo().search([
('employee_id', '=', employee.id),
('check_out', '!=', False),
], order='check_in desc', limit=10)
# Prepare locations JSON for JS
locations_json = json.dumps([{
'id': loc.id,
'name': loc.name,
'address': loc.address or '',
'latitude': loc.latitude,
'longitude': loc.longitude,
'radius': loc.radius,
} for loc in locations])
values = {
'employee': employee,
'locations': locations,
'is_checked_in': is_checked_in,
'current_attendance': current_attendance,
'today_hours': round(today_hours, 1),
'week_hours': round(week_hours, 1),
'recent_attendances': recent,
'google_maps_key': google_maps_key,
'enable_sounds': enable_sounds,
'locations_json': locations_json,
'page_name': 'clock',
}
return request.render('fusion_clock.portal_clock_page', values)
# =========================================================================
# Timesheet Page
# =========================================================================
@http.route('/my/clock/timesheets', type='http', auth='user', website=True)
def portal_timesheets(self, period='current', **kw):
"""Read-only timesheet view."""
employee = self._get_portal_employee()
if not employee:
return request.redirect('/my')
ICP = request.env['ir.config_parameter'].sudo()
schedule_type = ICP.get_param('fusion_clock.pay_period_type', 'biweekly')
period_start_str = ICP.get_param('fusion_clock.pay_period_start', '')
today = fields.Date.today()
# Calculate period dates
FusionReport = request.env['fusion.clock.report'].sudo()
period_start, period_end = FusionReport._calculate_current_period(
schedule_type, period_start_str, today
)
if period == 'last':
# Go back one period
if schedule_type == 'weekly':
period_start -= timedelta(days=7)
period_end -= timedelta(days=7)
elif schedule_type == 'biweekly':
period_start -= timedelta(days=14)
period_end -= timedelta(days=14)
elif schedule_type == 'monthly':
from dateutil.relativedelta import relativedelta
period_start -= relativedelta(months=1)
period_end = period_start.replace(day=28) + timedelta(days=4)
period_end -= timedelta(days=period_end.day)
else:
period_start -= timedelta(days=14)
period_end -= timedelta(days=14)
# Get attendance records
attendances = request.env['hr.attendance'].sudo().search([
('employee_id', '=', employee.id),
('check_in', '>=', datetime.combine(period_start, datetime.min.time())),
('check_in', '<', datetime.combine(period_end + timedelta(days=1), datetime.min.time())),
], order='check_in desc')
total_hours = sum(a.worked_hours or 0 for a in attendances if a.check_out)
net_hours = sum(a.x_fclk_net_hours or 0 for a in attendances if a.check_out)
total_breaks = sum(a.x_fclk_break_minutes or 0 for a in attendances if a.check_out)
values = {
'employee': employee,
'attendances': attendances,
'period_start': period_start,
'period_end': period_end,
'period': period,
'schedule_type': schedule_type,
'total_hours': round(total_hours, 1),
'net_hours': round(net_hours, 1),
'total_breaks': round(total_breaks, 0),
'page_name': 'timesheets',
}
return request.render('fusion_clock.portal_timesheet_page', values)
# =========================================================================
# Reports Page
# =========================================================================
@http.route('/my/clock/reports', type='http', auth='user', website=True)
def portal_reports(self, **kw):
"""View and download attendance reports."""
employee = self._get_portal_employee()
if not employee:
return request.redirect('/my')
reports = request.env['fusion.clock.report'].sudo().search([
('employee_id', '=', employee.id),
('state', 'in', ['generated', 'sent']),
], order='date_end desc')
values = {
'employee': employee,
'reports': reports,
'page_name': 'clock_reports',
}
return request.render('fusion_clock.portal_report_page', values)
@http.route('/my/clock/reports/<int:report_id>/download', type='http', auth='user', website=True)
def portal_report_download(self, report_id, **kw):
"""Download a specific report PDF."""
employee = self._get_portal_employee()
if not employee:
return request.redirect('/my')
report = request.env['fusion.clock.report'].sudo().browse(report_id)
if not report.exists() or report.employee_id.id != employee.id:
return request.redirect('/my/clock/reports')
if not report.report_pdf:
return request.redirect('/my/clock/reports')
pdf_data = base64.b64decode(report.report_pdf)
filename = report.report_pdf_filename or f"report_{report.id}.pdf"
return request.make_response(
pdf_data,
headers=[
('Content-Type', 'application/pdf'),
('Content-Disposition', f'attachment; filename="{filename}"'),
],
)