Hi there! I'm developing a custom module that allows users to add related stock moves to invoices. I want each one of this related stock moves added as an invoice line to the current invoice so I'm trying to create an invoice_line_ids from this related stock moves but its not working. I've been doing some modifications to the code and I get several errors, but I can't understand why the code is not working properly.
Here is my custom view
<odoo>
<record id="invoice_stock_moves" model="ir.ui.view">
<field name="name">account.invoice.related_stock_moves</field>
<field name="model">account.invoice</field>
<field name="inherit_id" ref="account.invoice_supplier_form"/>
<field name="arch" type="xml">
<xpath expr="//page" position="after">
<page string="Movimientos asociados" attrs="{'invisible': [('partner_id', '=', False)]}">
<field name="related_stock_moves" widget="many2many" options="{'no_create': True}" domain="['&', ('state','=','done'), ('picking_partner_id','=',context.get('partner_id')), '&', ('x_invoice_id','=',False)]" attrs="{'readonly':[('state','not in',('draft',))]}">
<tree>
<field name="state" invisible="1"/>
<field name="date" />
<field name="picking_partner_id" invisible="1"/>
<field name="reference" />
<field name="product_id" />
<field name="product_uom_qty" string="Cantidad" />
<field name="product_uom" />
</tree>
</field>
</page>
</xpath>
</field>
</record>
</odoo>
And here my .py defining the model
# -*- coding: utf-8 -*-
from odoo import api, fields, models
import logging
_logger = logging.getLogger(__name__)
class Move(models.Model):
_inherit = 'stock.move'
x_invoice_id = fields.Many2one('account.invoice',
string="Factura de referencia", ondelete='set null')
class Invoice(models.Model):
_inherit = 'account.invoice'
related_stock_moves = fields.One2many('stock.move',
'x_invoice_id', 'related_stock_moves', string="Movimiento asociado")
invoice_line_ids = fields.One2many('account.invoice.line',
'invoice_id', string="Líneas de la factura", compute='_add_lines')
## Retrieve product_id and product_uom_qty
@api.depends('related_stock_moves')
@api.one
def _add_lines(self):
for move in self.related_stock_moves:
self.env['account.invoice.line'].create({
'account_id': self.account_id.id,
'invoice_id': self.id,
'product_id': move.product_id.id,
'quantity': move.product_uom_qty,
'name': move.product_id.description,
'price_unit': '0.0'
})
I'm not sure if I should be using a computed field, I want the invoice lines added when a related stock move is added.
Any help is kindly appreciated, thanks for your time <3
I have updated my answer for your requirement, please check to it.