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

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
2301 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.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Ya es posible hacer Upgrade de v17 a v17.1 ?
v17
Avatar
Avatar
1
oct 25
1307
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
2370
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
1256
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.

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