sale_order_line.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. from odoo import api, fields, models
  4. class SaleOrderLine(models.Model):
  5. _inherit = "sale.order.line"
  6. margin = fields.Float(
  7. "Margin", compute='_compute_margin',
  8. digits='Product Price', store=True, groups="base.group_user", precompute=True)
  9. margin_percent = fields.Float(
  10. "Margin (%)", compute='_compute_margin', store=True, groups="base.group_user", precompute=True)
  11. purchase_price = fields.Float(
  12. string="Cost", compute="_compute_purchase_price",
  13. digits='Product Price', store=True, readonly=False, precompute=True,
  14. groups="base.group_user")
  15. @api.depends('product_id', 'company_id', 'currency_id', 'product_uom')
  16. def _compute_purchase_price(self):
  17. for line in self:
  18. if not line.product_id:
  19. line.purchase_price = 0.0
  20. continue
  21. line = line.with_company(line.company_id)
  22. product_cost = line.product_id.standard_price
  23. line.purchase_price = line._convert_price(product_cost, line.product_id.uom_id)
  24. @api.depends('price_subtotal', 'product_uom_qty', 'purchase_price')
  25. def _compute_margin(self):
  26. for line in self:
  27. line.margin = line.price_subtotal - (line.purchase_price * line.product_uom_qty)
  28. line.margin_percent = line.price_subtotal and line.margin/line.price_subtotal
  29. def _convert_price(self, product_cost, from_uom):
  30. self.ensure_one()
  31. if not product_cost:
  32. # If the standard_price is 0
  33. # Avoid unnecessary computations
  34. # and currency conversions
  35. if not self.purchase_price:
  36. return product_cost
  37. from_currency = self.product_id.cost_currency_id
  38. to_cur = self.currency_id or self.order_id.currency_id
  39. to_uom = self.product_uom
  40. if to_uom and to_uom != from_uom:
  41. product_cost = from_uom._compute_price(
  42. product_cost,
  43. to_uom,
  44. )
  45. return from_currency._convert(
  46. from_amount=product_cost,
  47. to_currency=to_cur,
  48. company=self.company_id or self.env.company,
  49. date=self.order_id.date_order or fields.Date.today(),
  50. round=False,
  51. ) if to_cur and product_cost else product_cost
  52. # The pricelist may not have been set, therefore no conversion
  53. # is needed because we don't know the target currency..