Pular para o conteúdo
Odoo Menu
  • Entrar
  • Experimente grátis
  • Aplicativos
    Finanças
    • Financeiro
    • Faturamento
    • Despesas
    • Planilhas (BI)
    • Documentos
    • Assinar Documentos
    Vendas
    • CRM
    • Vendas
    • PDV Loja
    • PDV Restaurantes
    • Assinaturas
    • Locação
    Websites
    • Criador de Sites
    • e-Commerce
    • Blog
    • Fórum
    • Chat ao Vivo
    • e-Learning
    Cadeia de mantimentos
    • Inventário
    • Fabricação
    • PLM - Ciclo de Vida do Produto
    • Compras
    • Manutenção
    • Qualidade
    Recursos Humanos
    • Funcionários
    • Recrutamento
    • Folgas
    • Avaliações
    • Indicações
    • Frota
    Marketing
    • Redes Sociais
    • Marketing por E-mail
    • Marketing por SMS
    • Eventos
    • Automação de Marketing
    • Pesquisas
    Serviços
    • Projeto
    • Planilhas de Horas
    • Serviço de Campo
    • Central de Ajuda
    • Planejamento
    • Compromissos
    Produtividade
    • Mensagens
    • Aprovações
    • Internet das Coisas
    • VoIP
    • Conhecimento
    • WhatsApp
    Aplicativos de terceiros Odoo Studio Plataforma Odoo Cloud
  • Setores
    Varejo
    • Loja de livros
    • Loja de roupas
    • Loja de móveis
    • Mercearia
    • Loja de ferramentas
    • Loja de brinquedos
    Comida e hospitalidade
    • Bar e Pub
    • Restaurante
    • Fast Food
    • Hospedagem
    • Distribuidor de bebidas
    • Hotel
    Imóveis
    • Imobiliária
    • Escritório de arquitetura
    • Construção
    • Administração de propriedades
    • Jardinagem
    • Associação de proprietários de imóveis
    Consultoria
    • Escritório de Contabilidade
    • Parceiro Odoo
    • Agência de marketing
    • Escritório de advocacia
    • Aquisição de talentos
    • Auditoria e Certificação
    Fabricação
    • Têxtil
    • Metal
    • Móveis
    • Alimentação
    • Cervejaria
    • Presentes corporativos
    Saúde e Boa forma
    • Clube esportivo
    • Loja de óculos
    • Academia
    • Profissionais de bem-estar
    • Farmácia
    • Salão de cabeleireiro
    Comércio
    • Handyman
    • Hardware e Suporte de TI
    • Sistemas de energia solar
    • Sapataria
    • Serviços de limpeza
    • Serviços de climatização
    Outros
    • Organização sem fins lucrativos
    • Agência Ambiental
    • Aluguel de outdoors
    • Fotografia
    • Aluguel de bicicletas
    • Revendedor de software
    Navegar por todos os setores
  • Comunidade
    Aprenda
    • Tutoriais
    • Documentação
    • Certificações
    • Treinamento
    • Blog
    • Podcast
    Empodere a Educação
    • Programa de educação
    • Scale Up! Jogo de Negócios
    • Visite a Odoo
    Obtenha o Software
    • Baixar
    • Comparar edições
    • Releases
    Colaborar
    • Github
    • Fórum
    • Eventos
    • Traduções
    • Torne-se um parceiro
    • Serviços para parceiros
    • Cadastre seu escritório contábil
    Obtenha os serviços
    • Encontre um parceiro
    • Encontre um Contador
    • Conheça um consultor
    • Serviços de Implementação
    • Referências de Clientes
    • Suporte
    • Upgrades
    Github YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Faça uma demonstração
  • Preços
  • Ajuda

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

  • CRM
  • e-Commerce
  • Financeiro
  • Inventário
  • PoS
  • Projeto
  • MRP
All apps
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
É necessário estar registrado para interagir com a comunidade.
Todas as publicações Pessoas Emblemas
Marcadores (Ver tudo)
odoo accounting v14 pos v15
Sobre este fórum
Ajuda

Help me with this code.

Inscrever

Seja notificado quando houver atividade nesta publicação

Esta pergunta foi sinalizada
codereview
2 Respostas
2205 Visualizações
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
Cancelar
Avatar
Jainesh Shah(Aktiv Software)
Melhor resposta

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
Cancelar
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
Melhor resposta

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
Cancelar
Jenish M
Autor

Thanks for the answer, but nothing changes.

Está gostando da discussão? Não fique apenas lendo, participe!

Crie uma conta hoje mesmo para aproveitar os recursos exclusivos e interagir com nossa incrível comunidade!

Inscreva-se
Publicações relacionadas Respostas Visualizações Atividade
Help review canceling purchase code
code review
Avatar
Avatar
2
mar. 15
5669
.update() method not updating values
code
Avatar
0
set. 23
2619
Why is the hr.attendance date column called "name"?
code
Avatar
0
ago. 16
4967
How to refresh the form view in coding in openerp 7?
code
Avatar
0
mar. 15
5432
line code.
code
Avatar
0
jul. 24
3437
Comunidade
  • Tutoriais
  • Documentação
  • Fórum
Open Source
  • Baixar
  • Github
  • Runbot
  • Traduções
Serviços
  • Odoo.sh Hosting
  • Suporte
  • Upgrade
  • Desenvolvimentos personalizados
  • Educação
  • Encontre um Contador
  • Encontre um parceiro
  • Torne-se um parceiro
Sobre nós
  • Nossa empresa
  • Ativos da marca
  • Contato
  • Empregos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidade
  • Segurança
الْعَرَبيّة 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 é um conjunto de aplicativos de negócios em código aberto que cobre todas as necessidades de sua empresa: CRM, comércio eletrônico, contabilidade, estoque, ponto de venda, gerenciamento de projetos, etc.

A proposta de valor exclusiva Odoo é ser, ao mesmo tempo, muito fácil de usar e totalmente integrado.

Site feito com

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