|
| 1 | +from odoo import models, fields, api |
| 2 | +from odoo.exceptions import ValidationError |
| 3 | + |
| 4 | + |
| 5 | +class PurchaseOrderDiscount(models.Model): |
| 6 | + _name = "purchase.order.discount" |
| 7 | + _description = "Purchase Order Discount" |
| 8 | + |
| 9 | + order_id = fields.One2many("purchase.order", "discount_id") |
| 10 | + discount_type = fields.Selection( |
| 11 | + selection=[ |
| 12 | + ("value", "$"), |
| 13 | + ("percentage", "%"), |
| 14 | + ], |
| 15 | + default="value", |
| 16 | + ) |
| 17 | + discount_in_value = fields.Float(string="Discount") |
| 18 | + discount_in_percentage = fields.Float(compute="_compute_discount_percentage", store=True, readonly=True) |
| 19 | + order_line_id = fields.Many2one("purchase.order.line") |
| 20 | + |
| 21 | + @api.depends("discount_type", "discount_in_value", "order_id.amount_total") |
| 22 | + def _compute_discount_percentage(self): |
| 23 | + for record in self: |
| 24 | + if record.discount_type == "value" and record.order_id.amount_total > 0: |
| 25 | + record.discount_in_percentage = (record.discount_in_value * 100) / (record.order_id.amount_total) |
| 26 | + elif record.discount_type == "percentage": |
| 27 | + record.discount_in_percentage = record.discount_in_value |
| 28 | + else: |
| 29 | + record.discount_in_percentage = 0.0 |
| 30 | + |
| 31 | + @api.constrains("discount_in_value", "discount_type", "order_id.amount_total") |
| 32 | + def _check_discount_price(self): |
| 33 | + for record in self: |
| 34 | + if record.discount_type == "percentage": |
| 35 | + if record.discount_in_value < 0 or record.discount_in_value > 100: |
| 36 | + raise ValidationError("discount value is not valid please check again") |
| 37 | + if record.discount_type == "value": |
| 38 | + if record.discount_in_value < 0 or record.discount_in_value > record.order_id.amount_total: |
| 39 | + raise ValidationError("discount value is not valid please check again") |
| 40 | + |
| 41 | + def apply_discount(self): |
| 42 | + self.order_id.order_line.discount = self.discount_in_percentage |
| 43 | + |
| 44 | + def apply_cancle(self): |
| 45 | + pass |
0 commit comments