@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 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 "";
  }
  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 "";
  }
  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();
    }
  }