I was facing an issue in two way matching algorithm for Incoming Receipts & Vendor bills in my Odoo installation. As vendor bills are tagged in Purchase Orders only through use of ‘Create Bill’, I had to make an algorithm to calculate the matching. Remember, the match would only work if the supply chain members follows the right way of doing it, otherwise, it would fail. That’s what happened, it fails almost 3 times out of 10. Then I realized, the invoice needs to be pinned automatically in the stock.picking model, instead of purchase.order model at the time a Receipt is validated, to keep the tracking for my matching.
While doing so, first challenge is to pin an invoice to a purchase id. By default, the model for invoicing, ‘account.invoice’ has a foreign read only key for purchase, which is purchase_id. But remember, this is a read only field, and can’t be written/created in a new or existing record using record. I dig down the Odoo codes a little under purchase/models/account_invoice.py and could find the Odoo function that can do the job for us. It’s called ‘purchase_order_change()’.
Here is a snippet of adding an invoice automatically to a purchase ID:
invoice_id = self.env['account.invoice'].create({
'type': 'in_invoice',
'purchase_id': self.purchase_id.id,
'partner_id': self.purchase_id.partner_id.id,
})
invoice_id.purchase_order_change()
This will create an invoice in Draft state. Remember, you need to validate this invoice, if you would like to create the invoice number, not just an invoice entry. You may do it manually or you may do it automatically ‘How to Automatically Validate an Invoice in Odoo‘
Remember, I am triggering the snippet from the stock.picking, not from purchase.order, which is why, the ‘self’, is related to stock.picking and calling self.purchase_id to link the original purchase_id that triggered the stock.picking record.
Now, a small tip. What if, if you want to align the invoice to only have the products you have received in this particular receipt? Easy as pie:
for invoice_line in invoice_id.mapped('invoice_line_ids'):
check = 1
for move_line in self.mapped('move_line_ids'):
if invoice_line.product_id.id == move_line.porduct_id.id:
check = 0
if check:
invoice_line.unlink()
Simple! Isn’t it? Happy coding!