deisy 5 лет назад
Сommit
3c3470c220

+ 6 - 0
__init__.py

@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+# For copyright and license notices, see __openerp__.py file in module root
+# directory
+##############################################################################
+import models


+ 44 - 0
__openerp__.py

@@ -0,0 +1,44 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    Copyright (C) 2015  ADHOC SA  (http://www.adhoc.com.ar)
+#    All Rights Reserved.
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    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/>.
+#
+##############################################################################
+{
+    'name': 'Partner Credit Limit',
+    'version': '8.0.1.1.0',
+    'summary': 'Valida límite de crédito, límite de cheque y morosidad',
+    'description': """Partner Credit Limit
+    When approving a Sale Order it computes the sum of:
+        * The credit the Partner has to paid
+        * The amount of Sale Orders aproved but not yet invoiced
+        * The invoices that are in draft state
+        * The amount of the Sale Order to be aproved
+    and compares it with the credit limit of the partner. If the
+    credit limit is less it does not allow to approve the Sale
+    Order""",
+    'author': 'ADHOC SA/Eiru',
+    'license': 'AGPL-3',
+    'depends': ['sale','account','extra_data_dikasa'],
+    'data': [
+        'security/partner_credit_limit_security.xml',
+        'views/template.xml',
+        'views/partner_view.xml',
+        ],
+    'installable': True,
+}
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

+ 28 - 0
i18n/en.po

@@ -0,0 +1,28 @@
+# Translation of Odoo Server.
+# This file contains the translation of the following modules:
+# * partner_credit_limit
+# 
+# Translators:
+msgid ""
+msgstr ""
+"Project-Id-Version: odoo-addons (8.0)\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2015-09-09 23:57+0000\n"
+"PO-Revision-Date: 2015-09-01 18:01+0000\n"
+"Last-Translator: Juan Jose Scarafia <scarafia.juanjose@gmail.com>\n"
+"Language-Team: English (http://www.transifex.com/adhoc/ingadhoc-odoo-addons-8-0/language/en/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: \n"
+"Language: en\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+#. module: partner_credit_limit
+#: model:res.groups,name:partner_credit_limit.credit_config
+msgid "Config Credit Limit On partners"
+msgstr "Config Credit Limit On partners"
+
+#. module: partner_credit_limit
+#: model:ir.model,name:partner_credit_limit.model_sale_order
+msgid "Sales Order"
+msgstr "Sales Order"

+ 28 - 0
i18n/es.po

@@ -0,0 +1,28 @@
+# Translation of Odoo Server.
+# This file contains the translation of the following modules:
+# * partner_credit_limit
+# 
+# Translators:
+msgid ""
+msgstr ""
+"Project-Id-Version: odoo-addons (8.0)\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2016-01-05 13:55+0000\n"
+"PO-Revision-Date: 2015-09-01 18:01+0000\n"
+"Last-Translator: <>\n"
+"Language-Team: Spanish (http://www.transifex.com/adhoc/ingadhoc-odoo-addons-8-0/language/es/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: \n"
+"Language: es\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+#. module: partner_credit_limit
+#: model:res.groups,name:partner_credit_limit.credit_config
+msgid "Config Credit Limit On partners"
+msgstr ""
+
+#. module: partner_credit_limit
+#: model:ir.model,name:partner_credit_limit.model_sale_order
+msgid "Sales Order"
+msgstr "Pedido de venta"

+ 3 - 0
models/__init__.py

@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+import account_invoice
+import sale

BIN
models/__init__.pyc


+ 77 - 0
models/account_invoice.py

@@ -0,0 +1,77 @@
+#-*- coding:utf-8 -*-
+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.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.\
+                    Puede pasar la politica de facturación del pedido a "Pago antes de envío" en la \
+                    pestaña "Otra información"'
+            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.multi
+    def save_payments_invoice(self,values):
+        bank_payments_type_id = values['bankPayments']['bank_payments_type_id']
+        payment_type = self.env['res.bank.payments.type'].search([('id', '=', bank_payments_type_id)])
+        domain = [('id', '=', self.partner_id.id)]
+        partner = self.env['res.partner'].search(domain)
+        # import web_pdb; web_pdb.set_trace()
+        if payment_type.code == 'CH' and values['amountPayments'] > partner.check_limit:
+            # raise Warning(_("El monto a pagar excede el límite de crédito concedido en cheques"))
+            return {
+                'process': False,
+                'removeModal': False,
+                'message' : "El monto a pagar excede el límite de crédito concedido en cheques"
+          }
+        return super(account_invoice, self).save_payments_invoice()

BIN
models/account_invoice.pyc


+ 62 - 0
models/sale.py

@@ -0,0 +1,62 @@
+#-*- coding:utf-8 -*-
+from openerp import models, api, _
+from openerp.exceptions import Warning
+from datetime import datetime, date
+
+
+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.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 crédito suficiente.\
+                    Puede pasar la política de facturación del pedido a "Pago antes de envío" en la \
+                    pestaña "Otra información"'
+            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

BIN
models/sale.pyc


+ 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>

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

@@ -0,0 +1,32 @@
+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();
+    },
+  });
+}

+ 28 - 0
views/partner_view.xml

@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="utf-8"?>
+<openerp>
+    <data>
+        <!-- make readonly for everyone -->
+        <record id="view_credit_readonly_partner_form" model="ir.ui.view">
+            <field name="name">res.partner.partner_credit_limit.form</field>
+            <field name="model">res.partner</field>
+            <field name="inherit_id" ref="account.view_partner_property_form"/>
+            <field name="arch" type="xml">
+                <xpath expr="//form[@string='Partners']//field[@name='credit_limit']" position="attributes">
+                    <attribute name="readonly">1</attribute>
+                </xpath>
+            </field>
+        </record>
+        <!-- Make not readonly for user_edit_credit_limit  -->
+        <record id="view_credit_editable_partner_form" model="ir.ui.view">
+            <field name="name">res.partner.partner_credit_limit.form</field>
+            <field name="model">res.partner</field>
+            <field name="inherit_id" ref="partner_credit_limit.view_credit_readonly_partner_form"/>
+            <field name="groups_id" eval="[(6, 0, [ref('partner_credit_limit.credit_config')])]"/>
+            <field name="arch" type="xml">
+                <xpath expr="//form[@string='Partners']//field[@name='credit_limit']" position="attributes">
+                    <attribute name="readonly">0</attribute>
+                </xpath>
+            </field>
+        </record>
+    </data>
+</openerp>

+ 10 - 0
views/template.xml

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<openerp>
+  <data>
+    <template id="partner_credit_limit_assets_backend" inherit_id="web.assets_backend">
+      <xpath expr="." position="inside">
+        <script type="text/javascript" src="/partner_credit_limit/static/src/js/warning.js"/>
+      </xpath>
+    </template>
+  </data>
+</openerp>