Fixes issue 33086: Accounting info not loaded when login
authorSanjota <sanjota.nelagi@promantia.com>
Thu, 02 Jun 2016 12:39:23 +0200
changeset 28900 f99d0caa788f
parent 28899 4f8e8fd51a68
child 28901 3a1ad2624dae
Fixes issue 33086: Accounting info not loaded when login

Unhomogeneous behavior depending on Org Access when role is defined at "Organization" user level.
Accounting info was not loaded when login with a role without access to any general ledger's organization.
src/org/openbravo/base/secureApp/Attribute_data.xsql
src/org/openbravo/base/secureApp/LoginUtils.java
src/org/openbravo/erpCommon/utility/OBLedgerUtils.java
--- a/src/org/openbravo/base/secureApp/Attribute_data.xsql	Mon May 30 18:33:13 2016 +0200
+++ b/src/org/openbravo/base/secureApp/Attribute_data.xsql	Thu Jun 02 12:39:23 2016 +0200
@@ -24,10 +24,10 @@
         WHERE a.C_AcctSchema_ID=ae.C_ACCTSCHEMA_ID 
         AND ae.ISACTIVE = 'Y'
         AND a.AD_CLIENT_ID IN ('1') 
-        AND a.AD_ORG_ID IN ('1')
+        AND a.C_AcctSchema_ID IN ('1')
       ]]></Sql>
       <Parameter name="clientlist" optional="true" type="replace" after="AND a.AD_CLIENT_ID IN (" text="'1'"/>
-      <Parameter name="orglist" optional="true" type="replace" after="AND a.AD_ORG_ID IN (" text="'1'"/>
+      <Parameter name="acctId" optional="true" type="replace" after="AND a.C_AcctSchema_ID IN (" text="'1'"/>
    </SqlMethod>
    <SqlMethod name="selectIsSOTrx" type="preparedStatement" return="multiple">
       <SqlMethodComment></SqlMethodComment>
--- a/src/org/openbravo/base/secureApp/LoginUtils.java	Mon May 30 18:33:13 2016 +0200
+++ b/src/org/openbravo/base/secureApp/LoginUtils.java	Thu Jun 02 12:39:23 2016 +0200
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2014 Openbravo S.L.U.
+ * Copyright (C) 2001-2016 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -21,6 +21,7 @@
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 
+import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.openbravo.base.HttpBaseUtils;
 import org.openbravo.base.exception.OBException;
@@ -32,6 +33,7 @@
 import org.openbravo.erpCommon.businessUtility.Preferences;
 import org.openbravo.erpCommon.security.SessionLogin;
 import org.openbravo.erpCommon.utility.DimensionDisplayUtility;
+import org.openbravo.erpCommon.utility.OBLedgerUtils;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.access.RoleOrganization;
 import org.openbravo.model.ad.domain.Preference;
@@ -257,9 +259,23 @@
       vars.setSessionValue("#Client_SMTP", data[0].smtphost);
       data = null;
 
-      AttributeData[] attr = AttributeData.select(conn,
-          Utility.getContext(conn, vars, "#User_Client", "LoginHandler"),
-          Utility.getContext(conn, vars, "#User_Org", "LoginHandler"));
+      String[] orgList = Utility.getContext(conn, vars, "#User_Org", "LoginHandler").split(",");
+      AttributeData[] attr = null;
+      int j = 0;
+      String acctschemaId = null;
+
+      for (String orgIdString : orgList) {
+        String orgId = orgIdString.replace("'", "");
+        acctschemaId = OBLedgerUtils.getOrgLedger(orgId);
+        if (StringUtils.isNotEmpty(acctschemaId)) {
+          acctschemaId = "'" + acctschemaId + "'";
+          break;
+        }
+      }
+
+      attr = AttributeData.select(conn,
+          Utility.getContext(conn, vars, "#User_Client", "LoginHandler"), acctschemaId);
+
       if (attr != null && attr.length > 0) {
         vars.setSessionValue("$C_AcctSchema_ID", attr[0].value);
         if (orgCurrency.length > 0) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/erpCommon/utility/OBLedgerUtils.java	Thu Jun 02 12:39:23 2016 +0200
@@ -0,0 +1,114 @@
+/*
+ *************************************************************************
+ * 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) 2016 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.erpCommon.utility;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+import org.hibernate.Query;
+import org.openbravo.dal.core.OBContext;
+import org.openbravo.dal.service.OBDal;
+import org.openbravo.model.common.enterprise.Organization;
+import org.openbravo.model.financialmgmt.accounting.coa.AcctSchema;
+
+/**
+ * Utilities to get AcctSchema
+ */
+public class OBLedgerUtils {
+  private static Logger log4j = Logger.getLogger(OBLedgerUtils.class);
+
+  /**
+   * Returns the ledger id for the given organization id.
+   * 
+   * If the org id is empty, it returns null. If the given organization has no ledger, it tries to
+   * get its legal entity's ledger. If not found, it returns the organization client's ledger
+   * 
+   * @param orgId
+   *          Organization Id whose ledger is needed
+   * 
+   * @return String ledgerId ledger id for the given organization. Null if not found
+   */
+  public static String getOrgLedger(String orgId) {
+    try {
+      OBContext.setAdminMode(true);
+
+      if (StringUtils.isBlank(orgId)) {
+        // No organization
+        return null;
+      }
+      final Organization org = OBDal.getInstance().get(Organization.class, orgId);
+      if (org == null) {
+        // No organization
+        return null;
+      }
+      String acctSchemaId = getOrgLedgerRecursive(orgId);
+      if (!StringUtils.isEmpty(acctSchemaId)) {
+        // Get ledger of organization tree
+        return acctSchemaId;
+      }
+      String clientId = StringUtils.equals(orgId, "0") ? OBContext.getOBContext()
+          .getCurrentClient().getId() : org.getClient().getId();
+      // Get client base Ledger
+      return getClientLedger(clientId);
+
+    } catch (Exception e) {
+      log4j.error("Impossible to get ledger for organization id " + orgId, e);
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+
+    return null;
+  }
+
+  private static String getOrgLedgerRecursive(String orgId) {
+    try {
+      OBContext.setAdminMode(true);
+      StringBuffer where = new StringBuffer();
+      where.append(" select " + Organization.PROPERTY_GENERALLEDGER + ".id");
+      where.append(" from " + Organization.ENTITY_NAME);
+      where.append(" where ad_isorgincluded(:orgId, " + Organization.PROPERTY_ID + ", "
+          + Organization.PROPERTY_CLIENT + ".id) <> -1");
+      where.append(" and " + Organization.PROPERTY_GENERALLEDGER + " is not null");
+      where.append(" order by ad_isorgincluded(:orgId, " + Organization.PROPERTY_ID + ", "
+          + Organization.PROPERTY_CLIENT + ".id)");
+      Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+      qry.setParameter("orgId", orgId);
+      qry.setMaxResults(1);
+      return (String) qry.uniqueResult();
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+  }
+
+  private static String getClientLedger(String clientId) {
+    try {
+      OBContext.setAdminMode(true);
+      StringBuffer where = new StringBuffer();
+      where.append(" select " + AcctSchema.PROPERTY_ID);
+      where.append(" from " + AcctSchema.ENTITY_NAME);
+      where.append(" where " + AcctSchema.PROPERTY_CLIENT + ".id = :clientId");
+      where.append(" order by " + AcctSchema.PROPERTY_NAME);
+      Query qry = OBDal.getInstance().getSession().createQuery(where.toString());
+      qry.setParameter("clientId", clientId);
+      qry.setMaxResults(1);
+      return (String) qry.uniqueResult();
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+  }
+}