@Override
  protected String doIt() throws Exception {
    // Obtiene fecha actual del sistema
    calendario.getTime();

    // Si el día es el 1ero del mes le resto uno al mes y calculo la Pauta de Rebajas del mes
    // anterior
    if (calendario.get(Calendar.DAY_OF_MONTH) == 1) {
      calendario.add(Calendar.DAY_OF_MONTH, -1);
      fechaActual = calendario.getTime();
    }

    int month = 0;
    int year = 0;

    month = calendario.get(Calendar.MONTH) + 1;
    year = calendario.get(Calendar.YEAR);
    String fecha = "";

    if (month < 10) {
      fecha = "0" + month + "-" + year;
    } else {
      fecha = "" + month + "-" + year;
    }

    String SQLDel = "DELETE FROM XX_VMR_PatternOfDiscount";

    try {
      PreparedStatement pstmtDel = DB.prepareStatement(SQLDel, null);
      ResultSet rsDel = pstmtDel.executeQuery();
      rsDel.close();
      pstmtDel.close();

    } catch (Exception e) {
      log.log(Level.SEVERE, SQLDel, e);
      return "";
    }

    String SQL =
        "SELECT SUM(XX_INITIALINVENTORYQUANTITY) AS CANTINI, "
            + "SUM(XX_INITIALINVENTORYAMOUNT) AS MONTOINI, "
            + "(SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + "
            + "SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + SUM(XX_MOVEMENTQUANTITY) + "
            + "SUM(XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, (SUM(XX_INITIALINVENTORYAMOUNT) + "
            + "SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + "
            + "SUM(XX_MOVEMENTAMOUNT) + SUM(XX_AdjustmentsAmount)) AS MONTOFIN, "
            + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYQUANTITY) + "
            + "SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + "
            + "SUM(XX_MOVEMENTQUANTITY) + SUM(XX_ADJUSTMENTSQUANTITY))/2) AS CANTPROM, "
            + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYAMOUNT) + SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + "
            + "SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + SUM(XX_MOVEMENTAMOUNT) + "
            + "SUM(XX_AdjustmentsAmount))/2) AS MONTOPROM, M_Product_ID "
            + "FROM XX_VCN_Inventory "
            + "WHERE XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
            + " GROUP BY M_Product_ID";

    try {
      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) { // System.out.println(rs.getInt(7));
        cantInventIni = rs.getInt(1);
        montoInventIni = rs.getBigDecimal(2);
        cantInventFin = rs.getInt(3);
        montoInventFin = rs.getBigDecimal(4);
        cantInventProm = rs.getBigDecimal(5);
        montoInventProm = rs.getBigDecimal(6);
        /*System.out.println(cantInventIni);
        System.out.println(montoInventIni);
        System.out.println(cantInventFin);
        System.out.println(montoInventFin);
        System.out.println(cantInventProm);
        System.out.println(montoInventProm);*/

        if ((rs.getInt(7) != 0)
            && (cantInventFin != 0)
            && (montoInventFin != new BigDecimal(0))
            && (cantInventProm != new BigDecimal(0))
            && (montoInventProm != new BigDecimal(0))) {
          String SQL2 =
              "SELECT SUM(XX_SALESQUANTITY), SUM(XX_SALESAMOUNT), M_Product_ID "
                  + "FROM XX_VCN_Inventory "
                  + "WHERE M_Product_ID="
                  + rs.getInt(7)
                  + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                  + " GROUP BY M_Product_ID";

          try {
            PreparedStatement pstmt2 = DB.prepareStatement(SQL2, null);
            ResultSet rs2 = pstmt2.executeQuery();

            while (rs2.next()) {
              cantVentaMes = rs2.getInt(1);
              montoVentaMes = rs2.getBigDecimal(2);
              /*System.out.println(cantVentaMes);
              System.out.println(montoVentaMes);*/

              if ((cantVentaMes != 0) && (montoVentaMes != new BigDecimal(0))) {
                cantRotacion =
                    new BigDecimal(cantVentaMes * 12)
                        .divide(cantInventProm, 2, RoundingMode.HALF_UP);

                MProduct producto = new MProduct(Env.getCtx(), rs.getInt(7), null);

                String SQL3 =
                    "SELECT SUM(XX_INITIALINVENTORYQUANTITY) AS CANTINI, "
                        + "SUM(XX_INITIALINVENTORYAMOUNT) AS MONTOINI, "
                        + "(SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + "
                        + "SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + SUM(XX_MOVEMENTQUANTITY) + "
                        + "SUM(XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, (SUM(XX_INITIALINVENTORYAMOUNT) + "
                        + "SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + "
                        + "SUM(XX_MOVEMENTAMOUNT) + SUM(XX_AdjustmentsAmount)) AS MONTOFIN, "
                        + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYQUANTITY) + "
                        + "SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + "
                        + "SUM(XX_MOVEMENTQUANTITY) + SUM(XX_ADJUSTMENTSQUANTITY))/2) AS CANTPROM, "
                        + "((SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_INITIALINVENTORYAMOUNT) + SUM(XX_PREVIOUSADJUSTMENTSAMOUNT) + "
                        + "SUM(XX_SHOPPINGAMOUNT) + SUM(XX_SALESAMOUNT) + SUM(XX_MOVEMENTAMOUNT) + "
                        + "SUM(XX_AdjustmentsAmount))/2) AS MONTOPROM, XX_VMR_Department_ID "
                        + "FROM XX_VCN_Inventory "
                        + "WHERE XX_VMR_Department_ID="
                        + producto.getXX_VMR_Department_ID()
                        + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                        + " GROUP BY XX_VMR_Department_ID";

                try {
                  PreparedStatement pstmt3 = DB.prepareStatement(SQL3, null);
                  ResultSet rs3 = pstmt3.executeQuery();

                  while (rs3.next()) {
                    cantInvIniDep = rs3.getInt(1);
                    montoInvIniDep = rs3.getBigDecimal(2);
                    cantInvFinDep = rs.getInt(3);
                    montoInvFinDep = rs.getBigDecimal(4);
                    cantInvPromDep = rs.getBigDecimal(5);
                    montoInvPromDep = rs.getBigDecimal(6);
                    /*System.out.println(cantInvIniDep);
                    System.out.println(montoInvIniDep);
                    System.out.println(cantInvFinDep);
                    System.out.println(montoInvFinDep);
                    System.out.println(cantInvPromDep);
                    System.out.println(montoInvPromDep);*/

                    if ((cantInvFinDep != 0)
                        && (montoInvFinDep != new BigDecimal(0))
                        && (cantInvPromDep != new BigDecimal(0))
                        && (montoInvPromDep != new BigDecimal(0))) {
                      String SQL4 =
                          "SELECT SUM(XX_SALESQUANTITY), SUM(XX_SALESAMOUNT), XX_VMR_Department_ID "
                              + "FROM XX_VCN_Inventory "
                              + "WHERE XX_VMR_Department_ID="
                              + producto.getXX_VMR_Department_ID()
                              + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                              + " GROUP BY XX_VMR_Department_ID";

                      try {
                        PreparedStatement pstmt4 = DB.prepareStatement(SQL4, null);
                        ResultSet rs4 = pstmt4.executeQuery();

                        while (rs4.next()) {
                          cantVentaMesDep = rs4.getInt(1);
                          montoVentaMesDep = rs4.getBigDecimal(2);
                          /*System.out.println(cantVentaMesDep);
                          System.out.println(montoVentaMesDep);*/

                          if ((cantVentaMesDep != 0) && (montoVentaMesDep != new BigDecimal(0))) {
                            cantRotaDep =
                                new BigDecimal(cantVentaMesDep * 12)
                                    .divide(cantInvPromDep, 2, RoundingMode.HALF_UP);
                            // System.out.println(cantRotacion+"rota"+cantRotaDep+"dsssss"+cantRotacion.compareTo(cantRotaDep));
                            if (cantRotacion.compareTo(cantRotaDep) < 0) {
                              int cant = 0;
                              int consecutive = 0;
                              BigDecimal monto = new BigDecimal(0);
                              int patternDiscountID = 0;

                              String SQL5 =
                                  "SELECT (SUM(XX_INITIALINVENTORYQUANTITY) + SUM(XX_PREVIOUSADJUSTMENTSQUANTITY) + "
                                      + "SUM(XX_SHOPPINGQUANTITY) + SUM(XX_SALESQUANTITY) + SUM(XX_MOVEMENTQUANTITY) + "
                                      + "SUM(XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, M_Product_ID, "
                                      + "XX_VMR_Category_ID, XX_CONSECUTIVEPRICE, M_AttributeSetInstance_ID "
                                      + "FROM XX_VCN_Inventory "
                                      + "WHERE M_Product_ID="
                                      + rs.getInt(7)
                                      + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                                      + "GROUP BY M_Product_ID, XX_VMR_Category_ID, XX_CONSECUTIVEPRICE, M_AttributeSetInstance_ID";

                              try {
                                PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
                                ResultSet rs5 = pstmt5.executeQuery();

                                while (rs5.next()) {
                                  cant = rs5.getInt(1);
                                  consecutive = rs5.getInt(4);

                                  if ((cant != 0) && (consecutive != 0)) {
                                    String SQL6 =
                                        "SELECT DISTINCT(i.XX_ConsecutivePrice), i.M_Product_ID, "
                                            + "i.M_AttributeSetInstance_ID, c.Created, c.XX_SalePrice, "
                                            + "m.XX_VMR_TypeInventory_ID, r.XX_Range1, r.XX_Range2, r.XX_Range3 "
                                            + "FROM XX_VCN_Inventory i, XX_VMR_PriceConsecutive c, M_Product m, XX_VMR_RangeDaysPromote r "
                                            + "WHERE i.M_Product_ID="
                                            + rs.getInt(7)
                                            + " AND i.M_Product_ID=c.M_Product_ID "
                                            + "AND i.M_Product_ID=m.M_Product_ID "
                                            + "AND i.M_AttributeSetInstance_ID="
                                            + rs5.getInt(5)
                                            + " AND i.M_AttributeSetInstance_ID=c.M_AttributeSetInstance_ID "
                                            + "AND i.XX_ConsecutivePrice="
                                            + rs5.getInt(4)
                                            + " AND i.XX_VMR_Category_ID=r.XX_VMR_Category_ID "
                                            + "AND m.XX_VMR_TypeInventory_ID=r.XX_VMR_TypeInventory_ID "
                                            + "AND i.XX_INVENTORYMONTH='11' AND i.XX_INVENTORYYEAR='2009' "; // to_char(i.Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy')";

                                    try {
                                      PreparedStatement pstmt6 = DB.prepareStatement(SQL6, null);
                                      ResultSet rs6 = pstmt6.executeQuery();

                                      if (rs6.next()) {
                                        monto = rs6.getBigDecimal(5);
                                        long fechaInicial = rs6.getDate(4).getTime();
                                        long fechaFinal = fechaActual.getTime();
                                        long diferencia = fechaFinal - fechaInicial;
                                        double dias =
                                            Math.floor(diferencia / (1000 * 60 * 60 * 24));
                                        diasVida = (int) dias;
                                        /*System.out.println(rs6.getInt(7));
                                        System.out.println(rs6.getInt(8));
                                        System.out.println(rs6.getInt(9));*/
                                        patternDiscountID = getPatternOfDiscount(rs.getInt(7));

                                        if (patternDiscountID != 0) {
                                          // instancio pauta de rebaja con el id que devolvio
                                          patternDiscount =
                                              new X_XX_VMR_PatternOfDiscount(
                                                  Env.getCtx(), patternDiscountID, null);
                                        } else {
                                          // instancio pauta de rebaja nueva
                                          patternDiscount =
                                              new X_XX_VMR_PatternOfDiscount(Env.getCtx(), 0, null);
                                        }

                                        if ((diasVida >= rs6.getInt(7))
                                            && (diasVida < rs6.getInt(8))) {
                                          patternDiscount.setM_Product_ID(producto.get_ID());
                                          patternDiscount.setXX_QuantityPromotion20(
                                              patternDiscount.getXX_QuantityPromotion20() + cant);
                                          patternDiscount.setXX_AmountPromotion20(
                                              patternDiscount
                                                  .getXX_AmountPromotion20()
                                                  .add(monto.multiply(new BigDecimal(cant))));
                                          patternDiscount.save();
                                        } else if ((diasVida >= rs6.getInt(8))
                                            && ((rs6.getInt(9) == 0)
                                                || (diasVida < rs6.getInt(9)))) {
                                          patternDiscount.setM_Product_ID(producto.get_ID());
                                          patternDiscount.setXX_QuantityPromotion30(
                                              patternDiscount.getXX_QuantityPromotion30() + cant);
                                          patternDiscount.setXX_AmountPromotion30(
                                              patternDiscount
                                                  .getXX_AmountPromotion30()
                                                  .add(monto.multiply(new BigDecimal(cant))));
                                          patternDiscount.save();
                                        } else if ((diasVida >= rs6.getInt(9))
                                            && (rs6.getInt(9) != 0)) {
                                          patternDiscount.setM_Product_ID(producto.get_ID());
                                          patternDiscount.setXX_QuantityPromotion50(
                                              patternDiscount.getXX_QuantityPromotion50() + cant);
                                          patternDiscount.setXX_AmountPromotion50(
                                              patternDiscount
                                                  .getXX_AmountPromotion50()
                                                  .add(monto.multiply(new BigDecimal(cant))));
                                          patternDiscount.save();
                                        }

                                        if (patternDiscount.get_ID() != 0) {
                                          quantity =
                                              patternDiscount.getXX_QuantityPromotion20()
                                                  + patternDiscount.getXX_QuantityPromotion30()
                                                  + patternDiscount.getXX_QuantityPromotion50();
                                          amount =
                                              patternDiscount
                                                  .getXX_AmountPromotion20()
                                                  .add(patternDiscount.getXX_AmountPromotion30())
                                                  .add(patternDiscount.getXX_AmountPromotion50());

                                          patternDiscount.setXX_FinalInventoryQuantity(quantity);
                                          patternDiscount.setXX_FinalInventoryAmount(amount);
                                          patternDiscount.setXX_DATE(fecha);
                                          patternDiscount.save();
                                        }
                                      }
                                      rs6.close();
                                      pstmt6.close();
                                    } catch (SQLException e) {
                                      e.printStackTrace();
                                    }
                                  }
                                }
                                rs5.close();
                                pstmt5.close();
                              } catch (SQLException e) {
                                e.printStackTrace();
                              }
                            }
                          } else {
                            int cant = 0;
                            int consecutive = 0;
                            BigDecimal monto = new BigDecimal(0);
                            int patternDiscountID = 0;

                            String SQL5 =
                                "SELECT (SUM(i.XX_INITIALINVENTORYQUANTITY) + SUM(i.XX_PREVIOUSADJUSTMENTSQUANTITY) + "
                                    + "SUM(i.XX_SHOPPINGQUANTITY) + SUM(i.XX_SALESQUANTITY) + SUM(i.XX_MOVEMENTQUANTITY) + "
                                    + "SUM(i.XX_ADJUSTMENTSQUANTITY)) AS CANTFIN, i.M_Product_ID, "
                                    + "i.XX_VMR_Category_ID, i.XX_CONSECUTIVEPRICE, i.M_AttributeSetInstance_ID "
                                    + "FROM XX_VCN_Inventory i, M_Product m "
                                    + "WHERE i.M_Product_ID="
                                    + rs.getInt(7)
                                    + " AND m.M_Product_ID=i.M_Product_ID "
                                    + "AND m.XX_VMR_TypeInventory_ID="
                                    + typeInv
                                    + " AND XX_INVENTORYMONTH='11' AND XX_INVENTORYYEAR='2009' " // to_char(Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy') "
                                    + "GROUP BY M_Product_ID, XX_VMR_Category_ID, XX_CONSECUTIVEPRICE, M_AttributeSetInstance_ID";

                            try {
                              PreparedStatement pstmt5 = DB.prepareStatement(SQL5, null);
                              ResultSet rs5 = pstmt5.executeQuery();

                              while (rs5.next()) {
                                cant = rs5.getInt(1);
                                consecutive = rs5.getInt(4);

                                if ((cant != 0) && (consecutive != 0)) {
                                  String SQL6 =
                                      "SELECT DISTINCT(i.XX_ConsecutivePrice), i.M_Product_ID, "
                                          + "i.M_AttributeSetInstance_ID, c.Created, c.XX_SalePrice, "
                                          + "m.XX_VMR_TypeInventory_ID, r.XX_Range1, r.XX_Range2, r.XX_Range3 "
                                          + "FROM XX_VCN_Inventory i, XX_VMR_PriceConsecutive c, M_Product m, XX_VMR_RangeDaysPromote r "
                                          + "WHERE i.M_Product_ID="
                                          + rs.getInt(7)
                                          + " AND i.M_Product_ID=c.M_Product_ID "
                                          + "AND i.M_Product_ID=m.M_Product_ID "
                                          + "AND i.M_AttributeSetInstance_ID="
                                          + rs5.getInt(5)
                                          + " AND i.M_AttributeSetInstance_ID=c.M_AttributeSetInstance_ID "
                                          + "AND i.XX_ConsecutivePrice="
                                          + rs5.getInt(4)
                                          + " AND i.XX_VMR_Category_ID=r.XX_VMR_Category_ID "
                                          + "AND m.XX_VMR_TypeInventory_ID=r.XX_VMR_TypeInventory_ID "
                                          + "AND i.XX_INVENTORYMONTH='11' AND i.XX_INVENTORYYEAR='2009' "; // to_char(i.Updated,'mmyyyy')=to_char(to_date('"+fecha+"','mm-yyyy'),'mmyyyy')";

                                  try {
                                    PreparedStatement pstmt6 = DB.prepareStatement(SQL6, null);
                                    ResultSet rs6 = pstmt6.executeQuery();

                                    if (rs6.next()) {
                                      monto = rs6.getBigDecimal(5);
                                      long fechaInicial = rs6.getDate(4).getTime();
                                      long fechaFinal = fechaActual.getTime();
                                      long diferencia = fechaFinal - fechaInicial;
                                      double dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));
                                      diasVida = (int) dias;

                                      patternDiscountID = getPatternOfDiscount(rs.getInt(7));

                                      if (patternDiscountID != 0) {
                                        // instancio pauta de rebaja con el id que devolvio
                                        patternDiscount =
                                            new X_XX_VMR_PatternOfDiscount(
                                                Env.getCtx(), patternDiscountID, null);
                                      } else {
                                        // instancio pauta de rebaja nueva;
                                        patternDiscount =
                                            new X_XX_VMR_PatternOfDiscount(Env.getCtx(), 0, null);
                                      }

                                      if (diasVida > rs6.getInt(9)) {
                                        patternDiscount.setM_Product_ID(producto.get_ID());
                                        patternDiscount.setXX_DATE(fecha);
                                        patternDiscount.setXX_QuantityPromotion50(cant);
                                        patternDiscount.setXX_AmountPromotion50(
                                            monto.multiply(new BigDecimal(cant)));

                                        if ((patternDiscount.getXX_QuantityPromotion20() != 0)
                                            || (patternDiscount.getXX_QuantityPromotion30() != 0)
                                            || (patternDiscount.getXX_QuantityPromotion50() != 0)) {
                                          quantity =
                                              patternDiscount.getXX_QuantityPromotion20()
                                                  + patternDiscount.getXX_QuantityPromotion30()
                                                  + patternDiscount.getXX_QuantityPromotion50();
                                          amount =
                                              patternDiscount
                                                  .getXX_AmountPromotion20()
                                                  .add(patternDiscount.getXX_AmountPromotion30())
                                                  .add(patternDiscount.getXX_AmountPromotion50());

                                          patternDiscount.setXX_FinalInventoryQuantity(quantity);
                                          patternDiscount.setXX_FinalInventoryAmount(amount);
                                        }
                                        patternDiscount.save();
                                      }
                                    }
                                    rs6.close();
                                    pstmt6.close();
                                  } catch (SQLException e) {
                                    e.printStackTrace();
                                  }
                                }
                              }
                              rs5.close();
                              pstmt5.close();
                            } catch (SQLException e) {
                              e.printStackTrace();
                            }
                          }
                        }
                        rs4.close();
                        pstmt4.close();
                      } catch (SQLException e) {
                        e.printStackTrace();
                      }
                    }
                  }
                  rs3.close();
                  pstmt3.close();
                } catch (SQLException e) {
                  e.printStackTrace();
                }
              }
            }
            rs2.close();
            pstmt2.close();
          } catch (SQLException e) {
            e.printStackTrace();
          }
        }
      }
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }

    if (getCountPatternOfDiscount() != 0) {
      // Abre la ventana de Pauta de Rebajas
      AWindow window_patternDiscount = new AWindow();
      Query query = Query.getEqualQuery("ISACTIVE", "Y");
      String wind = Env.getCtx().getContext("#XX_L_W_PATTERNOFDISCOUNT_ID");
      Integer win = Integer.parseInt(wind);
      window_patternDiscount.initWindow(win, query);
      AEnv.showCenterScreen(window_patternDiscount);

      // LLama al proceso de exportar la data de compiere al as/400
      MPInstance mpi =
          new MPInstance(
              Env.getCtx(),
              Env.getCtx().getContextAsInt("#XX_L_PROCESSPATTERNDISCOUNT_ID"),
              patternDiscount.get_ID());
      mpi.save();

      ProcessInfo pi =
          new ProcessInfo("", Env.getCtx().getContextAsInt("#XX_L_PROCESSPATTERNDISCOUNT_ID"));
      pi.setRecord_ID(mpi.getRecord_ID());
      pi.setAD_PInstance_ID(mpi.get_ID());
      pi.setAD_Process_ID(Env.getCtx().getContextAsInt("#XX_L_PROCESSPATTERNDISCOUNT_ID"));
      pi.setClassName("");
      pi.setTitle("");

      ProcessCtl pc = new ProcessCtl(null, pi, null);
      pc.start();

      return "";
    } else {
      return "No hay Pauta de Rebajas";
    }
  }
  /** Procesa los traspasos de el archivo excel */
  public StringBuffer procesarMovimientos(Vector<Movimiento> traspasos) {

    // Iterar sobre cada uno de los traspasos
    Iterator<Movimiento> itr = traspasos.iterator();
    Movimiento mov = null;

    MMovement movimiento = null;
    MMovementLine linea = null;
    StringBuffer buffer = new StringBuffer();

    String nl = " ----- ";

    // Consulta que me dice cuanto me queda en inventario de ese producto
    String sql =
        " WITH  DISPONIBLE AS ( select m_product_id, available from (SELECT M_PRODUCT_ID, sum(available) as available FROM  (SELECT M_PRODUCT_ID, SUM(QTY) AS AVAILABLE FROM M_STORAGEDETAIL  "
            + " WHERE M_LOCATOR_ID =? AND QTYTYPE = 'H'  AND M_AttributeSetInstance_ID>=0  AND M_lOCATOR_ID >= 0  GROUP BY M_PRODUCT_ID HAVING SUM(QTY) > 0  union all  SELECT M_PRODUCT_ID, "
            + " -1*SUM(CANT) AS NOTAVAILABLE FROM  (SELECT M_PRODUCT_ID,SUM(XX_DESIREDQUANTITY) AS CANT FROM XX_VMR_DISTRIBDETAILTEMP where m_warehouse_id=? GROUP BY M_PRODUCT_ID  union all  SELECT M_PRODUCT_ID, SUM(XX_DISTRIBUTEDQTY) AS CANT "
            + " from XX_VMR_PO_PRODUCTDISTRIB D JOIN XX_VMR_ORDER P ON (P.XX_VMR_DISTRIBUTIONHEADER_ID = D.XX_VMR_DISTRIBUTIONHEADER_ID) WHERE P.XX_ORDERREQUESTSTATUS = 'PE' GROUP BY M_PRODUCT_ID  union all  SELECT M_PRODUCT_ID,"
            + " SUM(XX_DISTRIBUTEDQTY) AS CANT from XX_VMR_PO_PRODUCTDISTRIB D JOIN XX_VMR_DistributionHeader H ON (h.XX_VMR_DISTRIBUTIONHEADER_ID = D.XX_VMR_DISTRIBUTIONHEADER_ID) WHERE H.XX_DistributionStatus IN ('QR', 'QT') GROUP BY M_PRODUCT_ID  )"
            + " GROUP BY M_PRODUCT_ID  ) GROUP BY M_PRODUCT_ID) where available>0) SELECT sum(IV.available) FROM  DISPONIBLE iv "
            + " JOIN M_PRODUCT p ON ( IV.M_PRODUCT_ID = p.M_PRODUCT_ID) JOIN XX_VMR_VENDORPRODREF vr ON ( vr.XX_VMR_VENDORPRODREF_ID = p.XX_VMR_VENDORPRODREF_ID)  LEFT OUTER JOIN M_ATTRIBUTESETINSTANCE att ON (p.M_ATTRIBUTESETINSTANCE_ID = att.M_ATTRIBUTESETINSTANCE_ID ) "
            + " WHERE    IV.M_PRODUCT_ID = ? GROUP BY iv.M_PRODUCT_ID, p.VALUE||'-'||p.NAME, iv.M_PRODUCT_ID, att.description, p.M_ATTRIBUTESETINSTANCE_ID HAVING SUM(IV.available)>0  ORDER BY iv.M_PRODUCT_ID";
    // System.out.println(sql);
    PreparedStatement ps = DB.prepareStatement(sql, null);
    ResultSet rs = null;

    while (itr.hasNext()) {
      mov = itr.next();
      movimiento = new MMovement(Env.getCtx(), 0, get_TrxName());

      // Se deben llenar los campos necesarios
      movimiento.setC_DocType_ID(1000335); // Movimiento entre CDs
      String mss = Msg.getMsg(Env.getCtx(), "XX_ImportedMovement", new String[] {archivo});
      movimiento.setDescription(mss);
      movimiento.setMovementDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));

      // Si el origen es centro de distribucion, entonces es el locator chequeado
      MLocator desde = Utilities.obtenerLocatorEnTienda(mov.origen);
      movimiento.setM_Locator_ID(desde.get_ID());

      // El locator hasta, que es el locator chequeado del almacen destino
      MLocator hasta = Utilities.obtenerLocatorEnTransito(mov.destino);
      movimiento.setM_LocatorTo_ID(hasta.get_ID());

      // El resto de los campos
      movimiento.setXX_VMR_Department_ID(mov.departamento);
      /**
       * movimiento.setXX_TransferMotive_ID(
       * Env.getCtx().getContextAsInt("#XX_L_AUTOMATICTRANSFER_ID"));
       */
      movimiento.setM_WarehouseFrom_ID(mov.origen);
      movimiento.setM_WarehouseTo_ID(mov.destino);
      MWarehouse origen = new MWarehouse(getCtx(), mov.origen, null);
      movimiento.setAD_Org_ID(origen.getAD_Org_ID());

      try {
        if (!movimiento.save()) continue;
        commit();
        movimiento.load(get_TrxName());

        // Se copian cada una de las lineas al movimiento
        MProduct producto = null;
        BigDecimal precioVenta = null, costoCompra = null;
        Integer consecutivo = null;
        BigDecimal cantidadMovimiento = null,
            cantidadDisponible = null,
            cantidadDisponibleTotal = null;

        int created_lines = 0;
        for (int i = 0; i < mov.productos.size(); i++) {

          producto = new MProduct(Env.getCtx(), mov.productos.get(i), get_TrxName());
          System.out.println("Producto: " + producto.getValue());
          // Calcular los consecutivos en funcion del inventario
          try {
            ps.setInt(1, Utilities.obtenerLocatorEnTienda(mov.origen).getM_Locator_ID());
            ps.setInt(2, mov.origen);
            ps.setInt(3, producto.get_ID());
            cantidadMovimiento = mov.cantidades.get(i);
            cantidadDisponibleTotal = Env.ZERO;

            rs = ps.executeQuery();

            // Debo buscar las cantidades que tengo en el almacen origen de ese producto

            int cantidadInventario = 0;

            if (rs.next()) {

              cantidadInventario = rs.getInt(1);

              // Crear la linea - si la cantidad disponible es positiva
              if (cantidadInventario > 0) {

                if (cantidadMovimiento.intValue() > cantidadInventario)
                  cantidadMovimiento = new BigDecimal(cantidadInventario);

                // Si la cantidad total en inventario es positiva, ahora buscamos la cantidad que
                // hay por lote
                String sql3 =
                    " SELECT STO.M_ATTRIBUTESETINSTANCE_ID, STO.QTY AS QTYONHAND "
                        + " FROM M_STORAGEDETAIL STO WHERE STO.M_PRODUCT_ID = "
                        + producto.get_ID()
                        + " AND STO.M_LOCATOR_ID = "
                        + Utilities.obtenerLocatorEnTienda(mov.origen).getM_Locator_ID()
                        + " AND STO.QTYTYPE = '"
                        + X_Ref_Quantity_Type.ON_HAND.getValue()
                        + "' "
                        + " AND STO.QTY > 0 "
                        + " AND STO.M_AttributeSetInstance_ID>=0"
                        + " AND STO.M_lOCATOR_ID >= 0"
                        + " ORDER BY STO.M_ATTRIBUTESETINSTANCE_ID ASC";
                PreparedStatement ps3 = DB.prepareStatement(sql3, null);
                ResultSet rs3 = ps3.executeQuery();
                while (rs3.next() && cantidadMovimiento.intValue() > 0) {
                  linea = new MMovementLine(Env.getCtx(), 0, get_TrxName());
                  linea.setM_LocatorTo_ID(movimiento.getM_LocatorTo_ID());
                  linea.setM_Locator_ID(movimiento.getM_Locator_ID());
                  linea.setM_Movement_ID(movimiento.get_ID());
                  linea.setM_Product_ID(producto.get_ID());
                  linea.setM_AttributeSetInstance_ID(rs3.getInt(1));
                  linea.setAD_Org_ID(origen.getAD_Org_ID());
                  linea.setXX_SalePrice(new BigDecimal(0.01));

                  if (producto.getXX_VMR_Brand_ID() != 0)
                    linea.setXX_VMR_Brand_ID(producto.getXX_VMR_Brand_ID());
                  if (producto.getXX_VMR_Line_ID() != 0)
                    linea.setXX_VMR_Line_ID(producto.getXX_VMR_Line_ID());
                  if (producto.getXX_VMR_Section_ID() != 0)
                    linea.setXX_VMR_Section_ID(producto.getXX_VMR_Section_ID());

                  if (producto.getC_TaxCategory_ID() != 0) {
                    linea.setC_TaxCategory_ID(producto.getC_TaxCategory_ID());

                    // Si es mayor que la cantidad solicitada
                    if (rs3.getInt(2) > cantidadMovimiento.intValue()) {

                      linea.setQtyRequired(cantidadMovimiento);
                      linea.setMovementQty(cantidadMovimiento);
                      cantidadMovimiento = Env.ZERO;

                    } else {

                      linea.setQtyRequired(new BigDecimal(rs3.getInt(2)));
                      linea.setMovementQty(new BigDecimal(rs3.getInt(2)));
                      cantidadMovimiento =
                          cantidadMovimiento.subtract(new BigDecimal(rs3.getInt(2)));
                    }
                    // En este caso se almacena
                    if (linea.save()) created_lines++;
                  }
                }
                DB.closeStatement(ps3);
                DB.closeResultSet(rs3);
              }
            }

            // No fueron suficientes piezas
            if (cantidadMovimiento.compareTo(Env.ZERO) == 1) {

              if (mov.cantidades.get(i).compareTo(new BigDecimal(cantidadInventario)) == 1) {

                buffer.append(producto.getValue());
                buffer.append(" " + producto.getName() + " ");
                String msg =
                    Msg.getMsg(
                        Env.getCtx(),
                        "XX_ReqLessThanAvail",
                        new String[] {
                          "" + mov.cantidades.get(i),
                          "" + cantidadInventario,
                          Msg.translate(getCtx(), "All")
                        });
                buffer.append(msg);
                buffer.append(nl);
              }
            }

          } catch (SQLException e) {
            buffer.append(Msg.translate(Env.getCtx(), "XX_ProductPConsecNotFound"));
            buffer.append(" : ");
            buffer.append(producto.getValue() + "-" + producto.getName());
            buffer.append(" - ");
            buffer.append(nl);
          } finally {

          }
        }
        // System.out.println("MOVIMIENTO: "+movimiento.getM_Movement_ID());
        // Si no se creo ninguna linea
        if (created_lines == 0) {
          movimiento.delete(true, get_TrxName());
          buffer.append(Msg.translate(Env.getCtx(), "XX_MovementIgnored") + " ");
          buffer.append(mov.toString());
          buffer.append(nl);
          // AGREGADO POR GHUCHET
        } else {
          //					completarMovimiento(movimiento);
        }
        // HASTA AQUI AGREGADO POR GHUCHET
      } catch (Exception e) {
        log.log(Level.SEVERE, Msg.translate(Env.getCtx(), "XX_DatabaseAccessError"), e);
        buffer.append(Msg.translate(Env.getCtx(), "XX_DatabaseAccessError"));
        buffer.append(nl);
      }
    }
    return buffer;
  }
  public String readFile() throws IOException {

    File inputWorkbook = new File(archivo);
    Workbook w;
    try {
      String msg = "";
      w = Workbook.getWorkbook(inputWorkbook);
      // Get the first sheet
      Sheet sheet = w.getSheet(0);

      // int defaultRows = sheet.getRows();

      // Si la cantidad de columnas es 4
      if (sheet.getColumns() >= 4 && sheet.getRows() > 1) {

        // Valido que las cabeceras tengan el formato correcto
        if (!sheet.getCell(0, 0).getContents().equals("ORIGEN")
            || !sheet.getCell(1, 0).getContents().equals("DESTINO")
            || !sheet.getCell(2, 0).getContents().equals("PRODUCTO")
            || !sheet.getCell(3, 0).getContents().equals("PIEZAS")) {
          msg = Msg.translate(getCtx(), "Column Names");
          return msg;
        }

        // El vector que almacena la estructura de traspasos
        Vector<Movimiento> movimientos = new Vector<Movimiento>();
        Iterator<Movimiento> iterator_movimientos = null;
        Movimiento movimiento_temporal = null, movimiento_nuevo = null;
        for (int i = 1;
            i < sheet.getRows() && getStore(sheet.getCell(0, i).getContents()) != null;
            i++) {

          // Capturo el origen
          MWarehouse origen = getStore(sheet.getCell(0, i).getContents());
          MWarehouse destino = getStore(sheet.getCell(1, i).getContents());

          String isStore = "N";
          // Aca debo bucar los values de los m_warehouse que son cd
          String sql =
              "SELECT XX_IsStore FROM M_Warehouse WHERE M_Warehouse_ID in ( "
                  + origen.getM_Warehouse_ID()
                  + ","
                  + destino.getM_Warehouse_ID()
                  + ")";
          PreparedStatement pstmt = null;
          ResultSet rs = null;
          try {
            pstmt = DB.prepareStatement(sql, null);
            rs = pstmt.executeQuery();

            while (rs.next()) {
              if (rs.getString(1).equals("Y")) isStore = rs.getString(1);
            }

          } catch (Exception a) {
            log.log(Level.SEVERE, sql, a);
          } finally {
            DB.closeResultSet(rs);
            DB.closeStatement(pstmt);
          }

          if (origen == null || isStore.equals("Y"))
            return Msg.translate(getCtx(), "Cell A Error")
                + (i + 1)
                + " "
                + sheet.getCell(0, i).getContents();

          // Capturo el destino

          if (destino == null || isStore.equals("Y"))
            return Msg.translate(getCtx(), "Cell B Error")
                + (i + 1)
                + " "
                + sheet.getCell(1, i).getContents();

          // Capturo el producto
          String p_id = sheet.getCell(2, i).getContents();
          MProduct producto = getProduct(p_id);
          if (producto == null) {
            return Msg.translate(getCtx(), "Cell C Error")
                + (i + 1)
                + " "
                + sheet.getCell(2, i).getContents();
          }

          // Capturo las piezas
          Double piezas = null;
          try {
            if (sheet.getCell(3, i) != null)
              piezas = Double.parseDouble(sheet.getCell(3, i).getContents());
          } catch (NumberFormatException e) {
            return Msg.translate(getCtx(), "Cell D Error")
                + (i + 1)
                + " "
                + sheet.getCell(3, i).getContents();
          }
          if (piezas == null) {
            return Msg.translate(getCtx(), "Cell D Error")
                + (i + 1)
                + " "
                + sheet.getCell(3, i).getContents();
          }

          // Agregar cada fila al vector de traspasos
          iterator_movimientos = movimientos.iterator();
          boolean encontrado = false;
          while (iterator_movimientos.hasNext()) {
            movimiento_temporal = iterator_movimientos.next();

            // Si un traspaso anterior va a la misma tienda, departamento, etc
            if (movimiento_temporal.origen == origen.get_ID()) {
              if (movimiento_temporal.destino == destino.get_ID()) {
                if (movimiento_temporal.departamento == producto.getXX_VMR_Department_ID()) {
                  // Entonces agregar algo al objeto traspaso

                  movimiento_temporal.agregarCantidades(producto.get_ID(), piezas);
                  encontrado = true;
                  break;
                }
              }
            }
          }

          // Si no se encontró en el vector de traspasos agregarlo
          if (!encontrado) {
            movimiento_nuevo =
                new Movimiento(
                    origen.get_ID(), destino.get_ID(), producto.getXX_VMR_Department_ID());
            movimiento_nuevo.agregarCantidades(producto.get_ID(), piezas);
            movimientos.add(movimiento_nuevo);
          }
        }

        // Una vez leido todo el archivo se procede a crear los traspasos
        // System.out.println(traspasos);
        return procesarMovimientos(movimientos).toString();

      } else {
        return Msg.translate(getCtx(), "4 Columns");
      }
    } catch (BiffException e) {
      log.log(Level.SEVERE, e.getMessage());
    }
    return "";
  }
  private void fillProductTable() {

    int row = 0;
    try {
      String get_details =
          " SELECT XX_VMR_DiscountAppliDetail_ID FROM XX_VMR_DiscountAppliDetail "
              + " WHERE XX_VMR_DiscountRequest_ID = "
              + header.get_ID();
      PreparedStatement pstmt = DB.prepareStatement(get_details, null);
      // Setting the query parameters
      ResultSet rs = pstmt.executeQuery();
      while (rs.next()) {
        row = xProductTable.getRowCount();
        xProductTable.setRowCount(row + 1);
        MVMRDiscountAppliDetail detail =
            new MVMRDiscountAppliDetail(Env.getCtx(), rs.getInt(1), null);

        IDColumn id = new IDColumn(rs.getInt(1));
        id.setSelected(true);
        xProductTable.setValueAt(id, row, 0);

        MProduct prod = new MProduct(Env.getCtx(), detail.getM_Product_ID(), null);
        xProductTable.setValueAt(new KeyNamePair(prod.get_ID(), prod.getValue()), row, 1);
        xProductTable.setValueAt(prod.getKeyNamePair(), row, 3);

        X_XX_VMR_VendorProdRef ref_proveedor =
            new X_XX_VMR_VendorProdRef(Env.getCtx(), prod.getXX_VMR_VendorProdRef_ID(), null);
        xProductTable.setValueAt(
            new KeyNamePair(ref_proveedor.get_ID(), ref_proveedor.getValue()), row, 2);

        // Colocar el consecutivo de precio
        DecimalFormat formato = new DecimalFormat("000");
        X_XX_VMR_PriceConsecutive priceConsecutive =
            new X_XX_VMR_PriceConsecutive(Env.getCtx(), detail.getXX_PriceConsecutive_ID(), null);

        xProductTable.setValueAt(formato.format(priceConsecutive.getXX_PriceConsecutive()), row, 4);

        xProductTable.setValueAt(detail.getXX_LoweringQuantity(), row, 5);
        xProductTable.setValueAt(detail.getXX_LoweringQuantity(), row, 6);

        X_XX_VMR_Category cat =
            new X_XX_VMR_Category(Env.getCtx(), prod.getXX_VMR_Category_ID(), null);
        xProductTable.setValueAt(cat.getKeyNamePair(), row, 7);

        X_XX_VMR_Department dep =
            new X_XX_VMR_Department(Env.getCtx(), header.getXX_VMR_Department_ID(), null);
        xProductTable.setValueAt(dep.getKeyNamePair(), row, 8);

        X_XX_VMR_Line lin = new X_XX_VMR_Line(Env.getCtx(), detail.getXX_VMR_Line_ID(), null);
        xProductTable.setValueAt(lin.getKeyNamePair(), row, 9);

        X_XX_VMR_Section sec =
            new X_XX_VMR_Section(Env.getCtx(), detail.getXX_VMR_Section_ID(), null);
        xProductTable.setValueAt(sec.getKeyNamePair(), row, 10);

        if (priceConsecutive.getM_AttributeSetInstance_ID() != 0) {
          MAttributeSetInstance attins =
              new MAttributeSetInstance(
                  Env.getCtx(), priceConsecutive.getM_AttributeSetInstance_ID(), null);
          xProductTable.setValueAt(
              new KeyNamePair(attins.get_ID(), attins.getDescription()), row, 11);
        } else {
          xProductTable.setValueAt(new KeyNamePair(0, ""), row, 11);
        }
      }
      rs.close();
      pstmt.close();
    } catch (Exception E) {
      E.printStackTrace();
    }
  }