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

from datetime import datetime

class AccountInvoice(models.Model):
    _inherit = "account.invoice"

    @api.constrains('date_invoice')
    def check_invoice_date_validate(self):
        """Validate & Raise user warning if Invoice date is before last confirmed invoice's date
        """
        for invoice in self:
            if invoice.date_invoice:
                inv_type = invoice.type

                invoices = self.search([('type','=',invoice.type), ('date_invoice','!=',False), ('state','not in',('draft','cancel'))], order="date_invoice desc", limit=1)
                inv_date = invoices and invoices[0].date_invoice
                if inv_date and datetime.strptime(invoice.date_invoice, "%Y-%m-%d") < datetime.strptime(inv_date, "%Y-%m-%d") and invoice.id != invoices[0].id:
                    raise ValidationError(_("Validation Failed!\n\nInvoice Date must be after last confirmed invoice. (%s)"%(inv_date)))
