# -*- coding: utf-8 -*-

from odoo import Command, api, models

class EstateProperty(models.Model):
    _inherit = "estate.property"

    def action_sold(self):
        """
        Create an invoice when a property is sold
        """
        # Run the parent method first so that nothing is
        # invoiced if an error is raised
        parent = super().action_sold()

        # If ever this is called on several records
        for property in self:        
            # Prepare the values
            vals = {
                'partner_id'        : property.buyer_id.id,
                'move_type'         : 'out_invoice',
                'invoice_line_ids'  : [
                    Command.create({
                        'name'      : property.name,
                        'quantity'  : 1.0,
                        'price_unit': property.selling_price * 0.6
                    }),
                    Command.create({
                        'name'      : "Administrative fees",
                        'quantity'  : 1.0,
                        'price_unit': 100.00
                    }),
                ],
                }
            # Create the invoice
            self.env['account.move'].create(vals)

        return parent