Ejemplo n.º 1
0
 @Override
 public String toString() {
   StringBuilder resultado = new StringBuilder();
   resultado.append("Traspaso\n");
   MWarehouse warehouse = new MWarehouse(Env.getCtx(), origen, null);
   resultado.append(" " + warehouse.getValue());
   warehouse = new MWarehouse(Env.getCtx(), destino, null);
   resultado.append(" -> " + warehouse.getValue() + "\n");
   MProduct product = null;
   resultado.append("[");
   for (int i = 0; i < cantidades.size(); i++) {
     product = new MProduct(Env.getCtx(), this.productos.get(i), null);
     resultado.append(product.getValue() + "-" + product.getName());
     resultado.append(" - " + cantidades.get(i) + "\n");
   }
   resultado.append("]");
   return resultado.toString();
 }
  public void generateLabels() {

    Cursor hourglassCursor = new Cursor(Cursor.WAIT_CURSOR);
    xProductTable.stopEditor(true);
    m_frame.setCursor(hourglassCursor);
    PrintService psZebra_glued = null;
    PrintService psZebra_flat = null;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);

    int id_label_glued = Env.getCtx().getContextAsInt("#XX_L_TYPELABELENGOMADA_ID");
    int id_label_flat = Env.getCtx().getContextAsInt("#XX_L_TYPELABELCOLGANTE_ID");

    int glued = 0, flats = 0;
    for (int row = 0; row < xProductTable.getRowCount(); row++) {
      IDColumn idcol = (IDColumn) xProductTable.getValueAt(row, 0);
      if (idcol != null && idcol.isSelected()) {
        KeyNamePair product_kp = (KeyNamePair) xProductTable.getValueAt(row, 3);
        MProduct product = new MProduct(Env.getCtx(), product_kp.getKey(), null);

        if (product.getXX_VMR_TypeLabel_ID() == id_label_glued) {
          glued++;
        } else if (product.getXX_VMR_TypeLabel_ID() == id_label_flat) {
          flats++;
        } else {
          X_XX_VMR_TypeLabel label_type =
              new X_XX_VMR_TypeLabel(Env.getCtx(), product.getXX_VMR_TypeLabel_ID(), null);

          String mss =
              Msg.getMsg(
                  Env.getCtx(),
                  "XX_WrongLabelType",
                  new String[] {label_type.getValue(), label_type.getName()});
          ADialog.error(m_WindowNo, m_frame, mss);
          dispose();
          return;
        }
      }
    }
    psZebra_glued = services[printer_glued];
    psZebra_flat = services[printer_flat];
    for (int row = 0; row < xProductTable.getRowCount(); row++) {
      IDColumn idcol = (IDColumn) xProductTable.getValueAt(row, 0);
      if (idcol != null && idcol.isSelected()) {
        KeyNamePair product_kp = (KeyNamePair) xProductTable.getValueAt(row, 3);
        MProduct product = new MProduct(Env.getCtx(), product_kp.getKey(), null);

        if (product.getXX_VMR_TypeLabel_ID() == id_label_glued) {
          print_labels(psZebra_glued, row, true);
        } else {
          print_labels(psZebra_flat, row, false);
        }
      }
    }
    if (flats + glued > 0) {
      ADialog.info(m_WindowNo, m_frame, "XX_PrintedLabels");
    }
    dispose();
  }
  @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";
    }
  }
  public String priceBandBeco(
      Ctx ctx, int WindowNo, GridTab mTab, GridField mField, Object value, Object oldValue) {
    System.out.println("pricebandBeco");

    PreparedStatement pstmtC = null;
    ResultSet rsC = null;
    try {

      MVMRPOLineRefProv lineRefProv =
          new MVMRPOLineRefProv(ctx, (Integer) mTab.getValue("XX_VMR_PO_LineRefProv_ID"), null);
      MOrder order = new MOrder(ctx, lineRefProv.getC_Order_ID(), null);

      // String conceptoProducto = ctx.getContext(WindowNo, "XX_ConceptValue_ID");
      Integer conceptoProducto = lineRefProv.getXX_VME_ConceptValue_ID();

      // String seccionProducto = ctx.getContext(WindowNo,"XX_SECTION_ID");
      Integer seccionProducto = lineRefProv.getXX_VMR_Section_ID();

      // String lineaProducto = ctx.getContext(WindowNo,"XX_LINE_ID");
      Integer lineaProducto = lineRefProv.getXX_VMR_Line_ID();

      // String departamentoProducto = ctx.getContext(WindowNo,"XX_VMR_DEPARTMENT_ID");
      Integer departamentoProducto = order.getXX_VMR_DEPARTMENT_ID();

      /** Agregado por Javier Pino, para que funcione en distribucion */
      if (mTab.getValue("M_Product_ID") != null) {
        MProduct producto = new MProduct(ctx, (Integer) mTab.getValue("M_Product_ID"), null);
        conceptoProducto = producto.getXX_VME_ConceptValue_ID();
        departamentoProducto = producto.getXX_VMR_Department_ID();
        seccionProducto = producto.getXX_VMR_Section_ID();
        lineaProducto = producto.getXX_VMR_Line_ID();
      }
      /** Fin agregado Javier Pino */
      String conceptoComparar = null;

      String SQLA =
          "select P.xx_comparisonvalue_id "
              + "from xx_vme_priceband P , xx_vme_conceptvalue C "
              + "where C.XX_VME_ConceptValue_ID = "
              + conceptoProducto
              + " and "
              +
              // "where C.XX_VME_ConceptValue_ID = 1000002 and " +
              // "where C.XX_VME_ConceptValue_ID = 1000002 and " +
              "C.XX_VME_ConceptValue_id = P.xx_conceptvalue_id";

      // System.out.println("sqla "+SQLA);

      PreparedStatement pstmtA = DB.prepareStatement(SQLA, null);
      ResultSet rsA = pstmtA.executeQuery();

      if (rsA.next()) {
        conceptoComparar = rsA.getString("xx_comparisonvalue_id");
        // conceptoComparar="1000002";
      }
      rsA.close();
      pstmtA.close();

      Double promedioSeccion = 0.0;
      Double promedioLinea = 0.0;
      Double promedioDepartamento = 0.0;

      String SQL =
          "SELECT AVG(AUX.A) valor FROM "
              + "(SELECT MAX(P.XX_SALEPRICE) A, P.M_PRODUCT_ID "
              + "FROM XX_VMR_PRICECONSECUTIVE P, M_PRODUCT M "
              + "WHERE ";

      if (conceptoComparar == null) {
        SQL += "M.XX_VME_ConceptValue_ID IS NULL and ";
      } else {
        SQL += "M.XX_VME_ConceptValue_ID=" + conceptoComparar + " and ";
      }

      SQL +=
          "M.XX_VMR_Section_ID = "
              + seccionProducto
              + " "
              +
              //			"P.m_product_id <> "+ctx.getContext(WindowNo, "M_Product_ID")+" and "+
              "AND P.M_PRODUCT_ID = M.M_PRODUCT_ID "
              + "group by P.M_PRODUCT_ID) AUX";

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

      // System.out.println("sql "+SQL);

      if (rs.next()) {
        promedioSeccion = rs.getDouble("valor");
      }
      rs.close();
      pstmt.close();

      if (promedioSeccion == 0.0) {
        String SQL2 =
            "SELECT AVG(AUX.A) valor FROM "
                + "(SELECT MAX(P.XX_SALEPRICE) A, P.M_PRODUCT_ID "
                + "FROM XX_VMR_PRICECONSECUTIVE P, M_PRODUCT M "
                + "WHERE ";

        if (conceptoComparar == null) {
          SQL2 += "M.XX_VME_ConceptValue_ID IS NULL and ";
        } else {
          SQL2 += "M.XX_VME_ConceptValue_ID=" + conceptoComparar + " and ";
        }

        SQL2 +=
            "M.XX_VMR_Line_ID = "
                + lineaProducto
                + " "
                +
                //				 			  "P.m_product_id <> "+ctx.getContext(WindowNo, "M_Product_ID")+" and "+
                "AND P.M_PRODUCT_ID = M.M_PRODUCT_ID "
                + "group by P.M_PRODUCT_ID) AUX";

        PreparedStatement pstmt2 = DB.prepareStatement(SQL2, null);
        ResultSet rs2 = pstmt2.executeQuery();
        // System.out.println("sql2"+SQL2);

        if (rs2.next()) {
          promedioLinea = rs2.getDouble("valor");
        }
        rs2.close();
        pstmt2.close();

        if (promedioLinea == 0.0) {
          String SQL3 =
              "SELECT AVG(AUX.A) valor FROM "
                  + "(SELECT MAX(P.XX_SALEPRICE) A, P.M_PRODUCT_ID "
                  + "FROM XX_VMR_PRICECONSECUTIVE P, m_product M "
                  + "WHERE ";

          if (conceptoComparar == null) {
            SQL2 += "M.XX_VME_ConceptValue_ID IS NULL and ";
          } else {
            SQL2 += "M.XX_VME_ConceptValue_ID=" + conceptoComparar + " and ";
          }

          SQL3 +=
              "M.XX_VMR_Department_ID = "
                  + departamentoProducto
                  + " "
                  +
                  //		 			  			 "P.m_product_id <> "+ctx.getContext(WindowNo, "M_Product_ID")+" and
                  // "+
                  "AND P.M_PRODUCT_ID = M.M_PRODUCT_ID "
                  + "group by P.M_PRODUCT_ID) AUX";

          PreparedStatement pstmt3 = DB.prepareStatement(SQL3, null);
          ResultSet rs3 = pstmt3.executeQuery();
          // System.out.println("TRES");
          if (rs3.next()) {
            promedioDepartamento = rs3.getDouble("valor");
          }
          rs3.close();
          pstmt3.close();
        }
      }

      Double promedio = promedioSeccion + promedioLinea + promedioDepartamento;

      System.out.println("Promedio -> " + promedio);

      // Si no tiene precio en depart, linea y seccion
      if (promedio == 0.0) {
        return "";
      }

      String SQLC =
          "SELECT * "
              + "FROM xx_vme_priceband P , xx_vme_conceptvalue C "
              + "WHERE C.xx_vme_conceptvalue_id = "
              + conceptoProducto
              + " AND "
              + "C.xx_vme_conceptvalue_id = P.xx_conceptvalue_id";

      pstmtC = DB.prepareStatement(SQLC, null);
      rsC = pstmtC.executeQuery();

      System.out.println(SQLC);

      if (rsC.next()) {
        Double precioProducto = new Double(ctx.getContext(WindowNo, "XX_SalePricePlusTax"));
        Double low = rsC.getDouble("xx_lowrank");
        Double high = rsC.getDouble("xx_highrank");

        // if((low-rsC.getDouble("xx_percentagevalue")) < 0 )
        // {
        //	low = new Double(0);
        // }

        Double percentage = rsC.getDouble("xx_percentagevalue");

        Double incrementaBanda = promedio * (percentage / 100);

        String operador = rsC.getString("xx_operating");

        DB.closeStatement(pstmtC);
        DB.closeResultSet(rsC);

        // Menor que 10000012
        // Mayor que 10000013

        C_OrderCallout precio = new C_OrderCallout();

        System.out.println(operador);

        if (operador.equals("Minor")) {
          // Double bandaMayor = (promedio - promedio*(low/100))+incrementaBanda;
          // Double bandaMenor = (promedio - promedio*(high/(100)))-incrementaBanda;

          BigDecimal doubleAux =
              new BigDecimal((promedio - promedio * (low / 100)) + incrementaBanda);
          doubleAux = doubleAux.setScale(2, BigDecimal.ROUND_HALF_UP);
          Double bandaMayor = doubleAux.doubleValue();

          doubleAux = new BigDecimal((promedio - promedio * (high / (100))) - incrementaBanda);
          doubleAux = doubleAux.setScale(2, BigDecimal.ROUND_HALF_UP);
          Double bandaMenor = doubleAux.doubleValue();

          if ((precioProducto <= bandaMayor) && (precioProducto >= bandaMenor)) {
            System.out.println(1);
            mTab.setValue("XX_CanSetDefinitive", "Y");
            return "";
          } else {
            // Si el precio no esta entre las bandas entonces no lo dejo colocar el precio como
            // definitivo
            mTab.setValue("XX_CanSetDefinitive", "N");
            return "Advertencia, el precio debe estar entre las bandas "
                + bandaMenor
                + " y "
                + bandaMayor
                + " Precio BECO bandas "
                + precio.priceBeco(new BigDecimal(bandaMenor))
                + " y "
                + PrecioBecoRebaja(new BigDecimal(bandaMayor));
          }
        }

        if (operador.equals("higher")) {
          // Double bandaMayor = (promedio + promedio*(high/(100))+incrementaBanda);
          // Double bandaMenor = (promedio + promedio*(low/100))-incrementaBanda;

          BigDecimal doubleAux =
              new BigDecimal((promedio + promedio * (high / (100)) + incrementaBanda));
          doubleAux = doubleAux.setScale(2, BigDecimal.ROUND_HALF_UP);
          Double bandaMayor = doubleAux.doubleValue();

          doubleAux = new BigDecimal((promedio + promedio * (low / 100)) - incrementaBanda);
          doubleAux = doubleAux.setScale(2, BigDecimal.ROUND_HALF_UP);
          Double bandaMenor = doubleAux.doubleValue();

          if ((precioProducto <= bandaMayor) && (precioProducto >= bandaMenor)) {
            System.out.println(2);
            mTab.setValue("XX_CanSetDefinitive", "Y");
            return "";
          } else {
            // Si el precio no esta entre las bandas entonces no lo dejo colocar el precio como
            // definitivo
            mTab.setValue("XX_CanSetDefinitive", "N");

            String message =
                "Advertencia, el precio deberia estar entre las bandas "
                    + ""
                    + bandaMenor
                    + " y "
                    + bandaMayor
                    + "Precio BECO bandas";
            // +precio.priceBeco(new BigDecimal(bandaMenor))+" y ";
            // + PrecioBecoRebaja(new BigDecimal(bandaMayor));

            return message;
          }
        }
      }

      return "";
    } catch (Exception e) {
      System.out.println("Error an la base de datos " + e.getMessage());
    } finally {
      DB.closeStatement(pstmtC);
      DB.closeResultSet(rsC);
    }

    return "";
  }
Ejemplo n.º 5
0
  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 "";
  }
Ejemplo n.º 6
0
  /** 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 void print_labels(PrintService psZebra, int row, boolean glued) {
    try {

      IDColumn column = (IDColumn) xProductTable.getValueAt(row, 0);
      KeyNamePair knp_product = (KeyNamePair) xProductTable.getValueAt(row, 3);
      KeyNamePair knp_att = (KeyNamePair) xProductTable.getValueAt(row, 11);

      MVMRDiscountAppliDetail detail =
          new MVMRDiscountAppliDetail(Env.getCtx(), column.getRecord_ID(), null);

      int cantidadEtiquetas = ((Number) xProductTable.getValueAt(row, 6)).intValue();

      MProduct producto = new MProduct(Env.getCtx(), knp_product.getKey(), null);
      String name = producto.getName();
      /*
       * Caracteristica larga
       * */
      X_XX_VMR_LongCharacteristic caracLarga =
          new X_XX_VMR_LongCharacteristic(
              Env.getCtx(), producto.getXX_VMR_LongCharacteristic_ID(), null);
      X_M_AttributeSet attrSet =
          new X_M_AttributeSet(Env.getCtx(), producto.getM_AttributeSet_ID(), null);

      DecimalFormat formato = new DecimalFormat(".##");

      // String attr = "AMARILLO T=G                  ";
      // "CHEMISE CABALLERO             "

      X_XX_VMR_Department dep =
          new X_XX_VMR_Department(Env.getCtx(), producto.getXX_VMR_Department_ID(), null);
      String departmentCode = dep.getValue();

      X_XX_VMR_Line lin = new X_XX_VMR_Line(Env.getCtx(), producto.getXX_VMR_Line_ID(), null);
      String lineCode = lin.getValue();

      X_XX_VMR_Section sec =
          new X_XX_VMR_Section(Env.getCtx(), producto.getXX_VMR_Section_ID(), null);
      String seccionCode = sec.getValue();
      String precio = formato.format(detail.getXX_PriceBeforeDiscount());

      MVMRDiscountRequest headerDiscount =
          new MVMRDiscountRequest(Env.getCtx(), detail.getXX_VMR_DiscountRequest_ID(), null);
      MWarehouse tienda = new MWarehouse(Env.getCtx(), headerDiscount.getM_Warehouse_ID(), null);

      X_XX_VMR_PriceConsecutive consecutivoViejo =
          new X_XX_VMR_PriceConsecutive(Env.getCtx(), detail.getXX_VMR_PriceConsecutive_ID(), null);
      // Debo buscar semana, mes y año de la fecha de creacion del consecutivo

      Date date = (Date) consecutivoViejo.getCreated();
      Calendar cal = new GregorianCalendar();
      cal.setTime(date);
      int mes = cal.get(Calendar.MONTH) + 1;
      int año = cal.get(Calendar.YEAR);
      int semana = cal.get(Calendar.WEEK_OF_YEAR);

      BigDecimal impuesto = new BigDecimal(0);

      if (producto.getC_TaxCategory_ID() != 0) {

        String sql_rate =
            " SELECT (RATE) FROM C_TAX "
                + " WHERE C_TaxCategory_ID= "
                + producto.getC_TaxCategory_ID()
                + " AND ValidFrom <= to_date('"
                + date.toString().substring(0, 10)
                + "','yyyy-mm-dd')"
                + " and rownum = 1 "
                + " order by ValidFrom desc ";
        try {
          PreparedStatement prst_tax = DB.prepareStatement(sql_rate, null);
          ResultSet rs_tax = prst_tax.executeQuery();
          if (rs_tax.next()) {

            impuesto = rs_tax.getBigDecimal(1).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
          }
          rs_tax.close();
          prst_tax.close();
        } catch (Exception e) {
          System.out.println("error al calcular el impuesto");
        }
      }

      String product_plus_correlative =
          "" + producto.getValue() + consecutivoTostring(consecutivoViejo.getXX_PriceConsecutive());

      String s = "";
      DocPrintJob job = psZebra.createPrintJob();

      if (impuesto.compareTo(new BigDecimal(0)) > 0) {
        precio =
            formato.format(
                (detail
                        .getXX_PriceBeforeDiscount()
                        .add((detail.getXX_PriceBeforeDiscount()).multiply(impuesto)))
                    .setScale(2, BigDecimal.ROUND_HALF_UP));
        s =
            "^XA^PRD^XZ\n"
                + "^XA^JMA^\n"
                + "^LH07,02^FS\n"
                + "^FO10,03^BE,25,N^BY3, 0.5,45^FD"
                + product_plus_correlative
                + "^FS\n"
                + "^FO10,62^AA,15,12^FD"
                + departmentCode
                + "-"
                + lineCode
                + "-"
                + seccionCode
                + "-"
                + product_plus_correlative
                + "       ^FS\n"
                + "^FO10,82^AA,20,10^FD"
                + name
                + "^FS\n";
        if (!attrSet.getName().isEmpty()
            && attrSet.get_ID() != Env.getCtx().getContextAsInt("#XX_L_P_ATTRIBUTESETST_ID")) {
          s =
              s
                  + "^FO10,97^AA,20,10^FD"
                  + (attrSet.getName().length() > 30
                      ? attrSet.getName().substring(0, 29)
                      : attrSet.getName())
                  + "^FS\n";
        } else if (caracLarga != null
            && caracLarga.getName() != null
            && !caracLarga.getName().isEmpty()) {
          s =
              s
                  + "^FO10,97^AA,20,10^FD"
                  + (caracLarga.getName().length() > 30
                      ? caracLarga.getName().substring(0, 29)
                      : caracLarga.getName())
                  + "^FS\n";
        }
        s =
            s
                + "^FO10,116^AA,14,10^FDPRECIO BS^FS\n"
                + "^FO10,170^AB,11,07^FDRIF J-00046517-7   Incluye IVA "
                + impuesto.multiply(new BigDecimal(100))
                + "%^FS\n"
                + "^FO10,153^AB,11,07^CI10^FD"
                + semana
                + " "
                + mes
                + " "
                + año
                + "^FS\n"
                + "^FO10,138^AA,11,09^FDBsF.^FS\n"
                + "^FO35,136^AB,11,07^CI10^FD         "
                + precio
                + "^FS\n"
                + "^PQ"
                + cantidadEtiquetas
                + "^FS\n"
                + "^XZ\n"
                +
                // Control label
                "^XA^PRD^XZ\n"
                + "^XA^JMA^\n"
                + "^LH00,15^FS\n"
                + "^FO2,5^AD,38,10^FD*CONTROL*     "
                + semana
                + " "
                + mes
                + ""
                + año
                + "^FS\n"
                + "^FO05,45^A0,30,07^FD                  TDA:  "
                + tienda.getValue()
                + "^FS\n"
                + "^FO28,48^A0,15,14^FDCANT:     "
                + cantidadEtiquetas
                + "      PRECIO      "
                + precio
                + "^FS\n"
                + "^FO05,95^A0,18,10^FD"
                + departmentCode
                + "-"
                + lineCode
                + "-"
                + seccionCode
                + "- "
                + product_plus_correlative
                + "^FS\n"
                + "^FO05,120^A0,18,10^FD"
                + name
                + "^FS\n"
                + "^FO05,140^A0,18,10^FD                                                  ^FS\n"
                + "^PQ1^FS\n"
                + "^XZ";
      } else {
        s =
            "^XA^PRD^XZ\n"
                + "^XA^JMA^\n"
                + "^LH07,02^FS\n"
                + "^FO10,03^BE,25,N^BY3, 0.5,45^FD"
                + product_plus_correlative
                + "^FS\n"
                + "^FO10,62^AA,15,12^FD"
                + departmentCode
                + "-"
                + lineCode
                + "-"
                + seccionCode
                + "-"
                + product_plus_correlative
                + "       ^FS\n"
                + "^FO10,82^AA,20,10^FD"
                + name
                + "^FS\n"
                + "^FO10,97^AA,20,10^FD                                                  ^FS\n"
                + "^FO10,116^AA,14,10^FDPRECIO BS^FS\n"
                + "^FO10,170^AB,11,07^FDRIF J-00046517-7   Exento de Iva%^FS\n"
                + "^FO10,153^AB,11,07^CI10^FD"
                + semana
                + " "
                + mes
                + " "
                + año
                + "^FS\n"
                + "^FO10,138^AA,11,09^FDBsF.^FS\n"
                + "^FO35,136^AB,11,07^CI10^FD         "
                + precio
                + "^FS\n"
                + "^PQ"
                + cantidadEtiquetas
                + "^FS\n"
                + "^XZ\n"
                +
                // Control label
                "^XA^PRD^XZ\n"
                + "^XA^JMA^\n"
                + "^LH00,15^FS\n"
                + "^FO2,5^AD,38,10^FD*CONTROL*     "
                + semana
                + " "
                + mes
                + ""
                + año
                + "^FS\n"
                + "^FO05,45^A0,30,07^FD                  TDA:  "
                + tienda.getValue()
                + "^FS\n"
                + "^FO28,48^A0,15,14^FDCANT:     "
                + cantidadEtiquetas
                + "      PRECIO      "
                + precio
                + "^FS\n"
                + "^FO05,95^A0,18,10^FD"
                + departmentCode
                + "-"
                + lineCode
                + "-"
                + seccionCode
                + "- "
                + product_plus_correlative
                + "^FS\n"
                + "^FO05,120^A0,18,10^FD"
                + name
                + "^FS\n"
                + "^FO05,140^A0,18,10^FD                                                  ^FS\n"
                + "^PQ1^FS\n"
                + "^XZ";
      }

      byte[] by = s.getBytes();
      DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
      Doc doc = new SimpleDoc(by, flavor, null);
      job.print(doc, null);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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();
    }
  }
  /** Process Button Pressed - Process Matching */
  private void cmd_newProduct() {
    // Selecciono el departamento
    int depart = 0;
    String SQL =
        "Select XX_VMR_DEPARTMENT_ID "
            + "from XX_VMR_VENDORPRODREF "
            + "where XX_VMR_VENDORPRODREF_ID="
            + LineRefProv.getXX_VMR_VendorProdRef_ID();

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

      while (rs.next()) {
        depart = rs.getInt("XX_VMR_DEPARTMENT_ID");
      }

      rs.close();
      pstmt.close();

    } catch (Exception a) {
      log.log(Level.SEVERE, SQL, a);
    }

    MVMRVendorProdRef vendorProdRef =
        new MVMRVendorProdRef(Env.getCtx(), LineRefProv.getXX_VMR_VendorProdRef_ID(), null);

    if (vendorProdRef.getXX_VMR_ProductClass_ID() > 0
        && vendorProdRef.getXX_VMR_TypeLabel_ID() > 0) {
      MOrder order = new MOrder(Env.getCtx(), LineRefProv.getC_Order_ID(), null);

      // Selecciono el departamento
      X_XX_VMR_Department dept =
          new X_XX_VMR_Department(Env.getCtx(), vendorProdRef.getXX_VMR_Department_ID(), null);
      int category = dept.getXX_VMR_Category_ID();

      // Selecciono la línea
      X_XX_VMR_Line line = new X_XX_VMR_Line(Env.getCtx(), vendorProdRef.getXX_VMR_Line_ID(), null);
      int typeInventory = line.getXX_VMR_TypeInventory_ID();

      MProduct newProduct =
          new MProduct(
              Env.getCtx(),
              vendorProdRef.getXX_VMR_Department_ID(),
              vendorProdRef.getXX_VMR_Line_ID(),
              vendorProdRef.getXX_VMR_Section_ID(),
              vendorProdRef.get_ID(),
              vendorProdRef.getC_TaxCategory_ID(),
              vendorProdRef.getXX_VME_ConceptValue_ID(),
              typeInventory,
              null);

      // Se buscará si por la referencia para producto ya existe para asignarle el Tipo de
      // Exhibición
      String sql =
          "select * from M_Product where XX_VMR_DEPARTMENT_ID = "
              + vendorProdRef.getXX_VMR_Department_ID()
              + " and "
              + "XX_VMR_LINE_ID = "
              + vendorProdRef.getXX_VMR_Line_ID()
              + " and XX_VMR_SECTION_ID = "
              + vendorProdRef.getXX_VMR_Section_ID()
              + " and "
              + "XX_VMR_VendorProdRef_id = "
              + vendorProdRef.getXX_VMR_VendorProdRef_ID()
              + " order by M_Product_ID desc";
      PreparedStatement pstmt = DB.prepareStatement(sql, null);
      ResultSet rs = null;
      try {
        rs = pstmt.executeQuery();
        if (rs.next())
          newProduct.setXX_VMR_TypeExhibition_ID(rs.getInt("XX_VMR_TypeExhibition_ID"));
      } catch (SQLException e) {

        e.printStackTrace();
      } finally {
        DB.closeResultSet(rs);
        DB.closeStatement(pstmt);
      }

      if (vendorProdRef.getXX_VMR_Section_ID() > 0) {
        X_XX_VMR_Section section =
            new X_XX_VMR_Section(Env.getCtx(), vendorProdRef.getXX_VMR_Section_ID(), null);
        newProduct.setName(section.getName());
      } else {
        newProduct.setName(vendorProdRef.getName());
      }
      newProduct.setXX_VMR_Category_ID(category);
      newProduct.setXX_VMR_LongCharacteristic_ID(vendorProdRef.getXX_VMR_LongCharacteristic_ID());
      newProduct.setXX_VMR_Brand_ID(vendorProdRef.getXX_VMR_Brand_ID());
      newProduct.setXX_VMR_UnitConversion_ID(vendorProdRef.getXX_VMR_UnitConversion_ID());
      newProduct.setXX_PiecesBySale_ID(vendorProdRef.getXX_PiecesBySale_ID());
      newProduct.setXX_VMR_UnitPurchase_ID(vendorProdRef.getXX_VMR_UnitPurchase_ID());
      newProduct.setXX_SaleUnit_ID(vendorProdRef.getXX_SaleUnit_ID());
      newProduct.setC_Country_ID(order.getC_Country_ID());
      newProduct.setIsActive(true);
      newProduct.setC_BPartner_ID(vendorProdRef.getC_BPartner_ID());
      newProduct.setXX_VMR_TypeLabel_ID(vendorProdRef.getXX_VMR_TypeLabel_ID());
      newProduct.setXX_VMR_ProductClass_ID(vendorProdRef.getXX_VMR_ProductClass_ID());
      newProduct.setM_AttributeSet_ID(Env.getCtx().getContextAsInt("#XX_L_P_ATTRIBUTESETST_ID"));
      newProduct.setProductType(X_Ref_M_Product_ProductType.ITEM.getValue());
      newProduct.save();

    } else {
      // Creo variables de sesion para atraparlas en la ventana producto
      Env.getCtx().setContext("#Depart_Aux", depart);
      Env.getCtx().setContext("#Section_Aux", LineRefProv.getXX_VMR_Section_ID());
      Env.getCtx().setContext("#Line_Aux", LineRefProv.getXX_VMR_Line_ID());
      Env.getCtx().setContext("#VendorRef_Aux", LineRefProv.getXX_VMR_VendorProdRef_ID());
      Env.getCtx().setContext("#FromProcess_Aux", "Y");

      AWindow window_product = new AWindow();
      Query query = Query.getNoRecordQuery("M_Product", true);
      window_product.initWindow(140, query);
      AEnv.showCenterScreen(window_product);

      // Obtenemos el GridController para setear la variable m_changed=true
      JRootPane jRootPane = ((JRootPane) window_product.getComponent(0));
      JLayeredPane jLayeredPane = (JLayeredPane) jRootPane.getComponent(1);
      JPanel jPanel = (JPanel) jLayeredPane.getComponent(0);
      APanel aPanel = (APanel) jPanel.getComponent(0);
      VTabbedPane vTabbedPane = (VTabbedPane) aPanel.getComponent(0);
      GridController gridController = (GridController) vTabbedPane.getComponent(0);
      GridTable mTable = gridController.getMTab().getTableModel();
      mTable.setChanged(true);

      MProduct.loadLineRefProv(LineRefProv, Env.getCtx());

      // Borro las variables de sesion creadas
      Env.getCtx().remove("#Depart_Aux");
      Env.getCtx().remove("#FromProcess_Aux");
      Env.getCtx().remove("#Line_Aux");
      Env.getCtx().remove("#Section_Aux");
      Env.getCtx().remove("#VendorRef_Aux");
    }
  } //  cmd_newProduct