# -*- 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


class SalePlafondConfirm(models.TransientModel):
	_name = "sale.plafond.confirm"

	name = fields.Html()
	
	@api.model
	def default_get(self, fields):
		res = super(SalePlafondConfirm, self).default_get(fields)
		context = self.env.context or {}
		if context.get('active_model', '') == 'sale.order':
			limit, partner_name, sale_total, invoice_total = context['limit'], context['customer'], context['sale_total'], context['invoice_total']
			if not invoice_total:
				res.update({'name': 'Customer <b>%s</b> Plafond limit is %s. But you tried to confirm sales order with amount %s.<br/><br/>\
										Click <b>Confirm</b> if you still want to confirm this Sale.' % (partner_name, limit, sale_total)})
			else:
				res.update({'name': 'Customer <b>%s</b> Plafond limit is %s.<br/><br/>Unpaid Invoice(s) total: %s<br/><br/>\
										But you tried to confirm sales order with amount %s.<br/><br/>\
										Click <b>Confirm</b> if you still want to confirm this Sale.' % (partner_name, limit, invoice_total, sale_total)})
		return res

	@api.multi
	def action_confirm(self):
		context = self.env.context or {}
		if context.get('active_model', '') == 'sale.order':
			sale = self.env['sale.order'].browse(context['active_ids'])
			if self.env.user.has_group('sale_plafond.group_sale_allow_plafond'):
				return sale.with_context(allow_confirm=True).action_confirm()
			else:
				return sale.write({'state': 'to_approve_plafond'})