'Compute the invoice status of a SO. Possible statuses:
- no: if the SO is not in status \'sale\' or \'done\', we consider that there is nothing to
invoice. This is also hte default value if the conditions of no other status is met.
- to invoice: if any SO line is \'to invoice\', the whole SO is \'to invoice\'
- invoiced: if all SO lines are invoiced, the SO is invoiced.
- upselling: if all SO lines are invoiced or upselling, the status is upselling.
The invoice_ids are obtained thanks to the invoice lines of the SO lines, and we also search
for possible refunds created directly from existing invoices. This is necessary since such a
refund is not directly linked to the SO.'

@api.depends('state', 'order_line.invoice_status')
def _get_invoiced(self):

    for order in self:
        invoice_ids = order.order_line.mapped('invoice_lines').mapped('invoice_id').filtered((lambda r: (r.type in ['out_invoice', 'out_refund'])))
        refunds = invoice_ids.search([('origin', 'like', order.name)]).filtered((lambda r: (r.type in ['out_invoice', 'out_refund'])))
        invoice_ids |= refunds.filtered((lambda r: (order.name in [origin.strip() for origin in r.origin.split(',')])))
        refund_ids = self.env['account.invoice'].browse()
        if invoice_ids:
            for inv in invoice_ids:
                refund_ids += refund_ids.search([('type', '=', 'out_refund'), ('origin', '=', inv.number), ('origin', '!=', False), ('journal_id', '=', inv.journal_id.id)])
        deposit_product_id = self.env['sale.advance.payment.inv']._default_product_id()
        line_invoice_status = [line.invoice_status for line in order.order_line if (line.product_id != deposit_product_id)]
        if (order.state not in ('sale', 'done')):
            invoice_status = 'no'
        elif any(((invoice_status == 'to    invoice') for invoice_status in line_invoice_status)):
            invoice_status = 'to    invoice'
        elif all(((invoice_status == 'invoiced') for invoice_status in line_invoice_status)):
            invoice_status = 'invoiced'
        elif all(((invoice_status in ['invoiced', 'upselling']) for invoice_status in line_invoice_status)):
            invoice_status = 'upselling'
        else:
            invoice_status = 'no'
        order.update({'invoice_count': len(set((invoice_ids.ids + refund_ids.ids))), 'invoice_ids': (invoice_ids.ids + refund_ids.ids), 'invoice_status': invoice_status})
