|
| 1 | +from odoo import models, fields, api |
| 2 | +from odoo.exceptions import UserError |
| 3 | + |
| 4 | +class CostDistributionWizard(models.TransientModel): |
| 5 | + _name = "cost.distribution.wizard" |
| 6 | + _description = "A Wizard to distribute cost over other sales order lines." |
| 7 | + |
| 8 | + order_line_id = fields.Many2one("sale.order.line", string="Order Line") |
| 9 | + order_line_ids = fields.Many2many("sale.order.line", string="Order Lines") |
| 10 | + order_line_cost = fields.Float(string="Cost to Distribute") |
| 11 | + order_id = fields.Many2one("sale.order") |
| 12 | + price_subtotal = fields.Float("Price Subtotal") |
| 13 | + |
| 14 | + @api.model |
| 15 | + def default_get(self, fields_list): |
| 16 | + res = super(CostDistributionWizard, self).default_get(fields_list) |
| 17 | + order_id = self.env.context.get("order_id") |
| 18 | + default_order_line_id = self.env.context.get("default_order_line_id") |
| 19 | + default_price_subtotal = self.env.context.get("default_price_subtotal", 0) |
| 20 | + |
| 21 | + if order_id: |
| 22 | + order = self.env["sale.order"].browse(order_id) |
| 23 | + order_line_ids = order.order_line.ids |
| 24 | + if default_order_line_id in order_line_ids: |
| 25 | + order_line_ids.remove(default_order_line_id) |
| 26 | + |
| 27 | + res.update({ |
| 28 | + "order_id": order_id, |
| 29 | + "order_line_ids": [(6, 0, order_line_ids)], |
| 30 | + "order_line_cost": default_price_subtotal, |
| 31 | + }) |
| 32 | + |
| 33 | + distributed_cost = round(default_price_subtotal / len(order_line_ids), 2) if order_line_ids else 0 |
| 34 | + for line in self.env["sale.order.line"].browse(order_line_ids): |
| 35 | + line.write({"distributed_cost": distributed_cost}) |
| 36 | + |
| 37 | + return res |
| 38 | + |
| 39 | + def distribute_cost(self): |
| 40 | + total_cost_distributed = sum(line.distributed_cost for line in self.order_line_ids) |
| 41 | + |
| 42 | + if total_cost_distributed > self.price_subtotal: |
| 43 | + raise UserError("Distributed price is greater than the distributable price.") |
| 44 | + |
| 45 | + for line in self.order_line_ids: |
| 46 | + line.price_subtotal += line.distributed_cost |
| 47 | + |
| 48 | + original_order_line = self.env["sale.order.line"].browse(self.env.context.get("default_order_line_id")) |
| 49 | + original_order_line.price_subtotal -= total_cost_distributed |
| 50 | + |
| 51 | + if total_cost_distributed == original_order_line.price_subtotal: |
| 52 | + pass |
0 commit comments