Example #1
0
  /**
   * Find the periods in a calendar year it need not be a standard period (used in MRP)
   *
   * @param C_Year_ID Year
   * @param periodType Period Type
   * @param ctx context
   * @param trx trx
   * @return MPeriod[]
   */
  public static MPeriod[] getAllPeriodsInYear(int C_Year_ID, String periodType, Ctx ctx, Trx trx) {

    List<MPeriod> periods = new ArrayList<MPeriod>();
    String sql = "SELECT * FROM C_Period WHERE IsActive='Y'";

    sql = sql + " AND C_Year_ID = ?";

    if (periodType != null) sql = sql + " AND PeriodType = ? ";

    sql = sql + " order by StartDate ";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, C_Year_ID);

      if (periodType != null) pstmt.setString(2, periodType);

      rs = pstmt.executeQuery();
      while (rs.next()) periods.add(new MPeriod(ctx, rs, trx));
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    MPeriod[] retValue = new MPeriod[periods.size()];
    periods.toArray(retValue);
    return retValue;
  }
Example #2
0
  /**
   * Returns the previous period
   *
   * @param period MPeriod
   * @param periodCount Count
   * @param trx trx
   * @param ctx Ctx
   * @return MPeriod
   */
  public static MPeriod getPreviousPeriod(MPeriod period, Ctx ctx, Trx trx) {

    MPeriod newPeriod = null;
    String sql =
        "SELECT * FROM C_Period WHERE "
            + "C_Period.IsActive='Y' AND PeriodType='S' "
            + "AND C_Period.C_Year_ID IN "
            + "(SELECT C_Year_ID FROM C_Year WHERE C_Year.C_Calendar_ID = ? ) "
            + "AND ((C_Period.C_Year_ID * 1000) + C_Period.PeriodNo) "
            + " < ((? * 1000) + ?) ORDER BY C_Period.C_Year_ID DESC, C_Period.PeriodNo DESC";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, period.getC_Calendar_ID());
      pstmt.setInt(2, period.getC_Year_ID());
      pstmt.setInt(3, period.getPeriodNo());
      rs = pstmt.executeQuery();
      if (rs.next()) newPeriod = new MPeriod(ctx, rs, trx);
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    return newPeriod;
  }
 /**
  * ************************************************************************ Create Missing
  * Document Types
  *
  * @param ctx context
  * @param AD_Client_ID client
  * @param sp server process
  * @param trx transaction
  */
 public static void createDocumentTypes(Ctx ctx, int AD_Client_ID, SvrProcess sp, Trx trx) {
   s_log.info("AD_Client_ID=" + AD_Client_ID);
   String sql =
       "SELECT rl.Value, rl.Name "
           + "FROM AD_Ref_List rl "
           + "WHERE rl.AD_Reference_ID=183"
           + " AND rl.IsActive='Y' AND NOT EXISTS "
           + " (SELECT * FROM C_DocType dt WHERE dt.AD_Client_ID=? AND rl.Value=dt.DocBaseType)";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, trx);
     pstmt.setInt(1, AD_Client_ID);
     rs = pstmt.executeQuery();
     while (rs.next()) {
       String name = rs.getString(2);
       String value = rs.getString(1);
       s_log.config(name + "=" + value);
       MDocType dt = new MDocType(ctx, value, name, trx);
       if (dt.save()) {
         if (sp != null) sp.addLog(0, null, null, name);
         else s_log.fine(name);
       } else {
         if (sp != null) sp.addLog(0, null, null, "Not created: " + name);
         else s_log.warning("Not created: " + name);
       }
     }
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeResultSet(rs);
     DB.closeStatement(pstmt);
   }
 } //	createDocumentTypes
Example #4
0
 /**
  * Find first Year Period of DateAcct based on Client Calendar
  *
  * @param ctx context
  * @param C_Calendar_ID calendar
  * @param DateAcct date
  * @return active first Period
  */
 public static MPeriod getFirstInYear(Ctx ctx, int C_Calendar_ID, Timestamp DateAcct) {
   MPeriod retValue = null;
   String sql =
       "SELECT * "
           + "FROM C_Period "
           + "WHERE C_Year_ID IN "
           + "(SELECT p.C_Year_ID "
           + "FROM C_Year y"
           + " INNER JOIN C_Period p ON (y.C_Year_ID=p.C_Year_ID) "
           + "WHERE y.C_Calendar_ID=?"
           + "	AND ? BETWEEN StartDate AND EndDate)"
           + " AND IsActive='Y' AND PeriodType='S' "
           + "ORDER BY StartDate";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, (Trx) null);
     pstmt.setInt(1, C_Calendar_ID);
     pstmt.setTimestamp(2, DateAcct);
     rs = pstmt.executeQuery();
     if (rs.next()) // 	first only
     retValue = new MPeriod(ctx, rs, null);
   } catch (SQLException e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   return retValue;
 } //	getFirstInYear
  void dynDepartament() {
    KeyNamePair cat = (KeyNamePair) categoryCombo.getSelectedItem();
    departmentCombo.removeActionListener(this);
    departmentCombo.removeAllItems();

    String sql = "SELECT XX_VMR_DEPARTMENT_ID, VALUE||'-'||NAME " + " FROM XX_VMR_DEPARTMENT ";

    if (cat != null && cat.getKey() != -1) {
      sql += " WHERE XX_VMR_CATEGORY_ID = " + cat.getKey();
    }
    sql += " ORDER BY VALUE||'-'||NAME ";
    sql = MRole.getDefault().addAccessSQL(sql, "", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      rs = pstmt.executeQuery();

      departmentCombo.addItem(new KeyNamePair(-1, null));
      while (rs.next()) {
        departmentCombo.addItem(new KeyNamePair(rs.getInt(1), rs.getString(2)));
      }
      rs.close();
      pstmt.close();

      departmentCombo.addActionListener(this);
      departmentCombo.setEnabled(true);
      departmentCombo.setEditable(true);
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
  }
Example #6
0
  /**
   * Find all the year records in a Calendar, it need not be a standard period (used in MRP)
   *
   * @param C_Calendar_ID calendar
   * @param ctx context
   * @param trx trx
   * @return MYear[]
   */
  public static MYear[] getAllYearsInCalendar(int C_Calendar_ID, Ctx ctx, Trx trx) {

    List<MYear> years = new ArrayList<MYear>();
    String sql = "SELECT * FROM C_Year WHERE " + "IsActive='Y' AND C_Calendar_ID = ? ";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, C_Calendar_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) years.add(new MYear(ctx, rs, trx));

    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {

      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }

    MYear[] retValue = new MYear[years.size()];
    years.toArray(retValue);
    return retValue;
  }
Example #7
0
 /**
  * Get Accessible Goals
  *
  * @param ctx context
  * @return array of goals
  */
 public static MGoal[] getGoals(Ctx ctx) {
   ArrayList<MGoal> list = new ArrayList<MGoal>();
   String sql = "SELECT * FROM PA_Goal WHERE IsActive='Y' " + "ORDER BY SeqNo";
   sql =
       MRole.getDefault(ctx, false)
           .addAccessSQL(sql, "PA_Goal", false, true); // 	RW to restrict Access
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, (Trx) null);
     rs = pstmt.executeQuery();
     while (rs.next()) {
       MGoal goal = new MGoal(ctx, rs, null);
       goal.updateGoal(false);
       list.add(goal);
     }
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   MGoal[] retValue = new MGoal[list.size()];
   list.toArray(retValue);
   return retValue;
 } //	getGoals
Example #8
0
 /**
  * Get Restriction Lines
  *
  * @param reload reload data
  * @return array of lines
  */
 public MGoalRestriction[] getRestrictions(boolean reload) {
   if (m_restrictions != null && !reload) return m_restrictions;
   ArrayList<MGoalRestriction> list = new ArrayList<MGoalRestriction>();
   //
   String sql =
       "SELECT * FROM PA_GoalRestriction "
           + "WHERE PA_Goal_ID=? AND IsActive='Y' "
           + "ORDER BY Org_ID, C_BPartner_ID, M_Product_ID";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, get_Trx());
     pstmt.setInt(1, getPA_Goal_ID());
     rs = pstmt.executeQuery();
     while (rs.next()) list.add(new MGoalRestriction(getCtx(), rs, get_Trx()));
   } catch (Exception e) {
     log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   //
   m_restrictions = new MGoalRestriction[list.size()];
   list.toArray(m_restrictions);
   return m_restrictions;
 } //	getRestrictions
Example #9
0
  /**
   * Find standard Period of DateAcct based on Client Calendar
   *
   * @param ctx context
   * @param C_Calendar_ID calendar
   * @param DateAcct date
   * @return active Period or null
   */
  public static MPeriod getOfCalendar(Ctx ctx, int C_Calendar_ID, Timestamp DateAcct) {
    if (DateAcct == null) {
      s_log.warning("No DateAcct");
      return null;
    }
    if (C_Calendar_ID == 0) {
      s_log.warning("No Calendar");
      return null;
    }
    //	Search in Cache first
    Iterator<MPeriod> it = s_cache.values().iterator();
    while (it.hasNext()) {
      MPeriod period = it.next();
      if (period.getC_Calendar_ID() == C_Calendar_ID
          && period.isStandardPeriod()
          && period.isInPeriod(DateAcct)) return period;
    }

    //	Get it from DB
    MPeriod retValue = null;
    String sql =
        "SELECT * FROM C_Period "
            + "WHERE C_Year_ID IN "
            + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID=?)"
            + " AND ? BETWEEN TRUNC(StartDate,'DD') AND TRUNC(EndDate,'DD')"
            + " AND IsActive='Y' AND PeriodType='S'";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, (Trx) null);
      pstmt.setInt(1, C_Calendar_ID);
      pstmt.setTimestamp(2, TimeUtil.getDay(DateAcct));
      rs = pstmt.executeQuery();
      while (rs.next()) {
        MPeriod period = new MPeriod(ctx, rs, null);
        Integer key = Integer.valueOf(period.getC_Period_ID());
        s_cache.put(key, period);
        if (period.isStandardPeriod()) retValue = period;
      }
    } catch (SQLException e) {
      s_log.log(Level.SEVERE, "DateAcct=" + DateAcct, e);
    } finally {
      DB.closeStatement(pstmt);
      DB.closeResultSet(rs);
    }
    if (retValue == null)
      s_log.warning(
          "No Standard Period for " + DateAcct + " (C_Calendar_ID=" + C_Calendar_ID + ")");
    return retValue;
  } //	get
Example #10
0
  /**
   * Set Resource Assignment - Callout
   *
   * @param oldS_ResourceAssignment_ID old value
   * @param newS_ResourceAssignment_ID new value
   * @param windowNo window
   * @throws Exception
   */
  @UICallout
  public void setS_ResourceAssignment_ID(
      String oldS_ResourceAssignment_ID, String newS_ResourceAssignment_ID, int windowNo)
      throws Exception {
    if (newS_ResourceAssignment_ID == null || newS_ResourceAssignment_ID.length() == 0) return;
    int S_ResourceAssignment_ID = Integer.parseInt(newS_ResourceAssignment_ID);
    if (S_ResourceAssignment_ID == 0) return;
    //
    super.setS_ResourceAssignment_ID(S_ResourceAssignment_ID);

    int M_Product_ID = 0;
    String Name = null;
    String Description = null;
    BigDecimal Qty = null;
    String sql =
        "SELECT p.M_Product_ID, ra.Name, ra.Description, ra.Qty "
            + "FROM S_ResourceAssignment ra"
            + " INNER JOIN M_Product p ON (p.S_Resource_ID=ra.S_Resource_ID) "
            + "WHERE ra.S_ResourceAssignment_ID=?";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, get_Trx());
      pstmt.setInt(1, S_ResourceAssignment_ID);
      rs = pstmt.executeQuery();
      if (rs.next()) {
        M_Product_ID = rs.getInt(1);
        Name = rs.getString(2);
        Description = rs.getString(3);
        Qty = rs.getBigDecimal(4);
      }
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    log.fine(
        "S_ResourceAssignment_ID=" + S_ResourceAssignment_ID + " - M_Product_ID=" + M_Product_ID);
    if (M_Product_ID != 0) {
      setM_Product_ID(M_Product_ID);
      if (Description != null) Name += " (" + Description + ")";
      if (!".".equals(Name)) setDescription(Name);
      if (Qty != null) setQty(Qty);
    }
  } //	setS_ResourceAssignment_ID
  private void llenarcombos() {
    dynCategory();
    dynDepartament();

    // Cargar el combo box de mes
    monthCombo.addItem(null);
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_January"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_February"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_March"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_April"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_May"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_June"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_July"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_August"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_September"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_October"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_November"));
    monthCombo.addItem(Msg.translate(Env.getCtx(), "XX_December"));

    // Cargar proveedores
    String sql = "SELECT b.C_BPARTNER_ID, b.NAME FROM C_BPARTNER b WHERE isVendor='Y' ";
    sql = MRole.getDefault().addAccessSQL(sql, "b", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
    sql += " ORDER BY b.NAME";
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
      pstmt = DB.prepareStatement(sql, null);
      rs = pstmt.executeQuery();
      loadKNP = new KeyNamePair(0, new String());
      comboBPartner.addItem(loadKNP);
      while (rs.next()) {
        loadKNP = new KeyNamePair(rs.getInt(1), rs.getString(2));
        comboBPartner.addItem(loadKNP);
        // comboBPartner.addItem(new KeyNamePair(rs.getInt(1), rs.getString(2)));
      }
      comboBPartner.setEditable(false);
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
  } // fin de llenar combos
Example #12
0
 /**
  * Get Goals with Measure
  *
  * @param ctx context
  * @param PA_Measure_ID measure
  * @return goals
  */
 public static MGoal[] getMeasureGoals(Ctx ctx, int PA_Measure_ID) {
   ArrayList<MGoal> list = new ArrayList<MGoal>();
   String sql = "SELECT * FROM PA_Goal WHERE IsActive='Y' AND PA_Measure_ID=? " + "ORDER BY SeqNo";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, (Trx) null);
     pstmt.setInt(1, PA_Measure_ID);
     rs = pstmt.executeQuery();
     while (rs.next()) list.add(new MGoal(ctx, rs, null));
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeStatement(pstmt);
     DB.closeResultSet(rs);
   }
   MGoal[] retValue = new MGoal[list.size()];
   list.toArray(retValue);
   return retValue;
 } //	getMeasureGoals
Example #13
0
  /**
   * gets all Periods in the Range
   *
   * @param startPeriod
   * @param endPeriod
   * @param calendar_ID
   * @return MPeriod[]
   */
  public static MPeriod[] getAllPeriodsInRange(
      MPeriod startPeriod, MPeriod endPeriod, int calendar_ID, Ctx ctx, Trx trx) {
    if ((startPeriod.getC_Calendar_ID() != calendar_ID)
        || (endPeriod.getC_Calendar_ID() != calendar_ID)) {
      log.saveError("Error", "Periods do not belong to the calendar");
      return null;
    }

    ArrayList<MPeriod> periods = new ArrayList<MPeriod>();
    String sql =
        "SELECT * FROM C_Period WHERE "
            + "C_Period.IsActive='Y' AND PeriodType='S' "
            + "AND C_Period.C_Year_ID IN "
            + "(SELECT C_Year_ID FROM C_Year WHERE C_Year.C_Calendar_ID = ? ) "
            + // calendar_ID
            "AND ((C_Period.C_Year_ID * 1000) + C_Period.PeriodNo) BETWEEN"
            + " (? * 1000 + ?) AND (? * 1000 + ? )"
            + // start Period year ID, Period Number , End Period Year ID, Period Number
            " ORDER BY C_Period.C_Year_ID ASC, C_Period.PeriodNo ASC";

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, calendar_ID);
      pstmt.setInt(2, startPeriod.getC_Year_ID());
      pstmt.setInt(3, startPeriod.getPeriodNo());
      pstmt.setInt(4, endPeriod.getC_Year_ID());
      pstmt.setInt(5, endPeriod.getPeriodNo());
      rs = pstmt.executeQuery();
      while (rs.next()) periods.add(new MPeriod(ctx, rs, trx));
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    MPeriod[] retValue = new MPeriod[periods.size()];
    periods.toArray(retValue);
    return retValue;
  }
Example #14
0
  /**
   * Get User Goals
   *
   * @param ctx context
   * @param AD_User_ID user
   * @return array of goals
   */
  public static MGoal[] getUserGoals(Ctx ctx) {
    int AD_Role_ID = ctx.getAD_Role_ID();
    MRole role = MRole.get(ctx, AD_Role_ID);
    int AD_User_ID = ctx.getAD_User_ID();

    if (AD_User_ID < 0) return getTestGoals(ctx);
    ArrayList<MGoal> list = new ArrayList<MGoal>();
    String sql =
        "SELECT * FROM PA_Goal g "
            + "WHERE IsActive='Y'"
            + " AND AD_Client_ID=?" //	#1
            + " AND (";
    if (!role.isWebStoreRole()) sql += " (AD_User_ID IS NULL AND AD_Role_ID IS NULL) OR ";
    sql +=
        " AD_User_ID=?" //	#2
            + " OR EXISTS (SELECT * FROM AD_User_Roles ur "
            + "WHERE ?=ur.AD_User_ID AND g.AD_Role_ID=ur.AD_Role_ID AND ur.IsActive='Y')) "
            + "ORDER BY SeqNo";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, (Trx) null);
      pstmt.setInt(1, ctx.getAD_Client_ID());
      pstmt.setInt(2, AD_User_ID);
      pstmt.setInt(3, AD_User_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        MGoal goal = new MGoal(ctx, rs, null);
        goal.updateGoal(false);
        list.add(goal);
      }
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    MGoal[] retValue = new MGoal[list.size()];
    list.toArray(retValue);
    return retValue;
  } //	getUserGoals
Example #15
0
  public static MRequestAction[] getActions(MRequest request) {
    ArrayList<MRequestAction> retVal = new ArrayList<MRequestAction>();
    String sql = "SELECT * FROM R_RequestAction WHERE R_Request_ID = ? ";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, request.get_Trx());
      pstmt.setInt(1, request.getR_Request_ID());
      rs = pstmt.executeQuery();
      while (rs.next()) retVal.add(new MRequestAction(request.getCtx(), rs, request.get_Trx()));
    } catch (Exception e) {
      log.severe(e.toString());
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }

    MRequestAction[] actions = new MRequestAction[retVal.size()];
    retVal.toArray(actions);
    return actions;
  }
Example #16
0
  /**
   * Load Regions (cached)
   *
   * @param ctx context
   */
  private static void loadAllRegions(Ctx ctx) {
    String sql = "SELECT * FROM C_Region WHERE IsActive='Y'";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, (Trx) null);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        MRegion r = new MRegion(ctx, rs, null);
        s_regions.put(String.valueOf(r.getC_Region_ID()), r);
        if (r.isDefault()) s_default = r;
      }
    } catch (SQLException e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }

    s_log.fine(s_regions.size() + " - default=" + s_default);
  } //	loadAllRegions
Example #17
0
 /**
  * Get Period Control
  *
  * @param requery requery
  * @return period controls
  */
 public MPeriodControl[] getPeriodControls(boolean requery) {
   if (m_controls != null && !requery) return m_controls;
   //
   ArrayList<MPeriodControl> list = new ArrayList<MPeriodControl>();
   String sql = "SELECT * FROM C_PeriodControl " + "WHERE C_Period_ID=?";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, get_Trx());
     pstmt.setInt(1, getC_Period_ID());
     rs = pstmt.executeQuery();
     while (rs.next()) list.add(new MPeriodControl(getCtx(), rs, get_Trx()));
   } catch (Exception e) {
     log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeResultSet(rs);
     DB.closeStatement(pstmt);
   }
   m_controls = new MPeriodControl[list.size()];
   list.toArray(m_controls);
   return m_controls;
 } //	getPeriodControls
Example #18
0
  /**
   * Find Period of Date based on Client Calendar, it need not be a standard period (used in MRP)
   *
   * @param ctx context
   * @param C_Calendar_ID calendar
   * @param Date date
   * @param trx trx
   * @return active Period or null
   */
  public static MPeriod getPeriod(Ctx ctx, int C_Calendar_ID, Timestamp Date, Trx trx) {
    if (Date == null) {
      s_log.warning("No Date");
      return null;
    }
    if (C_Calendar_ID == 0) {
      s_log.warning("No Calendar");
      return null;
    }

    //	Get it from DB
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    MPeriod retValue = null;
    String sql =
        "SELECT * FROM C_Period "
            + "WHERE C_Year_ID IN "
            + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID=?)"
            + " AND ? BETWEEN TRUNC(StartDate,'DD') AND TRUNC(EndDate,'DD')"
            + " AND IsActive='Y' ";
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, C_Calendar_ID);
      pstmt.setTimestamp(2, TimeUtil.getDay(Date));
      rs = pstmt.executeQuery();
      if (rs.next()) {
        retValue = new MPeriod(ctx, rs, trx);
      }
    } catch (SQLException e) {
      s_log.log(Level.SEVERE, "DateAcct=" + Date, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    if (retValue == null)
      s_log.warning("No Period for " + Date + " (C_Calendar_ID=" + C_Calendar_ID + ")");
    return retValue;
  } //	getPeriod
  // Datos
  void dynCategory() {

    categoryCombo.removeActionListener(this);
    String sql = "SELECT XX_VMR_CATEGORY_ID, VALUE||'-'||NAME " + " FROM XX_VMR_CATEGORY ";
    sql += " ORDER BY VALUE||'-'||NAME ";
    sql = MRole.getDefault().addAccessSQL(sql, "", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      rs = pstmt.executeQuery();

      categoryCombo.addItem(new KeyNamePair(-1, null));
      while (rs.next()) {
        categoryCombo.addItem(new KeyNamePair(rs.getInt(1), rs.getString(2)));
      }
      categoryCombo.addActionListener(this);
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
  }
  /** 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
  public String readFile() throws IOException {

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

      // int defaultRows = sheet.getRows();

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

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

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

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

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

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

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

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

          // Capturo el destino

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

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

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

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

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

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

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

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

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

    m_sql = new StringBuffer();
    m_sql2 = new StringBuffer();

    // Mostrar todos los ACC y AAP
    if (tableInit_option == 0) {
      m_sql.append(
          "select cb.value ||'-'|| cb.name vendor, co.name country, extract(month from cn.CREATED) month,"
              + " extract (year from cn.CREATED) year, NVL(round(sum(cn.XX_UNITPURCHASEPRICEBS),2),0) total,"
              + " dep.value || '-' || dep.name department, cat.value || '-' || cat.name category,"
              + " o.XX_VMR_DEPARTMENT_ID, o.XX_VMR_CATEGORY_ID, o.C_BPARTNER_ID vendorID"
              + " from  XX_CREDITNOTIFYRETURN cn, C_BPARTNER cb, C_COUNTRY co, C_ORDER o, XX_VMR_DEPARTMENT dep, XX_VMR_CATEGORY cat"
              + " where o.C_BPARTNER_ID=cb.C_BPARTNER_ID and co.C_COUNTRY_ID=o.C_COUNTRY_ID and"
              + " cn.XX_NOTIFICATIONTYPE='ACC'and cn.C_ORDER_ID=o.C_ORDER_ID and"
              + " dep.XX_VMR_DEPARTMENT_ID=o.XX_VMR_DEPARTMENT_ID and o.XX_VMR_CATEGORY_ID=cat.XX_VMR_CATEGORY_ID and o.AD_CLIENT_ID="
              + ctx.getAD_Client_ID()
              + " AND o.ISSOTRX = 'N'");

      m_groupBy =
          " group by cb.value ||'-'|| cb.name, co.name,  extract(month from cn.CREATED), extract (year from cn.CREATED), dep.value || '-' || dep.name,"
              + " cat.value || '-' || cat.name,o.XX_VMR_DEPARTMENT_ID, o.XX_VMR_CATEGORY_ID, o.C_BPARTNER_ID";

      m_sql2.append(
          "select cb.value ||'-'|| cb.name vendor, co.name country, det.XX_MONTH month,"
              + " det.XX_YEAR year, round(cn.XX_UNITPURCHASEPRICEBS,2) total, o.C_BPARTNER_ID vendorID,"
              + " o.XX_VMR_DEPARTMENT_ID, o.XX_VMR_CATEGORY_ID, cn.XX_CREDITNOTIFYRETURN_ID creditNotID, cn.XX_NOTIFICATIONTYPE tipo"
              + " from  XX_CREDITNOTIFYRETURN cn, C_BPARTNER cb, C_COUNTRY co, C_ORDER o, XX_VMR_DEPARTMENT dep, XX_VMR_CATEGORY cat, XX_VCN_DETAILADVICE det"
              + " where o.C_BPARTNER_ID=cb.C_BPARTNER_ID and co.C_COUNTRY_ID=o.C_COUNTRY_ID and cn.XX_NOTIFICATIONTYPE<>'ACC'"
              + " and cn.C_ORDER_ID=o.C_ORDER_ID and dep.XX_VMR_DEPARTMENT_ID=o.XX_VMR_DEPARTMENT_ID"
              + " and o.XX_VMR_CATEGORY_ID=cat.XX_VMR_CATEGORY_ID and det.XX_CREDITNOTIFYRETURN_ID=cn.XX_CREDITNOTIFYRETURN_ID and o.AD_CLIENT_ID="
              + ctx.getAD_Client_ID()
              + " AND o.ISSOTRX = 'N'");

      m_groupBy2 =
          " group by cb.value ||'-'|| cb.name, co.name,  det.XX_MONTH, det.XX_YEAR, cn.XX_UNITPURCHASEPRICEBS,"
              + " o.XX_VMR_DEPARTMENT_ID, o.XX_VMR_CATEGORY_ID, o.C_BPARTNER_ID, cn.XX_CREDITNOTIFYRETURN_ID, cn.XX_NOTIFICATIONTYPE";
      // Búsqueda por mes
      if (monthCombo.getSelectedIndex() != 0 && monthCombo.getSelectedItem() != null) {
        m_sql
            .append(" AND ")
            .append("extract(month from cn.created)=")
            .append(monthCombo.getSelectedIndex());
        m_sql2.append(" AND ").append("det.XX_MONTH=").append(monthCombo.getSelectedIndex());
      }
      // Búsqueda por año
      if (yearField.getValue() != null) {
        m_sql
            .append(" AND ")
            .append("extract(year from cn.created)=")
            .append(((BigDecimal) yearField.getValue()).intValue());
        m_sql2
            .append(" AND ")
            .append("det.XX_YEAR=")
            .append(((BigDecimal) yearField.getValue()).intValue());
      }
      // Búsqueda por proveedor
      if (comboBPartner.getSelectedIndex() != 0 && comboBPartner.getSelectedItem() != null) {
        if (((KeyNamePair) comboBPartner.getSelectedItem()).getKey() != 0) {
          int clave_vendor = ((KeyNamePair) comboBPartner.getSelectedItem()).getKey();
          m_sql.append(" AND ").append("o.C_BPartner_ID=").append(clave_vendor);
          m_sql2.append(" AND ").append("o.C_BPartner_ID=").append(clave_vendor);
        }
      }

      // agrego la categoria
      if (categoryCombo.getValue() != null) {
        KeyNamePair cat = (KeyNamePair) categoryCombo.getValue();
        if (cat.getKey() != -1) {
          m_sql.append(" AND o.XX_VMR_CATEGORY_ID = ").append(cat.getKey()).append(" ");
          m_sql2.append(" AND o.XX_VMR_CATEGORY_ID = ").append(cat.getKey()).append(" ");
        }
      }
      // agrego el departamento al query
      if (departmentCombo.getValue() != null) {
        KeyNamePair dep = (KeyNamePair) departmentCombo.getValue();
        if (dep.getKey() != -1) {
          m_sql.append(" AND o.XX_VMR_DEPARTMENT_ID = ").append(dep.getKey()).append(" ");
          m_sql2.append(" AND o.XX_VMR_DEPARTMENT_ID = ").append(dep.getKey()).append(" ");
        }
      }
    }

    String SQL = m_sql.toString() + m_groupBy;

    int i = 0;
    xTableACC.setRowCount(i);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(SQL, null);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        xTableACC.setRowCount(i + 1);
        // Proveedor
        xTableACC.setValueAt(rs.getString("vendor"), i, 0); // 1
        // País
        xTableACC.setValueAt(rs.getString("country"), i, 1);
        // Departamento
        xTableACC.setValueAt(rs.getString("department"), i, 2);
        // Categoría
        xTableACC.setValueAt(rs.getString("category"), i, 3);
        // Mes
        xTableACC.setValueAt(rs.getInt("month"), i, 4);
        // Año
        xTableACC.setValueAt(rs.getInt("year"), i, 5);
        // Compras hechas
        xTableACC.setValueAt(rs.getBigDecimal("total"), i, 6);

        // Se calculan los avisos cerrados(CER) de el mismo mes, año, proveedor, depto y categoría
        String SQL2 =
            "select nvl(round(sum(cn.XX_AMOUNT),2),0) totalDesc"
                + " from  XX_CREDITNOTIFYRETURN cn, C_BPARTNER cb, C_COUNTRY co, C_ORDER o, XX_VMR_DEPARTMENT dep, XX_VMR_CATEGORY cat"
                + " where o.C_BPARTNER_ID=cb.C_BPARTNER_ID and co.C_COUNTRY_ID=o.C_COUNTRY_ID"
                + " and cn.XX_NOTIFICATIONTYPE='ACC' and cn.C_ORDER_ID=o.C_ORDER_ID"
                + " and dep.XX_VMR_DEPARTMENT_ID=o.XX_VMR_DEPARTMENT_ID and o.XX_VMR_CATEGORY_ID=cat.XX_VMR_CATEGORY_ID"
                + " and XX_STATUS='CER' and extract(month from cn.CREATED)="
                + rs.getInt("month")
                + " and extract (year from cn.CREATED)="
                + rs.getInt("year")
                + " and o.C_BPARTNER_ID="
                + rs.getInt("vendorID")
                + " and o.AD_CLIENT_ID="
                + ctx.getAD_Client_ID()
                + " AND o.ISSOTRX = 'N'";
        PreparedStatement pstmt2 = null;
        ResultSet rs2 = null;

        try {
          pstmt2 = DB.prepareStatement(SQL2, null);
          rs2 = pstmt2.executeQuery();
          if (rs2.next()) xTableACC.setValueAt(rs2.getBigDecimal("totalDesc"), i, 7);
          else xTableACC.setValueAt(0, i, 7);
        } catch (SQLException e) {
          System.out.print(e.getMessage());
        } finally {
          DB.closeResultSet(rs2);
          DB.closeStatement(pstmt2);
        }

        // Se calculan los avisos pendientes(ACT) de el mismo mes, año, proveedor, depto y categoría
        String SQL3 =
            "select nvl(round(sum(cn.XX_AMOUNT),2),0) totalDesc"
                + " from  XX_CREDITNOTIFYRETURN cn, C_BPARTNER cb, C_COUNTRY co, C_ORDER o, XX_VMR_DEPARTMENT dep, XX_VMR_CATEGORY cat"
                + " where o.C_BPARTNER_ID=cb.C_BPARTNER_ID and co.C_COUNTRY_ID=o.C_COUNTRY_ID"
                + " and cn.XX_NOTIFICATIONTYPE='ACC' and cn.C_ORDER_ID=o.C_ORDER_ID"
                + " and dep.XX_VMR_DEPARTMENT_ID=o.XX_VMR_DEPARTMENT_ID and o.XX_VMR_CATEGORY_ID=cat.XX_VMR_CATEGORY_ID"
                + " and XX_STATUS='ACT' and extract(month from cn.CREATED)="
                + rs.getInt("month")
                + " and extract (year from cn.CREATED)="
                + rs.getInt("year")
                + " and o.C_BPARTNER_ID="
                + rs.getInt("vendorID")
                + " and o.AD_CLIENT_ID="
                + ctx.getAD_Client_ID()
                + " AND o.ISSOTRX = 'N'";
        PreparedStatement pstmt3 = null;
        ResultSet rs3 = null;
        try {
          pstmt3 = DB.prepareStatement(SQL3, null);
          rs3 = pstmt3.executeQuery();
          if (rs3.next()) xTableACC.setValueAt(rs3.getBigDecimal("totalDesc"), i, 8);
          else xTableACC.setValueAt(0, i, 8);
        } catch (SQLException e) {
          System.out.print(e.getMessage());
        } finally {
          DB.closeResultSet(rs3);
          DB.closeStatement(pstmt3);
        }

        i++;
      }

    } catch (SQLException e) {
      e.getMessage();
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }

    String sqlAAP = m_sql2.toString() + m_groupBy2;

    i = 0;
    xTableAAP.setRowCount(i);
    pstmt = null;
    rs = null;
    try {
      pstmt = DB.prepareStatement(sqlAAP, null);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        xTableAAP.setRowCount(i + 1);
        // Proveedor
        xTableAAP.setValueAt(
            new KeyNamePair(rs.getInt("vendorID"), rs.getString("vendor")), i, 0); // 1
        // País
        xTableAAP.setValueAt(
            new KeyNamePair(rs.getInt("creditNotID"), rs.getString("country")), i, 1);
        // Mes
        xTableAAP.setValueAt(rs.getInt("month"), i, 2);
        // Año
        xTableAAP.setValueAt(rs.getInt("year"), i, 3);
        // Tipo
        xTableAAP.setValueAt(rs.getString("tipo"), i, 4);
        // Compras hechas
        xTableAAP.setValueAt(rs.getBigDecimal("total"), i, 5);

        // Se calculan los avisos cerrados(CER) de el mismo mes, año, proveedor, depto y categoría
        String SQL2 =
            "select nvl(round(sum(cn.XX_AMOUNT),2),0) totalDesc"
                + " from  XX_CREDITNOTIFYRETURN cn, C_BPARTNER cb, C_COUNTRY co, C_ORDER o, XX_VMR_DEPARTMENT dep, XX_VMR_CATEGORY cat"
                + " where o.C_BPARTNER_ID=cb.C_BPARTNER_ID and co.C_COUNTRY_ID=o.C_COUNTRY_ID"
                + " and cn.XX_NOTIFICATIONTYPE<>'ACC' and cn.C_ORDER_ID=o.C_ORDER_ID"
                + " and dep.XX_VMR_DEPARTMENT_ID=o.XX_VMR_DEPARTMENT_ID and o.XX_VMR_CATEGORY_ID=cat.XX_VMR_CATEGORY_ID"
                + " and XX_STATUS='CER' and cn.XX_CREDITNOTIFYRETURN_ID="
                + rs.getInt("creditNotID")
                + " and o.C_BPARTNER_ID="
                + rs.getInt("vendorID")
                + " and o.AD_CLIENT_ID="
                + ctx.getAD_Client_ID()
                + " AND o.ISSOTRX = 'N'";
        PreparedStatement pstmt2 = null;
        ResultSet rs2 = null;

        try {
          pstmt2 = DB.prepareStatement(SQL2, null);
          rs2 = pstmt2.executeQuery();
          if (rs2.next()) xTableAAP.setValueAt(rs2.getBigDecimal("totalDesc"), i, 6);
          else xTableAAP.setValueAt(0, i, 6);
        } catch (SQLException e) {
          System.out.print(e.getMessage());
        } finally {
          DB.closeResultSet(rs2);
          DB.closeStatement(pstmt2);
        }

        // Se calculan los avisos pendientes(ACT) de el mismo mes, año, proveedor, depto y categoría
        String SQL3 =
            "select nvl(round(sum(cn.XX_AMOUNT),2),0) totalDesc"
                + " from  XX_CREDITNOTIFYRETURN cn, C_BPARTNER cb, C_COUNTRY co, C_ORDER o, XX_VMR_DEPARTMENT dep, XX_VMR_CATEGORY cat"
                + " where o.C_BPARTNER_ID=cb.C_BPARTNER_ID and co.C_COUNTRY_ID=o.C_COUNTRY_ID"
                + " and cn.XX_NOTIFICATIONTYPE<>'ACC' and cn.C_ORDER_ID=o.C_ORDER_ID"
                + " and dep.XX_VMR_DEPARTMENT_ID=o.XX_VMR_DEPARTMENT_ID and o.XX_VMR_CATEGORY_ID=cat.XX_VMR_CATEGORY_ID"
                + " and XX_STATUS='ACT' and cn.XX_CREDITNOTIFYRETURN_ID="
                + rs.getInt("creditNotID")
                + " and o.C_BPARTNER_ID="
                + rs.getInt("vendorID")
                + " and o.AD_CLIENT_ID="
                + ctx.getAD_Client_ID()
                + " AND o.ISSOTRX = 'N'";
        PreparedStatement pstmt3 = null;
        ResultSet rs3 = null;
        try {
          pstmt3 = DB.prepareStatement(SQL3, null);
          rs3 = pstmt3.executeQuery();
          if (rs3.next()) xTableAAP.setValueAt(rs3.getBigDecimal("totalDesc"), i, 7);
          else xTableAAP.setValueAt(0, i, 7);
        } catch (SQLException e) {
          System.out.print(e.getMessage());
        } finally {
          DB.closeResultSet(rs3);
          DB.closeStatement(pstmt3);
        }

        i++;
      }

    } catch (SQLException e) {
      e.getMessage();
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
  } //  tableInit
  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 "";
  }
Example #24
0
  /**
   * After Save
   *
   * @param newRecord new
   * @param success success
   * @return true if can be saved
   */
  protected boolean afterSave(boolean newRecord, boolean success) {
    boolean save = super.afterSave(newRecord, success);

    if (save) {
      if (get_ValueAsBigDecimal("XX_L_VCN_StorageCharge")
              .compareTo((BigDecimal) get_ValueOld("XX_L_VCN_StorageCharge"))
          != 0) {
        String msg =
            "¿Está seguro que quiere actualizar el porcentaje de gasto de almacenaje?. "
                + "\nEste cambio actualizará el factor de reposición de las tasas de cambio de periodo igual o posterior al actual.";
        Boolean ask = ADialog.ask(1, new Container(), msg);
        if (ask) {
          BigDecimal percentageIncreaseOld = (BigDecimal) get_ValueOld("XX_L_VCN_StorageCharge");
          BigDecimal percentageIncrease = get_ValueAsBigDecimal("XX_L_VCN_StorageCharge");
          Date time = Utilities.currentServerDate();
          Calendar date = Calendar.getInstance();
          date.setTime(time);
          date.set(Calendar.HOUR, 0);
          date.set(Calendar.MINUTE, 0);
          date.set(Calendar.SECOND, 0);
          date.set(Calendar.MILLISECOND, 0);
          BigDecimal multiplyRate = new BigDecimal(0);
          BigDecimal replacementFactor_aux = new BigDecimal(0);
          BigDecimal replacementFactor = new BigDecimal(0);
          int conversionRateID = 0;

          DateFormat formatter = new SimpleDateFormat("yyyy-MM");
          // Calendar to Date Conversion
          int year = date.get(Calendar.YEAR);
          int month = date.get(Calendar.MONTH);
          int day = date.get(Calendar.DATE);
          Date auxDate = new Date((year - 1900), month, day);
          String fecha = formatter.format(auxDate);

          String SQL =
              "Select C.XX_REPLACEMENTFACTOR, C.MULTIPLYRATE, C.C_CONVERSION_RATE_ID, C.XX_PERIOD_ID, P.STARTDATE "
                  + "\nFROM C_CONVERSION_RATE C, C_PERIOD P WHERE C.XX_PERIOD_ID =  P.C_PERIOD_ID AND "
                  + "\nP.ISACTIVE='Y' AND P.AD_CLIENT_ID = 1000012 AND P.STARTDATE >=  TO_DATE('"
                  + fecha
                  + "','YYYY-MM')";
          System.out.println(SQL);
          PreparedStatement pstmt = null;
          ResultSet rs = null;
          try {
            pstmt = DB.prepareStatement(SQL, null);
            rs = pstmt.executeQuery();

            int i = 0;
            while (rs.next()) {
              multiplyRate = rs.getBigDecimal("MultiplyRate");
              replacementFactor_aux = rs.getBigDecimal("XX_ReplacementFactor");
              conversionRateID = rs.getInt("C_CONVERSION_RATE_ID");

              // Si se esta en medio de un período se agrega a la tabla X_XX_VCN_ReplacementFactor
              // el factor de reposición anterior.
              Calendar start = Calendar.getInstance();
              start.setTime(rs.getDate("STARTDATE"));
              if (start.compareTo(date) <= 0) {
                X_XX_VCN_ReplacementFactor replacementFactorOld =
                    new X_XX_VCN_ReplacementFactor(Env.getCtx(), 0, null);
                replacementFactorOld.setC_Conversion_Rate_ID(conversionRateID);
                replacementFactorOld.setXX_ReplacementFactor(replacementFactor_aux);
                replacementFactorOld.setMultiplyRate(multiplyRate);
                replacementFactorOld.setXX_PercentageIncrease(percentageIncreaseOld);
                replacementFactorOld.save();
                replacementFactorOld.setValidTo(replacementFactorOld.getCreated());
                replacementFactorOld.save();
              }
              // Set Replacement Factor
              X_C_Conversion_Rate convertionRate =
                  new X_C_Conversion_Rate(Env.getCtx(), rs.getInt("C_CONVERSION_RATE_ID"), null);
              replacementFactor = multiplyRate.add((multiplyRate.multiply(percentageIncrease)));
              convertionRate.set_Value("XX_ReplacementFactor", replacementFactor);
              convertionRate.save();
              i++;
            }

            if (i > 0) {
              msg =
                  "Se actualizó el Factor de Reposición de las Tasas de Cambio de periodo igual o posterior al actual.";
              ADialog.info(1, new Container(), msg);
            }

          } catch (Exception e) {
            e.printStackTrace();
          } finally {
            DB.closeResultSet(rs);
            DB.closeStatement(pstmt);
          }
        } else {
          return false;
        }
      }
    }
    return save;
  }
  /**
   * Create Period Controls
   *
   * @param ctx context
   * @param AD_Client_ID client
   * @param sp server process
   * @param trx transaction
   */
  public static void createPeriodControls(Ctx ctx, int AD_Client_ID, SvrProcess sp, Trx trx) {
    s_log.info("AD_Client_ID=" + AD_Client_ID);

    //	Delete Duplicates
    String sql =
        "DELETE FROM C_PeriodControl "
            + "WHERE (C_Period_ID, DocBaseType) IN "
            + "(SELECT C_Period_ID, DocBaseType "
            + "FROM C_PeriodControl pc2 "
            + "GROUP BY C_Period_ID, DocBaseType "
            + "HAVING COUNT(*) > 1)"
            + " AND C_PeriodControl_ID NOT IN "
            + "(SELECT MIN(C_PeriodControl_ID) "
            + "FROM C_PeriodControl pc3 "
            + "GROUP BY C_Period_ID, DocBaseType)";
    int no = DB.executeUpdate(trx, sql);
    s_log.info("Duplicates deleted #" + no);

    //	Insert Missing
    sql =
        "SELECT DISTINCT p.AD_Client_ID, p.C_Period_ID, dbt.DocBaseType "
            + "FROM C_Period p, "
            + "C_DocBaseType dbt "
            + "WHERE p.AD_Client_ID=? "
            + " AND NOT EXISTS"
            + " (SELECT * FROM C_PeriodControl pc "
            + "WHERE pc.C_Period_ID=p.C_Period_ID AND pc.DocBaseType=dbt.DocBaseType)"
            + " AND (dbt.AD_Client_ID = 0 OR p.AD_Client_ID = dbt.AD_Client_ID)";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    int counter = 0;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, AD_Client_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        int Client_ID = rs.getInt(1);
        int C_Period_ID = rs.getInt(2);
        String DocBaseType = rs.getString(3);
        s_log.config(
            "AD_Client_ID="
                + Client_ID
                + ", C_Period_ID="
                + C_Period_ID
                + ", DocBaseType="
                + DocBaseType);
        //
        MPeriodControl pc = new MPeriodControl(ctx, Client_ID, C_Period_ID, DocBaseType, trx);
        if (pc.save()) {
          counter++;
          s_log.fine(pc.toString());
        } else s_log.warning("Not saved: " + pc);
      }
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    if (sp != null) sp.addLog(0, null, new BigDecimal(counter), "@C_PeriodControl_ID@ @Created@");
    s_log.info("Inserted #" + counter);
  } //	createPeriodControls
  /** 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;
  }