Exemplo n.º 1
0
  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 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();
    }
  }
  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);
  }
  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 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;
  }