Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Help me with this code.

Subscriure's

Get notified when there's activity on this post

This question has been flagged
codereview
2 Respostes
2199 Vistes
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)
Best Answer

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
Best Answer

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.

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Help review canceling purchase code
code review
Avatar
Avatar
2
de març 15
5667
.update() method not updating values
code
Avatar
0
de set. 23
2615
Why is the hr.attendance date column called "name"?
code
Avatar
0
d’ag. 16
4962
How to refresh the form view in coding in openerp 7?
code
Avatar
0
de març 15
5429
line code.
code
Avatar
0
de jul. 24
3437
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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