|
| 1 | +from odoo import Command, api, models |
| 2 | + |
| 3 | + |
| 4 | +class SaleOrder(models.Model): |
| 5 | + _inherit = "sale.order" |
| 6 | + |
| 7 | + @api.onchange('order_line') |
| 8 | + def _onchange_order_line(self): |
| 9 | + """ |
| 10 | + Triggered in the UI when order lines or global_discount changes. |
| 11 | + Applies the global discount to each order line. |
| 12 | + """ |
| 13 | + # Get the default discount productid |
| 14 | + discount_product_id = self.company_id.sale_discount_product_id |
| 15 | + |
| 16 | + # Separate Product lines and Discount lines [Old: without changed value, New: with changed value in UI] |
| 17 | + old_product_lines = self._origin.order_line.filtered(lambda line: line.product_id != discount_product_id) |
| 18 | + new_product_lines = self.order_line.filtered(lambda line: line.product_id != discount_product_id) |
| 19 | + old_discount_lines = (self._origin.order_line - old_product_lines) |
| 20 | + new_discount_lines = (self.order_line - new_product_lines) |
| 21 | + |
| 22 | + # Calculate Product total |
| 23 | + old_product_total = sum(old_product_lines.mapped('price_subtotal')) |
| 24 | + new_product_total = sum(new_product_lines.mapped('price_subtotal')) |
| 25 | + |
| 26 | + # If product lines exists, calculate new discount unit rates else remove discount lines |
| 27 | + if new_product_lines: |
| 28 | + if old_product_total != new_product_total: |
| 29 | + old_discount_units = old_discount_lines.mapped('price_unit') |
| 30 | + for index, line in enumerate(new_discount_lines): |
| 31 | + discount_percentage = (abs(old_discount_units[index]) / old_product_total * 100) if old_product_total else 0.0 |
| 32 | + line.price_unit = -((new_product_total * discount_percentage) / 100) |
| 33 | + else: |
| 34 | + commands = [Command.unlink(line_id) for line_id in new_discount_lines.mapped('id')] |
| 35 | + if commands: |
| 36 | + self.order_line = [c for c in commands] |
0 commit comments