Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • eLearning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Browse all Industries
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Services for Partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar 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
  • Proyecto
  • 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

Call a field value from hr_employee to hr_attendance?

Suscribirse

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

Se marcó esta pregunta
hremployeeattendanceinheritodoo8.0
7977 Vistas
Avatar
Uppili Arivukkannu

I'm trying to get hours base salary based on sign in and sign out data from attendance.

Now I'm getting hours based salary based on the worked hours from hr attendance.

I given the salary or wage as default value so it gives the value based on the default value.

Each employee has different salary so I have created a field named salary in employee.



class hr_employee(osv.osv):

_name = "hr.employee"

_description = "Employee"

_order = 'name_related'

_inherits = {'resource.resource': "resource_id"}

_inherit = ['mail.thread']

_mail_post_access = 'read'

def _get_image(self, cr, uid, ids, name, args, context=None):

result = dict.fromkeys(ids, False)

for obj in self.browse(cr, uid, ids, context=context):

result[obj.id] = tools.image_get_resized_images(obj.image)

return result

def _set_image(self, cr, uid, id, name, value, args, context=None):

return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)

_columns = {

#we need a related field in order to be able to sort the employee by name

'name_related': fields.related('resource_id', 'name', type='char', string='Name', readonly=True, store=True),

'country_id': fields.many2one('res.country', 'Nationality'),

'birthday': fields.date("Date of Birth"),

'ssnid': fields.char('SSN No', help='Social Security Number'),

'sinid': fields.char('SIN No', help="Social Insurance Number"),

'identification_id': fields.char('Identification No'),

'otherid': fields.char('Other Id'),

'gender': fields.selection([('male', 'Male'), ('female', 'Female')], 'Gender'),

'marital': fields.selection([('single', 'Single'), ('married', 'Married'), ('widower', 'Widower'), ('divorced', 'Divorced')], 'Marital Status'),

'department_id': fields.many2one('hr.department', 'Department'),

'address_id': fields.many2one('res.partner', 'Working Address'),

'address_home_id': fields.many2one('res.partner', 'Home Address'),

'bank_account_id': fields.many2one('res.partner.bank', 'Bank Account Number', domain="[('partner_id','=',address_home_id)]", help="Employee bank salary account"),

'work_phone': fields.char('Work Phone', readonly=False),

'mobile_phone': fields.char('Work Mobile', readonly=False),

'work_email': fields.char('Work Email', size=240),

'work_location': fields.char('Office Location'),

'notes': fields.text('Notes'),

'parent_id': fields.many2one('hr.employee', 'Manager'),

'category_ids': fields.many2many('hr.employee.category', 'employee_category_rel', 'emp_id', 'category_id', 'Tags'),

'child_ids': fields.one2many('hr.employee', 'parent_id', 'Subordinates'),

'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True, auto_join=True),

'coach_id': fields.many2one('hr.employee', 'Coach'),

'job_id': fields.many2one('hr.job', 'Job Title'),

'salary': fields.float('Salary'),

# image: all image fields are base64 encoded and PIL-supported

'image': fields.binary("Photo",

help="This field holds the image used as photo for the employee, limited to 1024x1024px."),

'image_medium': fields.function(_get_image, fnct_inv=_set_image,

string="Medium-sized photo", type="binary", multi="_get_image",

store = {

'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),

},

help="Medium-sized photo of the employee. It is automatically "\

"resized as a 128x128px image, with aspect ratio preserved. "\

"Use this field in form views or some kanban views."),

'image_small': fields.function(_get_image, fnct_inv=_set_image,

string="Small-sized photo", type="binary", multi="_get_image",

store = {

'hr.employee': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),

},

help="Small-sized photo of the employee. It is automatically "\

"resized as a 64x64px image, with aspect ratio preserved. "\

"Use this field anywhere a small image is required."),

'passport_id': fields.char('Passport No'),

'color': fields.integer('Color Index'),

'city': fields.related('address_id', 'city', type='char', string='City'),

'login': fields.related('user_id', 'login', type='char', string='Login', readonly=1),

'last_login': fields.related('user_id', 'date', type='datetime', string='Latest Connection', readonly=1),

}


I want to call this salary to hr_attendance so that every employee salary is computed based on the salary given in the hr_employee.

My code is:



class hr_attendance(osv.osv):

_name = "hr.attendance"

_description = "Attendance"

def _worked_hours_compute(self, cr, uid, ids, fieldnames, args, context=None):

"""For each hr.attendance record of action sign-in: assign 0.

For each hr.attendance record of action sign-out: assign number of hours since last sign-in.

"""

res = {}

for obj in self.browse(cr, uid, ids, context=context):

if obj.action == 'sign_in':

res[obj.id] = 0

elif obj.action == 'sign_out':

# Get the associated sign-in

last_signin_id = self.search(cr, uid, [

('employee_id', '=', obj.employee_id.id),

('name', '<', obj.name), ('action', '=', 'sign_in')

], limit=1, order='name DESC')

if last_signin_id:

last_signin = self.browse(cr, uid, last_signin_id, context=context)[0]

# Compute time elapsed between sign-in and sign-out

last_signin_datetime = datetime.strptime(last_signin.name, '%Y-%m-%d %H:%M:%S')

signout_datetime = datetime.strptime(obj.name, '%Y-%m-%d %H:%M:%S')

workedhours_datetime = (signout_datetime - last_signin_datetime)

res[obj.id] = ((workedhours_datetime.seconds) / 60) / 60.0

else:

res[obj.id] = False

return res


def _per_hour_compute(self, cr, uid, ids, fieldnames, args, context=None):

res = {}

for obj in self.browse(cr, uid, ids, context=context):

if obj.action == 'sign_in':

res[obj.id] = 0

elif obj.action == 'sign_out': 

last_signin_id = self.search(cr, uid, [

('employee_id', '=', obj.employee_id.id),

('name', '<', obj.name), ('action', '=', 'sign_in')

], limit=1, order='name DESC')

salary_id = self.search(cr, uid, [('employee_id', '=', obj.employee_id.id), ('salary')], limit=1)

if last_signin_id:

last_signin = self.browse(cr, uid, last_signin_id, context=context)[0]

salary_ids = self.browse(cr, uid, salary_id, context=context)[0] 

per_hour_wage = float(salary_ids.salary)

last_signin_datetime = datetime.strptime(last_signin.name, '%Y-%m-%d %H:%M:%S')

signout_datetime = datetime.strptime(obj.name, '%Y-%m-%d %H:%M:%S')

workedhours_datetime = (signout_datetime - last_signin_datetime)

total_hours = (((workedhours_datetime.seconds) / 60) / 60.0)

total_hours1 = 9.00 - 0.50

if total_hours > 9.50 and total_hours < 12.00:

res[obj.id] = (total_hours1 + 1.00) * (per_hour_wage)

else:

res[obj.id] = (total_hours1) * (per_hour_wage)

if total_hours < 9.50:

res[obj.id] = (total_hours) * (per_hour_wage)

else:

res[obj.id] = False

return res


But it shows error as

ValidateError

Field(s) `action` failed against a constraint: Error ! Sign in (resp. Sign out) must follow Sign out (resp. Sign in)

Error details:

Invalid leaf salary.

So I tried to inherit hr.employee


class hr_attendance(osv.osv):

_name = "hr.attendance"

_description = "Attendance"

_inherit = "hr.employee"


But it shows error


Integrity Error

The operation cannot be completed, probably due to the following:

- deletion: you may be trying to delete a record while other records still reference it

- creation/update: a mandatory field is not correctly set

[object with reference: name - name]


How can I achieve this. I want to call a value of a field(salary) in hr_employee to hr_attendance to compute the salary(per_hour_wage)?

Give me some solutions



0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

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

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Despite correct terminal outputs, Odoo's frontend displays a different value of check-out hours (a TZ problem)
hr employee attendance timezones
Avatar
0
may 23
2884
Flexible Working Hours
hr employee payroll attendance working_time
Avatar
0
nov 23
80
I want to store attendance for whole month for all the employee. Resuelto
hr employee attendance gridview v12
Avatar
Avatar
1
dic 19
4245
Sync/Copy data between models in Odoo 8
hr on_change employee inherit applicants
Avatar
0
abr 17
4816
Connect fingerprint devices to Odoo Resuelto
hr attendance
Avatar
Avatar
1
may 25
2059
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información 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 totalmente integrado.

Website made with

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