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