| 1 |
|
| 2 |
|
| 3 |
from odoo import models |
| 4 |
|
| 5 |
|
| 6 |
class AccountMoveLine(models.Model): |
| 7 |
_inherit = "account.move.line" |
| 8 |
|
| 9 |
def _get_cogs_value(self): |
| 10 |
price_unit = super()._get_cogs_value() |
| 11 |
|
| 12 |
so_line = self.sale_line_ids and self.sale_line_ids[-1] or False |
| 13 |
if so_line: |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
boms = so_line.move_ids.filtered(lambda m: m.state != 'cancel').mapped('bom_line_id.bom_id').filtered(lambda b: b.type == 'phantom') |
| 18 |
if boms: |
| 19 |
bom = boms.filtered(lambda b: b.product_id == so_line.product_id or b.product_tmpl_id == so_line.product_id.product_tmpl_id) |
| 20 |
if not bom: |
| 21 |
|
| 22 |
|
| 23 |
bom = self.env['mrp.bom']._bom_find(products=so_line.product_id, company_id=so_line.company_id.id, bom_type='phantom')[so_line.product_id] |
| 24 |
is_line_reversing = self.move_id.move_type == 'out_refund' |
| 25 |
account_moves = so_line.invoice_lines.move_id.filtered(lambda m: m.state == 'posted' and bool(m.reversed_entry_id) == is_line_reversing) |
| 26 |
posted_invoice_lines = account_moves.line_ids.filtered(lambda l: l.display_type == 'cogs' and l.product_id == self.product_id and l.balance > 0) |
| 27 |
qty_invoiced = sum([x.product_uom_id._compute_quantity(x.quantity, x.product_id.uom_id) for x in posted_invoice_lines]) |
| 28 |
reversal_cogs = posted_invoice_lines.move_id.reversal_move_ids.line_ids.filtered(lambda l: l.display_type == 'cogs' and l.product_id == self.product_id and l.balance > 0) |
| 29 |
qty_invoiced -= sum([line.product_uom_id._compute_quantity(line.quantity, line.product_id.uom_id) for line in reversal_cogs]) |
| 30 |
|
| 31 |
moves = so_line.move_ids |
| 32 |
average_price_unit = 0 |
| 33 |
|
| 34 |
components_qty = so_line._get_bom_component_qty(bom) |
| 35 |
storable_components = self.env['product.product'].search([('id', 'in', list(components_qty.keys())), ('is_storable', '=', True)]) |
| 36 |
for product in storable_components: |
| 37 |
factor = components_qty[product.id]['qty'] |
| 38 |
prod_moves = moves.filtered(lambda m: m.product_id == product) |
| 39 |
product = product.with_company(self.company_id) |
| 40 |
average_price_unit += factor * prod_moves._get_price_unit() |
| 41 |
price_unit = average_price_unit / bom.product_qty or price_unit |
| 42 |
return price_unit |