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

Help me with this code.

Suscribirse

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

Se marcó esta pregunta
codereview
2 Respuestas
2201 Vistas
Avatar
Jenish M

class PurchaseOrderInherit(models.Model):

     _inherit = "purchase.order.line"

     margin = fields.Float("Margin %", compute="_compute_margin",

inverse="_inverse_margin", digits='Product Price', store=True)

     mrp = fields.Float("MRP", help="Load from Product MRP(Latest)",

digits='Product Price')

     @api.onchange('product_id')

     def _compute_mrp(self):

         for rec in self:

             if rec.product_id:

                 rec.mrp = rec.product_id.lst_price

             else:

                 rec.mrp = False

     # Get Margin

     @api.depends("mrp", "product_qty", "price_subtotal", "product_id")

     def _compute_margin(self):

         for rec in self:

             if rec.mrp:

                 price_sub_mrp = self._get_tax_amount(rec.product_id,

rec.mrp)

                 margin = (price_sub_mrp * rec.product_qty) -

rec.price_subtotal

                 rec.margin = price_sub_mrp and margin / price_sub_mrp

             else:

                 rec.margin = False

     @api.onchange('margin')

     def _inverse_margin(self):

         for rec in self:

             if rec.order_id.mrp_updatable:

                 cost = rec.product_qty and rec.price_total /

rec.product_qty

                 rec.mrp = cost / (1 - rec.margin)

             else:

                 cost = rec.mrp * (1 - rec.margin)

                 cost_tax = self._get_tax_amount(rec.product_id, cost)

                 if rec.discount:

                     price_unit = cost_tax + cost_tax * (rec.discount / 100)

                 else:

                     price_unit = cost_tax

                 rec.price_unit = price_unit

     # Get price excluding tax amount

     def _get_tax_amount(self, product, price):

         taxes_id = product.taxes_id.filtered(

             lambda x: x.company_id.id == self.env.company.id

             or x.company_id.id == self.env.company.parent_id.id

         )

         if taxes_id:

             amount = taxes_id.compute_all(

                 price, product=product, partner=self.env["res.partner"]

             )

             amount = amount["total_excluded"]

         else:

             amount = price

         return amount

This is a custom code I have developed for purchase

It calculates the margin% for purchase and I have set a inverse method for margin so when ever I change the margin based on a Boolean(mrp_updateable) field it revere mrp or price_unit

But when I check this will results to some decimal point differences

If I change margin as 20 then when I save it shows 19.99 and if I change discount it changes price_unit

Can anyone review the code and help me

Thanks in advance..

0
Avatar
Descartar
Avatar
Jainesh Shah(Aktiv Software)
Mejor respuesta

Hello Mad Max ,

    

    The issue you are facing with the slight decimal point differences when changing the margin and saving 

    could be due to several factors such as precision errors in floating-point arithmetic or how Odoo handles rounding. 

    

    Here are a few steps to ensure your calculations are as precise as possible:


    1) Ensure Precision in Float Fields:

    Make sure the fields involved in the calculations (like margin, mrp, price_unit, etc.) have the appropriate precision.


    2) Use Rounding:

    Explicitly round your values to avoid precision issues when performing arithmetic operations.


    3) Refactor Calculation Logic:

    Ensure your calculation logic is consistent and uses precise arithmetic.


    Let's go through your code and make some adjustments to improve precision and clarity.


   //Code in comment//

   Hope this helps.

    

    If you need any help in customization feel free to contact us.


Thanks & Regards,


Email:  odoo@aktivsoftware.com           


Skype: kalpeshmaheshwari  

0
Avatar
Descartar
Jainesh Shah(Aktiv Software)

Code:

from odoo import api, fields, models
import math

class PurchaseOrderLineInherit(models.Model):
_inherit = "purchase.order.line"

margin = fields.Float("Margin %", compute="_compute_margin",
inverse="_inverse_margin", digits='Product Price', store=True)
mrp = fields.Float("MRP", help="Load from Product MRP (Latest)",
digits='Product Price')

@api.onchange('product_id')
def _compute_mrp(self):
for rec in self:
rec.mrp = rec.product_id.lst_price if rec.product_id else False

# Get Margin
@api.depends("mrp", "product_qty", "price_subtotal", "product_id")
def _compute_margin(self):
for rec in self:
if rec.mrp and rec.product_qty:
price_sub_mrp = self._get_tax_amount(rec.product_id, rec.mrp)
margin = (price_sub_mrp * rec.product_qty) - rec.price_subtotal
rec.margin = round(price_sub_mrp and margin / price_sub_mrp, 2)
else:
rec.margin = False

@api.onchange('margin')
def _inverse_margin(self):
for rec in self:
if rec.product_qty:
if rec.order_id.mrp_updatable:
cost = rec.price_total / rec.product_qty
rec.mrp = round(cost / (1 - rec.margin), 2) if rec.margin != 1 else cost
else:
cost = rec.mrp * (1 - rec.margin)
cost_tax = self._get_tax_amount(rec.product_id, cost)
price_unit = cost_tax + (cost_tax * (rec.discount / 100) if rec.discount else 0)
rec.price_unit = round(price_unit, 2)

# Get price excluding tax amount
def _get_tax_amount(self, product, price):
taxes_id = product.taxes_id.filtered(
lambda x: x.company_id.id == self.env.company.id
or x.company_id.id == self.env.company.parent_id.id
)

if taxes_id:
amount = taxes_id.compute_all(price, product=product, partner=self.env["res.partner"])
amount = amount["total_excluded"]
else:
amount = price

return amount

Jenish M
Autor

Thanks for the effort.
but no luck for me.

Avatar
Sayed Mohammed Aqeel Ebrahim
Mejor respuesta

Add Import for float_round and float_compare:

from odoo.tools.float_utils import float_round, float_compare

Update _compute_margin to use float_round:

rec.margin = float_round(rec.margin, precision_digits=rec._get_digits('Product Price'))

Update _inverse_margin to use float_round:

rec.mrp = float_round(rec.mrp, precision_digits=rec._ge(price_unit, precision_digits=rec._get_digits('Product Price'))

Add Helper Method _get_digits to fetch precision:

def _get_digits(self, precision_name):
    """Get the number of digits for the given precision."""
    return self.env['decimal.precision'].precision_get(precision_name)

0
Avatar
Descartar
Jenish M
Autor

Thanks for the answer, but nothing changes.

¿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
Help review canceling purchase code
code review
Avatar
Avatar
2
mar 15
5667
.update() method not updating values
code
Avatar
0
sept 23
2616
Why is the hr.attendance date column called "name"?
code
Avatar
0
ago 16
4966
How to refresh the form view in coding in openerp 7?
code
Avatar
0
mar 15
5429
line code.
code
Avatar
0
jul 24
3437
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