sale_order.py 1.5 KB

1234567891011121314151617181920212223242526272829303132
  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 SaleOrder(models.Model):
  5. _inherit = "sale.order"
  6. margin = fields.Monetary("Margin", compute='_compute_margin', store=True)
  7. margin_percent = fields.Float("Margin (%)", compute='_compute_margin', store=True, group_operator="avg")
  8. @api.depends('order_line.margin', 'amount_untaxed')
  9. def _compute_margin(self):
  10. if not all(self._ids):
  11. for order in self:
  12. order.margin = sum(order.order_line.mapped('margin'))
  13. order.margin_percent = order.amount_untaxed and order.margin/order.amount_untaxed
  14. else:
  15. # On batch records recomputation (e.g. at install), compute the margins
  16. # with a single read_group query for better performance.
  17. # This isn't done in an onchange environment because (part of) the data
  18. # may not be stored in database (new records or unsaved modifications).
  19. grouped_order_lines_data = self.env['sale.order.line'].read_group(
  20. [
  21. ('order_id', 'in', self.ids),
  22. ], ['margin', 'order_id'], ['order_id'])
  23. mapped_data = {m['order_id'][0]: m['margin'] for m in grouped_order_lines_data}
  24. for order in self:
  25. order.margin = mapped_data.get(order.id, 0.0)
  26. order.margin_percent = order.amount_untaxed and order.margin/order.amount_untaxed