Fixes issue 30077: Wrong customer balance with multicurrency credits
authorAlvaro Ferraz <alvaro.ferraz@openbravo.com>
Thu, 11 Jun 2015 12:43:23 +0200
changeset 27080 9d85d9a430b2
parent 27079 809bf54dbb34
child 27081 317d186e5a31
Fixes issue 30077: Wrong customer balance with multicurrency credits

Customer balance was not correctly updated when consuming credit generated in one currency in a payment with another currency.
Credit To Use grid in AddPayment will only show available credit in the currency of current payment.
Also, when changing the currency of a business partner with Set New Currency process, if exists available credit, the process will be able to convert automatically this credit into credit in the new curreny if a GLItem is selected, following this process: http://wiki.openbravo.com/wiki/How_to_convert_credit_to_a_different_currency
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PaymentInAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PaymentOutAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PurchaseInvoiceAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PurchaseOrderAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/SalesInvoiceAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/SalesOrderAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDisplayLogics.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/hqlinjections/CreditToUseTransformer.java
modules/org.openbravo.client.application/src/org/openbravo/client/application/ApplicationComponentProvider.java
src-db/database/sourcedata/AD_MESSAGE.xml
src-db/database/sourcedata/OBUIAPP_PARAMETER.xml
src-db/database/sourcedata/OBUIAPP_PROCESS.xml
src/org/openbravo/common/actionhandler/CheckAvailableCreditActionHandler.java
src/org/openbravo/common/actionhandler/SetNewBPCurrency.java
src/org/openbravo/financial/FinancialUtils.java
web/js/checkAvailableCredit.js
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Thu Jun 11 12:43:23 2015 +0200
@@ -1895,8 +1895,19 @@
   }
 
   public BigDecimal getCustomerCredit(BusinessPartner bp, boolean isReceipt, Organization Org) {
+    return getCustomerCredit(bp, isReceipt, Org, null);
+  }
+
+  public BigDecimal getCustomerCredit(BusinessPartner bp, boolean isReceipt, Organization Org,
+      Currency currency) {
     BigDecimal creditAmount = BigDecimal.ZERO;
-    for (FIN_Payment payment : getCustomerPaymentsWithCredit(Org, bp, isReceipt))
+    List<FIN_Payment> paymentList = null;
+    if (currency == null) {
+      paymentList = getCustomerPaymentsWithCredit(Org, bp, isReceipt);
+    } else {
+      paymentList = getCustomerPaymentsWithCredit(Org, bp, isReceipt, currency);
+    }
+    for (FIN_Payment payment : paymentList)
       creditAmount = creditAmount.add(payment.getGeneratedCredit()).subtract(
           payment.getUsedCredit());
     return creditAmount;
@@ -1923,6 +1934,15 @@
    */
   public List<FIN_Payment> getCustomerPaymentsWithCredit(Organization org, BusinessPartner bp,
       boolean isReceipt) {
+    return getCustomerPaymentsWithCredit(org, bp, isReceipt, null);
+  }
+
+  /**
+   * Returns the list of credit payments for the selected business partner that belongs to the legal
+   * entity's natural tree of the given organization
+   */
+  public List<FIN_Payment> getCustomerPaymentsWithCredit(Organization org, BusinessPartner bp,
+      boolean isReceipt, Currency currency) {
 
     try {
       OBContext.setAdminMode(true);
@@ -1936,6 +1956,9 @@
       Set<String> orgIds = OBContext.getOBContext().getOrganizationStructureProvider()
           .getChildTree(legalEntity.getId(), true);
       obcPayment.add(Restrictions.in("organization.id", orgIds));
+      if (currency != null) {
+        obcPayment.add(Restrictions.eq(FIN_Payment.PROPERTY_CURRENCY, currency));
+      }
       obcPayment.addOrderBy(FIN_Payment.PROPERTY_PAYMENTDATE, true);
       obcPayment.addOrderBy(FIN_Payment.PROPERTY_DOCUMENTNO, true);
 
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PaymentInAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PaymentInAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.financialmgmt.payment.FIN_Payment;
 
@@ -59,7 +60,9 @@
     BusinessPartner bpartner = paymentIn.getBusinessPartner();
     if (bpartner != null) {
       Organization org = paymentIn.getOrganization();
-      BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, true, org);
+      Currency currency = paymentIn.getCurrency();
+      BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, true, org,
+          currency);
       return customerCredit.signum() > 0;
     } else {
       return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PaymentOutAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PaymentOutAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.financialmgmt.payment.FIN_Payment;
 
@@ -59,7 +60,9 @@
       BusinessPartner bpartner = paymentOut.getBusinessPartner();
       if (bpartner != null) {
         Organization org = paymentOut.getOrganization();
-        BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, false, org);
+        Currency currency = paymentOut.getCurrency();
+        BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, false, org,
+            currency);
         return customerCredit.signum() > 0;
       } else {
         return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PurchaseInvoiceAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PurchaseInvoiceAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.invoice.Invoice;
 
@@ -60,7 +61,9 @@
       BusinessPartner bpartner = invoice.getBusinessPartner();
       if (bpartner != null) {
         Organization org = invoice.getOrganization();
-        BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, false, org);
+        Currency currency = invoice.getCurrency();
+        BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, false, org,
+            currency);
         return customerCredit.signum() > 0;
       } else {
         return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PurchaseOrderAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/PurchaseOrderAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.order.Order;
 
@@ -60,7 +61,9 @@
       BusinessPartner bpartner = order.getBusinessPartner();
       if (bpartner != null) {
         Organization org = order.getOrganization();
-        BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, false, org);
+        Currency currency = order.getCurrency();
+        BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, false, org,
+            currency);
         return (customerCredit.signum() > 0);
       } else {
         return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/SalesInvoiceAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/SalesInvoiceAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.invoice.Invoice;
 
@@ -59,7 +60,9 @@
     BusinessPartner bpartner = invoice.getBusinessPartner();
     if (bpartner != null) {
       Organization org = invoice.getOrganization();
-      BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, true, org);
+      Currency currency = invoice.getCurrency();
+      BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, true, org,
+          currency);
       return customerCredit.signum() > 0;
     } else {
       return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/SalesOrderAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/SalesOrderAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2014 Openbravo SLU
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.order.Order;
 
@@ -60,7 +61,9 @@
     BusinessPartner bpartner = order.getBusinessPartner();
     if (bpartner != null) {
       Organization org = order.getOrganization();
-      BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, true, org);
+      Currency currency = order.getCurrency();
+      BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner, true, org,
+          currency);
       return customerCredit.signum() > 0;
     } else {
       return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDisplayLogics.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDisplayLogics.java	Thu Jun 11 12:43:23 2015 +0200
@@ -28,6 +28,7 @@
 import org.openbravo.client.kernel.ComponentProvider;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
+import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.financialmgmt.payment.FIN_FinaccTransaction;
 
@@ -67,8 +68,9 @@
         BusinessPartner bpartner = OBDal.getInstance().get(BusinessPartner.class,
             strBusinessPartner);
         Organization org = OBDal.getInstance().get(Organization.class, context.get("ad_org_id"));
+        Currency currency = OBDal.getInstance().get(Currency.class, context.get("c_currency_id"));
         BigDecimal customerCredit = new AdvPaymentMngtDao().getCustomerCredit(bpartner,
-            "RCIN".equals(document), org);
+            "RCIN".equals(document), org, currency);
         return customerCredit.signum() > 0;
       } else {
         return false;
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/hqlinjections/CreditToUseTransformer.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/hqlinjections/CreditToUseTransformer.java	Thu Jun 11 12:43:23 2015 +0200
@@ -36,11 +36,16 @@
     transformedHQL = transformedHQL.replace("@whereClause@",
         getWhereClause(requestParameters, queryNamedParameters));
 
+    // Sets parameters
+    queryNamedParameters.put("currencyId", requestParameters.get("c_currency_id"));
+
     return transformedHQL;
   }
 
   private CharSequence getWhereClause(Map<String, String> requestParameters,
       Map<String, Object> queryNamedParameters) {
-    return " ";
+    StringBuffer whereClause = new StringBuffer();
+    whereClause.append(" and f.currency.id = :currencyId ");
+    return whereClause;
   }
 }
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ApplicationComponentProvider.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ApplicationComponentProvider.java	Thu Jun 11 12:43:23 2015 +0200
@@ -468,6 +468,7 @@
     globalResources.add(createStaticResource("web/js/periodControlStatus.js", true));
     globalResources.add(createStaticResource("web/js/productCharacteristicsProcess.js", true));
     globalResources.add(createStaticResource("web/js/validateCostingRuleProcess.js", true));
+    globalResources.add(createStaticResource("web/js/checkAvailableCredit.js", true));
 
     return globalResources;
   }
--- a/src-db/database/sourcedata/AD_MESSAGE.xml	Mon Jul 06 09:12:10 2015 +0200
+++ b/src-db/database/sourcedata/AD_MESSAGE.xml	Thu Jun 11 12:43:23 2015 +0200
@@ -17137,6 +17137,18 @@
 <!--1E4DFEDC675F4BD8AFA6A8D707D77FFF-->  <ISINCLUDEINI18N><![CDATA[N]]></ISINCLUDEINI18N>
 <!--1E4DFEDC675F4BD8AFA6A8D707D77FFF--></AD_MESSAGE>
 
+<!--1E7DAA08317D40A982A3484D3803A8B3--><AD_MESSAGE>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <AD_MESSAGE_ID><![CDATA[1E7DAA08317D40A982A3484D3803A8B3]]></AD_MESSAGE_ID>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <VALUE><![CDATA[BPCurrencyChangeRate]]></VALUE>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <MSGTEXT><![CDATA[It is not possible to convert credit automatically if current balance is 0 and foreign amount is different than 0. In this case, you should use a conversion rate instead.]]></MSGTEXT>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <MSGTYPE><![CDATA[W]]></MSGTYPE>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--1E7DAA08317D40A982A3484D3803A8B3-->  <ISINCLUDEINI18N><![CDATA[Y]]></ISINCLUDEINI18N>
+<!--1E7DAA08317D40A982A3484D3803A8B3--></AD_MESSAGE>
+
 <!--1EC11EDD0953422B9B4E8B54690CE345--><AD_MESSAGE>
 <!--1EC11EDD0953422B9B4E8B54690CE345-->  <AD_MESSAGE_ID><![CDATA[1EC11EDD0953422B9B4E8B54690CE345]]></AD_MESSAGE_ID>
 <!--1EC11EDD0953422B9B4E8B54690CE345-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
@@ -23218,6 +23230,22 @@
 <!--B077B434599241F6B04A8D01E8302C9C-->  <ISINCLUDEINI18N><![CDATA[N]]></ISINCLUDEINI18N>
 <!--B077B434599241F6B04A8D01E8302C9C--></AD_MESSAGE>
 
+<!--B080C88FF56E4F8594967A6164977D5F--><AD_MESSAGE>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <AD_MESSAGE_ID><![CDATA[B080C88FF56E4F8594967A6164977D5F]]></AD_MESSAGE_ID>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <VALUE><![CDATA[BPCurrencyChange]]></VALUE>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <MSGTEXT><![CDATA[Changing the currency of the Business Partner will not allow you to use available credit in the old currency.
+
+If you want to convert available credit in the old currency into credit in the new currency automatically, select a G/L Item. 
+
+Otherwise, you will have to do it manually following this document: http://wiki.openbravo.com/wiki/How_to_convert_credit_to_a_different_currency]]></MSGTEXT>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <MSGTYPE><![CDATA[W]]></MSGTYPE>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--B080C88FF56E4F8594967A6164977D5F-->  <ISINCLUDEINI18N><![CDATA[Y]]></ISINCLUDEINI18N>
+<!--B080C88FF56E4F8594967A6164977D5F--></AD_MESSAGE>
+
 <!--B0976829EBD64E38B342821AABA3ADAB--><AD_MESSAGE>
 <!--B0976829EBD64E38B342821AABA3ADAB-->  <AD_MESSAGE_ID><![CDATA[B0976829EBD64E38B342821AABA3ADAB]]></AD_MESSAGE_ID>
 <!--B0976829EBD64E38B342821AABA3ADAB-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/src-db/database/sourcedata/OBUIAPP_PARAMETER.xml	Mon Jul 06 09:12:10 2015 +0200
+++ b/src-db/database/sourcedata/OBUIAPP_PARAMETER.xml	Thu Jun 11 12:43:23 2015 +0200
@@ -397,7 +397,7 @@
 <!--6B8309393CF44CCD977219C72458D625-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
 <!--6B8309393CF44CCD977219C72458D625-->  <FIELDLENGTH><![CDATA[10]]></FIELDLENGTH>
 <!--6B8309393CF44CCD977219C72458D625-->  <ISMANDATORY><![CDATA[N]]></ISMANDATORY>
-<!--6B8309393CF44CCD977219C72458D625-->  <DEFAULTVALUE><![CDATA[1]]></DEFAULTVALUE>
+<!--6B8309393CF44CCD977219C72458D625-->  <DEFAULTVALUE><![CDATA["1"]]></DEFAULTVALUE>
 <!--6B8309393CF44CCD977219C72458D625-->  <AD_ELEMENT_ID><![CDATA[534]]></AD_ELEMENT_ID>
 <!--6B8309393CF44CCD977219C72458D625-->  <ISFIXED><![CDATA[N]]></ISFIXED>
 <!--6B8309393CF44CCD977219C72458D625-->  <EVALUATEFIXEDVALUE><![CDATA[N]]></EVALUATEFIXEDVALUE>
@@ -696,6 +696,31 @@
 <!--D18581DE288A4E3891A8F047355D1CE5-->  <DISPLAYTITLE><![CDATA[Y]]></DISPLAYTITLE>
 <!--D18581DE288A4E3891A8F047355D1CE5--></OBUIAPP_PARAMETER>
 
+<!--D6043E3651464549808E039AACA8CE70--><OBUIAPP_PARAMETER>
+<!--D6043E3651464549808E039AACA8CE70-->  <OBUIAPP_PARAMETER_ID><![CDATA[D6043E3651464549808E039AACA8CE70]]></OBUIAPP_PARAMETER_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--D6043E3651464549808E039AACA8CE70-->  <AD_MODULE_ID><![CDATA[0]]></AD_MODULE_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <NAME><![CDATA[G/L Item]]></NAME>
+<!--D6043E3651464549808E039AACA8CE70-->  <DESCRIPTION><![CDATA[An alias for the Account Combination which can be commonly used in daily operations.]]></DESCRIPTION>
+<!--D6043E3651464549808E039AACA8CE70-->  <HELP><![CDATA[General ledger item.]]></HELP>
+<!--D6043E3651464549808E039AACA8CE70-->  <SEQNO><![CDATA[60]]></SEQNO>
+<!--D6043E3651464549808E039AACA8CE70-->  <AD_REFERENCE_ID><![CDATA[95E2A8B50A254B2AAE6774B8C2F28120]]></AD_REFERENCE_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <AD_REFERENCE_VALUE_ID><![CDATA[1A6C5E0A5868417786ECCF3C02B17D65]]></AD_REFERENCE_VALUE_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <COLUMNNAME><![CDATA[c_glitem_id]]></COLUMNNAME>
+<!--D6043E3651464549808E039AACA8CE70-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--D6043E3651464549808E039AACA8CE70-->  <FIELDLENGTH><![CDATA[0]]></FIELDLENGTH>
+<!--D6043E3651464549808E039AACA8CE70-->  <ISMANDATORY><![CDATA[N]]></ISMANDATORY>
+<!--D6043E3651464549808E039AACA8CE70-->  <AD_ELEMENT_ID><![CDATA[800080]]></AD_ELEMENT_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <ISFIXED><![CDATA[N]]></ISFIXED>
+<!--D6043E3651464549808E039AACA8CE70-->  <EVALUATEFIXEDVALUE><![CDATA[N]]></EVALUATEFIXEDVALUE>
+<!--D6043E3651464549808E039AACA8CE70-->  <OBUIAPP_PROCESS_ID><![CDATA[B5C942145F354ABEBC9F16235D80D776]]></OBUIAPP_PROCESS_ID>
+<!--D6043E3651464549808E039AACA8CE70-->  <STARTINNEWLINE><![CDATA[N]]></STARTINNEWLINE>
+<!--D6043E3651464549808E039AACA8CE70-->  <DISPLAYEDROWS><![CDATA[5]]></DISPLAYEDROWS>
+<!--D6043E3651464549808E039AACA8CE70-->  <DISPLAYTITLE><![CDATA[Y]]></DISPLAYTITLE>
+<!--D6043E3651464549808E039AACA8CE70--></OBUIAPP_PARAMETER>
+
 <!--DBD34BCBFA5D4FFDBA7DDD0565581728--><OBUIAPP_PARAMETER>
 <!--DBD34BCBFA5D4FFDBA7DDD0565581728-->  <OBUIAPP_PARAMETER_ID><![CDATA[DBD34BCBFA5D4FFDBA7DDD0565581728]]></OBUIAPP_PARAMETER_ID>
 <!--DBD34BCBFA5D4FFDBA7DDD0565581728-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/src-db/database/sourcedata/OBUIAPP_PROCESS.xml	Mon Jul 06 09:12:10 2015 +0200
+++ b/src-db/database/sourcedata/OBUIAPP_PROCESS.xml	Thu Jun 11 12:43:23 2015 +0200
@@ -467,7 +467,9 @@
 <!--B5C942145F354ABEBC9F16235D80D776-->  <UIPATTERN><![CDATA[OBUIAPP_PickAndExecute]]></UIPATTERN>
 <!--B5C942145F354ABEBC9F16235D80D776-->  <ISMULTIRECORD><![CDATA[N]]></ISMULTIRECORD>
 <!--B5C942145F354ABEBC9F16235D80D776-->  <IS_EXPLICIT_ACCESS><![CDATA[N]]></IS_EXPLICIT_ACCESS>
+<!--B5C942145F354ABEBC9F16235D80D776-->  <CLIENTSIDEVALIDATION><![CDATA[OB.CheckAvailableCredit.onProcess]]></CLIENTSIDEVALIDATION>
 <!--B5C942145F354ABEBC9F16235D80D776-->  <ISGRIDLEGACY><![CDATA[Y]]></ISGRIDLEGACY>
+<!--B5C942145F354ABEBC9F16235D80D776-->  <ON_LOAD_FUNCTION><![CDATA[OB.CheckAvailableCredit.onLoad]]></ON_LOAD_FUNCTION>
 <!--B5C942145F354ABEBC9F16235D80D776-->  <ISCANADDRECORDSTOSELECTOR><![CDATA[N]]></ISCANADDRECORDSTOSELECTOR>
 <!--B5C942145F354ABEBC9F16235D80D776--></OBUIAPP_PROCESS>
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/common/actionhandler/CheckAvailableCreditActionHandler.java	Thu Jun 11 12:43:23 2015 +0200
@@ -0,0 +1,59 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2015 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+package org.openbravo.common.actionhandler;
+
+import java.util.Map;
+
+import org.apache.commons.lang.StringUtils;
+import org.codehaus.jettison.json.JSONObject;
+import org.hibernate.ScrollableResults;
+import org.openbravo.base.exception.OBException;
+import org.openbravo.client.kernel.BaseActionHandler;
+import org.openbravo.financial.FinancialUtils;
+
+public class CheckAvailableCreditActionHandler extends BaseActionHandler {
+
+  @Override
+  protected JSONObject execute(Map<String, Object> parameters, String data) {
+    try {
+      final JSONObject jsonData = new JSONObject(data);
+      final String businessPartnerId = jsonData.getString("businessPartnerId");
+      final String currencyId = jsonData.getString("currencyId");
+      JSONObject result = new JSONObject();
+
+      if (currencyId != null && !StringUtils.isEmpty(currencyId)) {
+        ScrollableResults scroll = FinancialUtils.getPaymentsWithCredit(businessPartnerId,
+            currencyId);
+        try {
+          result.put("availableCredit", scroll.next());
+        } catch (Exception e) {
+          result.put("availableCredit", false);
+        } finally {
+          scroll.close();
+        }
+      } else {
+        result.put("availableCredit", false);
+      }
+      return result;
+    } catch (Exception e) {
+      throw new OBException(e);
+    }
+  }
+}
\ No newline at end of file
--- a/src/org/openbravo/common/actionhandler/SetNewBPCurrency.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/src/org/openbravo/common/actionhandler/SetNewBPCurrency.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2014 Openbravo SLU 
+ * All portions are Copyright (C) 2014-2015 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -23,17 +23,28 @@
 import java.util.Date;
 import java.util.Map;
 
+import org.apache.commons.lang.StringUtils;
 import org.codehaus.jettison.json.JSONObject;
+import org.hibernate.ScrollableResults;
+import org.openbravo.advpaymentmngt.process.FIN_PaymentProcess;
 import org.openbravo.advpaymentmngt.utility.FIN_Utility;
+import org.openbravo.base.provider.OBProvider;
 import org.openbravo.client.application.process.BaseProcessActionHandler;
 import org.openbravo.client.kernel.RequestContext;
+import org.openbravo.dal.core.DalUtil;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.erpCommon.utility.OBMessageUtils;
+import org.openbravo.financial.FinancialUtils;
 import org.openbravo.model.common.businesspartner.BusinessPartner;
 import org.openbravo.model.common.currency.ConversionRate;
 import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
+import org.openbravo.model.financialmgmt.gl.GLItem;
+import org.openbravo.model.financialmgmt.payment.FIN_Payment;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentDetail;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
+import org.openbravo.model.financialmgmt.payment.FIN_Payment_Credit;
 import org.openbravo.service.db.DbUtility;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -57,6 +68,7 @@
       final boolean strSetAmount = params.getBoolean("Amount");
       final boolean strUseDefaultConversion = params.getBoolean("Default_Conversion_Rate");
       final String strBpartnerId = jsonRequest.getString("C_BPartner_ID");
+      final String glItemId = params.getString("c_glitem_id");
       BigDecimal creditUsed = BigDecimal.ZERO;
       BigDecimal rate = BigDecimal.ZERO;
       Double amount = new Double(0);
@@ -87,6 +99,217 @@
       BusinessPartner businessPartner = OBDal.getInstance().get(BusinessPartner.class,
           strBpartnerId);
       creditUsed = businessPartner.getCreditUsed();
+
+      ScrollableResults scroll = null;
+      GLItem glItem = OBDal.getInstance().get(GLItem.class, glItemId);
+      Currency currency = OBDal.getInstance().get(Currency.class, strToCurrencyId);
+      BigDecimal creditAmount = BigDecimal.ZERO;
+      BigDecimal creditRate = BigDecimal.ONE;
+
+      // Convert available credit automatically
+      if (!StringUtils.equals(strFromCurrencyId, strToCurrencyId) && !StringUtils.isEmpty(glItemId)
+          && !StringUtils.equals(glItemId, "null")) {
+
+        // Get the rate
+        if (!strSetAmount) {
+          creditRate = rate;
+        } else if (creditUsed.compareTo(BigDecimal.ZERO) != 0) {
+          creditRate = BigDecimal.valueOf(amount).divide(creditUsed);
+        }
+
+        // Loop through all payment documents which generate credit
+        scroll = FinancialUtils.getPaymentsWithCredit(businessPartner.getId(), strFromCurrencyId);
+        int i = 0;
+        try {
+          while (scroll.next()) {
+            final String paymentCreditId = (String) scroll.get()[0];
+            final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
+                paymentCreditId);
+            creditAmount = paymentCredit.getGeneratedCredit().subtract(
+                paymentCredit.getUsedCredit());
+
+            // Create a payment to consume the credit with a glitem
+            FIN_Payment payment1 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
+            payment1.setPaymentDate(new Date());
+            payment1.setAmount(creditAmount);
+            payment1.setDocumentNo(FIN_Utility.getDocumentNo(payment1.getOrganization(), payment1
+                .getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
+            payment1.setProcessed(false);
+            payment1.setPosted("N");
+            payment1.setDescription("GL Item: " + glItem.getName());
+            payment1.setGeneratedCredit(BigDecimal.ZERO);
+            payment1.setUsedCredit(BigDecimal.ZERO);
+
+            // Create a payment detail to consume the credit with a glitem
+            FIN_PaymentDetail paymentDetail1 = OBProvider.getInstance()
+                .get(FIN_PaymentDetail.class);
+            paymentDetail1.setClient(paymentCredit.getClient());
+            paymentDetail1.setOrganization(paymentCredit.getOrganization());
+            paymentDetail1.setFinPayment(payment1);
+            paymentDetail1.setAmount(creditAmount);
+            paymentDetail1.setRefund(false);
+            paymentDetail1.setGLItem(glItem);
+            paymentDetail1.setPrepayment(false);
+
+            // Create a payment schedule detail to consume the credit with a glitem
+            FIN_PaymentScheduleDetail paymentScheduleDetail1 = OBProvider.getInstance().get(
+                FIN_PaymentScheduleDetail.class);
+            paymentScheduleDetail1.setClient(paymentCredit.getClient());
+            paymentScheduleDetail1.setOrganization(paymentCredit.getOrganization());
+            paymentScheduleDetail1.setPaymentDetails(paymentDetail1);
+            paymentScheduleDetail1.setAmount(creditAmount);
+
+            // Process the payment
+            paymentDetail1.getFINPaymentScheduleDetailList().add(paymentScheduleDetail1);
+            payment1.getFINPaymentDetailList().add(paymentDetail1);
+            OBDal.getInstance().save(payment1);
+            OBDal.getInstance().save(paymentDetail1);
+            OBDal.getInstance().save(paymentScheduleDetail1);
+            FIN_PaymentProcess.doProcessPayment(payment1, "D", false, null, null);
+
+            // Create a payment to refund the credit
+            FIN_Payment payment2 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
+            payment2.setPaymentDate(new Date());
+            payment2.setAmount(creditAmount.negate());
+            payment2.setDocumentNo(FIN_Utility.getDocumentNo(payment2.getOrganization(), payment2
+                .getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
+            payment2.setProcessed(false);
+            payment2.setPosted("N");
+            payment2.setDescription("Refunded payment: " + payment1.getDocumentNo());
+            payment2.setGeneratedCredit(BigDecimal.ZERO);
+            payment2.setUsedCredit(creditAmount);
+
+            // Create a payment credit to refund the credit
+            FIN_Payment_Credit paymentCredit2 = OBProvider.getInstance().get(
+                FIN_Payment_Credit.class);
+            paymentCredit2.setClient(paymentCredit.getClient());
+            paymentCredit2.setOrganization(paymentCredit.getOrganization());
+            paymentCredit2.setPayment(payment2);
+            paymentCredit2.setCreditPaymentUsed(paymentCredit);
+            paymentCredit2.setAmount(creditAmount);
+            paymentCredit2.setCurrency(paymentCredit.getCurrency());
+
+            // Create a payment detail to refund the credit
+            FIN_PaymentDetail paymentDetail2 = OBProvider.getInstance()
+                .get(FIN_PaymentDetail.class);
+            paymentDetail2.setClient(paymentCredit.getClient());
+            paymentDetail2.setOrganization(paymentCredit.getOrganization());
+            paymentDetail2.setFinPayment(payment2);
+            paymentDetail2.setAmount(creditAmount.negate());
+            paymentDetail2.setRefund(true);
+            paymentDetail2.setPrepayment(true);
+
+            // Create a payment schedule detail to refund the credit
+            FIN_PaymentScheduleDetail paymentScheduleDetail2 = OBProvider.getInstance().get(
+                FIN_PaymentScheduleDetail.class);
+            paymentScheduleDetail2.setClient(paymentCredit.getClient());
+            paymentScheduleDetail2.setOrganization(paymentCredit.getOrganization());
+            paymentScheduleDetail2.setPaymentDetails(paymentDetail2);
+            paymentScheduleDetail2.setAmount(creditAmount.negate());
+
+            // Process the payment
+            paymentDetail2.getFINPaymentScheduleDetailList().add(paymentScheduleDetail2);
+            payment2.getFINPaymentDetailList().add(paymentDetail2);
+            payment2.getFINPaymentCreditList().add(paymentCredit2);
+            paymentCredit.setUsedCredit(creditAmount);
+            OBDal.getInstance().save(paymentCredit);
+            OBDal.getInstance().save(payment2);
+            OBDal.getInstance().save(paymentCredit2);
+            OBDal.getInstance().save(paymentDetail2);
+            OBDal.getInstance().save(paymentScheduleDetail2);
+            FIN_PaymentProcess.doProcessPayment(payment2, "D", false, null, null);
+
+            i++;
+            if (i % 100 == 0) {
+              OBDal.getInstance().flush();
+              OBDal.getInstance().getSession().clear();
+            }
+          }
+
+          // Set the new currency
+          businessPartner.setCurrency(currency);
+
+          // Loop through all payment documents which generate credit
+          scroll.beforeFirst();
+          i = 0;
+          while (scroll.next()) {
+            final String paymentCreditId = (String) scroll.get()[0];
+            final FIN_Payment paymentCredit = OBDal.getInstance().get(FIN_Payment.class,
+                paymentCreditId);
+
+            // Create a payment to create the credit with a glitem
+            FIN_Payment payment3 = (FIN_Payment) DalUtil.copy(paymentCredit, false);
+            payment3.setPaymentDate(new Date());
+            payment3.setCurrency(currency);
+            payment3.setAmount(BigDecimal.ZERO);
+            payment3.setDocumentNo(FIN_Utility.getDocumentNo(payment3.getOrganization(), payment3
+                .getDocumentType().getDocumentCategory(), "DocumentNo_FIN_Payment"));
+            payment3.setProcessed(false);
+            payment3.setPosted("N");
+            payment3.setDescription("GL Item: " + glItem.getName());
+            payment3.setGeneratedCredit(creditAmount.multiply(creditRate));
+            payment3.setUsedCredit(BigDecimal.ZERO);
+
+            // Create a payment detail to create the credit with a glitem
+            FIN_PaymentDetail paymentDetail3 = OBProvider.getInstance()
+                .get(FIN_PaymentDetail.class);
+            paymentDetail3.setClient(paymentCredit.getClient());
+            paymentDetail3.setOrganization(paymentCredit.getOrganization());
+            paymentDetail3.setFinPayment(payment3);
+            paymentDetail3.setAmount(creditAmount.multiply(creditRate));
+            paymentDetail3.setRefund(false);
+            paymentDetail3.setPrepayment(true);
+
+            // Create a payment detail to create the credit with a glitem
+            FIN_PaymentDetail paymentDetail4 = OBProvider.getInstance()
+                .get(FIN_PaymentDetail.class);
+            paymentDetail4.setClient(paymentCredit.getClient());
+            paymentDetail4.setOrganization(paymentCredit.getOrganization());
+            paymentDetail4.setFinPayment(payment3);
+            paymentDetail4.setAmount(creditAmount.multiply(creditRate).negate());
+            paymentDetail4.setGLItem(glItem);
+            paymentDetail4.setRefund(false);
+            paymentDetail4.setPrepayment(false);
+
+            // Create a payment schedule detail to create the credit with a glitem
+            FIN_PaymentScheduleDetail paymentScheduleDetail3 = OBProvider.getInstance().get(
+                FIN_PaymentScheduleDetail.class);
+            paymentScheduleDetail3.setClient(paymentCredit.getClient());
+            paymentScheduleDetail3.setOrganization(paymentCredit.getOrganization());
+            paymentScheduleDetail3.setPaymentDetails(paymentDetail3);
+            paymentScheduleDetail3.setAmount(creditAmount.multiply(creditRate));
+
+            // Create a payment schedule detail to create the credit with a glitem
+            FIN_PaymentScheduleDetail paymentScheduleDetail4 = OBProvider.getInstance().get(
+                FIN_PaymentScheduleDetail.class);
+            paymentScheduleDetail4.setClient(paymentCredit.getClient());
+            paymentScheduleDetail4.setOrganization(paymentCredit.getOrganization());
+            paymentScheduleDetail4.setPaymentDetails(paymentDetail4);
+            paymentScheduleDetail4.setAmount(creditAmount.multiply(creditRate).negate());
+
+            // Process the payment
+            paymentDetail3.getFINPaymentScheduleDetailList().add(paymentScheduleDetail3);
+            paymentDetail4.getFINPaymentScheduleDetailList().add(paymentScheduleDetail4);
+            payment3.getFINPaymentDetailList().add(paymentDetail3);
+            payment3.getFINPaymentDetailList().add(paymentDetail4);
+            OBDal.getInstance().save(payment3);
+            OBDal.getInstance().save(paymentDetail3);
+            OBDal.getInstance().save(paymentDetail4);
+            OBDal.getInstance().save(paymentScheduleDetail3);
+            OBDal.getInstance().save(paymentScheduleDetail4);
+            FIN_PaymentProcess.doProcessPayment(payment3, "D", false, null, null);
+
+            i++;
+            if (i % 100 == 0) {
+              OBDal.getInstance().flush();
+              OBDal.getInstance().getSession().clear();
+            }
+          }
+        } finally {
+          scroll.close();
+        }
+      }
+
       if (strSetAmount && creditUsed.compareTo(BigDecimal.valueOf(amount)) != 0) {
         businessPartner.setCreditUsed(BigDecimal.valueOf(amount));
       }
--- a/src/org/openbravo/financial/FinancialUtils.java	Mon Jul 06 09:12:10 2015 +0200
+++ b/src/org/openbravo/financial/FinancialUtils.java	Thu Jun 11 12:43:23 2015 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2012 Openbravo SLU
+ * All portions are Copyright (C) 2012-2015 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -27,6 +27,9 @@
 
 import org.apache.commons.lang.time.DateUtils;
 import org.apache.log4j.Logger;
+import org.hibernate.Query;
+import org.hibernate.ScrollMode;
+import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.util.Check;
@@ -43,6 +46,7 @@
 import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.plm.Product;
+import org.openbravo.model.financialmgmt.payment.FIN_Payment;
 import org.openbravo.model.pricing.pricelist.PriceList;
 import org.openbravo.model.pricing.pricelist.PriceListVersion;
 import org.openbravo.model.pricing.pricelist.ProductPrice;
@@ -341,4 +345,27 @@
         procedureName, parameters, null);
     return lineNetAmount;
   }
+
+  /**
+   * Get all the payment details with available credit
+   * 
+   * @param businessPartner
+   * @param currency
+   * @return
+   */
+  public static ScrollableResults getPaymentsWithCredit(String businessPartnerId, String currencyId) {
+    StringBuilder hql = new StringBuilder();
+    hql.append(" SELECT t1." + FIN_Payment.PROPERTY_ID);
+    hql.append(" FROM " + FIN_Payment.ENTITY_NAME + " as t1");
+    hql.append(" WHERE t1." + FIN_Payment.PROPERTY_BUSINESSPARTNER + ".id = :businessPartnerId");
+    hql.append(" AND t1." + FIN_Payment.PROPERTY_CURRENCY + ".id = :currencyId");
+    hql.append(" AND t1." + FIN_Payment.PROPERTY_GENERATEDCREDIT + " <> 0");
+    hql.append(" AND t1." + FIN_Payment.PROPERTY_GENERATEDCREDIT + " <> t1."
+        + FIN_Payment.PROPERTY_USEDCREDIT);
+    final Query query = OBDal.getInstance().getSession().createQuery(hql.toString());
+    query.setParameter("businessPartnerId", businessPartnerId);
+    query.setParameter("currencyId", currencyId);
+    ScrollableResults scroll = query.scroll(ScrollMode.SCROLL_SENSITIVE);
+    return scroll;
+  }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/web/js/checkAvailableCredit.js	Thu Jun 11 12:43:23 2015 +0200
@@ -0,0 +1,60 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.0  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2015 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+OB.CheckAvailableCredit = {};
+
+OB.CheckAvailableCredit.onLoad = function (view) {
+  var callback, form = view.theForm,
+      businessPartnerId = view.parentWindow.view.getContextInfo().C_BPartner_ID,
+      currencyId = form.getItem('C_Currency_ID').getValue();
+  
+  callback = function (response, data, request) {    
+    if (data.availableCredit) {
+      view.messageBar.setMessage(isc.OBMessageBar.TYPE_INFO, null, OB.I18N.getLabel('BPCurrencyChange'));
+      form.getItem('c_glitem_id').visible = true;
+    }
+    else {
+      form.getItem('c_glitem_id').visible = false;
+    }
+    form.redraw();
+  };
+
+  OB.RemoteCallManager.call('org.openbravo.common.actionhandler.CheckAvailableCreditActionHandler', {
+	businessPartnerId: businessPartnerId,
+	currencyId: currencyId
+  }, {}, callback);  
+};
+
+OB.CheckAvailableCredit.onProcess = function (view, actionHandlerCall, clientSideValidationFail) {
+  var form = view.theForm,                    
+      currencyFromId = view.parentWindow.view.getContextInfo().inpbpCurrencyId,
+      currencyToId = form.getItem('C_Currency_ID').getValue(),
+      glItemId = form.getItem('c_glitem_id').getValue(),
+      setAmount = form.getItem("Amount").getValue(),
+      currentBalance = view.parentWindow.view.getContextInfo().inpsoCreditused,
+      foreignAmount = form.getItem('Foreign_Amount').getValue();
+      
+  if (currencyFromId !== currencyToId && glItemId && setAmount === true && currentBalance === 0 && foreignAmount !== 0) {
+	view.messageBar.setMessage(isc.OBMessageBar.TYPE_ERROR, null, OB.I18N.getLabel('BPCurrencyChangeRate'));
+    return clientSideValidationFail();
+  }
+  else {
+    actionHandlerCall();
+  }
+};
\ No newline at end of file