// Determines the Contract Date of a Phase or a Task, based on the Standard
 // Duration in Days of the Standard Phase or the Standard Task
 private String calculateContractDate(
     String strStartDate, String strStdDuration, DateFormat DateFormatter) throws ParseException {
   String strContractDate = "";
   if (strStartDate != null
       && !strStartDate.equals("")
       && strStdDuration != null
       && !strStdDuration.equals("")) {
     strContractDate = strStartDate; // Contract Date equals to Starting
     // Date
     Integer StdDuration = Integer.parseInt(strStdDuration) - 1;
     int DaysLeft = StdDuration;
     while (DaysLeft > 0) {
       strContractDate = Utility.addDaysToDate(strContractDate, "1", DateFormatter); // Contract
       // Date equals
       // to Starting
       // Date
       // plus one day until the standard
       // duration in days is reached
       if (!Utility.isWeekendDay(strContractDate, DateFormatter))
         DaysLeft--; // If strContractDate is a weekend day, looks
       // for the next labor day
     }
   }
   return strContractDate;
 }
  private BusinessPartnerCategoryData getEditVariables(Connection con, VariablesSecureApp vars)
      throws IOException, ServletException {
    BusinessPartnerCategoryData data = new BusinessPartnerCategoryData();
    ServletException ex = null;
    try {
      data.adOrgId = vars.getRequiredGlobalVariable("inpadOrgId", windowId + "|AD_Org_ID");
      data.adOrgIdr = vars.getStringParameter("inpadOrgId_R");
      data.cBpGroupId = vars.getRequestGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      data.value = vars.getStringParameter("inpvalue");
      data.name = vars.getRequiredStringParameter("inpname");
      data.description = vars.getStringParameter("inpdescription");
      data.isactive = vars.getStringParameter("inpisactive", "N");
      data.isdefault = vars.getStringParameter("inpisdefault", "N");
      data.adClientId = vars.getRequiredGlobalVariable("inpadClientId", windowId + "|AD_Client_ID");
      data.createdby = vars.getUser();
      data.updatedby = vars.getUser();
      data.adUserClient = Utility.getContext(this, vars, "#User_Client", windowId, accesslevel);
      data.adOrgClient =
          Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel);
      data.updatedTimeStamp = vars.getStringParameter("updatedTimestamp");

      if (data.value.equals(""))
        data.value =
            Utility.getDocumentNoConnection(con, this, vars.getClient(), "C_BP_Group", true);
    } catch (ServletException e) {
      vars.setEditionData(tabId, data);
      throw e;
    }
    // Behavior with exception for numeric fields is to catch last one if we have multiple ones
    if (ex != null) {
      vars.setEditionData(tabId, data);
      throw ex;
    }
    return data;
  }
  private void processButton(VariablesSecureApp vars, String strClient) throws ServletException {
    String pinstance = SequenceIdData.getUUID();
    OBError myMessage = null;
    try {
      if (strClient.equals("")) {
        myMessage = new OBError();
        myMessage.setType("Error");
        myMessage.setTitle(
            Utility.parseTranslation(
                this, vars, vars.getLanguage(), "@DeleteClient_NoClientSelected@"));
        myMessage.setMessage(
            Utility.parseTranslation(
                this, vars, vars.getLanguage(), "@DeleteClient_SelectClient@"));
      } else {
        Client client = OBDal.getInstance().get(Client.class, strClient);
        SystemService.getInstance().deleteClient(client);
      }
    } catch (Exception e) {
      myMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage());
      e.printStackTrace();
      log4j.warn("Error");
    }
    if (myMessage == null) {
      myMessage = new OBError();
      myMessage.setType("Success");
      myMessage.setTitle("");
      myMessage.setMessage(Utility.messageBD(this, "Success", vars.getLanguage()));
    }

    vars.setMessage("DeleteClient", myMessage);
  }
 private void refreshSessionNew(VariablesSecureApp vars) throws IOException, ServletException {
   BusinessPartnerCategoryData[] data =
       BusinessPartnerCategoryData.selectEdit(
           this,
           vars.getSessionValue("#AD_SqlDateTimeFormat"),
           vars.getLanguage(),
           vars.getStringParameter("inpcBpGroupId", ""),
           Utility.getContext(this, vars, "#User_Client", windowId),
           Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel));
   if (data == null || data.length == 0) return;
   refreshSessionEdit(vars, data);
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    VariablesSecureApp vars = new VariablesSecureApp(request);

    if (vars.commandIn("DEFAULT")) {
      String strProcessId = vars.getStringParameter("inpProcessId");
      String strWindow = vars.getStringParameter("inpwindowId");
      String strTab = vars.getStringParameter("inpTabId");
      String strProjectType = vars.getStringParameter("inpcProjecttypeId", "");
      String strKey = vars.getGlobalVariable("inpcProjectId", strWindow + "|C_Project_ID");
      if (!ProjectSetTypeData.hasProjectType(this, strKey))
        printPage(response, vars, strKey, strProjectType, strWindow, strTab, strProcessId);
      else bdError(request, response, "ProjectSetTypeError", vars.getLanguage());
    } else if (vars.commandIn("SAVE")) {
      String strWindow = vars.getStringParameter("inpwindowId");
      String strProjectType = vars.getStringParameter("inpcProjecttypeId");
      String strDateFrom = vars.getStringParameter("inpDateFrom");
      String strKey = vars.getRequestGlobalVariable("inpcProjectId", strWindow + "|C_Project_ID");
      String strTab = vars.getStringParameter("inpTabId");

      String strWindowPath = Utility.getTabURL(strTab, "R", true);
      if (strWindowPath.equals("")) strWindowPath = strDefaultServlet;

      OBError myMessage = processButton(vars, strKey, strProjectType, strDateFrom, strWindow);
      vars.setMessage(strTab, myMessage);
      printPageClosePopUp(response, vars, strWindowPath);
    } else pageErrorPopUp(response);
  }
 private String substituteContextParameters(String currentWhereClause) {
   // This method will check for any remaining @param@s
   // If there are still some in the whereclause, they will be resolved by calling the getContext()
   // method
   if (!currentWhereClause.contains("@")) {
     return currentWhereClause;
   }
   String localWhereClause = currentWhereClause;
   while (localWhereClause.contains("@")) {
     int firstAtIndex = localWhereClause.indexOf("@");
     String prefix = localWhereClause.substring(0, firstAtIndex);
     String restOfClause = localWhereClause.substring(firstAtIndex + 1);
     int secondAtIndex = restOfClause.indexOf("@");
     if (secondAtIndex == -1) {
       // No second @. We return the clause as it is
       return localWhereClause;
     }
     String suffix = restOfClause.substring(secondAtIndex + 1);
     String param = restOfClause.substring(0, secondAtIndex);
     String paramValue =
         Utility.getContext(
             new DalConnectionProvider(false),
             RequestContext.get().getVariablesSecureApp(),
             param,
             RequestContext.get().getRequestParameter("windowId"));
     localWhereClause = prefix + getTypedParameterAlias() + suffix;
     typedParameters.add(paramValue);
   }
   return localWhereClause;
 }
 public void onUpdate(@Observes EntityUpdateEvent event) {
   if (!isValidEvent(event)) {
     return;
   }
   VariablesSecureApp vars = null;
   try {
     vars = RequestContext.get().getVariablesSecureApp();
   } catch (Exception e) {
     logger.error("Error:", e);
   }
   String currentTabId = vars.getStringParameter("tabId");
   if (BOM_PRODUCTION.equals(currentTabId)) {
     final Entity productionLineEntity =
         ModelProvider.getInstance().getEntity(ProductionLine.ENTITY_NAME);
     final BigDecimal ZERO = new BigDecimal("0");
     final Property productionPlanProperty =
         productionLineEntity.getProperty(ProductionLine.PROPERTY_PRODUCTIONPLAN);
     final Property movementQtyProperty =
         productionLineEntity.getProperty(ProductionLine.PROPERTY_MOVEMENTQUANTITY);
     final ProductionPlan productionPlan =
         (ProductionPlan) event.getCurrentState(productionPlanProperty);
     final BigDecimal currentMovementQty = (BigDecimal) event.getCurrentState(movementQtyProperty);
     final BigDecimal previousMovementQty =
         (BigDecimal) event.getPreviousState(movementQtyProperty);
     OBCriteria<ProductionLine> productionLineCriteria =
         OBDal.getInstance().createCriteria(ProductionLine.class);
     productionLineCriteria.add(
         Restrictions.eq(ProductionLine.PROPERTY_PRODUCTIONPLAN, productionPlan));
     productionLineCriteria.add(Restrictions.gt(ProductionLine.PROPERTY_MOVEMENTQUANTITY, ZERO));
     if (productionLineCriteria.count() > 0 && previousMovementQty != currentMovementQty) {
       if (currentMovementQty.compareTo(ZERO) == 1 && previousMovementQty.compareTo(ZERO) != 1) {
         String language = OBContext.getOBContext().getLanguage().getLanguage();
         ConnectionProvider conn = new DalConnectionProvider(false);
         throw new OBException(
             Utility.messageBD(conn, "@ConsumedProductWithPostiveQty@", language));
       } else if (currentMovementQty.compareTo(ZERO) == -1
           && previousMovementQty.compareTo(ZERO) != -1
           && productionLineCriteria.count() == 1) {
         String language = OBContext.getOBContext().getLanguage().getLanguage();
         ConnectionProvider conn = new DalConnectionProvider(false);
         throw new OBException(
             Utility.messageBD(conn, "@ProducedProductWithNegativeQty@", language));
       }
     }
   }
 }
  private void printPage(
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strDocTypeTarget,
      String strTabId,
      String strCInvoiceId)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: dataSheet");
    XmlDocument xmlDocument =
        xmlEngine
            .readXmlTemplate("org/openbravo/erpCommon/ad_callouts/CallOut")
            .createXmlDocument();

    SEInOutDocTypeData[] data = SEInOutDocTypeData.select(this, strDocTypeTarget);

    StringBuffer resultado = new StringBuffer();
    if (data == null || data.length == 0) resultado.append("var respuesta = null;");
    else {
      resultado.append("var calloutName='SL_Invoice_DocType';\n\n");
      resultado.append("var respuesta = new Array(");

      // check if doc type target is different, in this case assing new
      // documentno otherwise matain the previous one
      String strDoctypetargetinvoice =
          SEInOutDocTypeData.selectDoctypetargetinvoice(this, strCInvoiceId);

      if (strDoctypetargetinvoice == null
          || strDoctypetargetinvoice.equals("")
          || !strDoctypetargetinvoice.equals(strDocTypeTarget)) {
        String strDocumentNo = Utility.getDocumentNo(this, vars.getClient(), "C_Invoice", false);
        if (data[0].isdocnocontrolled.equals("Y")) strDocumentNo = data[0].currentnext;
        resultado.append("new Array(\"inpdocumentno\", \"<" + strDocumentNo + ">\"),");
      } else if (strDoctypetargetinvoice != null
          && !strDoctypetargetinvoice.equals("")
          && strDoctypetargetinvoice.equals(strDocTypeTarget))
        resultado.append(
            "new Array(\"inpdocumentno\", \""
                + SEInOutDocTypeData.selectActualinvoicedocumentno(this, strCInvoiceId)
                + "\"),");
      // ------

      resultado.append("new Array(\"inpdocbasetype\", \"" + data[0].docbasetype + "\")");
      String strPaymentRule = "";
      if (data[0].docbasetype.endsWith("C")) {
        strPaymentRule = "P";
        resultado.append(", new Array(\"inppaymentrule\", \"" + strPaymentRule + "\"),");
        String strNamePaymentRule = ListData.selectName(this, "195", "P");
        resultado.append("new Array(\"PaymentRule_BTN\", \"" + strNamePaymentRule + "\")");
      }
      resultado.append(");");
    }
    xmlDocument.setParameter("array", resultado.toString());
    xmlDocument.setParameter("frameName", "appFrame");
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
 private String getDisplayLogicContext(VariablesSecureApp vars, boolean isNew)
     throws IOException, ServletException {
   log4j.debug("Output: Display logic context fields");
   String result =
       "var strShowAudit=\""
           + (isNew ? "N" : Utility.getContext(this, vars, "ShowAudit", windowId))
           + "\";\n";
   return result;
 }
 // Determines the Starting Date of a Phase or a Task
 private String calculateStartDate(String strLastContractDate, DateFormat DateFormatter)
     throws ParseException {
   String strStartDate = "";
   if (strLastContractDate != null && !strLastContractDate.equals("")) {
     strStartDate = strLastContractDate; // Start Date equals to Last
     // Contract Date
     do {
       strStartDate = Utility.addDaysToDate(strStartDate, "1", DateFormatter); // Start Date equals
       // to Last Contract
       // Date plus one day
     } while (Utility.isWeekendDay(strStartDate, DateFormatter)); // If
     // strStartDate
     // is a
     // weekend
     // day,
     // looks
     // for
     // the
     // next
     // labor
     // day
   }
   return strStartDate;
 }
 /**
  * Checks that no other ADTree structured tree exists for this table, throws an exception if this
  * occurs
  *
  * @param table table being checked
  * @param treeStructure treestructure of the added/updated tree
  * @param recordId null if a new record is being created or id of the record being modified
  */
 private void checkTreeStructure(Table table, String treeStructure, String recordId) {
   if (ADTREE_STRUCTURE.equals(treeStructure)) {
     // Check that there is no other ADTree Defined for this table
     OBCriteria<TableTree> obq = OBDal.getInstance().createCriteria(TableTree.class);
     obq.add(Restrictions.eq(TableTree.PROPERTY_TABLE, table));
     obq.add(Restrictions.eq(TableTree.PROPERTY_TREESTRUCTURE, treeStructure));
     if (recordId != null) {
       obq.add(Restrictions.ne(TableTree.PROPERTY_ID, recordId));
     }
     if (obq.count() > 0) {
       String language = OBContext.getOBContext().getLanguage().getLanguage();
       ConnectionProvider conn = new DalConnectionProvider(false);
       throw new OBException(Utility.messageBD(conn, "OBUIAPP_OneADTreePerTable", language));
     }
   }
 }
  public static OBError openClosePeriodControl(String periodControlId) {
    OBError myMessage = new OBError();
    OBContext.setAdminMode(true);
    Process process = null;
    try {
      process = OBDal.getInstance().get(Process.class, "168");
    } finally {
      OBContext.restorePreviousMode();
    }

    Map<String, String> parameters = new HashMap<String, String>();
    final ProcessInstance pinstance =
        CallProcess.getInstance().call(process, periodControlId, parameters);
    VariablesSecureApp vars = RequestContext.get().getVariablesSecureApp();
    try {
      ConnectionProvider conn = new DalConnectionProvider(false);
      myMessage =
          Utility.getProcessInstanceMessage(
              conn, vars, PInstanceProcessData.select(conn, pinstance.getId()));
    } catch (ServletException e) {
      throw new OBException("Failure getting error message", e);
    }
    return myMessage;
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    TableSQLData tableSQL = null;
    VariablesSecureApp vars = new VariablesSecureApp(request);
    Boolean saveRequest = (Boolean) request.getAttribute("autosave");

    if (saveRequest != null && saveRequest) {
      String currentOrg = vars.getStringParameter("inpadOrgId");
      String currentClient = vars.getStringParameter("inpadClientId");
      boolean editableTab =
          (!org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
                  this, vars.getRole(), tabId)
              && (currentOrg.equals("")
                  || Utility.isElementInList(
                      Utility.getContext(this, vars, "#User_Org", windowId, accesslevel),
                      currentOrg))
              && (currentClient.equals("")
                  || Utility.isElementInList(
                      Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                      currentClient)));

      OBError myError = new OBError();
      String commandType = request.getParameter("inpCommandType");
      String strcBpGroupId = request.getParameter("inpcBpGroupId");

      if (editableTab) {
        int total = 0;

        if (commandType.equalsIgnoreCase("EDIT") && !strcBpGroupId.equals(""))
          total = saveRecord(vars, myError, 'U');
        else total = saveRecord(vars, myError, 'I');

        if (!myError.isEmpty() && total == 0) throw new OBException(myError.getMessage());
      }
      vars.setSessionValue(request.getParameter("mappingName") + "|hash", vars.getPostDataHash());
      vars.setSessionValue(tabId + "|Header.view", "EDIT");

      return;
    }

    try {
      tableSQL =
          new TableSQLData(
              vars,
              this,
              tabId,
              Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel),
              Utility.getContext(this, vars, "#User_Client", windowId),
              Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    String strOrderBy = vars.getSessionValue(tabId + "|orderby");
    if (!strOrderBy.equals("")) {
      vars.setSessionValue(tabId + "|newOrder", "1");
    }

    if (vars.commandIn("DEFAULT")) {

      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      if (strView.equals("")) {
        strView = defaultTabView;

        if (strView.equals("EDIT")) {
          if (strC_BP_Group_ID.equals("")) strC_BP_Group_ID = firstElement(vars, tableSQL);
          if (strC_BP_Group_ID.equals("")) strView = "RELATION";
        }
      }
      if (strView.equals("EDIT"))
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);
      else printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("DIRECT")) {
      String strC_BP_Group_ID = vars.getStringParameter("inpDirectKey");

      if (strC_BP_Group_ID.equals(""))
        strC_BP_Group_ID =
            vars.getRequiredGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      else vars.setSessionValue(windowId + "|C_BP_Group_ID", strC_BP_Group_ID);

      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "EDIT");

      printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

    } else if (vars.commandIn("TAB")) {

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      String strC_BP_Group_ID = "";
      if (strView.equals("")) {
        strView = defaultTabView;
        if (strView.equals("EDIT")) {
          strC_BP_Group_ID = firstElement(vars, tableSQL);
          if (strC_BP_Group_ID.equals("")) strView = "RELATION";
        }
      }
      if (strView.equals("EDIT")) {

        if (strC_BP_Group_ID.equals("")) strC_BP_Group_ID = firstElement(vars, tableSQL);
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

      } else printPageDataSheet(response, vars, "", tableSQL);
    } else if (vars.commandIn("SEARCH")) {
      vars.getRequestGlobalVariable("inpParamName", tabId + "|paramName");

      vars.getRequestGlobalVariable("inpParamUpdated", tabId + "|paramUpdated");
      vars.getRequestGlobalVariable("inpParamUpdatedBy", tabId + "|paramUpdatedBy");
      vars.getRequestGlobalVariable("inpParamCreated", tabId + "|paramCreated");
      vars.getRequestGlobalVariable("inpparamCreatedBy", tabId + "|paramCreatedBy");

      vars.removeSessionValue(windowId + "|C_BP_Group_ID");
      String strC_BP_Group_ID = "";

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      if (strView.equals("")) strView = defaultTabView;

      if (strView.equals("EDIT")) {
        strC_BP_Group_ID = firstElement(vars, tableSQL);
        if (strC_BP_Group_ID.equals("")) {
          // filter returns empty set
          strView = "RELATION";
          // switch to grid permanently until the user changes the view again
          vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", strView);
        }
      }

      if (strView.equals("EDIT"))
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);
      else printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("RELATION")) {

      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "RELATION");
      printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("NEW")) {

      printPageEdit(response, request, vars, true, "", tableSQL);

    } else if (vars.commandIn("EDIT")) {

      @SuppressWarnings("unused") // In Expense Invoice tab this variable is not used, to be fixed
      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "EDIT");

      setHistoryCommand(request, "EDIT");
      printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

    } else if (vars.commandIn("NEXT")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");

      String strNext = nextElement(vars, strC_BP_Group_ID, tableSQL);

      printPageEdit(response, request, vars, false, strNext, tableSQL);
    } else if (vars.commandIn("PREVIOUS")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");

      String strPrevious = previousElement(vars, strC_BP_Group_ID, tableSQL);

      printPageEdit(response, request, vars, false, strPrevious, tableSQL);
    } else if (vars.commandIn("FIRST_RELATION")) {

      vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", "0");
      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("PREVIOUS_RELATION")) {

      String strInitRecord =
          vars.getSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber");
      String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
      int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
      if (strInitRecord.equals("") || strInitRecord.equals("0")) {
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", "0");
      } else {
        int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
        initRecord -= intRecordRange;
        strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", strInitRecord);
      }
      vars.removeSessionValue(windowId + "|C_BP_Group_ID");

      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("NEXT_RELATION")) {

      String strInitRecord =
          vars.getSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber");
      String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
      int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
      int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
      if (initRecord == 0) initRecord = 1;
      initRecord += intRecordRange;
      strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", strInitRecord);
      vars.removeSessionValue(windowId + "|C_BP_Group_ID");

      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("FIRST")) {

      String strFirst = firstElement(vars, tableSQL);

      printPageEdit(response, request, vars, false, strFirst, tableSQL);
    } else if (vars.commandIn("LAST_RELATION")) {

      String strLast = lastElement(vars, tableSQL);
      printPageDataSheet(response, vars, strLast, tableSQL);
    } else if (vars.commandIn("LAST")) {

      String strLast = lastElement(vars, tableSQL);

      printPageEdit(response, request, vars, false, strLast, tableSQL);
    } else if (vars.commandIn("SAVE_NEW_RELATION", "SAVE_NEW_NEW", "SAVE_NEW_EDIT")) {

      OBError myError = new OBError();
      int total = saveRecord(vars, myError, 'I');
      if (!myError.isEmpty()) {
        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
      } else {
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsInserted");
          myError.setMessage(total + " " + myError.getMessage());
          vars.setMessage(tabId, myError);
        }
        if (vars.commandIn("SAVE_NEW_NEW"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
        else if (vars.commandIn("SAVE_NEW_EDIT"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
      }
    } else if (vars.commandIn(
        "SAVE_EDIT_RELATION", "SAVE_EDIT_NEW", "SAVE_EDIT_EDIT", "SAVE_EDIT_NEXT")) {

      String strC_BP_Group_ID =
          vars.getRequiredGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      OBError myError = new OBError();
      int total = saveRecord(vars, myError, 'U');
      if (!myError.isEmpty()) {
        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
      } else {
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
          myError.setMessage(total + " " + myError.getMessage());
          vars.setMessage(tabId, myError);
        }
        if (vars.commandIn("SAVE_EDIT_NEW"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
        else if (vars.commandIn("SAVE_EDIT_EDIT"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        else if (vars.commandIn("SAVE_EDIT_NEXT")) {
          String strNext = nextElement(vars, strC_BP_Group_ID, tableSQL);
          vars.setSessionValue(windowId + "|C_BP_Group_ID", strNext);
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        } else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
      }
    } else if (vars.commandIn("DELETE")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");
      // BusinessPartnerCategoryData data = getEditVariables(vars);
      int total = 0;
      OBError myError = null;
      if (org.openbravo.erpCommon.utility.WindowAccessData.hasNotDeleteAccess(
          this, vars.getRole(), tabId)) {
        myError =
            Utility.translateError(
                this,
                vars,
                vars.getLanguage(),
                Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
        vars.setMessage(tabId, myError);
      } else {
        try {
          total =
              BusinessPartnerCategoryData.delete(
                  this,
                  strC_BP_Group_ID,
                  Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                  Utility.getContext(this, vars, "#User_Org", windowId, accesslevel));
        } catch (ServletException ex) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          if (!myError.isConnectionAvailable()) {
            bdErrorConnection(response);
            return;
          } else vars.setMessage(tabId, myError);
        }
        if (myError == null && total == 0) {
          myError =
              Utility.translateError(
                  this,
                  vars,
                  vars.getLanguage(),
                  Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
          vars.setMessage(tabId, myError);
        }
        vars.removeSessionValue(windowId + "|cBpGroupId");
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "RELATION");
      }
      if (myError == null) {
        myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsDeleted");
        myError.setMessage(total + " " + myError.getMessage());
        vars.setMessage(tabId, myError);
      }
      response.sendRedirect(strDireccion + request.getServletPath());

    } else if (vars.commandIn("SAVE_XHR")) {

      OBError myError = new OBError();
      JSONObject result = new JSONObject();
      String commandType = vars.getStringParameter("inpCommandType");
      char saveType = "NEW".equals(commandType) ? 'I' : 'U';
      try {
        int total = saveRecord(vars, myError, saveType);
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
          myError.setMessage(total + " " + myError.getMessage());
          myError.setType("Success");
        }
        result.put("oberror", myError.toMap());
        result.put("tabid", vars.getStringParameter("tabID"));
        result.put("redirect", strDireccion + request.getServletPath() + "?Command=" + commandType);
      } catch (Exception e) {
        log4j.error("Error saving record (XHR request): " + e.getMessage(), e);
        myError.setType("Error");
        myError.setMessage(e.getMessage());
      }

      response.setContentType("application/json");
      PrintWriter out = response.getWriter();
      out.print(result.toString());
      out.flush();
      out.close();
    } else if (vars.getCommand().toUpperCase().startsWith("BUTTON")
        || vars.getCommand().toUpperCase().startsWith("SAVE_BUTTON")) {
      pageErrorPopUp(response);
    } else pageError(response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    VariablesSecureApp vars = new VariablesSecureApp(request);

    // Get user Client's base currency
    String strUserCurrencyId = Utility.stringBaseCurrencyId(this, vars.getClient());
    if (vars.commandIn("DEFAULT", "DEFAULT_COMPARATIVE")) {
      String strDateFrom =
          vars.getGlobalVariable(
              "inpDateFrom", "ReportRefundSalesDimensionalAnalyses|dateFrom", "");
      String strDateTo =
          vars.getGlobalVariable("inpDateTo", "ReportRefundSalesDimensionalAnalyses|dateTo", "");
      String strDateFromRef =
          vars.getGlobalVariable(
              "inpDateFromRef", "ReportRefundSalesDimensionalAnalyses|dateFromRef", "");
      String strDateToRef =
          vars.getGlobalVariable(
              "inpDateToRef", "ReportRefundSalesDimensionalAnalyses|dateToRef", "");
      String strPartnerGroup =
          vars.getGlobalVariable(
              "inpPartnerGroup", "ReportRefundSalesDimensionalAnalyses|partnerGroup", "");
      String strcBpartnerId =
          vars.getInGlobalVariable(
              "inpcBPartnerId_IN",
              "ReportRefundSalesDimensionalAnalyses|partner",
              "",
              IsIDFilter.instance);
      String strProductCategory =
          vars.getGlobalVariable(
              "inpProductCategory", "ReportRefundSalesDimensionalAnalyses|productCategory", "");
      String strmProductId =
          vars.getInGlobalVariable(
              "inpmProductId_IN",
              "ReportRefundSalesDimensionalAnalyses|product",
              "",
              IsIDFilter.instance);
      // ad_ref_list.value where reference_id = 800087
      String strNotShown =
          vars.getInGlobalVariable(
              "inpNotShown",
              "ReportRefundSalesDimensionalAnalyses|notShown",
              "",
              IsPositiveIntFilter.instance);
      String strShown =
          vars.getInGlobalVariable(
              "inpShown",
              "ReportRefundSalesDimensionalAnalyses|shown",
              "",
              IsPositiveIntFilter.instance);
      String strOrg =
          vars.getGlobalVariable("inpOrg", "ReportRefundSalesDimensionalAnalyses|org", "");
      String strsalesrepId =
          vars.getGlobalVariable(
              "inpSalesrepId", "ReportRefundSalesDimensionalAnalyses|salesrep", "");
      String strmWarehouseId =
          vars.getGlobalVariable(
              "inpmWarehouseId", "ReportRefundSalesDimensionalAnalyses|warehouseId", "");
      String strOrder =
          vars.getGlobalVariable(
              "inpOrder", "ReportRefundSalesDimensionalAnalyses|order", "Normal");
      String strMayor =
          vars.getNumericGlobalVariable(
              "inpMayor", "ReportRefundSalesDimensionalAnalyses|mayor", "");
      String strMenor =
          vars.getNumericGlobalVariable(
              "inpMenor", "ReportRefundSalesDimensionalAnalyses|menor", "");
      String strRatioMayor =
          vars.getNumericGlobalVariable(
              "inpRatioMayor", "ReportRefundSalesDimensionalAnalyses|ratioMayor", "");
      String strRatioMenor =
          vars.getNumericGlobalVariable(
              "inpRatioMenor", "ReportRefundSalesDimensionalAnalyses|ratioMenor", "");
      String strCurrencyId =
          vars.getGlobalVariable(
              "inpCurrencyId", "ReportRefundSalesDimensionalAnalyses|currency", strUserCurrencyId);
      String strComparative = "";
      if (vars.commandIn("DEFAULT_COMPARATIVE"))
        strComparative =
            vars.getRequestGlobalVariable(
                "inpComparative", "ReportRefundSalesDimensionalAnalyses|comparative");
      else
        strComparative =
            vars.getGlobalVariable(
                "inpComparative", "ReportRefundSalesDimensionalAnalyses|comparative", "N");
      printPageDataSheet(
          response,
          vars,
          strComparative,
          strDateFrom,
          strDateTo,
          strPartnerGroup,
          strcBpartnerId,
          strProductCategory,
          strmProductId,
          strNotShown,
          strShown,
          strDateFromRef,
          strDateToRef,
          strOrg,
          strsalesrepId,
          strmWarehouseId,
          strOrder,
          strMayor,
          strMenor,
          strRatioMayor,
          strRatioMenor,
          strCurrencyId);
    } else if (vars.commandIn("EDIT_HTML", "EDIT_HTML_COMPARATIVE")) {
      String strDateFrom =
          vars.getRequestGlobalVariable(
              "inpDateFrom", "ReportRefundSalesDimensionalAnalyses|dateFrom");
      String strDateTo =
          vars.getRequestGlobalVariable("inpDateTo", "ReportRefundSalesDimensionalAnalyses|dateTo");
      String strDateFromRef =
          vars.getRequestGlobalVariable(
              "inpDateFromRef", "ReportRefundSalesDimensionalAnalyses|dateFromRef");
      String strDateToRef =
          vars.getRequestGlobalVariable(
              "inpDateToRef", "ReportRefundSalesDimensionalAnalyses|dateToRef");
      String strPartnerGroup =
          vars.getRequestGlobalVariable(
              "inpPartnerGroup", "ReportRefundSalesDimensionalAnalyses|partnerGroup");
      String strcBpartnerId =
          vars.getRequestInGlobalVariable(
              "inpcBPartnerId_IN",
              "ReportRefundSalesDimensionalAnalyses|partner",
              IsIDFilter.instance);
      String strProductCategory =
          vars.getRequestGlobalVariable(
              "inpProductCategory", "ReportRefundSalesDimensionalAnalyses|productCategory");
      String strmProductId =
          vars.getRequestInGlobalVariable(
              "inpmProductId_IN",
              "ReportRefundSalesDimensionalAnalyses|product",
              IsIDFilter.instance);
      // ad_ref_list.value where reference_id = 800087
      String strNotShown = vars.getInStringParameter("inpNotShown", IsPositiveIntFilter.instance);
      String strShown = vars.getInStringParameter("inpShown", IsPositiveIntFilter.instance);
      String strOrg =
          vars.getRequestGlobalVariable("inpOrg", "ReportRefundSalesDimensionalAnalyses|org");
      String strsalesrepId =
          vars.getRequestGlobalVariable(
              "inpSalesrepId", "ReportRefundSalesDimensionalAnalyses|salesrep");
      String strmWarehouseId =
          vars.getRequestGlobalVariable(
              "inpmWarehouseId", "ReportRefundSalesDimensionalAnalyses|warehouseId");
      String strOrder =
          vars.getRequestGlobalVariable("inpOrder", "ReportRefundSalesDimensionalAnalyses|order");
      String strMayor = vars.getNumericParameter("inpMayor", "");
      String strMenor = vars.getNumericParameter("inpMenor", "");
      String strRatioMayor = vars.getNumericParameter("inpRatioMayor", "");
      String strRatioMenor = vars.getNumericParameter("inpRatioMenor", "");
      String strComparative = vars.getStringParameter("inpComparative", "N");
      String strCurrencyId =
          vars.getGlobalVariable(
              "inpCurrencyId", "ReportRefundSalesDimensionalAnalyses|currency", strUserCurrencyId);
      printPageHtml(
          request,
          response,
          vars,
          strComparative,
          strDateFrom,
          strDateTo,
          strPartnerGroup,
          strcBpartnerId,
          strProductCategory,
          strmProductId,
          strNotShown,
          strShown,
          strDateFromRef,
          strDateToRef,
          strOrg,
          strsalesrepId,
          strmWarehouseId,
          strOrder,
          strMayor,
          strMenor,
          strRatioMayor,
          strRatioMenor,
          strCurrencyId);
    } else pageErrorPopUp(response);
  }
  private void printPageHtml(
      HttpServletRequest request,
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strComparative,
      String strDateFrom,
      String strDateTo,
      String strPartnerGroup,
      String strcBpartnerId,
      String strProductCategory,
      String strmProductId,
      String strNotShown,
      String strShown,
      String strDateFromRef,
      String strDateToRef,
      String strOrg,
      String strsalesrepId,
      String strmWarehouseId,
      String strOrder,
      String strMayor,
      String strMenor,
      String strRatioMayor,
      String strRatioMenor,
      String strCurrencyId)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: print html");
    XmlDocument xmlDocument = null;
    String strOrderby = "";
    String[] discard = {"", "", "", "", "", "", ""};
    String[] discard1 = {
      "selEliminarBody1",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard"
    };
    if (strOrg.equals("")) strOrg = vars.getOrg();
    if (strComparative.equals("Y")) discard1[0] = "selEliminarBody2";
    String strTitle = "";
    strTitle =
        Utility.messageBD(this, "From", vars.getLanguage())
            + " "
            + strDateFrom
            + " "
            + Utility.messageBD(this, "To", vars.getLanguage())
            + " "
            + strDateTo;
    if (!strPartnerGroup.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "ForBPartnerGroup", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectBpgroup(this, strPartnerGroup);
    if (!strProductCategory.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "ProductCategory", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectProductCategory(
                  this, strProductCategory);
    if (!strsalesrepId.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "TheSalesRep", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectSalesrep(this, strsalesrepId);
    if (!strmWarehouseId.equals(""))
      strTitle =
          strTitle
              + " "
              + Utility.messageBD(this, "And", vars.getLanguage())
              + " "
              + Utility.messageBD(this, "TheWarehouse", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectMwarehouse(this, strmWarehouseId);

    ReportRefundSalesDimensionalAnalysesData[] data = null;
    String[] strShownArray = {"", "", "", "", "", "", ""};
    if (strShown.startsWith("(")) strShown = strShown.substring(1, strShown.length() - 1);
    if (!strShown.equals("")) {
      strShown = Replace.replace(strShown, "'", "");
      strShown = Replace.replace(strShown, " ", "");
      StringTokenizer st = new StringTokenizer(strShown, ",", false);
      int intContador = 0;
      while (st.hasMoreTokens()) {
        strShownArray[intContador] = st.nextToken();
        intContador++;
      }
    }
    String[] strTextShow = {"", "", "", "", "", "", ""};
    int intDiscard = 0;
    int intAuxDiscard = -1;
    for (int i = 0; i < 7; i++) {
      if (strShownArray[i].equals("1")) {
        strTextShow[i] = "C_BP_GROUP.NAME";
        intDiscard++;
      } else if (strShownArray[i].equals("2")) {
        strTextShow[i] =
            "AD_COLUMN_IDENTIFIER(to_char('C_Bpartner'), to_char( C_BPARTNER.C_BPARTNER_ID), to_char('"
                + vars.getLanguage()
                + "'))";
        intDiscard++;
      } else if (strShownArray[i].equals("3")) {
        strTextShow[i] = "M_PRODUCT_CATEGORY.NAME";
        intDiscard++;
      } else if (strShownArray[i].equals("4")) {
        strTextShow[i] =
            "AD_COLUMN_IDENTIFIER(to_char('M_Product'), to_char( M_PRODUCT.M_PRODUCT_ID), to_char('"
                + vars.getLanguage()
                + "'))|| CASE WHEN uomsymbol IS NULL THEN '' ELSE to_char(' ('||uomsymbol||')') END";
        intAuxDiscard = i;
        intDiscard++;
      } else if (strShownArray[i].equals("5")) {
        strTextShow[i] = "C_ORDER.DOCUMENTNO";
        intDiscard++;
      } else if (strShownArray[i].equals("6")) {
        strTextShow[i] = "AD_USER.FIRSTNAME||' '||' '||AD_USER.LASTNAME";
        intDiscard++;
      } else if (strShownArray[i].equals("7")) {
        strTextShow[i] = "M_WAREHOUSE.NAME";
        intDiscard++;
      } else {
        strTextShow[i] = "''";
        discard[i] = "display:none;";
      }
    }
    if (intDiscard != 0 || intAuxDiscard != -1) {
      int k = 1;
      if (intDiscard == 1) {
        strOrderby = " ORDER BY NIVEL" + k + ",";
      } else {
        strOrderby = " ORDER BY ";
      }
      while (k < intDiscard) {
        strOrderby = strOrderby + "NIVEL" + k + ",";
        k++;
      }
      if (k == 1) {
        if (strOrder.equals("Normal")) {
          strOrderby = " ORDER BY NIVEL" + k;
        } else if (strOrder.equals("Amountasc")) {
          strOrderby = " ORDER BY LINENETAMT ASC";
        } else if (strOrder.equals("Amountdesc")) {
          strOrderby = " ORDER BY LINENETAMT DESC";
        } else if (strOrder.equals("Ratioasc")) {
          strOrderby = " ORDER BY RATIO ASC";
        } else if (strOrder.equals("Ratiodesc")) {
          strOrderby = " ORDER BY RATIO DESC";
        } else {
          strOrderby = "1";
        }
      } else {
        if (strOrder.equals("Normal")) {
          strOrderby += "NIVEL" + k;
        } else if (strOrder.equals("Amountasc")) {
          strOrderby += "LINENETAMT ASC";
        } else if (strOrder.equals("Amountdesc")) {
          strOrderby += "LINENETAMT DESC";
        } else if (strOrder.equals("Ratioasc")) {
          strOrderby += "RATIO ASC";
        } else if (strOrder.equals("Ratiodesc")) {
          strOrderby += "RATIO DESC";
        } else {
          strOrderby = "1";
        }
      }

    } else {
      strOrderby = " ORDER BY 1";
    }
    String strHaving = "";
    if (!strMayor.equals("") && !strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) > " + strMayor + " AND SUM(LINENETAMT) < " + strMenor;
    } else if (!strMayor.equals("") && strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) > " + strMayor;
    } else if (strMayor.equals("") && !strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) < " + strMenor;
    } else {
    }
    if (strHaving.equals("")) {
      if (!strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor
                + " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else if (!strRatioMayor.equals("") && strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor;
      } else if (strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else {
      }
    } else {
      if (!strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor
                + " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else if (!strRatioMayor.equals("") && strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor;
      } else if (strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else {
      }
    }
    strOrderby = strHaving + strOrderby;

    // Checks if there is a conversion rate for each of the transactions of
    // the report
    String strConvRateErrorMsg = "";
    OBError myMessage = null;
    myMessage = new OBError();
    if (strComparative.equals("Y")) {
      try {
        data =
            ReportRefundSalesDimensionalAnalysesData.select(
                this,
                strCurrencyId,
                strTextShow[0],
                strTextShow[1],
                strTextShow[2],
                strTextShow[3],
                strTextShow[4],
                strTextShow[5],
                strTextShow[6],
                Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
                Utility.getContext(
                    this, vars, "#User_Client", "ReportRefundInvoiceCustomerDimensionalAnalyses"),
                strDateFrom,
                DateTimeData.nDaysAfter(this, strDateTo, "1"),
                strPartnerGroup,
                strcBpartnerId,
                strProductCategory,
                strmProductId,
                strsalesrepId,
                strmWarehouseId,
                strDateFromRef,
                DateTimeData.nDaysAfter(this, strDateToRef, "1"),
                strOrderby);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      }
    } else {
      try {
        data =
            ReportRefundSalesDimensionalAnalysesData.selectNoComparative(
                this,
                strCurrencyId,
                strTextShow[0],
                strTextShow[1],
                strTextShow[2],
                strTextShow[3],
                strTextShow[4],
                strTextShow[5],
                strTextShow[6],
                Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
                Utility.getContext(
                    this, vars, "#User_Client", "ReportRefundInvoiceCustomerDimensionalAnalyses"),
                strDateFrom,
                DateTimeData.nDaysAfter(this, strDateTo, "1"),
                strPartnerGroup,
                strcBpartnerId,
                strProductCategory,
                strmProductId,
                strsalesrepId,
                strmWarehouseId,
                strOrderby);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      }
    }
    strConvRateErrorMsg = myMessage.getMessage();
    // If a conversion rate is missing for a certain transaction, an error
    // message window pops-up.
    if (!strConvRateErrorMsg.equals("") && strConvRateErrorMsg != null) {
      advisePopUp(
          request,
          response,
          "ERROR",
          Utility.messageBD(this, "NoConversionRateHeader", vars.getLanguage()),
          strConvRateErrorMsg);
    } else { // Otherwise, the report is launched
      if (data.length == 0 || data == null) {
        data = ReportRefundSalesDimensionalAnalysesData.set();
      } else {
        int contador = intDiscard;
        if (intAuxDiscard != -1) contador = intAuxDiscard;
        int k = 1;
        if (strComparative.equals("Y")) {
          for (int j = contador; j > 0; j--) {
            discard1[k] = "fieldTotalQtyNivel" + String.valueOf(j);
            discard1[k + 12] = "fieldTotalRefundQtyNivel" + String.valueOf(j);
            discard1[k + 24] = "fieldUomsymbol" + String.valueOf(j);
            discard1[k + 6] = "fieldTotalRefQtyNivel" + String.valueOf(j);
            discard1[k + 18] = "fieldTotalRefRefundQtyNivel" + String.valueOf(j);
            k++;
          }
        } else {
          for (int j = contador; j > 0; j--) {
            discard1[k] = "fieldNoncomparativeTotalQtyNivel" + String.valueOf(j);
            discard1[k + 10] = "fieldNoncomparativeTotalRefundQtyNivel" + String.valueOf(j);
            discard1[k + 20] = "fieldNoncomparativeUomsymbol" + String.valueOf(j);
            k++;
          }
        }
      }
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpCommon/ad_reports/ReportRefundSalesDimensionalAnalysesEdition",
                  discard1)
              .createXmlDocument();
      xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
      xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
      xmlDocument.setParameter("theme", vars.getTheme());
      xmlDocument.setParameter("eliminar2", discard[1]);
      xmlDocument.setParameter("eliminar3", discard[2]);
      xmlDocument.setParameter("eliminar4", discard[3]);
      xmlDocument.setParameter("eliminar5", discard[4]);
      xmlDocument.setParameter("eliminar6", discard[5]);
      xmlDocument.setParameter("eliminar7", discard[6]);
      xmlDocument.setParameter("title", strTitle);
      String strCurISOSym = Utility.stringISOSymbol(this, strCurrencyId);
      strCurISOSym = strCurISOSym.replace('(', ' ');
      strCurISOSym = strCurISOSym.replace(')', ' ');
      xmlDocument.setParameter("convisosym", strCurISOSym);
      xmlDocument.setParameter("constante", "100");
      if (strComparative.equals("Y")) {
        xmlDocument.setData("structure1", data);
      } else {
        xmlDocument.setData("structure2", data);
      }
      response.setContentType("text/html; charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.println(xmlDocument.print());
      out.close();
    }
  }
  private void printPageDataSheet(
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strComparative,
      String strDateFrom,
      String strDateTo,
      String strPartnerGroup,
      String strcBpartnerId,
      String strProductCategory,
      String strmProductId,
      String strNotShown,
      String strShown,
      String strDateFromRef,
      String strDateToRef,
      String strOrg,
      String strsalesrepId,
      String strmWarehouseId,
      String strOrder,
      String strMayor,
      String strMenor,
      String strRatioMayor,
      String strRatioMenor,
      String strCurrencyId)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: dataSheet");
    String discard[] = {"selEliminarHeader1"};
    String strCommand = "EDIT_PDF";
    if (strComparative.equals("Y")) {
      discard[0] = "selEliminarHeader2";
      strCommand = "EDIT_PDF_COMPARATIVE";
    }
    XmlDocument xmlDocument = null;
    xmlDocument =
        xmlEngine
            .readXmlTemplate(
                "org/openbravo/erpCommon/ad_reports/ReportRefundSalesDimensionalAnalysesFilter",
                discard)
            .createXmlDocument();

    ToolBar toolbar =
        new ToolBar(
            this,
            vars.getLanguage(),
            "ReportRefundSalesDimensionalAnalysesFilter",
            false,
            "",
            "",
            "",
            false,
            "ad_reports",
            strReplaceWith,
            false,
            true);
    toolbar.prepareSimpleToolBarTemplate();
    xmlDocument.setParameter("toolbar", toolbar.toString());

    try {
      WindowTabs tabs =
          new WindowTabs(
              this,
              vars,
              "org.openbravo.erpCommon.ad_reports.ReportRefundSalesDimensionalAnalyses");
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      xmlDocument.setParameter("childTabContainer", tabs.childTabs());
      xmlDocument.setParameter("theme", vars.getTheme());
      NavigationBar nav =
          new NavigationBar(
              this,
              vars.getLanguage(),
              "ReportRefundSalesDimensionalAnalyses.html",
              classInfo.id,
              classInfo.type,
              strReplaceWith,
              tabs.breadcrumb());
      xmlDocument.setParameter("navigationBar", nav.toString());
      LeftTabsBar lBar =
          new LeftTabsBar(
              this,
              vars.getLanguage(),
              "ReportRefundSalesDimensionalAnalyses.html",
              strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.manualTemplate());
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
    {
      OBError myMessage = vars.getMessage("ReportRefundSalesDimensionalAnalyses");
      vars.removeMessage("ReportRefundSalesDimensionalAnalyses");
      if (myMessage != null) {
        xmlDocument.setParameter("messageType", myMessage.getType());
        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
      }
    }

    xmlDocument.setParameter("calendar", vars.getLanguage().substring(0, 2));
    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("dateFrom", strDateFrom);
    xmlDocument.setParameter("dateFromdisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateFromsaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateTo", strDateTo);
    xmlDocument.setParameter("dateTodisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateTosaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateFromRef", strDateFromRef);
    xmlDocument.setParameter("dateFromRefdisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateFromRefsaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateToRef", strDateToRef);
    xmlDocument.setParameter("dateToRefdisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateToRefsaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("cBpGroupId", strPartnerGroup);
    xmlDocument.setParameter("mProductCategoryId", strProductCategory);
    xmlDocument.setParameter("adOrgId", strOrg);
    xmlDocument.setParameter("salesRepId", strsalesrepId);
    xmlDocument.setParameter("mWarehouseId", strmWarehouseId);
    xmlDocument.setParameter("normal", strOrder);
    xmlDocument.setParameter("amountasc", strOrder);
    xmlDocument.setParameter("amountdesc", strOrder);
    xmlDocument.setParameter("ratioasc", strOrder);
    xmlDocument.setParameter("ratiodesc", strOrder);
    xmlDocument.setParameter("mayor", strMayor);
    xmlDocument.setParameter("menor", strMenor);
    xmlDocument.setParameter("ratioMayor", strRatioMayor);
    xmlDocument.setParameter("ratioMenor", strRatioMenor);
    xmlDocument.setParameter("comparative", strComparative);
    xmlDocument.setParameter("command", strCommand);
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLEDIR",
              "C_BP_Group_ID",
              "",
              "",
              Utility.getContext(
                  this, vars, "#AccessibleOrgTree", "ReportRefundSalesDimensionalAnalyses"),
              Utility.getContext(
                  this, vars, "#User_Client", "ReportRefundSalesDimensionalAnalyses"),
              0);
      Utility.fillSQLParameters(
          this,
          vars,
          null,
          comboTableData,
          "ReportRefundSalesDimensionalAnalyses",
          strPartnerGroup);
      xmlDocument.setData("reportC_BP_GROUPID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLEDIR",
              "M_Product_Category_ID",
              "",
              "",
              Utility.getContext(
                  this, vars, "#AccessibleOrgTree", "ReportRefundSalesDimensionalAnalyses"),
              Utility.getContext(
                  this, vars, "#User_Client", "ReportRefundSalesDimensionalAnalyses"),
              0);
      Utility.fillSQLParameters(
          this,
          vars,
          null,
          comboTableData,
          "ReportRefundSalesDimensionalAnalyses",
          strProductCategory);
      xmlDocument.setData(
          "reportM_PRODUCT_CATEGORYID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLEDIR",
              "AD_Org_ID",
              "",
              "",
              Utility.getContext(
                  this, vars, "#AccessibleOrgTree", "ReportRefundSalesDimensionalAnalyses"),
              Utility.getContext(
                  this, vars, "#User_Client", "ReportRefundSalesDimensionalAnalyses"),
              0);
      Utility.fillSQLParameters(
          this, vars, null, comboTableData, "ReportRefundSalesDimensionalAnalyses", strOrg);
      xmlDocument.setData("reportAD_ORGID", "liststructure", comboTableData.select(false));
      comboTableData = null;

    } catch (Exception ex) {
      throw new ServletException(ex);
    }
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLE",
              "SalesRep_ID",
              "AD_User SalesRep",
              "",
              Utility.getContext(
                  this, vars, "#AccessibleOrgTree", "ReportRefundSalesDimensionalAnalyses"),
              Utility.getContext(
                  this, vars, "#User_Client", "ReportRefundSalesDimensionalAnalyses"),
              0);
      Utility.fillSQLParameters(
          this, vars, null, comboTableData, "ReportRefundSalesDimensionalAnalyses", strsalesrepId);
      xmlDocument.setData("reportSalesRep_ID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    xmlDocument.setData(
        "reportCBPartnerId_IN",
        "liststructure",
        SelectorUtilityData.selectBpartner(
            this,
            Utility.getContext(this, vars, "#AccessibleOrgTree", ""),
            Utility.getContext(this, vars, "#User_Client", ""),
            strcBpartnerId));
    xmlDocument.setData(
        "reportMProductId_IN",
        "liststructure",
        SelectorUtilityData.selectMproduct(
            this,
            Utility.getContext(this, vars, "#AccessibleOrgTree", ""),
            Utility.getContext(this, vars, "#User_Client", ""),
            strmProductId));
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLEDIR",
              "M_Warehouse_ID",
              "",
              "",
              Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportSalesDimensionalAnalyze"),
              Utility.getContext(
                  this, vars, "#User_Client", "ReportRefundSalesDimensionalAnalyses"),
              0);
      Utility.fillSQLParameters(
          this,
          vars,
          null,
          comboTableData,
          "ReportRefundSalesDimensionalAnalyses",
          strmWarehouseId);
      xmlDocument.setData("reportM_WAREHOUSEID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    xmlDocument.setParameter("ccurrencyid", strCurrencyId);
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLEDIR",
              "C_Currency_ID",
              "",
              "",
              Utility.getContext(
                  this, vars, "#AccessibleOrgTree", "ReportRefundSalesDimensionalAnalyses"),
              Utility.getContext(
                  this, vars, "#User_Client", "ReportRefundSalesDimensionalAnalyses"),
              0);
      Utility.fillSQLParameters(
          this, vars, null, comboTableData, "ReportRefundSalesDimensionalAnalyses", strCurrencyId);
      xmlDocument.setData("reportC_Currency_ID", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    if (vars.getLanguage().equals("en_US")) {
      xmlDocument.setData(
          "structure1", ReportRefundSalesDimensionalAnalysesData.selectNotShown(this, strShown));
      xmlDocument.setData(
          "structure2",
          strShown.equals("")
              ? new ReportRefundSalesDimensionalAnalysesData[0]
              : ReportRefundSalesDimensionalAnalysesData.selectShown(this, strShown));
    } else {
      xmlDocument.setData(
          "structure1",
          ReportRefundSalesDimensionalAnalysesData.selectNotShownTrl(
              this, vars.getLanguage(), strShown));
      xmlDocument.setData(
          "structure2",
          strShown.equals("")
              ? new ReportRefundSalesDimensionalAnalysesData[0]
              : ReportRefundSalesDimensionalAnalysesData.selectShownTrl(
                  this, vars.getLanguage(), strShown));
    }

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
  private void printPageDataPDF(
      HttpServletRequest request,
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strFinReconciliationId,
      String strFinFinancialAccountName,
      String strDateTo,
      String strReportType)
      throws IOException, ServletException {
    log4j.debug("Output: Reconciliation PDF report");

    String reportType = (strReportType == null) ? "DETAIL" : strReportType;

    String strMainReportName =
        "@basedesign@/org/openbravo/advpaymentmngt/ad_reports/ReportReconciliation.jrxml";
    FIN_Reconciliation reconciliation = null;
    OBContext.setAdminMode(true);
    try {
      reconciliation = OBDal.getInstance().get(FIN_Reconciliation.class, strFinReconciliationId);
    } finally {
      OBContext.restorePreviousMode();
    }
    HashMap<String, Object> parameters = new HashMap<String, Object>();

    String strLanguage = vars.getLanguage();
    String strBaseDesign = getBaseDesignPath(strLanguage);

    JasperReport subReportOutstandingPayment;
    JasperReport subReportOutstandingDeposit;
    JasperReport subReportUnreconciledBankStatementLines;
    try {
      subReportOutstandingPayment =
          Utility.getTranslatedJasperReport(
              this,
              strBaseDesign + "/org/openbravo/advpaymentmngt/ad_reports/OutstandingPayment.jrxml",
              vars.getLanguage(),
              strBaseDesign);

      subReportOutstandingDeposit =
          Utility.getTranslatedJasperReport(
              this,
              strBaseDesign + "/org/openbravo/advpaymentmngt/ad_reports/OutstandingDeposit.jrxml",
              vars.getLanguage(),
              strBaseDesign);

      subReportUnreconciledBankStatementLines =
          Utility.getTranslatedJasperReport(
              this,
              strBaseDesign
                  + "/org/openbravo/advpaymentmngt/ad_reports/UnreconciledBankStatement.jrxml",
              vars.getLanguage(),
              strBaseDesign);

    } catch (JRException e) {
      throw new ServletException(e.getMessage());
    }

    String dateFormat =
        OBPropertiesProvider.getInstance().getOpenbravoProperties().getProperty("dateFormat.java");
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    List<BigDecimal> amtPayDep = getOutstandingPaymentAndDepositTotal(reconciliation);
    BigDecimal accountBalanceOB = getBalanceOfAccount(reconciliation);
    BigDecimal totalOutPayment = amtPayDep.get(0);
    BigDecimal totalOutDeposit = amtPayDep.get(1);
    BigDecimal totalUnreconciledBs = getUnreconciledBankStatmentLinesTotal(reconciliation);

    // Parameters
    parameters.put("REPORT_TYPE", reportType);

    // Common
    parameters.put("FINACCOUNT_INFO", strFinFinancialAccountName);
    parameters.put("DATEFORMAT", sdf);
    parameters.put("RECONCILIATION_ID", strFinReconciliationId);
    parameters.put("ACC_BAL_OB", accountBalanceOB);
    parameters.put(
        "ADJ_ACC_BAL_OB",
        accountBalanceOB.add(totalOutPayment).subtract(totalOutDeposit).add(totalUnreconciledBs));

    parameters.put("SHOW_BAND_PAYMENT", (totalOutPayment.compareTo(BigDecimal.ZERO) != 0));
    parameters.put("SHOW_BAND_DEPOSIT", (totalOutDeposit.compareTo(BigDecimal.ZERO) != 0));
    parameters.put("SHOW_BAND_BSLINE", (totalUnreconciledBs.compareTo(BigDecimal.ZERO) != 0));

    // Summary
    parameters.put("AMT_OUT_PAYMENT", totalOutPayment);
    parameters.put("AMT_OUT_DEPOSIT", totalOutDeposit);
    parameters.put("AMT_UNREC_BSLINE", totalUnreconciledBs);

    OBContext.setAdminMode(true);
    try {
      parameters.put("DATE", reconciliation.getEndingDate());
      parameters.put("END_BALANCE", reconciliation.getEndingBalance());
    } finally {
      OBContext.restorePreviousMode();
    }

    parameters.put("SUBREP_OUTPAYMENT", subReportOutstandingPayment);
    parameters.put("SUBREP_OUTDEPOSIT", subReportOutstandingDeposit);
    parameters.put("SUBREP_UNRECBS", subReportUnreconciledBankStatementLines);

    response.setContentType("text/html; charset=UTF-8");
    renderJR(vars, response, strMainReportName, "pdf", parameters, null, null);
  }
  /**
   * Translates the filter criteria ({@link #addFilterParameter(String, String)}) to a valid HQL
   * where clause (without the 'where' keyword). After calling this method the method {@link
   * #getNamedParameters()} can be called. Note that currently only filtering on string and boolean
   * properties is supported. Also filtering on the identifier of a referenced business object is
   * supported.
   *
   * @return a valid where clause or an empty string if not set.
   */
  public String getWhereClause() {

    if (whereClause != null) {
      return whereClause;
    }

    // add some default filter parameters
    filterParameters.put(
        JsonConstants.QUERY_PARAM_USER, OBContext.getOBContext().getUser().getId());
    if (!filterParameters.containsKey(JsonConstants.QUERY_PARAM_CLIENT)) {
      filterParameters.put(
          JsonConstants.QUERY_PARAM_CLIENT, OBContext.getOBContext().getUser().getId());
    }

    final SimpleDateFormat simpleDateFormat = JsonUtils.createDateFormat();

    Check.isNotNull(entity, "Entity must be set");

    final StringBuilder sb = new StringBuilder();
    boolean addAnd = false;
    final StringBuilder orgPart = new StringBuilder();
    final List<Property> propertyDone = new ArrayList<Property>();
    String whereParameterValue = null;
    for (String key : filterParameters.keySet()) {
      String value = filterParameters.get(key);

      if (key.equals(JsonConstants.WHERE_PARAMETER)) {
        // there are cases where null is set as a string
        // handle this
        if (value.equals("null") || value.length() == 0) {
          continue;
        }
        whereParameterValue = value;
        continue;
      }

      // handle the case that we should filter on the accessible organizations
      if (key.equals(JsonConstants.ORG_PARAMETER)) {
        if (entity.isOrganizationEnabled() && value != null && value.length() > 0) {
          final Set<String> orgs =
              OBContext.getOBContext().getOrganizationStructureProvider().getNaturalTree(value);
          if (orgs.size() > 0) {
            if (getMainAlias() != null) {
              orgPart.append(" " + getMainAlias() + ".organization in (");
            } else {
              orgPart.append(" organization in (");
            }
            boolean addComma = false;
            for (String org : orgs) {
              if (addComma) {
                orgPart.append(",");
              }
              orgPart.append("'" + org + "'");
              addComma = true;
            }
            orgPart.append(") ");
          }
        }
        continue;
      }

      // determine the property
      final List<Property> properties = JsonUtils.getPropertiesOnPath(getEntity(), key);
      if (properties.isEmpty()) {
        continue;
      }
      final Property property = properties.get(properties.size() - 1);
      // invalid propname, ignore this one
      // TODO: possibly warn about it
      if (property == null || propertyDone.contains(property)) {
        continue;
      }
      propertyDone.add(property);

      // we know the property and the string representation of the value...
      // do the conversion

      if (addAnd) {
        if (doOr) {
          sb.append(" or ");
        } else {
          sb.append(" and ");
        }
      }

      String leftWherePart = null;
      if (isDoOr()) {
        leftWherePart = resolveJoins(properties, key);
      } else if (getMainAlias() != null) {
        leftWherePart = getMainAlias() + "." + key.trim();
      } else {
        leftWherePart = key;
      }

      // get rid of the identifier and replace it with the real property name
      // or with the concatenation if there are multiple parts
      // NOTE: the if and else check against the key variable and not the leftwherepart
      // because the key contains the original string (with the _identifier part).
      // Within the if the leftWherePart is used because it contains the join aliases
      if (key.equals(JsonConstants.IDENTIFIER) || key.endsWith("." + JsonConstants.IDENTIFIER)) {
        // the identifierProperties are read from the owning entity of the
        // property, that should work fine, as this last property is always part of the
        // identifier
        final List<Property> identifierProperties = property.getEntity().getIdentifierProperties();
        Check.isTrue(
            identifierProperties.contains(property),
            "Property " + property + " not part of identifier of " + property.getEntity());
        final String prefix;
        final int index = leftWherePart.lastIndexOf(".");
        if (key.equals(JsonConstants.IDENTIFIER)) {
          prefix = getMainAlias() + ".";
        } else if (index == -1) {
          prefix = "";
        } else {
          // the + 1 makes sure that the dot is included
          prefix = leftWherePart.substring(0, index + 1);
        }
        leftWherePart = createIdentifierLeftClause(identifierProperties, prefix);

        // if the value consists of multiple parts then filtering won't work
        // only search on the first part then, is pragmatic but very workable
        if (value != null && value.contains(IdentifierProvider.SEPARATOR)) {
          final int separatorIndex = value.indexOf(IdentifierProvider.SEPARATOR);
          value = value.substring(0, separatorIndex);
        }
      }

      // NOTE: If you change this part, make sure that you sync the changes with the
      // SelectorDataSourceFilter. Check issue https://issues.openbravo.com/view.php?id=14239

      // NOTE the typedParameters.add call must be done after the call to
      // getTypedParameterAlias, this to get the correct alias codes
      if (key.equals(JsonConstants.IDENTIFIER)) {
        if (textMatching == TextMatching.exact) {
          sb.append(leftWherePart + " = " + getTypedParameterAlias());
          typedParameters.add(value);
        } else if (textMatching == TextMatching.startsWith) {
          sb.append(
              "upper("
                  + leftWherePart
                  + ") like "
                  + getTypedParameterAlias()
                  + " escape '"
                  + ESCAPE_CHAR
                  + "' ");
          typedParameters.add(escapeLike(value.toUpperCase()) + "%");
        } else {
          sb.append(
              "upper("
                  + leftWherePart
                  + ") like "
                  + getTypedParameterAlias()
                  + " escape '"
                  + ESCAPE_CHAR
                  + "' ");
          typedParameters.add("%" + escapeLike(value.toUpperCase()).replaceAll(" ", "%") + "%");
        }
      } else if (!property.isPrimitive()) {
        // an in parameter use it...
        if (value.contains(JsonConstants.IN_PARAMETER_SEPARATOR)) {
          final List<String> values = new ArrayList<String>();
          final String[] separatedValues = value.split(JsonConstants.IN_PARAMETER_SEPARATOR);
          for (String separatedValue : separatedValues) {
            values.add(separatedValue);
          }
          sb.append(leftWherePart + ".id in (" + getTypedParameterAlias() + ")");
          typedParameters.add(values);
        } else {
          sb.append(leftWherePart + ".id = " + getTypedParameterAlias());
          typedParameters.add(value);
        }
      } else if (String.class == property.getPrimitiveObjectType()) {
        if (textMatching == TextMatching.exact) {
          sb.append(leftWherePart + " = " + getTypedParameterAlias());
          typedParameters.add(value);
        } else if (textMatching == TextMatching.startsWith) {
          sb.append(
              "upper("
                  + leftWherePart
                  + ") like "
                  + getTypedParameterAlias()
                  + " escape '"
                  + ESCAPE_CHAR
                  + "' ");
          typedParameters.add(escapeLike(value.toUpperCase()) + "%");
        } else {
          sb.append(
              "upper("
                  + leftWherePart
                  + ") like "
                  + getTypedParameterAlias()
                  + " escape '"
                  + ESCAPE_CHAR
                  + "' ");
          typedParameters.add("%" + escapeLike(value.toUpperCase()).replaceAll(" ", "%") + "%");
        }
      } else if (Boolean.class == property.getPrimitiveObjectType()) {
        final String alias = getTypedParameterAlias();
        typedParameters.add(new Boolean(value));
        sb.append(leftWherePart + " = " + alias);
      } else if (property.isNumericType()) {
        try {
          final String alias = getTypedParameterAlias();
          final BigDecimal bdValue = new BigDecimal(value);
          if (Long.class == property.getPrimitiveObjectType()) {
            typedParameters.add(bdValue.longValue());
          } else if (Integer.class == property.getPrimitiveObjectType()) {
            typedParameters.add(bdValue.intValue());
          } else {
            typedParameters.add(bdValue);
          }
          sb.append(leftWherePart + " = " + alias);
        } catch (NumberFormatException e) {
          // ignore on purpose, incorrect value entered by user
          // add a dummy whereclause to make the query format correct
          sb.append(" 1=1 ");
        }
      } else if (Date.class.isAssignableFrom(property.getPrimitiveObjectType())) {
        try {
          final Calendar cal = Calendar.getInstance();
          cal.setTime(simpleDateFormat.parse(value));
          final String alias1 = getTypedParameterAlias();
          typedParameters.add(cal.get(Calendar.DATE));
          final String alias2 = getTypedParameterAlias();
          typedParameters.add(cal.get(Calendar.MONTH) + 1);
          final String alias3 = getTypedParameterAlias();
          typedParameters.add(cal.get(Calendar.YEAR));
          sb.append(
              " (day("
                  + leftWherePart
                  + ") = "
                  + alias1
                  + " and month("
                  + leftWherePart
                  + ") = "
                  + alias2
                  + " and year("
                  + leftWherePart
                  + ") = "
                  + alias3
                  + ") ");
        } catch (Exception e) {
          // ignore these errors, just don't filter then
          // add a dummy whereclause to make the query format correct
          sb.append(" 1=1 ");
        }

        // } else if (property.isDate() || property.isDatetime()) {
        // NOTE: dates arrive in the format of the user....
        // sb.append(leftWherePart + " = ?");
        // typedParameters.add(value);
      } else {
        // TODO: support this....
        throw new UnsupportedOperationException(
            "Type "
                + property.getPrimitiveObjectType()
                + " not yet supported for parameter "
                + key);
      }
      addAnd = true;
    }

    log.debug("Whereclause for entity " + entity.getName());
    log.debug(sb.toString());
    for (Object param : typedParameters) {
      log.debug(param);
    }
    log.debug("Textmatching " + textMatching);

    if (sb.length() == 0) {
      whereClause = orgPart.length() > 0 ? orgPart.toString() : "";
    } else {
      whereClause =
          "(" + sb.toString() + ")" + (orgPart.length() > 0 ? " and " + orgPart.toString() : "");
    }
    if (whereParameterValue != null) {
      if (whereClause.length() > 0) {
        whereClause = " (" + whereClause + ") and (" + whereParameterValue + ") ";
      } else {
        whereClause = " " + whereParameterValue;
      }
    }
    if (whereClause.trim().length() > 0) {
      whereClause = " where " + whereClause;
    }

    // handle special transactional range parameter
    if (whereClause.contains(JsonConstants.QUERY_PARAM_TRANSACTIONAL_RANGE)) {
      final String alias = getTypedParameterAlias();
      String windowId = RequestContext.get().getRequestParameter("windowId");
      if (windowId == null) {
        windowId = "";
      }
      final String range =
          Utility.getTransactionalDate(
              new DalConnectionProvider(false),
              RequestContext.get().getVariablesSecureApp(),
              windowId);
      final int rangeNum = Integer.parseInt(range);
      final Calendar cal = Calendar.getInstance();
      cal.add(Calendar.DAY_OF_MONTH, -1 * rangeNum);
      whereClause = whereClause.replace(JsonConstants.QUERY_PARAM_TRANSACTIONAL_RANGE, alias);
      typedParameters.add(cal.getTime());
    }

    if (whereClause.contains(JsonConstants.QUERY_PARAM_CLIENT)) {
      final String alias = getTypedParameterAlias();
      String clientId = (String) DalUtil.getId(OBContext.getOBContext().getCurrentClient());
      whereClause = whereClause.replace(JsonConstants.QUERY_PARAM_CLIENT, alias);
      typedParameters.add(clientId);
    }
    whereClause = setRequestParameters(whereClause);
    whereClause = substituteContextParameters(whereClause);

    return whereClause;
  }
  private void printPageDataSheet(
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strC_BP_Group_ID,
      TableSQLData tableSQL)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: dataSheet");

    String strParamName = vars.getSessionValue(tabId + "|paramName");

    boolean hasSearchCondition = false;
    vars.removeEditionData(tabId);
    hasSearchCondition =
        (tableSQL.hasInternalFilter() && ("").equals(strParamName))
            || !(("").equals(strParamName) || ("%").equals(strParamName));
    String strOffset = vars.getSessionValue(tabId + "|offset");
    String selectedRow = "0";
    if (!strC_BP_Group_ID.equals("")) {
      selectedRow = Integer.toString(getKeyPosition(vars, strC_BP_Group_ID, tableSQL));
    }

    String[] discard = {"isNotFiltered", "isNotTest"};
    if (hasSearchCondition) discard[0] = new String("isFiltered");
    if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest");
    XmlDocument xmlDocument =
        xmlEngine
            .readXmlTemplate(
                "org/openbravo/erpWindows/BusinessPartnerCategory/BusinessPartnerCategory_Relation",
                discard)
            .createXmlDocument();

    boolean hasReadOnlyAccess =
        org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
            this, vars.getRole(), tabId);
    ToolBar toolbar =
        new ToolBar(
            this,
            true,
            vars.getLanguage(),
            "BusinessPartnerCategory",
            false,
            "document.frmMain.inpcBpGroupId",
            "grid",
            "..",
            "".equals("Y"),
            "BusinessPartnerCategory",
            strReplaceWith,
            false,
            false,
            false,
            false,
            !hasReadOnlyAccess);
    toolbar.setTabId(tabId);

    toolbar.setDeleteable(true && !hasReadOnlyAccess);
    toolbar.prepareRelationTemplate(
        "N".equals("Y"),
        hasSearchCondition,
        !vars.getSessionValue("#ShowTest", "N").equals("Y"),
        false,
        Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y"));
    xmlDocument.setParameter("toolbar", toolbar.toString());

    StringBuffer orderByArray = new StringBuffer();
    vars.setSessionValue(tabId + "|newOrder", "1");
    String positions = vars.getSessionValue(tabId + "|orderbyPositions");
    orderByArray.append("var orderByPositions = new Array(\n");
    if (!positions.equals("")) {
      StringTokenizer tokens = new StringTokenizer(positions, ",");
      boolean firstOrder = true;
      while (tokens.hasMoreTokens()) {
        if (!firstOrder) orderByArray.append(",\n");
        orderByArray.append("\"").append(tokens.nextToken()).append("\"");
        firstOrder = false;
      }
    }
    orderByArray.append(");\n");
    String directions = vars.getSessionValue(tabId + "|orderbyDirections");
    orderByArray.append("var orderByDirections = new Array(\n");
    if (!positions.equals("")) {
      StringTokenizer tokens = new StringTokenizer(directions, ",");
      boolean firstOrder = true;
      while (tokens.hasMoreTokens()) {
        if (!firstOrder) orderByArray.append(",\n");
        orderByArray.append("\"").append(tokens.nextToken()).append("\"");
        firstOrder = false;
      }
    }
    orderByArray.append(");\n");
    //    }

    xmlDocument.setParameter(
        "selectedColumn", "\nvar selectedRow = " + selectedRow + ";\n" + orderByArray.toString());
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("windowId", windowId);
    xmlDocument.setParameter("KeyName", "cBpGroupId");
    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("theme", vars.getTheme());
    // xmlDocument.setParameter("buttonReference", Utility.messageBD(this, "Reference",
    // vars.getLanguage()));
    try {
      WindowTabs tabs = new WindowTabs(this, vars, tabId, windowId, false);
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      xmlDocument.setParameter("childTabContainer", tabs.childTabs());
      String hideBackButton = vars.getGlobalVariable("hideMenu", "#Hide_BackButton", "");
      NavigationBar nav =
          new NavigationBar(
              this,
              vars.getLanguage(),
              "BusinessPartnerCategory_Relation.html",
              "BusinessPartnerCategory",
              "W",
              strReplaceWith,
              tabs.breadcrumb(),
              hideBackButton.equals("true"));
      xmlDocument.setParameter("navigationBar", nav.toString());
      LeftTabsBar lBar =
          new LeftTabsBar(
              this, vars.getLanguage(), "BusinessPartnerCategory_Relation.html", strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.relationTemplate());
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
    {
      OBError myMessage = vars.getMessage(tabId);
      vars.removeMessage(tabId);
      if (myMessage != null) {
        xmlDocument.setParameter("messageType", myMessage.getType());
        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
      }
    }

    xmlDocument.setParameter("grid", Utility.getContext(this, vars, "#RecordRange", windowId));
    xmlDocument.setParameter("grid_Offset", strOffset);
    xmlDocument.setParameter("grid_SortCols", positions);
    xmlDocument.setParameter("grid_SortDirs", directions);
    xmlDocument.setParameter("grid_Default", selectedRow);

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
  private OBError processButton(
      VariablesSecureApp vars,
      String strKey,
      String strProjectType,
      String strDateFrom,
      String windowId) {
    Connection conn = null;
    OBError myMessage = new OBError();
    if (strProjectType == null || strProjectType.equals("")) {
      try {
        releaseRollbackConnection(conn);
      } catch (Exception ignored) {
      }
      log4j.warn("Rollback in transaction");
      myMessage.setType("Error");
      myMessage.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
      myMessage.setMessage(Utility.messageBD(this, "NoProjectTypeSelected", vars.getLanguage()));
    } else {
      try {
        conn = this.getTransactionConnection();
        ProjectSetTypeData[] data = ProjectSetTypeData.select(this, strProjectType);
        ProjectSetTypeData[] dataProject = ProjectSetTypeData.selectProject(this, strKey);
        String strProjectPhase = "";
        String strProjectTask = "";
        // Variables used for Project Scheduling purposes
        DateFormat DateFormatter = Utility.getDateFormatter(vars);
        int firstProjectPhase = 0;
        String strPhaseStartDate = "";
        String strPhaseContractDate = "";
        String strTaskStartDate = "";
        String strTaskContractDate = "";
        String strLastContractDate = "";

        for (int i = 0; data != null && i < data.length; i++) {
          strProjectPhase = SequenceIdData.getUUID();

          // Calculates the Starting Date of the Phase
          if (firstProjectPhase == 0) {
            strPhaseStartDate = strDateFrom;
          } else {
            strPhaseStartDate = calculateStartDate(strLastContractDate, DateFormatter);
          }
          // Calculates the Contract Date of the Phase
          strPhaseContractDate =
              calculateContractDate(strPhaseStartDate, data[i].stdduration, DateFormatter);

          try {
            if (ProjectSetTypeData.insertProjectPhase(
                    conn,
                    this,
                    strKey,
                    dataProject[0].adClientId,
                    dataProject[0].adOrgId,
                    vars.getUser(),
                    data[i].description,
                    data[i].mProductId,
                    data[i].cPhaseId,
                    strProjectPhase,
                    data[i].help,
                    data[i].name,
                    data[i].standardqty,
                    strPhaseStartDate,
                    strPhaseContractDate,
                    data[i].seqno)
                == 1) {
              strLastContractDate = strPhaseContractDate;
              ProjectSetTypeData[] data1 = ProjectSetTypeData.selectTask(this, data[i].cPhaseId);
              int firstProjectTask = 0;
              for (int j = 0; data1 != null && j < data1.length; j++) {
                strProjectTask = SequenceIdData.getUUID();

                // Calculates the Starting Date of the Task
                if (firstProjectTask == 0) {
                  strTaskStartDate = strPhaseStartDate;
                } else {
                  strTaskStartDate = calculateStartDate(strLastContractDate, DateFormatter);
                }
                // Calculates the Contract Date of the Task
                strTaskContractDate =
                    calculateContractDate(strTaskStartDate, data1[j].stdduration, DateFormatter);

                try {
                  ProjectSetTypeData.insertProjectTask(
                      conn,
                      this,
                      strProjectTask,
                      data1[j].cTaskId,
                      dataProject[0].adClientId,
                      dataProject[0].adOrgId,
                      vars.getUser(),
                      data1[j].seqno,
                      data1[j].name,
                      data1[j].description,
                      data1[j].help,
                      data1[j].mProductId,
                      strProjectPhase,
                      data1[j].standardqty,
                      strTaskStartDate,
                      strTaskContractDate);
                } catch (ServletException ex) {
                  myMessage =
                      Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                  releaseRollbackConnection(conn);
                  return myMessage;
                }

                strLastContractDate = strTaskContractDate;
                firstProjectTask++;
              }
              firstProjectPhase++;
            }
          } catch (ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
          }
        }

        // Updates project's Type and category
        String strProjectCategory = ProjectSetTypeData.selectProjectCategory(this, strProjectType);
        try {
          ProjectSetTypeData.update(
              conn, this, vars.getUser(), strProjectType, strProjectCategory, strKey);
        } catch (ServletException ex) {
          myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          releaseRollbackConnection(conn);
          return myMessage;
        }

        // Updates project's Starting and Contract Dates
        ProjectSetTypeData[] dataDates = ProjectSetTypeData.selectDates(this, strKey);
        String strStartDate = strDateFrom.equals("") ? dataDates[0].startdate : strDateFrom;
        String strContractDate =
            strLastContractDate.equals("") ? dataDates[0].datecontract : strLastContractDate;
        try {
          ProjectSetTypeData.updateDates(
              conn, this, vars.getUser(), strStartDate, strContractDate, strKey);
        } catch (ServletException ex) {
          myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          releaseRollbackConnection(conn);
          return myMessage;
        }

        releaseCommitConnection(conn);
        myMessage.setType("Success");
        myMessage.setTitle(Utility.messageBD(this, "Success", vars.getLanguage()));
      } catch (Exception e) {
        try {
          releaseRollbackConnection(conn);
        } catch (Exception ignored) {
        }
        e.printStackTrace();
        log4j.warn("Rollback in transaction");
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage());
      }
    }
    return myMessage;
  }
  private void printPageEdit(
      HttpServletResponse response,
      HttpServletRequest request,
      VariablesSecureApp vars,
      boolean boolNew,
      String strC_BP_Group_ID,
      TableSQLData tableSQL)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: edit");

    HashMap<String, String> usedButtonShortCuts;

    usedButtonShortCuts = new HashMap<String, String>();

    String strOrderByFilter = vars.getSessionValue(tabId + "|orderby");
    String orderClause = " C_BP_Group.Value";
    if (strOrderByFilter == null || strOrderByFilter.equals("")) strOrderByFilter = orderClause;
    /*{
      if (!strOrderByFilter.equals("") && !orderClause.equals("")) strOrderByFilter += ", ";
      strOrderByFilter += orderClause;
    }*/

    String strCommand = null;
    BusinessPartnerCategoryData[] data = null;
    XmlDocument xmlDocument = null;
    FieldProvider dataField = vars.getEditionData(tabId);
    vars.removeEditionData(tabId);
    String strParamName = vars.getSessionValue(tabId + "|paramName");

    boolean hasSearchCondition = false;
    hasSearchCondition =
        (tableSQL.hasInternalFilter() && ("").equals(strParamName))
            || !(("").equals(strParamName) || ("%").equals(strParamName));

    String strParamSessionDate =
        vars.getGlobalVariable(
            "inpParamSessionDate", Utility.getTransactionalDate(this, vars, windowId), "");
    String buscador = "";
    String[] discard = {"", "isNotTest"};

    if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest");
    if (dataField == null) {
      if (!boolNew) {
        discard[0] = new String("newDiscard");
        data =
            BusinessPartnerCategoryData.selectEdit(
                this,
                vars.getSessionValue("#AD_SqlDateTimeFormat"),
                vars.getLanguage(),
                strC_BP_Group_ID,
                Utility.getContext(this, vars, "#User_Client", windowId),
                Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel));

        if (!strC_BP_Group_ID.equals("") && (data == null || data.length == 0)) {
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
          return;
        }
        refreshSessionEdit(vars, data);
        strCommand = "EDIT";
      }

      if (boolNew || data == null || data.length == 0) {
        discard[0] = new String("editDiscard");
        strCommand = "NEW";
        data = new BusinessPartnerCategoryData[0];
      } else {
        discard[0] = new String("newDiscard");
      }
    } else {
      if (dataField.getField("cBpGroupId") == null || dataField.getField("cBpGroupId").equals("")) {
        discard[0] = new String("editDiscard");
        strCommand = "NEW";
        boolNew = true;
      } else {
        discard[0] = new String("newDiscard");
        strCommand = "EDIT";
      }
    }

    if (dataField == null) {
      if (boolNew || data == null || data.length == 0) {
        refreshSessionNew(vars);
        data =
            BusinessPartnerCategoryData.set(
                "",
                Utility.getDefault(
                    this, vars, "AD_Client_ID", "@AD_CLIENT_ID@", "192", "", dataField),
                Utility.getDefault(this, vars, "AD_Org_ID", "@AD_Org_ID@", "192", "", dataField),
                "Y",
                Utility.getDefault(this, vars, "CreatedBy", "", "192", "", dataField),
                BusinessPartnerCategoryData.selectDef4966_0(
                    this, Utility.getDefault(this, vars, "CreatedBy", "", "192", "", dataField)),
                Utility.getDefault(this, vars, "UpdatedBy", "", "192", "", dataField),
                BusinessPartnerCategoryData.selectDef4968_1(
                    this, Utility.getDefault(this, vars, "UpdatedBy", "", "192", "", dataField)),
                Utility.getDefault(this, vars, "Value", "", "192", "", dataField),
                Utility.getDefault(this, vars, "Name", "", "192", "", dataField),
                Utility.getDefault(this, vars, "Description", "", "192", "", dataField),
                Utility.getDefault(this, vars, "IsDefault", "", "192", "N", dataField));
      }
    }

    String currentOrg =
        (boolNew
            ? ""
            : (dataField != null ? dataField.getField("adOrgId") : data[0].getField("adOrgId")));
    if (!currentOrg.equals("") && !currentOrg.startsWith("'")) currentOrg = "'" + currentOrg + "'";
    String currentClient =
        (boolNew
            ? ""
            : (dataField != null
                ? dataField.getField("adClientId")
                : data[0].getField("adClientId")));
    if (!currentClient.equals("") && !currentClient.startsWith("'"))
      currentClient = "'" + currentClient + "'";

    boolean hasReadOnlyAccess =
        org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
            this, vars.getRole(), tabId);
    boolean editableTab =
        (!hasReadOnlyAccess
            && (currentOrg.equals("")
                || Utility.isElementInList(
                    Utility.getContext(this, vars, "#User_Org", windowId, accesslevel), currentOrg))
            && (currentClient.equals("")
                || Utility.isElementInList(
                    Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                    currentClient)));
    if (editableTab)
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpWindows/BusinessPartnerCategory/BusinessPartnerCategory_Edition",
                  discard)
              .createXmlDocument();
    else
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpWindows/BusinessPartnerCategory/BusinessPartnerCategory_NonEditable",
                  discard)
              .createXmlDocument();

    xmlDocument.setParameter("tabId", tabId);
    ToolBar toolbar =
        new ToolBar(
            this,
            editableTab,
            vars.getLanguage(),
            "BusinessPartnerCategory",
            (strCommand.equals("NEW")
                || boolNew
                || (dataField == null && (data == null || data.length == 0))),
            "document.frmMain.inpcBpGroupId",
            "",
            "..",
            "".equals("Y"),
            "BusinessPartnerCategory",
            strReplaceWith,
            true,
            false,
            false,
            Utility.hasTabAttachments(this, vars, tabId, strC_BP_Group_ID),
            !hasReadOnlyAccess);
    toolbar.setTabId(tabId);
    toolbar.setDeleteable(true);
    toolbar.prepareEditionTemplate(
        "N".equals("Y"),
        hasSearchCondition,
        vars.getSessionValue("#ShowTest", "N").equals("Y"),
        "STD",
        Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y"));
    xmlDocument.setParameter("toolbar", toolbar.toString());

    // set updated timestamp to manage locking mechanism
    if (!boolNew) {
      xmlDocument.setParameter(
          "updatedTimestamp",
          (dataField != null
              ? dataField.getField("updatedTimeStamp")
              : data[0].getField("updatedTimeStamp")));
    }

    boolean concurrentSave = vars.getSessionValue(tabId + "|concurrentSave").equals("true");
    if (concurrentSave) {
      // after concurrent save error, force autosave
      xmlDocument.setParameter("autosave", "Y");
    } else {
      xmlDocument.setParameter("autosave", "N");
    }
    vars.removeSessionValue(tabId + "|concurrentSave");

    try {
      WindowTabs tabs =
          new WindowTabs(this, vars, tabId, windowId, true, (strCommand.equalsIgnoreCase("NEW")));
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      // if (!strC_BP_Group_ID.equals("")) xmlDocument.setParameter("childTabContainer",
      // tabs.childTabs(false));
      // else xmlDocument.setParameter("childTabContainer", tabs.childTabs(true));
      xmlDocument.setParameter("childTabContainer", tabs.childTabs(false));
      String hideBackButton = vars.getGlobalVariable("hideMenu", "#Hide_BackButton", "");
      NavigationBar nav =
          new NavigationBar(
              this,
              vars.getLanguage(),
              "BusinessPartnerCategory_Relation.html",
              "BusinessPartnerCategory",
              "W",
              strReplaceWith,
              tabs.breadcrumb(),
              hideBackButton.equals("true"),
              !concurrentSave);
      xmlDocument.setParameter("navigationBar", nav.toString());
      LeftTabsBar lBar =
          new LeftTabsBar(
              this, vars.getLanguage(), "BusinessPartnerCategory_Relation.html", strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.editionTemplate(strCommand.equals("NEW")));
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    xmlDocument.setParameter("commandType", strCommand);
    xmlDocument.setParameter("buscador", buscador);
    xmlDocument.setParameter("windowId", windowId);
    xmlDocument.setParameter("changed", "");
    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("theme", vars.getTheme());
    final String strMappingName = Utility.getTabURL(tabId, "E", false);
    xmlDocument.setParameter("mappingName", strMappingName);
    xmlDocument.setParameter("confirmOnChanges", Utility.getJSConfirmOnChanges(vars, windowId));
    // xmlDocument.setParameter("buttonReference", Utility.messageBD(this, "Reference",
    // vars.getLanguage()));

    xmlDocument.setParameter("paramSessionDate", strParamSessionDate);

    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    OBError myMessage = vars.getMessage(tabId);
    vars.removeMessage(tabId);
    if (myMessage != null) {
      xmlDocument.setParameter("messageType", myMessage.getType());
      xmlDocument.setParameter("messageTitle", myMessage.getTitle());
      xmlDocument.setParameter("messageMessage", myMessage.getMessage());
    }
    xmlDocument.setParameter("displayLogic", getDisplayLogicContext(vars, boolNew));

    if (dataField == null) {
      xmlDocument.setData("structure1", data);

    } else {

      FieldProvider[] dataAux = new FieldProvider[1];
      dataAux[0] = dataField;

      xmlDocument.setData("structure1", dataAux);
    }

    try {
      ComboTableData comboTableData = null;
      String userOrgList = "";
      if (editableTab)
        userOrgList =
            Utility.getContext(this, vars, "#User_Org", windowId, accesslevel); // editable record
      else userOrgList = currentOrg;
      comboTableData =
          new ComboTableData(
              vars,
              this,
              "19",
              "AD_Org_ID",
              "",
              "",
              userOrgList,
              Utility.getContext(this, vars, "#User_Client", windowId),
              0);
      Utility.fillSQLParameters(
          this,
          vars,
          (dataField == null ? data[0] : dataField),
          comboTableData,
          windowId,
          (dataField == null ? data[0].getField("adOrgId") : dataField.getField("adOrgId")));
      xmlDocument.setData(
          "reportAD_Org_ID", "liststructure", comboTableData.select(!strCommand.equals("NEW")));
      comboTableData = null;
      xmlDocument.setParameter("Created_Format", vars.getSessionValue("#AD_SqlDateTimeFormat"));
      xmlDocument.setParameter(
          "Created_Maxlength",
          Integer.toString(vars.getSessionValue("#AD_SqlDateTimeFormat").length()));
      xmlDocument.setParameter("Updated_Format", vars.getSessionValue("#AD_SqlDateTimeFormat"));
      xmlDocument.setParameter(
          "Updated_Maxlength",
          Integer.toString(vars.getSessionValue("#AD_SqlDateTimeFormat").length()));
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new ServletException(ex);
    }

    xmlDocument.setParameter("scriptOnLoad", getShortcutScript(usedButtonShortCuts));

    final String refererURL = vars.getSessionValue(tabId + "|requestURL");
    vars.removeSessionValue(tabId + "|requestURL");
    if (!refererURL.equals("")) {
      final Boolean failedAutosave = (Boolean) vars.getSessionObject(tabId + "|failedAutosave");
      vars.removeSessionValue(tabId + "|failedAutosave");
      if (failedAutosave != null && failedAutosave) {
        final String jsFunction = "continueUserAction('" + refererURL + "');";
        xmlDocument.setParameter("failedAutosave", jsFunction);
      }
    }

    if (strCommand.equalsIgnoreCase("NEW")) {
      vars.removeSessionValue(tabId + "|failedAutosave");
      vars.removeSessionValue(strMappingName + "|hash");
    }

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
  @Override
  protected void execute(CalloutInfo info) throws ServletException {

    // General data

    String strBPartner = info.vars.getStringParameter("inpcBpartnerId");
    String strIsSOTrx = Utility.getContext(this, info.vars, "isSOTrx", info.getWindowId());
    String strOrgId = info.vars.getStringParameter("inpadOrgId");
    String strPriceList = "";
    String strUserRep = "";
    String strInvoiceRule = "";
    String strFinPaymentMethodId = "";
    String strPaymentrule = "";
    String strDeliveryViaRule = "";
    String strPaymentterm = "";
    String strDeliveryRule = "";
    String strDocTypeTarget = info.vars.getStringParameter("inpcDoctypetargetId");
    String docSubTypeSO = "";

    BpartnerMiscData[] data = BpartnerMiscData.select(this, strBPartner);
    if (data != null && data.length > 0) {
      strDeliveryRule =
          data[0].deliveryrule.equals("")
              ? info.vars.getStringParameter("inpdeliveryrule")
              : data[0].deliveryrule;
      strUserRep = SEOrderBPartnerData.userIdSalesRep(this, data[0].salesrepId);
      strUserRep =
          strUserRep.equals("") ? info.vars.getStringParameter("inpsalesrepId") : strUserRep;
      SLOrderDocTypeData[] docTypeData = SLOrderDocTypeData.select(this, strDocTypeTarget);
      if (docTypeData != null && docTypeData.length > 0) {
        docSubTypeSO = docTypeData[0].docsubtypeso;
      }
      strInvoiceRule =
          (docSubTypeSO.equals("PR") || docSubTypeSO.equals("WI") || data[0].invoicerule.equals("")
              ? info.vars.getStringParameter("inpinvoicerule")
              : data[0].invoicerule);
      strPaymentrule = (strIsSOTrx.equals("Y") ? data[0].paymentrule : data[0].paymentrulepo);
      strPaymentrule =
          strPaymentrule.equals("")
              ? info.vars.getStringParameter("inppaymentrule")
              : strPaymentrule;

      strPaymentterm = (strIsSOTrx.equals("Y") ? data[0].cPaymenttermId : data[0].poPaymenttermId);
      if (strPaymentterm.equalsIgnoreCase("")) {
        BpartnerMiscData[] paymentTerm =
            BpartnerMiscData.selectPaymentTerm(this, strOrgId, info.vars.getClient());
        if (paymentTerm.length != 0) {
          strPaymentterm =
              strPaymentterm.equals("") ? paymentTerm[0].cPaymenttermId : strPaymentterm;
        }
      }
      strPaymentterm =
          strPaymentterm.equals("")
              ? info.vars.getStringParameter("inpcPaymenttermId")
              : strPaymentterm;

      strFinPaymentMethodId =
          (strIsSOTrx.equals("Y") ? data[0].finPaymentmethodId : data[0].poPaymentmethodId);

      strPriceList = (strIsSOTrx.equals("Y") ? data[0].mPricelistId : data[0].poPricelistId);
      if (strPriceList.equalsIgnoreCase("")) {
        strPriceList =
            SEOrderBPartnerData.defaultPriceList(this, strIsSOTrx, info.vars.getClient());
      }
      strPriceList =
          strPriceList.equals("") ? info.vars.getStringParameter("inpmPricelistId") : strPriceList;
      strDeliveryViaRule =
          data[0].deliveryviarule.equals("")
              ? info.vars.getStringParameter("inpdeliveryviarule")
              : data[0].deliveryviarule;
    }

    // Price list

    info.addResult(
        "inpmPricelistId",
        strPriceList.equals("")
            ? Utility.getContext(this, info.vars, "#M_PriceList_ID", info.getWindowId())
            : strPriceList);

    // BPartner Location

    FieldProvider[] tdv = null;

    String strLocation = info.vars.getStringParameter("inpcBpartnerId_LOC");
    if (strLocation != null && !strLocation.isEmpty()) {
      info.addResult("inpcBpartnerLocationId", strLocation);
    }

    // Warehouses

    FieldProvider[] td = null;
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              info.vars,
              this,
              "18",
              "M_Warehouse_ID",
              "197",
              "",
              Utility.getReferenceableOrg(info.vars, info.vars.getStringParameter("inpadOrgId")),
              Utility.getContext(this, info.vars, "#User_Client", info.getWindowId()),
              0);
      Utility.fillSQLParameters(this, info.vars, null, comboTableData, info.getWindowId(), "");
      td = comboTableData.select(false);
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    if (td != null && td.length > 0) {
      info.addSelect("inpmWarehouseId");
      String strMwarehouse = SEOrderBPartnerData.mWarehouse(this, strBPartner);

      if (strMwarehouse.equals("")) {
        strMwarehouse = info.vars.getWarehouse();
      }

      for (int i = 0; i < td.length; i++) {
        info.addSelectResult(
            td[i].getField("id"),
            td[i].getField("name"),
            td[i].getField("id").equalsIgnoreCase(strMwarehouse));
      }
      info.endSelect();
    } else {
      info.addResult("inpmWarehouseId", null);
    }
    // Sales Representative

    FieldProvider[] tld = null;
    try {
      ComboTableData comboTableData =
          new ComboTableData(
              info.vars,
              this,
              "TABLE",
              "",
              "AD_User SalesRep",
              "",
              Utility.getContext(this, info.vars, "#AccessibleOrgTree", "SEOrderBPartner"),
              Utility.getContext(this, info.vars, "#User_Client", "SEOrderBPartner"),
              0);
      Utility.fillSQLParameters(this, info.vars, null, comboTableData, "SEOrderBPartner", "");
      tld = comboTableData.select(false);
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    if (tld != null && tld.length > 0) {
      info.addSelect("inpsalesrepId");
      for (int i = 0; i < tld.length; i++) {
        info.addSelectResult(
            tld[i].getField("id"),
            tld[i].getField("name"),
            tld[i].getField("id").equalsIgnoreCase(strUserRep));
      }

      info.endSelect();

    } else {
      info.addResult("inpsalesrepId", null);
    }

    // Invoice Rule

    FieldProvider[] l = null;
    try {
      ComboTableData comboTableData = null;
      if ("WR".equals(docSubTypeSO)) {
        comboTableData =
            new ComboTableData(
                info.vars,
                this,
                "LIST",
                "",
                "C_Order InvoiceRule",
                "Values for Invoice Rules for POS Sales orders",
                Utility.getContext(this, info.vars, "#AccessibleOrgTree", "SEOrderBPartner"),
                Utility.getContext(this, info.vars, "#User_Client", "SEOrderBPartner"),
                0);
      } else {
        comboTableData =
            new ComboTableData(
                info.vars,
                this,
                "LIST",
                "",
                "C_Order InvoiceRule",
                "",
                Utility.getContext(this, info.vars, "#AccessibleOrgTree", "SEOrderBPartner"),
                Utility.getContext(this, info.vars, "#User_Client", "SEOrderBPartner"),
                0);
      }
      Utility.fillSQLParameters(this, info.vars, null, comboTableData, "SEOrderBPartner", "");
      l = comboTableData.select(false);
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    if (l != null && l.length > 0) {
      info.addSelect("inpinvoicerule");
      for (int i = 0; i < l.length; i++) {
        info.addSelectResult(
            l[i].getField("id"),
            l[i].getField("name"),
            l[i].getField("id").equalsIgnoreCase(strInvoiceRule));
      }

      info.endSelect();

    } else {
      info.addResult("inpinvoicerule", null);
    }
    // Project

    info.addResult("inpcProjectId", "");

    // Project R

    info.addResult("inpcProjectId_R", "");

    // Financial Payment

    if (!"".equals(strFinPaymentMethodId)) {
      info.addResult("inpfinPaymentmethodId", strFinPaymentMethodId);
    }

    // Bill to

    if (strLocation != null && !strLocation.isEmpty()) {
      info.addResult("inpbilltoId", strLocation);
    }

    // Payment rule

    info.addResult("inppaymentrule", strPaymentrule);

    // Delivery via rule

    info.addResult("inpdeliveryviarule", strDeliveryViaRule);

    // Discount printed

    info.addResult(
        "inpisdiscountprinted", SEOrderBPartnerData.getIsDicountPrinted(this, strBPartner));

    // Payment term

    info.addResult("inpcPaymenttermId", strPaymentterm);

    // Delivery rule

    try {
      ComboTableData comboTableData =
          new ComboTableData(
              info.vars,
              this,
              "LIST",
              "",
              "C_Order DeliveryRule",
              "",
              Utility.getContext(this, info.vars, "#AccessibleOrgTree", "SEOrderBPartner"),
              Utility.getContext(this, info.vars, "#User_Client", "SEOrderBPartner"),
              0);
      Utility.fillSQLParameters(this, info.vars, null, comboTableData, "SEOrderBPartner", "");
      l = comboTableData.select(false);
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    if (strIsSOTrx.equals("N")) {
      info.addResult(
          "inpdeliveryrule",
          strDeliveryRule.equals("")
              ? ((l != null && l.length > 0) ? l[0].getField("id") : "null")
              : strDeliveryRule);
    } else {

      if (l != null && l.length > 0) {
        info.addSelect("inpdeliveryrule");

        for (int i = 0; i < l.length; i++) {
          info.addSelectResult(
              l[i].getField("id"),
              l[i].getField("name"),
              l[i].getField("id").equalsIgnoreCase(strDeliveryRule));
        }

        info.endSelect();
      } else {
        info.addResult("inpdeliveryrule", null);
      }
    }

    // Ad User

    try {
      ComboTableData comboTableData =
          new ComboTableData(
              info.vars,
              this,
              "TABLEDIR",
              "AD_User_ID",
              "",
              "AD_User C_BPartner User/Contacts",
              Utility.getContext(this, info.vars, "#AccessibleOrgTree", info.getWindowId()),
              Utility.getContext(this, info.vars, "#User_Client", info.getWindowId()),
              0);
      Utility.fillSQLParameters(this, info.vars, null, comboTableData, info.getWindowId(), "");
      tdv = comboTableData.select(false);
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    if (tdv != null && tdv.length > 0) {
      info.addSelect("inpadUserId");

      String contactID = info.vars.getStringParameter("inpcBpartnerId_CON");
      if (contactID.isEmpty()) {
        // If a contactID has not been specified, the first one is selected
        info.addSelectResult(tdv[0].getField("id"), tdv[0].getField("name"), true);
        for (int i = 1; i < tdv.length; i++) {
          info.addSelectResult(tdv[i].getField("id"), tdv[i].getField("name"), false);
        }
      } else {
        for (int i = 0; i < tdv.length; i++) {
          info.addSelectResult(
              tdv[i].getField("id"),
              tdv[i].getField("name"),
              tdv[i]
                  .getField("id")
                  .equalsIgnoreCase(info.vars.getStringParameter("inpcBpartnerId_CON")));
        }
      }
      info.endSelect();

    } else {
      info.addResult("inpadUserId", null);
    }

    // Message

    StringBuilder message = new StringBuilder();
    final String rtvendor = "C50A8AEE6F044825B5EF54FAAE76826F";
    final String rfcustomer = "FF808081330213E60133021822E40007";
    String strwindow = info.getStringParameter("inpwindowId", null);

    if (!(strwindow.equals(rtvendor) || strwindow.equals(rfcustomer))) {
      if ((!strBPartner.equals(""))
          && (FIN_Utility.isBlockedBusinessPartner(strBPartner, "Y".equals(strIsSOTrx), 1))) {
        // If the Business Partner is blocked for this document, show an information message.
        if (message.length() > 0) {
          message.append("<br>");
        }
        BusinessPartner bPartner = OBDal.getInstance().get(BusinessPartner.class, strBPartner);
        message.append(
            OBMessageUtils.messageBD("ThebusinessPartner")
                + " "
                + bPartner.getIdentifier()
                + " "
                + OBMessageUtils.messageBD("BusinessPartnerBlocked"));
      }
    }

    if (data != null
        && data.length > 0
        && new BigDecimal(data[0].creditavailable).compareTo(BigDecimal.ZERO) < 0
        && strIsSOTrx.equals("Y")) {
      if (message.length() > 0) {
        message.append("<br>");
      }
      String creditLimitExceed = "" + Double.parseDouble(data[0].creditavailable) * -1;
      message.append(
          Utility.messageBD(this, "CreditLimitOver", info.vars.getLanguage()) + creditLimitExceed);
    }

    info.addResult("MESSAGE", message.toString());
  }
  private void printPage(
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strKey,
      String strProjectType,
      String windowId,
      String strTab,
      String strProcessId)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: Button process Project set Type");

    ActionButtonDefaultData[] data = null;
    String strHelp = "", strDescription = "";
    if (vars.getLanguage().equals("en_US"))
      data = ActionButtonDefaultData.select(this, strProcessId);
    else data = ActionButtonDefaultData.selectLanguage(this, vars.getLanguage(), strProcessId);

    if (data != null && data.length != 0) {
      strDescription = data[0].description;
      strHelp = data[0].help;
    }
    String[] discard = {""};
    if (strHelp.equals("")) discard[0] = new String("helpDiscard");
    XmlDocument xmlDocument =
        xmlEngine
            .readXmlTemplate("org/openbravo/erpCommon/ad_actionButton/ProjectSetType", discard)
            .createXmlDocument();
    xmlDocument.setParameter("key", strKey);
    xmlDocument.setParameter("window", windowId);
    xmlDocument.setParameter("tab", strTab);
    xmlDocument.setParameter("calendar", vars.getLanguage().substring(0, 2));
    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter(
        "question", Utility.messageBD(this, "StartProcess?", vars.getLanguage()));
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("theme", vars.getTheme());
    xmlDocument.setParameter("description", strDescription);
    xmlDocument.setParameter("help", strHelp);

    try {
      ComboTableData comboTableData =
          new ComboTableData(
              vars,
              this,
              "TABLEDIR",
              "C_ProjectType_ID",
              "",
              "Project type service",
              Utility.getContext(this, vars, "#AccessibleOrgTree", ""),
              Utility.getContext(this, vars, "#User_Client", ""),
              0);
      Utility.fillSQLParameters(this, vars, null, comboTableData, "", strProjectType);
      xmlDocument.setData("reportcProjecttypeId", "liststructure", comboTableData.select(false));
      comboTableData = null;
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    ProjectSetTypeData[] dataDates = ProjectSetTypeData.selectDates(this, strKey);
    String strDateFrom =
        dataDates[0].startdate.equals("") ? DateTimeData.today(this) : dataDates[0].startdate;
    xmlDocument.setParameter("dateFrom", strDateFrom);
    xmlDocument.setParameter("dateFromdisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
    xmlDocument.setParameter("dateFromsaveFormat", vars.getSessionValue("#AD_SqlDateFormat"));

    xmlDocument.setParameter("cProjecttypeId", strProjectType);

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
  private int saveRecord(VariablesSecureApp vars, OBError myError, char type)
      throws IOException, ServletException {
    BusinessPartnerCategoryData data = null;
    int total = 0;
    if (org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
        this, vars.getRole(), tabId)) {
      OBError newError =
          Utility.translateError(
              this,
              vars,
              vars.getLanguage(),
              Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
      myError.setError(newError);
      vars.setMessage(tabId, myError);
    } else {
      Connection con = null;
      try {
        con = this.getTransactionConnection();
        data = getEditVariables(con, vars);
        data.dateTimeFormat = vars.getSessionValue("#AD_SqlDateTimeFormat");
        String strSequence = "";
        if (type == 'I') {
          strSequence = SequenceIdData.getUUID();
          if (log4j.isDebugEnabled()) log4j.debug("Sequence: " + strSequence);
          data.cBpGroupId = strSequence;
        }
        if (Utility.isElementInList(
                Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                data.adClientId)
            && Utility.isElementInList(
                Utility.getContext(this, vars, "#User_Org", windowId, accesslevel), data.adOrgId)) {
          if (type == 'I') {
            total = data.insert(con, this);
          } else {
            // Check the version of the record we are saving is the one in DB
            if (BusinessPartnerCategoryData.getCurrentDBTimestamp(this, data.cBpGroupId)
                .equals(vars.getStringParameter("updatedTimestamp"))) {
              total = data.update(con, this);
            } else {
              myError.setMessage(
                  Replace.replace(
                      Replace.replace(
                          Utility.messageBD(this, "SavingModifiedRecord", vars.getLanguage()),
                          "\\n",
                          "<br/>"),
                      "&quot;",
                      "\""));
              myError.setType("Error");
              vars.setSessionValue(tabId + "|concurrentSave", "true");
            }
          }

        } else {
          OBError newError =
              Utility.translateError(
                  this,
                  vars,
                  vars.getLanguage(),
                  Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
          myError.setError(newError);
        }
        releaseCommitConnection(con);
      } catch (Exception ex) {
        OBError newError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
        myError.setError(newError);
        try {
          releaseRollbackConnection(con);
        } catch (final Exception e) { // do nothing
        }
      }

      if (myError.isEmpty() && total == 0) {
        OBError newError =
            Utility.translateError(this, vars, vars.getLanguage(), "@CODE=DBExecuteError");
        myError.setError(newError);
      }
      vars.setMessage(tabId, myError);

      if (!myError.isEmpty()) {
        if (data != null) {
          if (type == 'I') {
            data.cBpGroupId = "";
          } else {

          }
          vars.setEditionData(tabId, data);
        }
      } else {
        vars.setSessionValue(windowId + "|C_BP_Group_ID", data.cBpGroupId);
      }
    }
    return total;
  }
  @Override
  protected String doAuthenticate(HttpServletRequest request, HttpServletResponse response)
      throws AuthenticationException, ServletException, IOException {

    final VariablesSecureApp vars = new VariablesSecureApp(request, false);
    final String sUserId = (String) request.getSession().getAttribute("#Authenticated_user");
    final String strAjax = vars.getStringParameter("IsAjaxCall");

    if (!StringUtils.isEmpty(sUserId)) {
      return sUserId;
    }

    VariablesHistory variables = new VariablesHistory(request);

    // Begins code related to login process

    final String strUser = vars.getStringParameter("user");
    final String strPass = vars.getStringParameter("password");
    username = strUser;

    if (StringUtils.isEmpty(strUser)) {
      // redirects to the menu or the menu with the target
      setTargetInfoInVariables(request, variables);
      return null; // just give up, return null
    }

    final String userId = LoginUtils.getValidUserId(conn, strUser, strPass);
    final String sessionId = createDBSession(request, strUser, userId);

    if (userId == null) {

      OBError errorMsg = new OBError();
      errorMsg.setType("Error");

      if (LoginUtils.checkUserPassword(conn, strUser, strPass) == null) {
        log4j.debug("Failed user/password. Username: "******" - Session ID:" + sessionId);
        errorMsg.setTitle("IDENTIFICATION_FAILURE_TITLE");
        errorMsg.setMessage("IDENTIFICATION_FAILURE_MSG");
      } else {
        log4j.debug(strUser + " is locked cannot activate session ID " + sessionId);
        errorMsg.setTitle("LOCKED_USER_TITLE");
        errorMsg.setMessage("LOCKED_USER_MSG");
      }

      // throw error message will be caught by LoginHandler
      throw new AuthenticationException("IDENTIFICATION_FAILURE_TITLE", errorMsg);
    }

    // Using the Servlet API instead of vars.setSessionValue to avoid breaking code
    // vars.setSessionValue always transform the key to upper-case
    request.getSession(true).setAttribute("#Authenticated_user", userId);

    vars.setSessionValue("#AD_SESSION_ID", sessionId);
    vars.setSessionValue("#LogginIn", "Y");

    if (!StringUtils.isEmpty(strAjax) && StringUtils.isEmpty(userId)) {
      bdErrorAjax(
          response,
          "Error",
          "",
          Utility.messageBD(this.conn, "NotLogged", variables.getLanguage()));
      return null;
    } else {
      // redirects to the menu or the menu with the target
      setTargetInfoInVariables(request, variables);
    }

    return userId;
  }
  private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strClient)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: Delete Client");

    ActionButtonDefaultData[] data = null;
    String strHelp = "", strDescription = "", strProcessId = "800147";
    if (vars.getLanguage().equals("en_US"))
      data = ActionButtonDefaultData.select(this, strProcessId);
    else data = ActionButtonDefaultData.selectLanguage(this, vars.getLanguage(), strProcessId);

    if (data != null && data.length != 0) {
      strDescription = data[0].description;
      strHelp = data[0].help;
    }
    String[] discard = {""};
    if (strHelp.equals("")) discard[0] = new String("helpDiscard");
    XmlDocument xmlDocument =
        xmlEngine
            .readXmlTemplate("org/openbravo/erpCommon/ad_process/DeleteClient", discard)
            .createXmlDocument();

    ToolBar toolbar =
        new ToolBar(
            this,
            vars.getLanguage(),
            "DeleteClient",
            false,
            "",
            "",
            "",
            false,
            "ad_process",
            strReplaceWith,
            false,
            true);
    toolbar.prepareSimpleToolBarTemplate();
    xmlDocument.setParameter("toolbar", toolbar.toString());

    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter(
        "alertMsg",
        "ALERT_MSG=\""
            + Utility.messageBD(this, "GoingToDeleteClient", vars.getLanguage())
            + "\";");
    xmlDocument.setParameter(
        "question", Utility.messageBD(this, "StartProcess?", vars.getLanguage()));
    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    xmlDocument.setParameter("description", strDescription);
    xmlDocument.setParameter("help", strHelp);
    xmlDocument.setParameter("Client", strClient);
    try {
      WindowTabs tabs =
          new WindowTabs(this, vars, "org.openbravo.erpCommon.ad_process.DeleteClient");
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      xmlDocument.setParameter("childTabContainer", tabs.childTabs());
      xmlDocument.setParameter("theme", vars.getTheme());
      NavigationBar nav =
          new NavigationBar(
              this,
              vars.getLanguage(),
              "DeleteClient.html",
              classInfo.id,
              classInfo.type,
              strReplaceWith,
              tabs.breadcrumb());
      xmlDocument.setParameter("navigationBar", nav.toString());
      LeftTabsBar lBar =
          new LeftTabsBar(this, vars.getLanguage(), "DeleteClient.html", strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.manualTemplate());
    } catch (Exception ex) {
      throw new ServletException(ex);
    }
    {
      OBError myMessage = vars.getMessage("DeleteClient");
      vars.removeMessage("DeleteClient");
      if (myMessage != null) {
        xmlDocument.setParameter("messageType", myMessage.getType());
        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
      }
    }
    xmlDocument.setData(
        "reportClientId", "liststructure", ClientComboData.selectAllClientsNoSystem1(this));

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
  public void execute(ProcessBundle bundle) throws Exception {
    dao = new AdvPaymentMngtDao();
    OBError msg = new OBError();
    msg.setType("Success");
    msg.setTitle(
        Utility.messageBD(bundle.getConnection(), "Success", bundle.getContext().getLanguage()));

    try {
      // retrieve custom params
      final String strAction = (String) bundle.getParams().get("action");

      // retrieve standard params
      final String recordID = (String) bundle.getParams().get("Fin_FinAcc_Transaction_ID");
      final FIN_FinaccTransaction transaction =
          dao.getObject(FIN_FinaccTransaction.class, recordID);
      final VariablesSecureApp vars = bundle.getContext().toVars();
      final ConnectionProvider conProvider = bundle.getConnection();
      final String language = bundle.getContext().getLanguage();

      OBContext.setAdminMode();
      try {
        if (strAction.equals("P")) {
          // ***********************
          // Process Transaction
          // ***********************
          boolean orgLegalWithAccounting =
              FIN_Utility.periodControlOpened(
                  transaction.TABLE_NAME,
                  transaction.getId(),
                  transaction.TABLE_NAME + "_ID",
                  "LE");
          boolean documentEnabled = getDocumentConfirmation(conProvider, transaction.getId());
          if (documentEnabled
              && !FIN_Utility.isPeriodOpen(
                  transaction.getClient().getId(),
                  AcctServer.DOCTYPE_FinAccTransaction,
                  transaction.getOrganization().getId(),
                  OBDateUtils.formatDate(transaction.getDateAcct()))
              && orgLegalWithAccounting) {
            msg.setType("Error");
            msg.setTitle(Utility.messageBD(conProvider, "Error", language));
            msg.setMessage(
                Utility.parseTranslation(conProvider, vars, language, "@PeriodNotAvailable@"));
            bundle.setResult(msg);
            OBDal.getInstance().rollbackAndClose();
            return;
          }
          final FIN_FinancialAccount financialAccount = transaction.getAccount();
          financialAccount.setCurrentBalance(
              financialAccount
                  .getCurrentBalance()
                  .add(transaction.getDepositAmount().subtract(transaction.getPaymentAmount())));
          transaction.setProcessed(true);
          FIN_Payment payment = transaction.getFinPayment();
          if (payment != null) {
            if (transaction.getBusinessPartner() == null) {
              transaction.setBusinessPartner(payment.getBusinessPartner());
            }
            payment.setStatus(payment.isReceipt() ? "RDNC" : "PWNC");
            transaction.setStatus(payment.isReceipt() ? "RDNC" : "PWNC");
            OBDal.getInstance().save(payment);
            if (transaction.getDescription() == null || "".equals(transaction.getDescription())) {
              transaction.setDescription(payment.getDescription());
            }
            Boolean invoicePaidold = false;
            for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
              for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                invoicePaidold = psd.isInvoicePaid();
                if (!invoicePaidold) {
                  if ((FIN_Utility.invoicePaymentStatus(payment).equals(payment.getStatus()))) {
                    psd.setInvoicePaid(true);
                  }
                  if (psd.isInvoicePaid()) {
                    FIN_Utility.updatePaymentAmounts(psd);
                    FIN_Utility.updateBusinessPartnerCredit(payment);
                  }
                  OBDal.getInstance().save(psd);
                }
              }
            }

          } else {
            transaction.setStatus(
                transaction.getDepositAmount().compareTo(transaction.getPaymentAmount()) > 0
                    ? "RDNC"
                    : "PWNC");
          }
          if (transaction.getForeignCurrency() != null
              && !transaction.getCurrency().equals(transaction.getForeignCurrency())
              && getConversionRateDocument(transaction).size() == 0) {
            insertConversionRateDocument(transaction);
          }
          OBDal.getInstance().save(financialAccount);
          OBDal.getInstance().save(transaction);
          OBDal.getInstance().flush();
          bundle.setResult(msg);

        } else if (strAction.equals("R")) {
          // ***********************
          // Reactivate Transaction
          // ***********************
          // Already Posted Document
          if ("Y".equals(transaction.getPosted())) {
            msg.setType("Error");
            msg.setTitle(Utility.messageBD(conProvider, "Error", language));
            msg.setMessage(
                Utility.parseTranslation(
                    conProvider,
                    vars,
                    language,
                    "@PostedDocument@" + ": " + transaction.getIdentifier()));
            bundle.setResult(msg);
            return;
          }
          // Already Reconciled
          if (transaction.getReconciliation() != null || "RPPC".equals(transaction.getStatus())) {
            msg.setType("Error");
            msg.setTitle(Utility.messageBD(conProvider, "Error", language));
            msg.setMessage(
                Utility.parseTranslation(
                    conProvider,
                    vars,
                    language,
                    "@APRM_ReconciledDocument@" + ": " + transaction.getIdentifier()));
            bundle.setResult(msg);
            return;
          }
          // Remove conversion rate at document level for the given transaction
          OBContext.setAdminMode();
          try {
            OBCriteria<ConversionRateDoc> obc =
                OBDal.getInstance().createCriteria(ConversionRateDoc.class);
            obc.add(
                Restrictions.eq(
                    ConversionRateDoc.PROPERTY_FINANCIALACCOUNTTRANSACTION, transaction));
            for (ConversionRateDoc conversionRateDoc : obc.list()) {
              OBDal.getInstance().remove(conversionRateDoc);
            }
            OBDal.getInstance().flush();
          } finally {
            OBContext.restorePreviousMode();
          }
          transaction.setProcessed(false);
          final FIN_FinancialAccount financialAccount = transaction.getAccount();
          financialAccount.setCurrentBalance(
              financialAccount
                  .getCurrentBalance()
                  .subtract(transaction.getDepositAmount())
                  .add(transaction.getPaymentAmount()));
          OBDal.getInstance().save(financialAccount);
          OBDal.getInstance().save(transaction);
          OBDal.getInstance().flush();
          FIN_Payment payment = transaction.getFinPayment();
          if (payment != null) {
            Boolean invoicePaidold = false;
            for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
              for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                invoicePaidold = psd.isInvoicePaid();
                if (invoicePaidold) {
                  boolean restore =
                      (FIN_Utility.seqnumberpaymentstatus(payment.getStatus()))
                          == (FIN_Utility.seqnumberpaymentstatus(
                              FIN_Utility.invoicePaymentStatus(payment)));
                  if (restore) {
                    FIN_Utility.restorePaidAmounts(psd);
                  }
                }
              }
            }
            payment.setStatus(payment.isReceipt() ? "RPR" : "PPM");
            transaction.setStatus(payment.isReceipt() ? "RPR" : "PPM");
            OBDal.getInstance().save(payment);
          } else {
            transaction.setStatus(
                transaction.getDepositAmount().compareTo(transaction.getPaymentAmount()) > 0
                    ? "RPR"
                    : "PPM");
          }
          OBDal.getInstance().save(transaction);
          OBDal.getInstance().flush();
          bundle.setResult(msg);
        }
        bundle.setResult(msg);
      } finally {
        OBContext.restorePreviousMode();
      }
    } catch (final Exception e) {
      OBDal.getInstance().rollbackAndClose();
      e.printStackTrace(System.err);
      msg.setType("Error");
      msg.setTitle(
          Utility.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
      msg.setMessage(FIN_Utility.getExceptionMessage(e));
      bundle.setResult(msg);
    }
  }