# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2014-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################
from odoo import models, fields, api
from odoo.exceptions import AccessError
from odoo.tools.translate import _

class SaleOrder(models.Model):
    _inherit = "sale.order"

    state = fields.Selection(selection_add=[('to_approve_plafond', 'To Approve (Plafond)')])

    @api.multi
    def action_confirm(self):
        context = self.env.context or {}
        for sale in self:
            if sale.state != 'to_approve_plafond':
                plafond = self.env['res.partner'].browse([sale.partner_id.id])[0].plafond
                allow_confirm = context.get('allow_confirm', False)

                sale_invoice_total = 0
                open_invoices = self.env['account.invoice'].search([('partner_id','=',sale.partner_id.id), ('type','=','out_invoice'), ('state','=','open')])
                for invoice in open_invoices:
                    sale_invoice_total += invoice.amount_total
                invoice_total = sale_invoice_total

                sale_invoice_total += sale.amount_total

                if plafond > 0.0 and sale_invoice_total > plafond and not allow_confirm:
                    return {
                        'type': 'ir.actions.act_window',
                        'name': 'Confirm Sales',
                        'res_model': 'sale.plafond.confirm',
                        'view_type': 'form',
                        'view_mode': 'form',
                        'target': 'new',
                        'context': {'limit': plafond, 'customer': sale.partner_id.name, 'sale_total': sale.amount_total, 'invoice_total': invoice_total}
                    }
            return super(SaleOrder, sale).action_confirm()
