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

add compute field to calculate employee loan amount

Suscribirse

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

Se marcó esta pregunta
computev17
1 Responder
2299 Vistas
Avatar
SmithJohn45

i have wrote 3 views which are used in below compute code, queries i tested on pgAdmin but i don't know why it is throwing error.

please help to resolve the issue, i am badly stuck here.

for rec in self:
    # clean_id = self._origin.id
    clean_id = 448 # BECAUSE above line throws error...
    req_date = rec.request_date
    query = """SELECT id, name, tenure_days, tenure_months, tenure_years FROM employee_tenure WHERE id = %s"""
    self.env.cr.execute(query, (clean_id,))
    result = self.env.cr.dictfetchall()
    #
    for row in result:
        if row.get('tenure_months') > 12:
            # get payslip line amount for rule_id 107
            query2 = """SELECT pl_amount FROM emp_pf_amount WHERE employee_id = %s"""
            self.env.cr.execute(query2, (clean_id,))
            result2 = self.env.cr.dictfetchall()
            x_amount = 0
            for pl_row in result2:
                x_amount = pl_row.get('pl_amount')
                rec['x_loan_applicable_amount'] = x_amount
            dt_string = req_date.strftime("%Y-%m-%d")
            dt1 = datetime.datetime.strptime(dt_string, "%Y-%m-%d")
            dt_month = dt1.month
            dt_month1 = '07'
            dt_date1 = '01'
            dt_month2 = '06'
            dt_date2 = '30'
            if dt_month in (7,8,9,10,11,12):
                dt_year1 = dt1.year
                dt_year2 = dt1.year + 1
            else:
                dt_year1 = dt1.year - 1
                dt_year2 = dt1.year

            dt_range = 'to_date(\''+dt_year1+'-'+dt_month1+'-'+dt_date1+'\','+'\'YYYY-MM-DD\''+') AND '+'to_date(\''+dt_year2+'-'+dt_month2+'-'+dt_date2+'\','+'\'YYYY-MM-DD\''+')'

            query3 = """SELECT emp_allocation_amount FROM emp_ann_leave_amount WHERE employee_id = %s AND date_from between %s"""
            self.env.cr.execute(query3, (clean_id, (dt_range,)))
            result3 = self.env.cr.dictfetchall()
            for pi_row in result3:
                x_amount += pi_row.get('pi_amount')
                rec['x_loan_applicable_amount'] = x_amount
        else:
            rec['x_loan_applicable_amount'] = 1


tested this here...


regards

0
Avatar
Descartar
SmithJohn45
Autor

i tested dt_range for syntax and it is showing as below:

to_date('2023-07-01','YYYY-MM-DD') AND to_date('2024-06-30','YYYY-MM-DD')

may be i am overlooking or something else, seniors experts please help to have working code.

regards

Avatar
SmithJohn45
Autor Mejor respuesta

i have managed, the code below is working fine. this is for juniors like me. just one thing i have work on which is clean_id , i have passed hard coded value because it is throwing error on the lines i have remarked.

for rec in self:

    # clean_id = rec.id

    # clean_id = self.id

    # clean_id = self._origin.id

    clean_id = 448

    req_date = rec.request_date

    query = """SELECT id, name, tenure_days, tenure_months, tenure_years FROM employee_tenure WHERE id = %s"""

    self.env.cr.execute(query, (clean_id,))

    result = self.env.cr.dictfetchall()

    # 

    for row in result:

        if row.get('tenure_months') > 12:

            # get payslip line amount for rule_id 107

            query2 = """SELECT pl_amount FROM emp_pf_amount WHERE employee_id = %s"""

            self.env.cr.execute(query2, (clean_id,))

            result2 = self.env.cr.dictfetchall()

            x_amount = 0

            for pl_row in result2:

                x_amount = pl_row.get('pl_amount')

                rec['x_loan_applicable_amount'] = x_amount

#

# get payslip input amount for rule_id 16

            # to create date_from and date_to from request_date year

            dt_string = req_date.strftime("%Y-%m-%d")

            dt1 = datetime.datetime.strptime(dt_string, "%Y-%m-%d")

            dt_month = dt1.month

            dt_month1 = '07'

            dt_date1 = '01'

            dt_month2 = '06'

            dt_date2 = '30'

            if dt_month in (7,8,9,10,11,12):

                dt_year1 = dt1.year

                dt_year2 = dt1.year + 1

            else:

                dt_year1 = dt1.year - 1

                dt_year2 = dt1.year

            dt_year1 = str(dt_year1)

            dt_year2 = str(dt_year2)

            # dt_range = 'to_date(\''+dt_year1+'-'+dt_month1+'-'+dt_date1+'\','+'\'YYYY-MM-DD\''+') AND '+'to_date(\''+dt_year2+'-'+dt_month2+'-'+dt_date2+'\','+'\'YYYY-MM-DD\''+')'

            dt_from = '\''+dt_year1+'-'+dt_month1+'-'+dt_date1+'\''

            dt_to = '\''+dt_year2+'-'+dt_month2+'-'+dt_date2+'\''

# query3 = """SELECT emp_allocation_amount FROM emp_ann_leave_amount WHERE employee_id = %s AND date_from between %s"""

            query3 = """SELECT emp_allocation_amount FROM emp_ann_leave_amount WHERE employee_id = %s AND date_from BETWEEN %s AND %s"""

            self.env.cr.execute(query3, (clean_id, dt_from, dt_to))

            result3 = self.env.cr.dictfetchall()

            for pi_row in result3:

                x_amount += pi_row.get('emp_allocation_amount')

                rec['x_loan_applicable_amount'] = x_amount

        else:

            rec['x_loan_applicable_amount'] = 1

happy coding.

regards

0
Avatar
Descartar
SmithJohn45
Autor

also the problem is resolved for clean_id which mentioned in my Answer above.

¿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
Ya es posible hacer Upgrade de v17 a v17.1 ?
v17
Avatar
Avatar
1
oct 25
1304
How to add a new Many2one field in res.config.settings? Resuelto
v17
Avatar
Avatar
Avatar
Avatar
4
oct 25
3697
Add field to ALL models in Odoo
v17
Avatar
Avatar
Avatar
2
sept 25
2366
How to disable Email notification - You have been assigned to Resuelto
v17
Avatar
Avatar
Avatar
Avatar
4
sept 25
7763
Selection Field Options Disappear from Database (PostgreSQL enum) on Module Upgrade
v17
Avatar
0
ago 25
1255
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