Przeglądaj źródła

Limite de credito ene cliente

sebas 4 lat temu
rodzic
commit
eca4c18181

+ 2 - 2
__openerp__.py

@@ -16,7 +16,8 @@
 #
 #    You should have received a copy of the GNU Affero General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
-#
+#     'views/partner_credito_limite.xml',
+#'security/partner_credit_limit_security.xml',
 ##############################################################################
 {
     'name': 'Limite de crédito en cliente',
@@ -38,7 +39,6 @@
     'data': [
         'views/template.xml',
         'views/partner_view.xml',
-        'views/partner_credito_limite.xml',
         ],
     'installable': True,
 }

+ 24 - 56
models/account_invoice.py

@@ -3,59 +3,27 @@ from openerp import models, api, _
 from openerp.exceptions import Warning
 from datetime import datetime, date
 
-
-class account_invoice(models.Model):
-    _inherit = "account.invoice"
-
-    def invoice_validate(self):
-        self.check_limit()
-       # self.check_morosidad()
-        return super(account_invoice, self).invoice_validate()
-
-    @api.one
-    def check_limit(self):
-
-        if self.contado == True:
-            return True
-
-        available_credit = self.partner_id.credit_limit - self.partner_id.credit
-
-        if self.amount_total > available_credit:
-            if not self.user_has_groups('partner_credito_limite.groups_partner_credito_limite'):
-                msg = 'No se puede confirmar el Pedido ya que el cliente no tiene crédito suficiente.\
-                    Pruebe marcar la opción "Contado" o pedir autorización para poder realizar la venta.'
-                raise Warning(_(msg))
-                return False
-            return True
-
-    # @api.multi
-    # def check_morosidad(self):
-    #    now = datetime.now()
-    #    hoy = datetime.strptime(now.strftime("%Y-%m-%d"),"%Y-%m-%d")
-    #    domain = [('id', '=', self.partner_id.id)]
-    #    partner = self.env['res.partner'].search(domain)
-    #    invoices = self.env['account.invoice'].search([('partner_id', '=',self.partner_id.id),('state', '=','open'),('type', '=', 'out_invoice'),('journal_id.type','=','sale')])
-    #    for item in invoices:
-    #        moveLine = self.env['account.move.line'].search([('move_id','=', item.move_id.id),('debit','>',0)])
-    #        if moveLine.date_maturity < now.strftime("%Y-%m-%d"):
-    #            vencimiento = datetime.strptime(moveLine.date_maturity,"%Y-%m-%d")
-    #            if (hoy-vencimiento).days > partner.morosidad:
-    #                raise Warning(_("El cliente %s tiene cuotas vencidas con más de %s días de atraso") % (partner.name, partner.morosidad))
-    #                return False
-    #    return True
-
-    # @api.model
-    # def save_payments_invoice(self,values):
-    #
-    #     bank_payments_type_id = values['bankPayments']['bank_payments_type_id']
-    #     partner = self.env['res.partner'].browse(values['partnerId'])
-    #
-    #     if bank_payments_type_id is not None:
-    #         payment_type = self.env['res.bank.payments.type'].browse(bank_payments_type_id)
-    #         if payment_type.code == 'CH' and values['amountPayments'] > partner.check_limit:
-    #             return {
-    #                 'process': False,
-    #                 'removeModal': False,
-    #                 'message' : "El monto a pagar excede el límite de crédito concedido en cheques"
-    #             }
-    #     return self.env['account.invoice'].save_payments_invoice(values)
+# 
+# class account_invoice(models.Model):
+#     _inherit = "account.invoice"
+#
+#     def invoice_validate(self):
+#         self.check_limit()
+#        # self.check_morosidad()
+#         return super(account_invoice, self).invoice_validate()
+#
+#     @api.one
+#     def check_limit(self):
+#
+#         if self.contado == True:
+#             return True
+#
+#         available_credit = self.partner_id.credit_limit - self.partner_id.credit
+#
+#         if self.amount_total > available_credit:
+#             if not self.user_has_groups('partner_credito_limite.groups_partner_credito_limite'):
+#                 msg = 'No se puede confirmar el Pedido ya que el cliente no tiene crédito suficiente.\
+#                     Pruebe marcar la opción "Contado" o pedir autorización para poder realizar la venta.'
+#                 raise Warning(_(msg))
+#                 return False
+#             return True

+ 55 - 29
models/sale.py

@@ -10,37 +10,63 @@ class sale_order(models.Model):
     @api.one
     def action_wait(self):
         self.check_limit()
-        # self.check_morosidad()
         return super(sale_order, self).action_wait()
 
     @api.one
     def check_limit(self):
 
-            if self.contado == True:
-                return True
-
-            available_credit = self.partner_id.credit_limit - self.partner_id.credit
-
-            if self.amount_total > available_credit:
-                if not self.user_has_groups('partner_credito_limite.groups_partner_credito_limite'):
-                    msg = 'No se puede confirmar el Pedido ya que el cliente no tiene crédito suficiente.\
-                        Pruebe marcar la opción "Contado"'
-                    raise Warning(_(msg))
-                    return False
-                return True
-
-    #@api.one
-    #def check_morosidad(self):
-    #    now = datetime.now()
-    #    hoy = datetime.strptime(now.strftime("%Y-%m-%d"),"%Y-%m-%d")
-    #    domain = [('id', '=', self.partner_id.id)]
-    #    partner = self.env['res.partner'].search(domain)
-    #    invoices = self.env['account.invoice'].search([('partner_id', '=',self.partner_id.id),('state', '=','open'),('type', '=', 'out_invoice'),('journal_id.type','=','sale')])
-    #    for item in invoices:
-    #        moveLine = self.env['account.move.line'].search([('move_id','=', item.move_id.id),('debit','>',0)])
-    #        if moveLine.date_maturity < now.strftime("%Y-%m-%d"):
-    #            vencimiento = datetime.strptime(moveLine.date_maturity,"%Y-%m-%d")
-    #            if partner.morosidad > 0 and (hoy-vencimiento).days > partner.morosidad:
-    #                raise Warning(_("El cliente %s tiene cuotas vencidas con más de %s días de atraso") % (partner.name, partner.morosidad))
-    #                return False
-    #    return True
+        if self.order_policy == 'prepaid':
+            return True
+
+        # We sum from all the sale orders that are aproved, the sale order
+        # lines that are not yet invoiced
+        domain = [('order_id.partner_id', '=', self.partner_id.id),
+                  ('invoiced', '=', False),
+                  ('order_id.state', 'not in', ['draft', 'cancel', 'sent'])]
+        order_lines = self.env['sale.order.line'].search(domain)
+        none_invoiced_amount = sum([x.price_subtotal for x in order_lines])
+
+        # We sum from all the invoices that are in draft the total amount
+        domain = [
+            ('partner_id', '=', self.partner_id.id), ('state', '=', 'draft')]
+        draft_invoices = self.env['account.invoice'].search(domain)
+        draft_invoices_amount = sum([x.amount_total for x in draft_invoices])
+
+        available_credit = self.partner_id.credit_limit - \
+            self.partner_id.credit - \
+            none_invoiced_amount - draft_invoices_amount
+
+        if self.amount_total > available_credit:
+            msg = _('No se puede confirmar el Pedido ya que el cliente no tiene credito suficiente.\
+                    Cambia el límite de cliente en su ficha e intente de nuevo"')
+            raise Warning(msg)
+            return False
+        return True
+
+
+# class sale_order(models.Model):
+#     _inherit = "sale.order"
+#
+#     @api.one
+#     def action_wait(self):
+#         self.check_limit()
+#         # self.check_morosidad()
+#         return super(sale_order, self).action_wait()
+#
+#     @api.one
+#     def check_limit(self):
+#
+#             if self.contado == True:
+#                 return True
+#
+#             available_credit = self.partner_id.credit_limit - self.partner_id.credit
+#
+#             if self.amount_total > available_credit:
+#                 if not self.user_has_groups('partner_credito_limite.credit_config'):
+#                     msg = 'No se puede confirmar el Pedido ya que el cliente no tiene crédito suficiente.\
+#                         Pruebe marcar la opción "Contado"'
+#                     raise Warning(_(msg))
+#                     return False
+#                 return True
+#
+#

+ 8 - 0
security/partner_credit_limit_security.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<openerp>
+<data noupdate="0">
+    <record id="credit_config" model="res.groups">
+        <field name="name">Config Credit Limit On partners</field>
+    </record>
+</data>
+</openerp>

+ 0 - 32
static/src/js/warning.js

@@ -1,32 +0,0 @@
-openerp.partner_credit_limit = function(instance){
-  var QWeb = instance.web.qweb;
-  _t = instance.web._t;
-
-  instance.web.CrashManager.include({
-
-    show_warning: function(error) {
-      if (!this.active) {
-        return;
-      }
-      if (error.data.exception_type === "except_osv") {
-        error = _.extend({}, error, {
-          data: _.extend({}, error.data, {
-            message: error.data.arguments[0] + "\n\n" + error.data.arguments[1]
-          })
-        });
-      }
-      new instance.web.Dialog(this, {
-        size: 'medium',
-        title: "Aviso del sistema ",
-        buttons: [{
-          text: _t("Ok"),
-          click: function() {
-            this.parents('.modal').modal('hide');
-          }
-        }],
-      }, $('<div>' + QWeb.render('CrashManager.warning', {
-        error: error
-      }) + '</div>')).open();
-    },
-  });
-}