|
| 1 | +from odoo import fields, models |
| 2 | + |
| 3 | + |
| 4 | +class SaleOrder(models.Model): |
| 5 | + _inherit = "sale.order" |
| 6 | + |
| 7 | + wizard_ids = fields.One2many( |
| 8 | + "sale.order.discount", "sale_order_id", string="Discount Wizards" |
| 9 | + ) |
| 10 | + |
| 11 | + def _update_discount(self): |
| 12 | + discount_product = self.env["product.product"].search([("name", "=", "Discount")], limit=1) |
| 13 | + if not discount_product: |
| 14 | + return |
| 15 | + |
| 16 | + total_amount = sum(line.price_subtotal for line in self.order_line if not line.is_discount_line()) |
| 17 | + |
| 18 | + discount_lines = self.order_line.filtered(lambda l: l.is_discount_line()) |
| 19 | + |
| 20 | + if not total_amount: |
| 21 | + discount_lines.unlink() |
| 22 | + return |
| 23 | + |
| 24 | + if self.wizard_ids: |
| 25 | + discount_percentage = self.wizard_ids[-1].discount_percentage |
| 26 | + else: |
| 27 | + discount_lines.unlink() |
| 28 | + return |
| 29 | + |
| 30 | + discount_amount = total_amount * discount_percentage |
| 31 | + |
| 32 | + if len(discount_lines) > 1: |
| 33 | + discount_lines[1:].unlink() |
| 34 | + discount_line = discount_lines[0] |
| 35 | + elif discount_lines: |
| 36 | + discount_line = discount_lines[0] |
| 37 | + else: |
| 38 | + discount_line = False |
| 39 | + |
| 40 | + vals = { |
| 41 | + "product_id": discount_product.id, |
| 42 | + "price_unit": -discount_amount, |
| 43 | + "name": f"Discount {discount_percentage * 100:.2f}%", |
| 44 | + "tax_id": [(6, 0, [])], |
| 45 | + } |
| 46 | + |
| 47 | + if discount_line: |
| 48 | + discount_line.write(vals) |
| 49 | + else: |
| 50 | + self.order_line.create({ |
| 51 | + **vals, |
| 52 | + "order_id": self.id, |
| 53 | + "product_uom_qty": 1, |
| 54 | + }) |
0 commit comments