|
| 1 | +from collections import defaultdict |
| 2 | +from odoo import _, models |
| 3 | + |
| 4 | + |
| 5 | +class SaleOrderInherit(models.Model): |
| 6 | + _inherit = "sale.order" |
| 7 | + |
| 8 | + def recalculate_discount(self): |
| 9 | + for order in self: |
| 10 | + discount_ol = order.order_line.filtered( |
| 11 | + lambda ol: ol.is_global_discount_line |
| 12 | + ) |
| 13 | + print(discount_ol) |
| 14 | + if not discount_ol: |
| 15 | + return |
| 16 | + |
| 17 | + discount_per = discount_ol[0].discount_percentage |
| 18 | + discount_product = discount_ol[0].product_id |
| 19 | + discount_ol.unlink() |
| 20 | + total_price_per_tax_groups = defaultdict(float) |
| 21 | + |
| 22 | + for line in order.order_line: |
| 23 | + if not line.product_uom_qty or not line.price_unit: |
| 24 | + continue |
| 25 | + |
| 26 | + total_price_per_tax_groups[line.tax_id] += ( |
| 27 | + line.price_unit * line.product_uom_qty |
| 28 | + ) |
| 29 | + |
| 30 | + if not total_price_per_tax_groups: |
| 31 | + return |
| 32 | + |
| 33 | + elif len(total_price_per_tax_groups) == 1: |
| 34 | + taxes = next(iter(total_price_per_tax_groups.keys())) |
| 35 | + subtotal = total_price_per_tax_groups[taxes] |
| 36 | + self.env["sale.order.line"].create( |
| 37 | + { |
| 38 | + "order_id": order.id, |
| 39 | + "product_id": discount_product.id, |
| 40 | + "name": _("Discount: %(percent)s%%", percent=discount_per), |
| 41 | + "product_uom_qty": 1, |
| 42 | + "tax_id": [(6, 0, taxes.ids)], |
| 43 | + "price_unit": -subtotal * discount_per / 100, |
| 44 | + } |
| 45 | + ) |
| 46 | + |
| 47 | + else: |
| 48 | + vals_list = [ |
| 49 | + ( |
| 50 | + { |
| 51 | + "order_id": order.id, |
| 52 | + "product_id": discount_product.id, |
| 53 | + "name": _( |
| 54 | + "Discount: %(percent)s%%" |
| 55 | + "- On products with the following taxes %(taxes)s", |
| 56 | + percent=discount_per, |
| 57 | + taxes=", ".join(taxes.mapped("name")), |
| 58 | + ), |
| 59 | + "product_uom_qty": 1, |
| 60 | + "tax_id": [(6, 0, taxes.ids)], |
| 61 | + "price_unit": -subtotal * discount_per / 100, |
| 62 | + } |
| 63 | + ) |
| 64 | + for taxes, subtotal in total_price_per_tax_groups.items() |
| 65 | + ] |
| 66 | + self.env["sale.order.line"].create(vals_list) |
0 commit comments