Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

calculate late using Odoo studio

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
hr
2 Respuestas
1886 Vistas
Avatar
Mohamed Kandil

I want to calculate Late time in attendance

Late: If an employee comes after scheduled time then that count in late

how can I do it by studio /Odoo 17?

0
Avatar
Descartar
Avatar
Mohamed Kandil
Autor Mejor respuesta

I made a module with this code but the

scheduled_check_in  get null
from odoo import models, fields, api
from datetime import datetime

class HrAttendance(models.Model):
_inherit = 'hr.attendance'

# Make scheduled_check_in editable
scheduled_check_in = fields.Datetime(string="Scheduled Check-In", default=lambda self: self._default_scheduled_check_in())
late_minutes = fields.Integer(string="Late Minutes", compute="_compute_late_minutes", store=True)

def _default_scheduled_check_in(self):
"""
Automatically populate scheduled_check_in based on the employee's work schedule.
"""
if self.employee_id and self.employee_id.resource_calendar_id and self.check_in:
calendar = self.employee_id.resource_calendar_id
check_in_date = fields.Datetime.to_datetime(self.check_in).date()

# Get the work intervals for the check-in date
work_intervals = calendar._work_intervals_batch(
datetime.combine(check_in_date, datetime.min.time()),
datetime.combine(check_in_date, datetime.max.time()),
resources=self.employee_id.resource_id,
)

if work_intervals and self.employee_id.resource_id in work_intervals:
# Get the start time of the first work interval
return work_intervals[self.employee_id.resource_id][0][0]
return False

@api.depends('check_in', 'scheduled_check_in')
def _compute_late_minutes(self):
"""
Compute late_minutes as the difference between check_in and scheduled_check_in in whole minutes.
"""
for record in self:
if record.check_in and record.scheduled_check_in:
check_in_time = fields.Datetime.to_datetime(record.check_in)
scheduled_time = fields.Datetime.to_datetime(record.scheduled_check_in)

# Ensure both times are in the same timezone (if necessary)
check_in_time = check_in_time.replace(tzinfo=None)
scheduled_time = scheduled_time.replace(tzinfo=None)

if check_in_time > scheduled_time:
delta = check_in_time - scheduled_time
# Convert total seconds to minutes and round to the nearest integer
record.late_minutes = round(delta.total_seconds() / 60)
else:
record.late_minutes = 0
else:
record.late_minutes = 0

@api.model
def create(self, vals):
"""
Automatically populate scheduled_check_in when creating a new attendance record.
"""
if 'scheduled_check_in' not in vals and vals.get('employee_id') and vals.get('check_in'):
employee = self.env['hr.employee'].browse(vals['employee_id'])
if employee.resource_calendar_id:
calendar = employee.resource_calendar_id
check_in_date = fields.Datetime.to_datetime(vals['check_in']).date()

# Get the work intervals for the check-in date
work_intervals = calendar._work_intervals_batch(
datetime.combine(check_in_date, datetime.min.time()),
datetime.combine(check_in_date, datetime.max.time()),
resources=employee.resource_id,
)

if work_intervals and employee.resource_id in work_intervals:
# Get the start time of the first work interval
vals['scheduled_check_in'] = work_intervals[employee.resource_id][0][0]
return super(HrAttendance, self).create(vals)
0
Avatar
Descartar
Avatar
Hemangini Patel
Mejor respuesta

The attendance data is typically tracked in the hr.attendance model, and the scheduled working time is often linked to the resource.calendar or resource.calendar.attendance model.

  • hr.attendance: Tracks employee check-in and check-out times.
  • resource.calendar: Defines the working schedule for employees.

Steps to Configure in Studio

Step 1: Add a Field for "Late Time"
  1. Go to Studio.
  2. Open the Attendance (hr.attendance) model.
  3. Add a new computed field (e.g., Late Time) with the following configuration:
    • Field Name: x_late_time
    • Type: Float (or Integer for minutes)
    • Label: "Late Time (Minutes)"
    • Computation Logic: Use Python code.
Step 2: Write the Computation Logic

You can use the Odoo Studio computation editor or define the logic via Python. For Studio, you need to approximate it as follows:

if record.check_in: # Get the scheduled start time from the resource calendar scheduled_start = record.employee_id.resource_calendar_id.attendance_ids.filtered( lambda a: a.dayofweek == str(record.check_in.weekday()) ).mapped('hour_from') if scheduled_start: scheduled_start_time = record.check_in.replace( hour=int(scheduled_start[0]), minute=int((scheduled_start[0] % 1) * 60) ) if record.check_in > scheduled_start_time: late_minutes = (record.check_in - scheduled_start_time).total_seconds() / 60 result = late_minutes else: result = 0 else: result = 0

Step 3: Save the Changes

Once the computation is added, save and test the field.

Add a Filter for "Late Employees"
  1. In Studio, create a new filter for records where x_late_time > 0.
  2. This will allow you to easily see employees who were late.
0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
[{(!!@Nombre~LAN~Colombia#)}] ¿Cómo se llama Avianca en Colombia?
hr
Avatar
0
dic 25
5
Implementing HR Module? Resuelto
hr
Avatar
Avatar
1
nov 25
553
gratis trainingssessies
hr
Avatar
0
nov 25
6
Attendance Analysis – How to calculate Extra Hours with flexible start times
hr
Avatar
Avatar
2
oct 25
1111
block other users from editing a survey
hr
Avatar
Avatar
1
oct 25
930
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Sitio web hecho con

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now