Ejemplo n.º 1
0
 /**
  * Execute Script Loads environment and saves result
  *
  * @return null or Exception
  */
 public Exception execute() {
   m_result = null;
   if (m_variable == null
       || m_variable.length() == 0
       || m_script == null
       || m_script.length() == 0) {
     IllegalArgumentException e = new IllegalArgumentException("No variable/script");
     log.config(e.toString());
     return e;
   }
   Interpreter i = new Interpreter();
   loadEnvironment(i);
   try {
     log.config(m_script);
     i.eval(m_script);
   } catch (Exception e) {
     log.config(e.toString());
     return e;
   }
   try {
     m_result = i.get(m_variable);
     log.config("Result (" + m_result.getClass().getName() + ") " + m_result);
   } catch (Exception e) {
     log.config("Result - " + e);
     if (e instanceof NullPointerException)
       e = new IllegalArgumentException("Result Variable not found - " + m_variable);
     return e;
   }
   return null;
 } //  execute
Ejemplo n.º 2
0
 /**
  * ************************************************************************ 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
Ejemplo n.º 3
0
  /**
   * Is Period Open for Doc Base Type
   *
   * @param DocBaseType document base type
   * @param dateAcct accounting date
   * @return error message or null
   */
  public String isOpen(String DocBaseType, Timestamp dateAcct) {
    if (!isActive()) {
      s_log.warning("Period not active: " + getName());
      return "@C_Period_ID@ <> @IsActive@";
    }

    MAcctSchema as = MClient.get(getCtx(), getAD_Client_ID()).getAcctSchema();
    if (as != null && as.isAutoPeriodControl()) {
      if (!as.isAutoPeriodControlOpen(dateAcct)) return "@PeriodClosed@ - @AutoPeriodControl@";
      //	We are OK
      Timestamp today = new Timestamp(System.currentTimeMillis());
      if (isInPeriod(today) && as.getC_Period_ID() != getC_Period_ID()) {
        as.setC_Period_ID(getC_Period_ID());
        as.save();
      }
      return null;
    }

    //	Standard Period Control
    if (DocBaseType == null) {
      log.warning(getName() + " - No DocBaseType");
      return "@NotFound@ @DocBaseType@";
    }
    MPeriodControl pc = getPeriodControl(DocBaseType);
    if (pc == null) {
      log.warning(getName() + " - Period Control not found for " + DocBaseType);
      return "@NotFound@ @C_PeriodControl_ID@: " + DocBaseType;
    }
    log.fine(getName() + ": " + DocBaseType);
    if (pc.isOpen()) return null;
    return "@PeriodClosed@ - @C_PeriodControl_ID@ (" + DocBaseType + ", " + dateAcct + ")";
  } //	isOpen
Ejemplo n.º 4
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;
  }
Ejemplo n.º 5
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;
  }
  /** Associate Button Pressed */
  private void cmd_associate() {
    int productRow = xProductTable.getSelectedRow();
    log.config("Row=" + productRow);

    KeyNamePair product = (KeyNamePair) xProductTable.getValueAt(productRow, 0);

    doInsert(product.getKey(), 0);

    //  ** Load Table **
    tableInit_option = 1;
    tableInit();
    tableLoad(xAssociateTable);

    //  ** Load Table **
    tableInit_option = 2;
    tableInit();
    tableLoad(xProductTable);

    bDisassociate.setEnabled(true);
    bNewProduct.setEnabled(false);

    // Coloco la referencia como asociada
    // MVMRVendorProdRef vendorProdRef = new MVMRVendorProdRef(Env.getCtx(),
    // LineRefProv.getXX_VMR_VendorProdRef_ID(), null);
    // vendorProdRef.setXX_IsAssociated(true);
    // vendorProdRef.save();

  } //  cmd_associate
Ejemplo n.º 7
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;
  }
Ejemplo n.º 8
0
 /**
  * ************************************************************************ Start Database Process
  *
  * @param ProcedureName PL/SQL procedure name
  * @return true if success
  */
 private boolean startDBProcess(String ProcedureName) {
   //  execute on this thread/connection
   log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")");
   String sql = "{call " + ProcedureName + "(?)}";
   try {
     CallableStatement cstmt = DB.prepareCall(sql, ResultSet.CONCUR_UPDATABLE, null); // 	ro??
     cstmt.setInt(1, m_pi.getAD_PInstance_ID());
     cstmt.executeUpdate();
     cstmt.close();
   } catch (Exception e) {
     log.log(Level.SEVERE, sql, e);
     m_pi.setSummary(Msg.getMsg(m_wscctx, "ProcessRunError") + " " + e.getLocalizedMessage());
     m_pi.setError(true);
     return false;
   }
   //	log.fine(Log.l4_Data, "ProcessCtl.startProcess - done");
   return true;
 } //  startDBProcess
  /**
   * Fill the table using m_sql
   *
   * @param table table
   */
  private static void tableLoad(MiniTable table) {
    //	log.finest(m_sql + " - " +  m_groupBy);
    String sql =
        MRole.getDefault()
                .addAccessSQL(m_sql.toString(), "tab", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
            + m_groupBy
            + m_orderBy;

    log.finest(sql);
    try {
      Statement stmt = DB.createStatement();
      ResultSet rs = stmt.executeQuery(sql);
      table.loadTable(rs);
      stmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    }
  } //  tableLoad
  private void fullAssociated() {

    boolean associated = true;

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where M_product IS NULL AND XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

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

      while (rs.next()) {
        associated = false;
      }

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

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

    if (associated == true) {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='Y'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);

      //			LineRefProv.setXX_ReferenceIsAssociated(true);
      //			LineRefProv.save();

      int dialog = Env.getCtx().getContextAsInt("#Dialog_Associate_Aux");

      if (dialog == 1) {
        ADialog.info(m_WindowNo, m_frame, "MustRefresh");
        Env.getCtx().remove("#Dialog_Associate_Aux");
      }

    } else {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='N'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);
      //			LineRefProv.setXX_ReferenceIsAssociated(false);
      //			LineRefProv.save();
    }
  }
Ejemplo n.º 11
0
 /**
  * ************************************************************************ Start Workflow.
  *
  * @param AD_Workflow_ID workflow
  * @return true if started
  */
 private boolean startWorkflow(int AD_Workflow_ID) {
   log.fine(AD_Workflow_ID + " - " + m_pi);
   boolean started = false;
   if (DB.isRemoteProcess()) {
     log.info("trying to running on the server");
     Server server = CConnection.get().getServer();
     try {
       if (server != null) { // 	See ServerBean
         log.info("running on the server");
         m_pi = server.workflow(m_wscctx, m_pi, AD_Workflow_ID);
         log.finest("server => " + m_pi);
         started = true;
       }
     } catch (Exception ex) {
       log.log(Level.SEVERE, "AppsServer error", ex);
       started = false;
     }
   }
   //	Run locally
   if (!started && !m_IsServerProcess) {
     log.info("running locally");
     MWorkflow wf = MWorkflow.get(m_wscctx, AD_Workflow_ID);
     MWFProcess wfProcess = null;
     if (m_pi.isBatch()) wfProcess = wf.start(m_pi); // 	may return null
     else wfProcess = wf.startWait(m_pi); // 	may return null
     started = wfProcess != null;
   }
   return started;
 } //  startWorkflow
Ejemplo n.º 12
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
Ejemplo n.º 13
0
 /**
  * ************************************************************************ Start Java Process
  * Class. instanciate the class implementing the interface ProcessCall. The class can be a
  * Server/Client class (when in Package org compiere.process or org.compiere.model) or a client
  * only class (e.g. in org.compiere.report)
  *
  * @return true if success
  */
 private boolean startProcess() {
   log.fine(m_pi.toString());
   boolean started = false;
   if (DB.isRemoteProcess()) {
     Server server = CConnection.get().getServer();
     try {
       if (server != null) { // 	See ServerBean
         m_pi = server.process(m_wscctx, m_pi);
         log.finest("server => " + m_pi);
         started = true;
       }
     } catch (UndeclaredThrowableException ex) {
       Throwable cause = ex.getCause();
       if (cause != null) {
         if (cause instanceof InvalidClassException)
           log.log(
               Level.SEVERE, "Version Server <> Client: " + cause.toString() + " - " + m_pi, ex);
         else
           log.log(Level.SEVERE, "AppsServer error(1b): " + cause.toString() + " - " + m_pi, ex);
       } else log.log(Level.SEVERE, " AppsServer error(1) - " + m_pi, ex);
       started = false;
     } catch (Exception ex) {
       Throwable cause = ex.getCause();
       if (cause == null) cause = ex;
       log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause);
       started = false;
     }
   }
   //	Run locally
   if (!started && !m_IsServerProcess) {
     ProcessCall myObject = null;
     try {
       Class myClass = Class.forName(m_pi.getClassName());
       myObject = (ProcessCall) myClass.newInstance();
       if (myObject == null) m_pi.setSummary("No Instance for " + m_pi.getClassName(), true);
       else myObject.startProcess(m_wscctx, m_pi, m_trx);
       if (m_trx != null) {
         m_trx.commit();
         m_trx.close();
       }
     } catch (Exception e) {
       if (m_trx != null) {
         m_trx.rollback();
         m_trx.close();
       }
       m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true);
       log.log(Level.SEVERE, m_pi.getClassName(), e);
     }
   }
   return !m_pi.isError();
 } //  startProcess
Ejemplo n.º 14
0
 /**
  * Set Environment for Interpreter
  *
  * @param i Interpreter
  */
 private void loadEnvironment(Interpreter i) {
   if (m_ctx == null) return;
   Iterator<String> it = m_ctx.keySet().iterator();
   while (it.hasNext()) {
     String key = it.next();
     Object value = m_ctx.get(key);
     try {
       if (value instanceof Boolean) i.set(key, ((Boolean) value).booleanValue());
       else if (value instanceof Integer) i.set(key, ((Integer) value).intValue());
       else if (value instanceof Double) i.set(key, ((Double) value).doubleValue());
       else i.set(key, value);
     } catch (EvalError ee) {
       log.log(Level.SEVERE, "", ee);
     }
   }
 } //  setEnvironment
Ejemplo n.º 15
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;
  }
  /**
   * verifica si hay productos asociados
   *
   * @param table table
   */
  private boolean verify() {
    String sql =
        "SELECT XX_VMR_ReferenceMatrix_ID "
            + "FROM XX_VMR_ReferenceMatrix "
            + "WHERE XX_VMR_PO_LINEREFPROV_ID="
            + (Integer) LineRefProv.getXX_VMR_PO_LineRefProv_ID();

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
      pstmt = DB.prepareStatement(sql, null);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        associatedReference_ID = rs.getInt("XX_VMR_ReferenceMatrix_ID");
        rs.close();
        pstmt.close();
        return true;
      }

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

      try {
        rs.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      try {
        pstmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return false;
  } //  tableLoad
  private boolean isInMatrix() {

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

    PreparedStatement pstmt = null;
    ResultSet rs = null;

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

      while (rs.next()) {
        return true;
      }

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

      try {
        rs.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      try {
        pstmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return false;
  }
Ejemplo n.º 18
0
  /**
   * 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
/**
 * Convert Vendors Reference to BECO products
 *
 * @author José Trías
 * @version
 */
public class XX_AssociateReference_Form extends CPanel
    implements FormPanel, ActionListener, TableModelListener, ListSelectionListener {
  /** */
  private static final long serialVersionUID = 1L;

  /**
   * Initialize Panel
   *
   * @param WindowNo window
   * @param frame frame
   */
  public void init(int WindowNo, FormFrame frame) {
    m_WindowNo = WindowNo;
    m_frame = frame;
    log.info(
        "WinNo="
            + m_WindowNo
            + " - AD_Client_ID="
            + m_AD_Client_ID
            + ", AD_Org_ID="
            + m_AD_Org_ID
            + ", By="
            + m_by);
    Env.getCtx().setIsSOTrx(m_WindowNo, false);

    try {
      //	UI
      jbInit();
      dynInit();
      frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
      frame.getContentPane().add(statusBar, BorderLayout.SOUTH);

    } catch (Exception e) {
      log.log(Level.SEVERE, "", e);
    }
  } //	init

  /** Window No */
  private int m_WindowNo = 0;
  /** FormFrame */
  private FormFrame m_frame;
  /** Logger */
  static CLogger log = CLogger.getCLogger(XX_AssociateReference_Form.class);

  private int m_AD_Client_ID = Env.getCtx().getAD_Client_ID();
  private int m_AD_Org_ID = Env.getCtx().getAD_Org_ID();
  private int m_by = Env.getCtx().getAD_User_ID();

  static StringBuffer m_sql = null;
  static String m_groupBy = "";
  static String m_orderBy = "";

  private static X_XX_VMR_PO_LineRefProv LineRefProv = null;

  private CLabel LineRefProv_Label = new CLabel();
  static Ctx ctx_aux = new Ctx();
  static Integer Product_ID;
  static Integer associatedReference_ID;
  private CPanel mainPanel = new CPanel();
  private StatusBar statusBar = new StatusBar();
  private BorderLayout mainLayout = new BorderLayout();
  private CPanel northPanel = new CPanel();
  private GridBagLayout northLayout = new GridBagLayout();
  private CButton bNewProduct = new CButton();
  private CPanel southPanel = new CPanel();
  private GridBagLayout southLayout = new GridBagLayout();
  private CButton bDisassociate = new CButton();
  private CPanel centerPanel = new CPanel();
  private BorderLayout centerLayout = new BorderLayout(5, 5);
  private JScrollPane xProductScrollPane = new JScrollPane();
  private TitledBorder xProductBorder =
      new TitledBorder(Msg.translate(Env.getCtx(), "SuggestedProducts"));
  private MiniTable xProductTable = new MiniTable();
  private JScrollPane xAssociateScrollPane = new JScrollPane();
  private TitledBorder xAssociateBorder =
      new TitledBorder(Msg.translate(Env.getCtx(), "AssociatedProduct"));
  private MiniTable xAssociateTable = new MiniTable();
  private CPanel xPanel = new CPanel();

  private static int tableInit_option;

  private FlowLayout xLayout = new FlowLayout(FlowLayout.CENTER, 10, 0);

  /**
   * Static Init.
   *
   * <pre>
   *  mainPanel
   *      northPanel
   *      centerPanel
   *          xMatched
   *          xPanel
   *          xMathedTo
   *      southPanel
   *  </pre>
   *
   * @throws Exception
   */
  private void jbInit() throws Exception {
    mainPanel.setLayout(mainLayout);
    northPanel.setLayout(northLayout);

    // LineRefProv_Label.setText(Msg.getMsg(Env.getCtx(), "RecordNo",new String[]
    // {""+LineRefProv.getXX_VMR_PO_LineRefProv_ID()}));
    LineRefProv_Label.setText("");
    southPanel.setLayout(southLayout);
    bNewProduct.setText(Msg.translate(Env.getCtx(), "NewProduct"));
    bNewProduct.setEnabled(true);
    bDisassociate.setText(Msg.translate(Env.getCtx(), "Disassociate"));
    bDisassociate.setEnabled(false);
    centerPanel.setLayout(centerLayout);
    xProductScrollPane.setBorder(xProductBorder);
    xProductScrollPane.setPreferredSize(new Dimension(450, 150));
    xAssociateScrollPane.setBorder(xAssociateBorder);
    xAssociateScrollPane.setPreferredSize(new Dimension(450, 58));

    xPanel.setLayout(xLayout);
    mainPanel.add(northPanel, BorderLayout.NORTH);
    northPanel.add(
        LineRefProv_Label,
        new GridBagConstraints(
            0,
            0,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.EAST,
            GridBagConstraints.NONE,
            new Insets(12, 12, 5, 5),
            0,
            0));

    mainPanel.add(southPanel, BorderLayout.SOUTH);

    mainPanel.add(centerPanel, BorderLayout.CENTER);
    centerPanel.add(xProductScrollPane, BorderLayout.NORTH);
    xProductScrollPane.getViewport().add(xProductTable, null);
    centerPanel.add(xAssociateScrollPane, BorderLayout.SOUTH);
    centerPanel.add(xPanel, BorderLayout.CENTER);
    xAssociateScrollPane.getViewport().add(xAssociateTable, null);

    southPanel.add(
        bDisassociate,
        new GridBagConstraints(
            2,
            0,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.EAST,
            GridBagConstraints.NONE,
            new Insets(5, 12, 5, 12),
            0,
            0));
    southPanel.add(
        bNewProduct,
        new GridBagConstraints(
            8,
            0,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(5, 12, 5, 12),
            0,
            0));
  } //  jbInit

  /** Dynamic Init. Table Layout, Visual, Listener */
  private void dynInit() {

    ColumnInfo[] layout =
        new ColumnInfo[] {
          new ColumnInfo(Msg.translate(Env.getCtx(), "M_Product_ID"), ".", KeyNamePair.class), //  1
          new ColumnInfo(Msg.translate(Env.getCtx(), "Name"), ".", String.class) //  2
        };

    xProductTable.prepareTable(layout, "", "", false, "");
    xAssociateTable.prepareTable(layout, "", "", true, "");

    xAssociateTable.setAutoResizeMode(3);
    xProductTable.setAutoResizeMode(3);

    //  Visual
    CompiereColor.setBackground(this);

    //  Listener
    xProductTable.getSelectionModel().addListSelectionListener(this);
    xAssociateTable.getModel().addTableModelListener(this);
    bDisassociate.addActionListener(this);
    bNewProduct.addActionListener(this);

    // pregunto si hay productos asociados para ver si cargo las tablas
    boolean ready = verify();

    if (ready == false) {

      tableInit_option = 0;
      tableInit();
      tableLoad(xProductTable);

    } else {
      tableInit_option = 1;
      tableInit();
      tableLoad(xAssociateTable);

      bNewProduct.setEnabled(false);
      bDisassociate.setEnabled(true);
    }

    xProductTable.addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {

              int rowP = xProductTable.getSelectedRow();

              if (!(rowP == -1)) {
                cmd_associate();
              }
            }
          }
        });

    //  Init
    statusBar.setStatusLine("");
    statusBar.setStatusDB(0);

    MOrder order = new MOrder(Env.getCtx(), LineRefProv.getC_Order_ID(), null);

    boolean block = false;
    String oS = order.getXX_OrderStatus();
    String compS = order.getDocStatus();
    if (oS.equals("AN") || compS.equals("CO")) {
      block = true;
    }

    if (order.isXX_OrderReadyStatus() && order.getXX_OrderType().equalsIgnoreCase("Nacional"))
      block = true;

    if (order.getXX_OrderType().equalsIgnoreCase("Importada")
        && order.get_ValueAsInt("XX_ImportingCompany_ID") != 0) {

      if (order.get_ValueAsInt("XX_ImportingCompany_ID")
          != Env.getCtx().getContextAsInt("#XX_L_VSI_CLIENTCENTROBECO_ID")) {
        block = true;
      }
    }

    if (order.getXX_StoreDistribution().equals("Y") || block) {
      xProductTable.setEnabled(false);
      xAssociateTable.setEnabled(false);
      bNewProduct.setEnabled(false);
      bDisassociate.setEnabled(false);
    }
  } //  dynInit

  /** Dispose */
  public void dispose() {
    if (m_frame != null) m_frame.dispose();
    m_frame = null;

    MOrder order = new MOrder(Env.getCtx(), LineRefProv.getC_Order_ID(), null);
    String oS = order.getXX_OrderStatus();
    String compS = order.getDocStatus();
    if (!oS.equals("AN") && !compS.equals("CO")) {

      if (isInMatrix()) {

        fullAssociated();

      } else {
        String SQL10 =
            "UPDATE XX_VMR_PO_LineRefProv "
                + " SET XX_ReferenceIsAssociated='N'"
                + " WHERE XX_VMR_PO_LineRefProv_ID="
                + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

        DB.executeUpdate(null, SQL10);
        //				LineRefProv.setXX_ReferenceIsAssociated(false);
        //				LineRefProv.save();
      }
    }

    // pelle

    String SQL =
        ("SELECT A.XX_REFERENCEISASSOCIATED AS ASOCIATE "
            + "FROM XX_VMR_PO_LINEREFPROV A , C_ORDER B "
            + "WHERE A.C_ORDER_ID = B.C_ORDER_ID "
            + "AND A.C_ORDER_ID = '"
            + LineRefProv.getC_Order_ID()
            + "' ");

    try {

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

      BigDecimal cifTotal = new BigDecimal(0);
      Boolean check = true;
      Integer maritimo = 0;
      Integer aereo = 0;
      Integer terrestre = 0;
      BigDecimal montoBs = new BigDecimal(0);
      BigDecimal rate = new BigDecimal(0);
      BigDecimal Seguro = new BigDecimal(0);
      BigDecimal perfleteInt = new BigDecimal(0);
      BigDecimal fleteInternac = new BigDecimal(0);

      Integer productid = 0;
      Integer poline = 0;
      BigDecimal costoitem = new BigDecimal(0);
      BigDecimal porcentitem = new BigDecimal(0);
      BigDecimal cifuni = new BigDecimal(0);
      BigDecimal percentarancel = new BigDecimal(0);
      BigDecimal arancelitem = new BigDecimal(0);
      BigDecimal rateseniat = new BigDecimal(0);
      BigDecimal montoseniat = new BigDecimal(0);
      BigDecimal ratetesoreria = new BigDecimal(0);
      BigDecimal montotesoreria = new BigDecimal(0);
      BigDecimal tasaaduana = new BigDecimal(0);
      BigDecimal part1 = new BigDecimal(0);
      BigDecimal part2 = new BigDecimal(0);
      BigDecimal iva = new BigDecimal(0);
      BigDecimal ivaactual = new BigDecimal(0);
      BigDecimal part = new BigDecimal(0);
      BigDecimal montesorerianac = new BigDecimal(0);

      while (rs.next()) {
        if (rs.getString("ASOCIATE").trim().equalsIgnoreCase("N")) {
          check = false;
        }
      }
      rs.close();
      pstmt.close();
      if (check == true) {

        String SQL2 =
            ("SELECT (A.TOTALLINES * B.MULTIPLYRATE) + A.XX_INTNACESTMEDAMOUNT + A.XX_ESTEEMEDINSURANCEAMOUNT  AS CIFTOTAL "
                + "FROM C_ORDER A, C_CONVERSION_RATE B "
                + "WHERE B.C_CONVERSION_RATE_ID = A.XX_CONVERSIONRATE_ID "
                + "AND A.C_ORDER_ID = '"
                + LineRefProv.getC_Order_ID()
                + "' "
                + "AND A.AD_Client_ID IN(0,"
                + Env.getCtx().getAD_Client_ID()
                + ") "
                + "AND B.AD_Client_ID IN(0,"
                + Env.getCtx().getAD_Client_ID()
                + ")");

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

        if (rs2.next()) {
          // Calculo del CIF Total

          cifTotal = rs2.getBigDecimal("CIFTOTAL");
        }
        rs2.close();
        pstmt2.close();

        // Busco la via de despacho de la O/C
        String SQL3 =
            ("SELECT XX_L_DISPATCHROUTE AS AEREO, XX_L_DISPATCHROUTEMAR AS MARITIMO, XX_L_DISPATCHROUTETER AS TERRESTRE "
                + "FROM XX_VSI_KEYNAMEINFO ");

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

        if (rs3.next()) {
          maritimo = rs3.getInt("MARITIMO");
          terrestre = rs3.getInt("TERRESTRE");
          aereo = rs3.getInt("AEREO");
        }
        rs3.close();
        pstmt3.close();

        String SQL4 =
            ("SELECT (A.TOTALLINES * B.MULTIPLYRATE) AS MONTO "
                + "FROM C_ORDER A, C_CONVERSION_RATE B "
                + "WHERE B.C_CONVERSION_RATE_ID = A.XX_CONVERSIONRATE_ID "
                + "AND A.C_ORDER_ID = '"
                + LineRefProv.getC_Order_ID()
                + "' ");

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

        if (rs4.next()) {
          // Monto de la O/C en Bs
          montoBs = rs4.getBigDecimal("MONTO");
        }
        rs4.close();
        pstmt4.close();

        if (order.getXX_VLO_DispatchRoute_ID() == maritimo) {

          String SQL5 =
              ("SELECT XX_RATE AS RATE "
                  + "FROM XX_VLO_DispatchRoute "
                  + "WHERE XX_VLO_DispatchRoute_ID = '"
                  + maritimo
                  + "' ");

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

          if (rs5.next()) {
            rate = rs5.getBigDecimal("RATE").divide(new BigDecimal(100));
            // (new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // Calculo del Seguro con Via Maritimo
            Seguro = montoBs.multiply(rate);
          }
          rs5.close();
          pstmt5.close();

        } else if (order.getXX_VLO_DispatchRoute_ID() == aereo) {
          String SQL5 =
              ("SELECT XX_RATE AS RATE "
                  + "FROM XX_VLO_DispatchRoute "
                  + "WHERE XX_VLO_DispatchRoute_ID = '"
                  + aereo
                  + "' ");

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

          if (rs5.next()) {
            rate = rs5.getBigDecimal("RATE").divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // Calculo del Seguro con Via aereo
            Seguro = montoBs.multiply(rate);
          }
          rs5.close();
          pstmt5.close();
        } else if (order.getXX_VLO_DispatchRoute_ID() == terrestre) {
          String SQL5 =
              ("SELECT XX_RATE AS RATE "
                  + "FROM XX_VLO_DispatchRoute "
                  + "WHERE XX_VLO_DispatchRoute_ID = '"
                  + terrestre
                  + "' ");

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

          if (rs5.next()) {
            rate = rs5.getBigDecimal("RATE").divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);

            // Calculo del Seguro con Via terrestre
            Seguro = montoBs.multiply(rate);
          }
          rs5.close();
          pstmt5.close();
        }

        // Busco el porcentaje del flete internacional segun el proveedor, puerto y pais de la O/C

        String SQL6 =
            ("SELECT DISTINCT A.XX_INTERFREESTIMATEPERT AS PERTFLEINTER "
                + "FROM XX_VLO_COSTSPERCENT A, C_ORDER B "
                + "WHERE B.XX_VLO_ARRIVALPORT_ID = '"
                + order.getXX_VLO_ArrivalPort_ID()
                + "' "
                + "AND B.C_BPARTNER_ID = '"
                + order.getC_BPartner_ID()
                + "' "
                + "AND B.C_COUNTRY_ID = '"
                + order.getC_Country_ID()
                + "' "
                + "AND B.XX_VLO_ARRIVALPORT_ID = A.XX_VLO_ARRIVALPORT_ID "
                + "AND B.XX_VLO_ARRIVALPORT_ID = A.XX_VLO_ARRIVALPORT_ID "
                + "AND B.C_BPARTNER_ID = A.C_BPARTNER_ID "
                + "AND B.C_COUNTRY_ID = A.C_COUNTRY_ID ");

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

        if (rs6.next()) {
          // Porcentaje del flete internacional
          perfleteInt =
              rs6.getBigDecimal("PERTFLEINTER")
                  .divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
          // Flete Internacional
          fleteInternac = montoBs.multiply(perfleteInt);
        }
        rs6.close();
        pstmt6.close();

        // Busco los productos que tienen asociados las Ref de la O/C

        String SQL7 =
            ("SELECT C.M_PRODUCT AS PRODUCT, A.XX_VMR_PO_LINEREFPROV_ID AS POLINE "
                + "FROM XX_VMR_PO_LINEREFPROV A, C_ORDER B, XX_VMR_REFERENCEMATRIX C "
                + "WHERE A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID "
                + "AND A.C_ORDER_ID = B.C_ORDER_ID "
                + "AND A.C_ORDER_ID = '"
                + LineRefProv.getC_Order_ID()
                + "' ");

        PreparedStatement pstmt7 = DB.prepareStatement(SQL7, null);
        ResultSet rs7 = pstmt7.executeQuery();

        while (rs7.next()) {
          // Calculo del Porcentaje de cada item = costo de cada item Bs / Monto O/C Bs
          productid = rs7.getInt("PRODUCT");
          poline = rs7.getInt("POLINE");

          // Costo de cada item Bs

          /*String SQL8 = ("SELECT (A.XX_UNITPURCHASEPRICE / B.XX_UNITCONVERSION) AS COSTO " +
          "FROM XX_VMR_PO_LINEREFPROV A, XX_VMR_UNITCONVERSION B, XX_VMR_REFERENCEMATRIX C, M_PRODUCT D " +
          "WHERE A.XX_VMR_UNITCONVERSION_ID = B.XX_VMR_UNITCONVERSION_ID " +
          "AND A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID " +
          "AND C.M_PRODUCT = D.M_PRODUCT_ID " +
          "AND C.M_PRODUCT = '"+productid+"' " +
          "AND A.XX_VMR_PO_LINEREFPROV_ID = '"+poline+"' ");*/

          String SQL8 =
              ("SELECT (A.LINENETAMT * E.MULTIPLYRATE) AS COSTO "
                  + "FROM XX_VMR_PO_LINEREFPROV A, XX_VMR_REFERENCEMATRIX C, M_PRODUCT D, C_CONVERSION_RATE E, C_ORDER F  "
                  + "WHERE A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID "
                  + "AND C.M_PRODUCT = D.M_PRODUCT_ID "
                  + "AND E.C_CONVERSION_RATE_ID = F.XX_CONVERSIONRATE_ID "
                  + "AND A.C_ORDER_ID = F.C_ORDER_ID "
                  + "AND C.M_PRODUCT = '"
                  + productid
                  + "' "
                  + "AND A.XX_VMR_PO_LINEREFPROV_ID = '"
                  + poline
                  + "' ");

          PreparedStatement pstmt8 = DB.prepareStatement(SQL8, null);
          ResultSet rs8 = pstmt8.executeQuery();

          if (rs8.next()) {
            costoitem = rs8.getBigDecimal("COSTO");

            // Porcentaje de cada item = costo de cada item Bs / Monto O/C Bs
            porcentitem = (costoitem.divide(montoBs, 8, RoundingMode.HALF_UP));

            // CIF Unitario = Porcentaje de cada Item * CIF total
            cifuni = porcentitem.multiply(cifTotal);

            // Busco Porcentaje Arancelario
            String SQL9 =
                ("SELECT (D.XX_PERCENTAGETARIFF/100) AS PERARANCEL "
                    + "FROM XX_VMR_PO_LINEREFPROV A, C_ORDER B, XX_VMR_REFERENCEMATRIX C, M_PRODUCT D "
                    + "WHERE A.XX_VMR_PO_LINEREFPROV_ID = C.XX_VMR_PO_LINEREFPROV_ID "
                    + "AND A.C_ORDER_ID = B.C_ORDER_ID "
                    + "AND C.M_PRODUCT = D.M_PRODUCT_ID "
                    + "AND D.M_PRODUCT_ID = '"
                    + productid
                    + "' "
                    + "AND A.C_ORDER_ID = '"
                    + LineRefProv.getC_Order_ID()
                    + "' ");

            PreparedStatement pstmt9 = DB.prepareStatement(SQL9, null);
            ResultSet rs9 = pstmt9.executeQuery();

            if (rs9.next()) {
              // Porcentaje Arancelario
              percentarancel = rs9.getBigDecimal("PERARANCEL");

              // Arancel de cada item = CIF unitario * Porcentaje Arancelario
              arancelitem = cifuni.multiply(percentarancel).add(arancelitem);
            }
            rs9.close();
            pstmt9.close();
          }
          rs8.close();
          pstmt8.close();

          // cif total(Creo que no hace falta) t arancel item se usan abajo
        } // end While rs7
        rs7.close();
        pstmt7.close();

        String SQL9 =
            ("SELECT XX_RATE/100 AS RATESENIAT FROM XX_VLO_IMPORTRATE WHERE NAME = 'Tasa de Servicio de aduanas SENIAT' "
                + "And AD_Client_ID IN(0,"
                + Env.getCtx().getAD_Client_ID()
                + ")");

        PreparedStatement pstmt9 = DB.prepareStatement(SQL9, null);
        ResultSet rs9 = pstmt9.executeQuery();

        if (rs9.next()) {
          rateseniat = rs9.getBigDecimal("RATESENIAT");
          montoseniat = arancelitem.multiply(rateseniat);

          String SQL10 =
              ("SELECT XX_RATE/100 AS RATETESORERIA FROM XX_VLO_IMPORTRATE WHERE NAME = 'Tasa de Servicio Aduana Tesorería' "
                  + "And AD_Client_ID IN(0,"
                  + Env.getCtx().getAD_Client_ID()
                  + ")");

          PreparedStatement pstmt10 = DB.prepareStatement(SQL10, null);
          ResultSet rs10 = pstmt10.executeQuery();

          if (rs10.next()) {
            ratetesoreria = rs10.getBigDecimal("RATETESORERIA");
            montotesoreria = arancelitem.multiply(ratetesoreria);

            // Monto Tasa aduanera =monto tasa seniat + monto tasa tesoreria
            tasaaduana = montoseniat.add(montotesoreria);
          }
          rs10.close();
          pstmt10.close();
        }
        rs9.close();
        pstmt9.close();

        // Calculo del IVA = (CIF total + Impuesto de importación + tasa aduanera) *%iva actual

        String SQL11 =
            ("SELECT MAX (VALIDFROM) AS FECHA, A.RATE/100 AS IVACT "
                + "FROM C_TAX A, C_TAXCATEGORY B "
                + "WHERE A.C_TAXCATEGORY_ID = B.C_TAXCATEGORY_ID "
                + "AND B.DESCRIPTION = 'Impuesto al Valor Agregado' "
                + "AND A.C_TAXCATEGORY_ID = B.C_TAXCATEGORY_ID "
                + "GROUP BY A.RATE ");

        PreparedStatement pstmt11 = DB.prepareStatement(SQL11, null);
        ResultSet rs11 = pstmt11.executeQuery();

        if (rs11.next()) {
          part1 = cifTotal.add(arancelitem);
          part2 = part1.add(tasaaduana);
          iva = part2.multiply(rs11.getBigDecimal("IVACT"));
        }
        rs11.close();
        pstmt11.close();

        // Monto tesorería Nacional = IVA + impuesto de importación + monto tasa tesoreria

        part = iva.add(arancelitem);
        montesorerianac = part.add(montotesoreria);

        // redondeo los BigDecimal
        montesorerianac = montesorerianac.setScale(2, BigDecimal.ROUND_UP);
        montoseniat = montoseniat.setScale(2, BigDecimal.ROUND_UP);

        String sql =
            "UPDATE C_Order po"
                + " SET XX_NatTreasuryEstAmount="
                + montesorerianac
                + "    , XX_SENIATESTEEMEDAMUNT="
                + montoseniat
                + " WHERE po.C_Order_ID="
                + LineRefProv.getC_Order_ID();
        DB.executeUpdate(null, sql);

      } // end if Check
      else {
        // alguna referencia no tiene producto asociado
        String sql =
            "UPDATE C_Order po"
                + " SET XX_NatTreasuryEstAmount="
                + 0
                + "    , XX_SENIATESTEEMEDAMUNT="
                + 0
                + " WHERE po.C_Order_ID="
                + LineRefProv.getC_Order_ID();
        DB.executeUpdate(null, sql);
      }

    } // end try
    catch (Exception e) {

    }
  } //	dispose

  /**
   * ************************************************************************ Action Listener
   *
   * @param e event
   */
  public void actionPerformed(ActionEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    if (e.getSource() == bDisassociate) cmd_disassociate();
    else if (e.getSource() == bNewProduct) cmd_newProduct();
  } //  actionPerformed

  /** Associate Button Pressed */
  private void cmd_associate() {
    int productRow = xProductTable.getSelectedRow();
    log.config("Row=" + productRow);

    KeyNamePair product = (KeyNamePair) xProductTable.getValueAt(productRow, 0);

    doInsert(product.getKey(), 0);

    //  ** Load Table **
    tableInit_option = 1;
    tableInit();
    tableLoad(xAssociateTable);

    //  ** Load Table **
    tableInit_option = 2;
    tableInit();
    tableLoad(xProductTable);

    bDisassociate.setEnabled(true);
    bNewProduct.setEnabled(false);

    // Coloco la referencia como asociada
    // MVMRVendorProdRef vendorProdRef = new MVMRVendorProdRef(Env.getCtx(),
    // LineRefProv.getXX_VMR_VendorProdRef_ID(), null);
    // vendorProdRef.setXX_IsAssociated(true);
    // vendorProdRef.save();

  } //  cmd_associate

  /** Disassociate Button Pressed */
  private void cmd_disassociate() {
    if (verify()) {
      // desasocio el producto
      X_XX_VMR_ReferenceMatrix matrix =
          new X_XX_VMR_ReferenceMatrix(Env.getCtx(), associatedReference_ID, null);
      matrix.delete(true);

      tableInit_option = 0;
      tableInit();
      tableLoad(xProductTable);

      tableInit_option = 1;
      tableInit();
      tableLoad(xAssociateTable);

      bDisassociate.setEnabled(false);
      bNewProduct.setEnabled(true);
    }
  } //  cmd_disassociate

  /** Hacer el insert en la tabla REFERENCEMATRIX */
  public void doInsert(int Product, int option) {

    // Asocio producto
    X_XX_VMR_ReferenceMatrix matrix = new X_XX_VMR_ReferenceMatrix(Env.getCtx(), 0, null);

    matrix.setXX_VALUE1(0);
    matrix.setXX_VALUE2(0);
    matrix.setXX_COLUMN(0);
    matrix.setXX_ROW(0);
    matrix.setXX_QUANTITYC(LineRefProv.getQty());
    matrix.setXX_QUANTITYV(LineRefProv.getSaleQty());
    matrix.setXX_QUANTITYO(LineRefProv.getXX_GiftsQty());
    matrix.setXX_VMR_PO_LineRefProv_ID((Integer) LineRefProv.get_Value("XX_VMR_PO_LineRefProv_ID"));
    matrix.setM_Product(Product);

    matrix.save();

    if (option == 1) {

      tableInit_option = 1;
      tableInit();
      tableLoad(xAssociateTable);

      bDisassociate.setEnabled(true);
      bNewProduct.setEnabled(false);
    }
  }

  /** 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

  /** cargar la linea a la cual está relacionada la referencia */
  public static void loadLineRefProv(X_XX_VMR_PO_LineRefProv LineRefProv_aux, Ctx ctx) {
    LineRefProv = LineRefProv_aux;
    ctx_aux = ctx;
  } //	LineRefProv

  /**
   * ************************************************************************ List Selection
   * Listener
   *
   * @param e event
   */
  public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting()) return;
    //	log.config( "VMatch.valueChanged");
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    setCursor(Cursor.getDefaultCursor());
  } //  valueChanged

  /**
   * ************************************************************************* Table Model Listener
   * - calculate matchd Qty
   *
   * @param e event
   */
  public void tableChanged(TableModelEvent e) {
    //  Matched From

    // statusBar.setStatusDB(noRows);
  } //  tableChanged

  /**
   * ************************************************************************ Initialize Table
   * access - create SQL, dateColumn. <br>
   * The driving table is "hdr", e.g. for hdr.C_BPartner_ID=.. The line table is "lin", e.g. for
   * lin.M_Product_ID=.. You use the dateColumn/qtyColumn variable directly as it is table specific.
   * <br>
   * The sql is dependent on MatchMode: - If Matched - all (fully or partially) matched records are
   * listed - If Not Matched - all not fully matched records are listed
   *
   * @param display (Invoice, Shipment, Order) see MATCH_*
   * @param matchToType (Invoice, Shipment, Order) see MATCH_*
   */
  private static void tableInit() {
    m_sql = new StringBuffer();

    if (tableInit_option == 0) {
      m_sql.append(
          "SELECT value,tab.M_Product_ID,tab.Name "
              + "FROM M_Product tab "
              + "WHERE XX_VMR_VENDORPRODREF_ID="
              + LineRefProv.getXX_VMR_VendorProdRef_ID()
              + " "
              + "AND ISACTIVE='Y' "
              + "AND M_ATTRIBUTESET_ID = "
              + Env.getCtx().getContextAsInt("#XX_L_P_ATTRIBUTESETST_ID"));

      /*//Si caracteristica larga es null
      if(LineRefProv.getXX_VMR_LongCharacteristic_ID()!=0)
      {
      	m_sql.append("AND XX_VMR_LONGCHARACTERISTIC_ID="+LineRefProv.getXX_VMR_LongCharacteristic_ID()+" ");
      }
      else{
      	m_sql.append("AND XX_VMR_LONGCHARACTERISTIC_ID IS NULL ");
      }*/

      m_orderBy = " order by M_Product_ID";
    } else if (tableInit_option == 1) {
      m_sql.append(
          "SELECT value,tab.M_Product_ID,tab.Name "
              + "FROM M_Product tab "
              + "WHERE tab.M_Product_ID IN "
              + "(select M_Product from XX_VMR_REFERENCEMATRIX where XX_VMR_PO_LINEREFPROV_ID="
              + (Integer) LineRefProv.getXX_VMR_PO_LineRefProv_ID()
              + ")");
    } else if (tableInit_option == 2) {
      m_sql.append(
          "SELECT value,tab.M_Product_ID,tab.Name "
              + "FROM M_Product tab "
              + "WHERE XX_VMR_VENDORPRODREF_ID = 0 AND M_PRODUCT_ID = 0");
    }
  } //  tableInit

  /**
   * Fill the table using m_sql
   *
   * @param table table
   */
  private static void tableLoad(MiniTable table) {
    //	log.finest(m_sql + " - " +  m_groupBy);
    String sql =
        MRole.getDefault()
                .addAccessSQL(m_sql.toString(), "tab", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
            + m_groupBy
            + m_orderBy;

    log.finest(sql);
    try {
      Statement stmt = DB.createStatement();
      ResultSet rs = stmt.executeQuery(sql);
      table.loadTable(rs);
      stmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    }
  } //  tableLoad

  /**
   * verifica si hay productos asociados
   *
   * @param table table
   */
  private boolean verify() {
    String sql =
        "SELECT XX_VMR_ReferenceMatrix_ID "
            + "FROM XX_VMR_ReferenceMatrix "
            + "WHERE XX_VMR_PO_LINEREFPROV_ID="
            + (Integer) LineRefProv.getXX_VMR_PO_LineRefProv_ID();

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
      pstmt = DB.prepareStatement(sql, null);
      rs = pstmt.executeQuery();

      while (rs.next()) {
        associatedReference_ID = rs.getInt("XX_VMR_ReferenceMatrix_ID");
        rs.close();
        pstmt.close();
        return true;
      }

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

      try {
        rs.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      try {
        pstmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return false;
  } //  tableLoad

  private void fullAssociated() {

    boolean associated = true;

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where M_product IS NULL AND XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

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

      while (rs.next()) {
        associated = false;
      }

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

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

    if (associated == true) {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='Y'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);

      //			LineRefProv.setXX_ReferenceIsAssociated(true);
      //			LineRefProv.save();

      int dialog = Env.getCtx().getContextAsInt("#Dialog_Associate_Aux");

      if (dialog == 1) {
        ADialog.info(m_WindowNo, m_frame, "MustRefresh");
        Env.getCtx().remove("#Dialog_Associate_Aux");
      }

    } else {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='N'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);
      //			LineRefProv.setXX_ReferenceIsAssociated(false);
      //			LineRefProv.save();
    }
  }

  private boolean isInMatrix() {

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

    PreparedStatement pstmt = null;
    ResultSet rs = null;

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

      while (rs.next()) {
        return true;
      }

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

      try {
        rs.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      try {
        pstmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }

    return false;
  }
} //  ConvertReference
  /** 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
Ejemplo n.º 21
0
  /**
   * Execute Process Instance and Lock UI. Calls lockUI and unlockUI if parent is a ASyncProcess
   *
   * <pre>
   * 	- Get Process Information
   *      - Call Class
   * 	- Submit SQL Procedure
   * 	- Run SQL Procedure
   * </pre>
   */
  public void run() {
    log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() + ", Record_ID=" + m_pi.getRecord_ID());

    //  Lock
    // lock();
    //	try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");}
    // catch (Exception e) {}

    //	Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint
    String ProcedureName = "";
    int AD_ReportView_ID = 0;
    int AD_Workflow_ID = 0;
    boolean IsReport = false;
    boolean IsDirectPrint = false;
    //
    String sql =
        "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," //	1..4
            + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," //	5..8
            + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE,"
            + " p.IsServerProcess "
            + "FROM AD_Process p"
            + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) "
            + "WHERE p.IsActive='Y'"
            + " AND i.AD_PInstance_ID=?";
    if (!Env.isBaseLanguage(m_wscctx, "AD_Process"))
      sql =
          "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," //	1..4
              + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," //	5..8
              + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE,"
              + " p.IsServerProcess "
              + "FROM AD_Process p"
              + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) "
              + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID"
              + " AND t.AD_Language='"
              + Env.getAD_Language(m_wscctx)
              + "') "
              + "WHERE p.IsActive='Y'"
              + " AND i.AD_PInstance_ID=?";
    //
    try {
      PreparedStatement pstmt =
          DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null);
      pstmt.setInt(1, m_pi.getAD_PInstance_ID());
      ResultSet rs = pstmt.executeQuery();
      if (rs.next()) {
        m_pi.setTitle(rs.getString(1));
        if (m_waiting != null) m_waiting.setTitle(m_pi.getTitle());
        ProcedureName = rs.getString(2);
        m_pi.setClassName(rs.getString(3));
        m_pi.setAD_Process_ID(rs.getInt(4));
        //	Report
        if ("Y".equals(rs.getString(5))) {
          IsReport = true;
          if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW))
            IsDirectPrint = true;
        }
        AD_ReportView_ID = rs.getInt(7);
        AD_Workflow_ID = rs.getInt(8);
        //
        int estimate = rs.getInt(9);
        if (estimate != 0) {
          m_pi.setEstSeconds(estimate + 1); //  admin overhead
          if (m_waiting != null) m_waiting.setTimerEstimate(m_pi.getEstSeconds());
        }
        m_IsServerProcess = "Y".equals(rs.getString(10));
      } else log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID());
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      m_pi.setSummary(
          Msg.getMsg(m_wscctx, "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true);
      // unlock();
      log.log(Level.SEVERE, "run", e);
      return;
    }

    //  No PL/SQL Procedure
    if (ProcedureName == null) ProcedureName = "";

    /** ******************************************************************** Workflow */
    if (AD_Workflow_ID > 0) {
      startWorkflow(AD_Workflow_ID);
      // unlock();
      return;
    }

    /** ******************************************************************** Start Optional Class */
    if (m_pi.getClassName() != null) {
      //	Run Class
      if (!startProcess()) {
        // unlock();
        return;
      }

      //  No Optional SQL procedure ... done
      if (!IsReport && ProcedureName.length() == 0) {
        // unlock ();
        return;
      }
      //  No Optional Report ... done
      if (IsReport && AD_ReportView_ID == 0) {
        // unlock ();
        return;
      }
    }

    //  If not a report, we need a prodedure name
    if (!IsReport && ProcedureName.length() == 0) {
      m_pi.setSummary(Msg.getMsg(m_wscctx, "ProcessNoProcedure"), true);
      // unlock();
      return;
    }

    /** ******************************************************************** Report submission */
    if (IsReport) {
      //	Optional Pre-Report Process
      if (ProcedureName.length() > 0) {
        if (!startDBProcess(ProcedureName)) {
          // unlock();
          return;
        }
      } //	Pre-Report

      //	Start Report	-----------------------------------------------
      boolean ok = ReportCtl.start(m_pi, IsDirectPrint);
      m_pi.setSummary("Report", !ok);
      // unlock ();
    }
    /** ******************************************************************** Process submission */
    else {
      if (!startDBProcess(ProcedureName)) {
        // unlock();
        return;
      }
      //	Success - getResult
      ProcessInfoUtil.setSummaryFromDB(m_pi);
      // unlock();
    } //	*** Process submission ***
    //	log.fine(Log.l3_Util, "ProcessCtl.run - done");
  } //  run
Ejemplo n.º 22
0
/**
 * Process Interface Controller.
 *
 * @author Jorg Janke
 * @version $Id: WProcessCtl.java,v 1.1 2009/04/15 11:27:15 vinhpt Exp $
 */
public class WProcessCtl extends Thread {
  /**
   * Async Process - Do it all. <code>
   * - Get Instance ID
   * - Get Parameters
   * - execute (lock - start process - unlock)
   *  </code> Creates a ProcessCtl instance, which calls lockUI and unlockUI if parent is a
   * ASyncProcess <br>
   * Called from ProcessCtl.startProcess, ProcessDialog.actionPerformed, APanel.cmd_print,
   * APanel.actionButton, VPaySelect.cmd_generate
   *
   * @param parent ASyncProcess & Container
   * @param WindowNo window no
   * @param pi ProcessInfo process info
   * @param trx Transaction
   * @return worker started ProcessCtl instance or null for workflow
   */
  public static WProcessCtl process(
      Object parent, int WindowNo, ProcessInfo pi, Trx trx, HttpServletRequest request) {
    log.fine("WindowNo=" + WindowNo + " - " + pi);
    WebSessionCtx wsc = WebSessionCtx.get(request);
    MPInstance instance = new MPInstance(wsc.ctx, pi.getAD_Process_ID(), pi.getRecord_ID());

    if (!instance.save()) {
      pi.setSummary(Msg.getMsg(wsc.ctx, "ProcessNoInstance"));
      pi.setError(true);
      return null;
    }
    pi.setAD_PInstance_ID(instance.getAD_PInstance_ID());

    //	Get Parameters (Dialog)
    /**
     * ProcessParameter para = new ProcessParameter (Env.getFrame((Container)parent), WindowNo, pi);
     * if (para.initDialog()) { para.setVisible(true); if (!para.isOK()) { pi.setSummary
     * (Msg.getMsg(Env.getCtx(), "ProcessCancelled")); pi.setError (true); return null; } }
     */
    //	execute
    WProcessCtl worker = new WProcessCtl(parent, pi, trx, wsc.ctx);
    worker.start(); // 	MUST be start!
    return worker;
  } //	execute

  /**
   * ************************************************************************ Constructor
   *
   * @param parent Container & ASyncProcess
   * @param pi Process info
   * @param trx Transaction Created in process(), VInvoiceGen.generateInvoices
   */
  public WProcessCtl(Object parent, ProcessInfo pi, Trx trx, Properties wscctx) {
    m_parent = parent;
    m_pi = pi;
    m_wscctx = wscctx;
    m_trx = trx; // 	handeled correctly
  } //  ProcessCtl

  private Object m_parent;
  private Properties m_wscctx;
  private ProcessInfo m_pi;
  private Trx m_trx;
  private Waiting m_waiting;
  private boolean m_IsServerProcess = false;

  /** Static Logger */
  private static CLogger log = CLogger.getCLogger(WProcessCtl.class);

  /**
   * Execute Process Instance and Lock UI. Calls lockUI and unlockUI if parent is a ASyncProcess
   *
   * <pre>
   * 	- Get Process Information
   *      - Call Class
   * 	- Submit SQL Procedure
   * 	- Run SQL Procedure
   * </pre>
   */
  public void run() {
    log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() + ", Record_ID=" + m_pi.getRecord_ID());

    //  Lock
    // lock();
    //	try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");}
    // catch (Exception e) {}

    //	Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint
    String ProcedureName = "";
    int AD_ReportView_ID = 0;
    int AD_Workflow_ID = 0;
    boolean IsReport = false;
    boolean IsDirectPrint = false;
    //
    String sql =
        "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," //	1..4
            + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," //	5..8
            + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE,"
            + " p.IsServerProcess "
            + "FROM AD_Process p"
            + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) "
            + "WHERE p.IsActive='Y'"
            + " AND i.AD_PInstance_ID=?";
    if (!Env.isBaseLanguage(m_wscctx, "AD_Process"))
      sql =
          "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," //	1..4
              + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," //	5..8
              + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE,"
              + " p.IsServerProcess "
              + "FROM AD_Process p"
              + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) "
              + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID"
              + " AND t.AD_Language='"
              + Env.getAD_Language(m_wscctx)
              + "') "
              + "WHERE p.IsActive='Y'"
              + " AND i.AD_PInstance_ID=?";
    //
    try {
      PreparedStatement pstmt =
          DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null);
      pstmt.setInt(1, m_pi.getAD_PInstance_ID());
      ResultSet rs = pstmt.executeQuery();
      if (rs.next()) {
        m_pi.setTitle(rs.getString(1));
        if (m_waiting != null) m_waiting.setTitle(m_pi.getTitle());
        ProcedureName = rs.getString(2);
        m_pi.setClassName(rs.getString(3));
        m_pi.setAD_Process_ID(rs.getInt(4));
        //	Report
        if ("Y".equals(rs.getString(5))) {
          IsReport = true;
          if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW))
            IsDirectPrint = true;
        }
        AD_ReportView_ID = rs.getInt(7);
        AD_Workflow_ID = rs.getInt(8);
        //
        int estimate = rs.getInt(9);
        if (estimate != 0) {
          m_pi.setEstSeconds(estimate + 1); //  admin overhead
          if (m_waiting != null) m_waiting.setTimerEstimate(m_pi.getEstSeconds());
        }
        m_IsServerProcess = "Y".equals(rs.getString(10));
      } else log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID());
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      m_pi.setSummary(
          Msg.getMsg(m_wscctx, "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true);
      // unlock();
      log.log(Level.SEVERE, "run", e);
      return;
    }

    //  No PL/SQL Procedure
    if (ProcedureName == null) ProcedureName = "";

    /** ******************************************************************** Workflow */
    if (AD_Workflow_ID > 0) {
      startWorkflow(AD_Workflow_ID);
      // unlock();
      return;
    }

    /** ******************************************************************** Start Optional Class */
    if (m_pi.getClassName() != null) {
      //	Run Class
      if (!startProcess()) {
        // unlock();
        return;
      }

      //  No Optional SQL procedure ... done
      if (!IsReport && ProcedureName.length() == 0) {
        // unlock ();
        return;
      }
      //  No Optional Report ... done
      if (IsReport && AD_ReportView_ID == 0) {
        // unlock ();
        return;
      }
    }

    //  If not a report, we need a prodedure name
    if (!IsReport && ProcedureName.length() == 0) {
      m_pi.setSummary(Msg.getMsg(m_wscctx, "ProcessNoProcedure"), true);
      // unlock();
      return;
    }

    /** ******************************************************************** Report submission */
    if (IsReport) {
      //	Optional Pre-Report Process
      if (ProcedureName.length() > 0) {
        if (!startDBProcess(ProcedureName)) {
          // unlock();
          return;
        }
      } //	Pre-Report

      //	Start Report	-----------------------------------------------
      boolean ok = ReportCtl.start(m_pi, IsDirectPrint);
      m_pi.setSummary("Report", !ok);
      // unlock ();
    }
    /** ******************************************************************** Process submission */
    else {
      if (!startDBProcess(ProcedureName)) {
        // unlock();
        return;
      }
      //	Success - getResult
      ProcessInfoUtil.setSummaryFromDB(m_pi);
      // unlock();
    } //	*** Process submission ***
    //	log.fine(Log.l3_Util, "ProcessCtl.run - done");
  } //  run

  /** Lock UI & show Waiting */
  /**
   * private void lock () { // log.info("..."); JFrame frame = Env.getFrame((Container)m_parent); if
   * (frame instanceof AWindow) ((AWindow)frame).setBusyTimer(m_pi.getEstSeconds()); else m_waiting
   * = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, m_pi.getEstSeconds());
   * SwingUtilities.invokeLater(new Runnable() { public void run() { log.finer("lock");
   * m_parent.lockUI(m_pi); } }); if (m_waiting != null) { m_waiting.toFront();
   * m_waiting.setVisible(true); } } // lock
   */
  /** Unlock UI & dispose Waiting. Called from run() */
  /**
   * private void unlock () { // log.info("..."); if (m_pi.isBatch()) m_pi.setIsTimeout(true);
   * SwingUtilities.invokeLater(new Runnable() { public void run() { String summary =
   * m_pi.getSummary(); log.finer("unlock - " + summary); if (summary != null &&
   * summary.indexOf("@") != -1) m_pi.setSummary(Msg.parseTranslation(Env.getCtx(), summary));
   * m_parent.unlockUI(m_pi); } }); // Remove Waiting/Processing Indicator if (m_waiting != null)
   * m_waiting.dispose(); m_waiting = null; } // unlock
   */
  /**
   * ************************************************************************ Start Workflow.
   *
   * @param AD_Workflow_ID workflow
   * @return true if started
   */
  private boolean startWorkflow(int AD_Workflow_ID) {
    log.fine(AD_Workflow_ID + " - " + m_pi);
    boolean started = false;
    if (DB.isRemoteProcess()) {
      log.info("trying to running on the server");
      Server server = CConnection.get().getServer();
      try {
        if (server != null) { // 	See ServerBean
          log.info("running on the server");
          m_pi = server.workflow(m_wscctx, m_pi, AD_Workflow_ID);
          log.finest("server => " + m_pi);
          started = true;
        }
      } catch (Exception ex) {
        log.log(Level.SEVERE, "AppsServer error", ex);
        started = false;
      }
    }
    //	Run locally
    if (!started && !m_IsServerProcess) {
      log.info("running locally");
      MWorkflow wf = MWorkflow.get(m_wscctx, AD_Workflow_ID);
      MWFProcess wfProcess = null;
      if (m_pi.isBatch()) wfProcess = wf.start(m_pi); // 	may return null
      else wfProcess = wf.startWait(m_pi); // 	may return null
      started = wfProcess != null;
    }
    return started;
  } //  startWorkflow

  /**
   * ************************************************************************ Start Java Process
   * Class. instanciate the class implementing the interface ProcessCall. The class can be a
   * Server/Client class (when in Package org compiere.process or org.compiere.model) or a client
   * only class (e.g. in org.compiere.report)
   *
   * @return true if success
   */
  private boolean startProcess() {
    log.fine(m_pi.toString());
    boolean started = false;
    if (DB.isRemoteProcess()) {
      Server server = CConnection.get().getServer();
      try {
        if (server != null) { // 	See ServerBean
          m_pi = server.process(m_wscctx, m_pi);
          log.finest("server => " + m_pi);
          started = true;
        }
      } catch (UndeclaredThrowableException ex) {
        Throwable cause = ex.getCause();
        if (cause != null) {
          if (cause instanceof InvalidClassException)
            log.log(
                Level.SEVERE, "Version Server <> Client: " + cause.toString() + " - " + m_pi, ex);
          else
            log.log(Level.SEVERE, "AppsServer error(1b): " + cause.toString() + " - " + m_pi, ex);
        } else log.log(Level.SEVERE, " AppsServer error(1) - " + m_pi, ex);
        started = false;
      } catch (Exception ex) {
        Throwable cause = ex.getCause();
        if (cause == null) cause = ex;
        log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause);
        started = false;
      }
    }
    //	Run locally
    if (!started && !m_IsServerProcess) {
      ProcessCall myObject = null;
      try {
        Class myClass = Class.forName(m_pi.getClassName());
        myObject = (ProcessCall) myClass.newInstance();
        if (myObject == null) m_pi.setSummary("No Instance for " + m_pi.getClassName(), true);
        else myObject.startProcess(m_wscctx, m_pi, m_trx);
        if (m_trx != null) {
          m_trx.commit();
          m_trx.close();
        }
      } catch (Exception e) {
        if (m_trx != null) {
          m_trx.rollback();
          m_trx.close();
        }
        m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true);
        log.log(Level.SEVERE, m_pi.getClassName(), e);
      }
    }
    return !m_pi.isError();
  } //  startProcess

  /**
   * ************************************************************************ Start Database Process
   *
   * @param ProcedureName PL/SQL procedure name
   * @return true if success
   */
  private boolean startDBProcess(String ProcedureName) {
    //  execute on this thread/connection
    log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")");
    String sql = "{call " + ProcedureName + "(?)}";
    try {
      CallableStatement cstmt = DB.prepareCall(sql, ResultSet.CONCUR_UPDATABLE, null); // 	ro??
      cstmt.setInt(1, m_pi.getAD_PInstance_ID());
      cstmt.executeUpdate();
      cstmt.close();
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
      m_pi.setSummary(Msg.getMsg(m_wscctx, "ProcessRunError") + " " + e.getLocalizedMessage());
      m_pi.setError(true);
      return false;
    }
    //	log.fine(Log.l4_Data, "ProcessCtl.startProcess - done");
    return true;
  } //  startDBProcess
} //	ProcessCtl
Ejemplo n.º 23
0
  /**
   * Before Save. Truncate Dates
   *
   * @param newRecord new
   * @return true
   */
  @Override
  protected boolean beforeSave(boolean newRecord) {
    Timestamp startdate = getStartDate();
    Timestamp enddate = getEndDate();

    if (enddate != null && startdate.after(enddate)) {

      s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodInvalidDate"));
      return false;
    }
    //	Truncate Dates
    startdate = TimeUtil.getDay(startdate);
    setStartDate(startdate);

    if (enddate != null) enddate = TimeUtil.getDay(enddate);
    else enddate = TimeUtil.getMonthLastDay(getStartDate());

    //		Adding the time component of 23:59:59 to the end date
    enddate = new Timestamp(enddate.getTime() + 86399000);
    setEndDate(enddate);

    MPeriod[] periods = getAllPeriodsInYear(getC_Year_ID(), "S", getCtx(), get_Trx());
    MPeriod[] allperiods = getAllPeriodsInCalendar(getC_Calendar_ID(), "S", getCtx(), get_Trx());
    //		Check for non-negative period number
    if (getPeriodNo() < 0) {
      s_log.saveError("Error", Msg.getMsg(getCtx(), "CalNegPeriodNo"));
      return false;
    }

    //		Check for standard period
    if (isStandardPeriod() == true) {
      // Check Period number is in ascending order

      Timestamp nextPeriodStartDate = null;
      Timestamp prevPeriodStartDate = null;

      // Get the next standard period number Start Date in this year
      String sql =
          "SELECT StartDate FROM C_Period WHERE "
              + "C_Period.IsActive='Y' AND PeriodType='S' "
              + "AND C_Period.C_Year_ID =? "
              + "AND C_Period.C_Period_ID <> ?"
              + "AND  C_Period.PeriodNo "
              + " >  ?  ORDER BY  C_Period.PeriodNo ASC";
      Object[][] result = null;
      result =
          QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo());

      if (result.length != 0) nextPeriodStartDate = (Timestamp) result[0][0];

      // Get the previous standard period number Start Date in this year
      sql =
          "SELECT StartDate FROM C_Period WHERE "
              + "C_Period.IsActive='Y' AND PeriodType='S'  "
              + "AND C_Period.C_Year_ID =? "
              + "AND C_Period.C_Period_ID <> ?"
              + "AND C_Period.PeriodNo "
              + "< ?  ORDER BY  C_Period.PeriodNo DESC";

      result =
          QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo());
      if (result.length != 0) prevPeriodStartDate = (Timestamp) result[0][0];

      if ((prevPeriodStartDate != null
          && TimeUtil.max(prevPeriodStartDate, startdate) == prevPeriodStartDate)) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc"));
        return false;
      }

      if ((nextPeriodStartDate != null
          && TimeUtil.max(nextPeriodStartDate, startdate) == startdate)) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc"));
        return false;
      }

      //  Check if the Standard Period is overlapping other periods.

      for (MPeriod period : allperiods) {
        if ((TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true
                || TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true)
            && period.getC_Period_ID() != getC_Period_ID()) {
          s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodOverlap"));
          return false;
        }
      }

    }
    //		Check for adjusting period
    else {
      boolean startflag = false;
      boolean endflag = false;
      for (MPeriod period : periods) {
        if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true)
          startflag = true;
        if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true)
          endflag = true;
        if (startflag == true && endflag == true) break;
      }
      if (startflag == false || endflag == false) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalAdjPeriod"));
        return false;
      }
    }
    return true;
  } //	beforeSave
Ejemplo n.º 24
0
/**
 * Location Region Model (Value Object)
 *
 * @author Jorg Janke
 * @version $Id: MRegion.java 8755 2010-05-12 18:30:14Z nnayak $
 */
public final class MRegion extends X_C_Region implements Comparator<PO>, Serializable {
  /** Logger for class MRegion */
  private static final org.compiere.util.CLogger log =
      org.compiere.util.CLogger.getCLogger(MRegion.class);
  /** */
  private static final long serialVersionUID = 1L;

  /**
   * 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

  /**
   * Get Country (cached)
   *
   * @param ctx context
   * @param C_Region_ID ID
   * @return Country
   */
  public static MRegion get(Ctx ctx, int C_Region_ID) {
    if (s_regions.isEmpty()) loadAllRegions(ctx);
    String key = String.valueOf(C_Region_ID);
    MRegion r = s_regions.get(ctx, key);
    if (r != null) return r;
    r = new MRegion(ctx, C_Region_ID, null);
    if (r.getC_Region_ID() == C_Region_ID) {
      s_regions.put(key, r);
      return r;
    }
    return null;
  } //	get

  /**
   * Get Default Region
   *
   * @param ctx context
   * @return Region or null
   */
  public static MRegion getDefault(Ctx ctx) {
    if (s_regions.isEmpty()) loadAllRegions(ctx);
    return s_default;
  } //	get

  /**
   * Return Regions as Array
   *
   * @param ctx context
   * @return MCountry Array
   */
  public static MRegion[] getRegions(Ctx ctx) {
    if (s_regions.isEmpty()) loadAllRegions(ctx);
    MRegion[] retValue = new MRegion[s_regions.size()];
    s_regions.values().toArray(retValue);
    Arrays.sort(retValue, new MRegion(ctx, 0, null));
    return retValue;
  } //	getRegions

  /**
   * Return Array of Regions of Country
   *
   * @param ctx context
   * @param C_Country_ID country
   * @return MRegion Array
   */
  public static MRegion[] getRegions(Ctx ctx, int C_Country_ID) {
    if (s_regions.isEmpty()) loadAllRegions(ctx);
    ArrayList<MRegion> list = new ArrayList<MRegion>();
    Iterator<MRegion> it = s_regions.values().iterator();
    while (it.hasNext()) {
      MRegion r = it.next();
      if (r.getC_Country_ID() == C_Country_ID) list.add(r);
    }
    //  Sort it
    MRegion[] retValue = new MRegion[list.size()];
    list.toArray(retValue);
    Arrays.sort(retValue, new MRegion(ctx, 0, null));
    return retValue;
  } //	getRegions

  /** Region Cache */
  private static final CCachePerm<String, MRegion> s_regions =
      new CCachePerm<String, MRegion>("C_Region", 100);
  /** Default Region */
  private static MRegion s_default = null;
  /** Static Logger */
  private static CLogger s_log = CLogger.getCLogger(MRegion.class);

  /**
   * ************************************************************************ Create empty Region
   *
   * @param ctx context
   * @param C_Region_ID id
   * @param trx transaction
   */
  public MRegion(Ctx ctx, int C_Region_ID, Trx trx) {
    super(ctx, C_Region_ID, trx);
    if (C_Region_ID == 0) {}
  } //  MRegion

  /**
   * Create Region from current row in ResultSet
   *
   * @param ctx context
   * @param rs result set
   * @param trx transaction
   */
  public MRegion(Ctx ctx, ResultSet rs, Trx trx) {
    super(ctx, rs, trx);
  } //	MRegion

  /**
   * Parent Constructor
   *
   * @param country country
   * @param regionName Region Name
   */
  public MRegion(MCountry country, String regionName) {
    super(country.getCtx(), 0, country.get_Trx());
    setC_Country_ID(country.getC_Country_ID());
    setName(regionName);
  } //  MRegion

  /**
   * Return Name
   *
   * @return Name
   */
  @Override
  public String toString() {
    return getName();
  } //  toString

  /**
   * Compare
   *
   * @param o1 object 1
   * @param o2 object 2
   * @return -1,0, 1
   */
  @Override
  public int compare(PO o1, PO o2) {
    String s1 = o1.toString();
    if (s1 == null) s1 = "";
    String s2 = o2.toString();
    if (s2 == null) s2 = "";
    return s1.compareTo(s2);
  } //	compare

  /**
   * Test / Load
   *
   * @param args
   */
  public static void main(String[] args) {
    Compiere.startup(true);
    /**
     * To add your regions, complete the code below. Please make sure that the file is converted via
     * the Java utility native2ascii - i.e. all seven bit code with /u0000 unicode stuff
     */
    int C_Country_ID = 216; // 	Japan
    MCountry country = new MCountry(Env.getCtx(), C_Country_ID, null);
    // Hokkaido
    MRegion temp = new MRegion(country, "\u5317\u6d77\u9053");
    temp.setDescription("\u5317\u6d77\u9053(Hokkaido)");
    temp.save();
    // Aomori
    temp = new MRegion(country, "\u9752\u68ee\u770c");
    temp.setDescription("\u9752\u68ee\u770c(Aomori)");
    temp.save();
    // Iwate
    temp = new MRegion(country, "\u5ca9\u624b\u770c");
    temp.setDescription("\u5ca9\u624b\u770c(Iwate)");
    temp.save();
    // Miyagi
    temp = new MRegion(country, "\u5bae\u57ce\u770c");
    temp.setDescription("\u5bae\u57ce\u770c(Miyagi)");
    temp.save();
    // Akita
    temp = new MRegion(country, "\u79cb\u7530\u770c");
    temp.setDescription("\u79cb\u7530\u770c(Akita)");
    temp.save();
    // Yamagata
    temp = new MRegion(country, "\u5c71\u5f62\u770c");
    temp.setDescription("\u5c71\u5f62\u770c(Yamagata)");
    temp.save();
    // Fukushima
    temp = new MRegion(country, "\u798f\u5cf6\u770c");
    temp.setDescription("\u798f\u5cf6\u770c(Fukushima)");
    temp.save();
    // Ibaraki
    temp = new MRegion(country, "\u8328\u57ce\u770c");
    temp.setDescription("\u8328\u57ce\u770c(Ibaraki)");
    temp.save();
    // Gunma
    temp = new MRegion(country, "\u7fa4\u99ac\u770c");
    temp.setDescription("\u7fa4\u99ac\u770c(Gunma)");
    temp.save();
    // Saitama
    temp = new MRegion(country, "\u57fc\u7389\u770c");
    temp.setDescription("\u57fc\u7389\u770c(Saitama)");
    temp.save();
    // Chiba
    temp = new MRegion(country, "\u5343\u8449\u770c");
    temp.setDescription("\u5343\u8449\u770c(Chiba)");
    temp.save();
    // Tokyo
    temp = new MRegion(country, "\u6771\u4eac\u90fd");
    temp.setDescription("\u6771\u4eac\u90fd(Tokyo)");
    temp.save();
    // Kanagawa
    temp = new MRegion(country, "\u795e\u5948\u5ddd\u770c");
    temp.setDescription("\u795e\u5948\u5ddd\u770c(Kanagawa)");
    temp.save();
    // Niigata
    temp = new MRegion(country, "\u65b0\u6f5f\u770c");
    temp.setDescription("\u65b0\u6f5f\u770c(Niigata)");
    temp.save();
    // Toyama
    temp = new MRegion(country, "\u5bcc\u5c71\u770c");
    temp.setDescription("\u5bcc\u5c71\u770c(Toyama)");
    temp.save();
    // Ishikawa
    temp = new MRegion(country, "\u77f3\u5ddd\u770c");
    temp.setDescription("\u77f3\u5ddd\u770c(Ishikawa)");
    temp.save();
    // Fukui
    temp = new MRegion(country, "\u798f\u4e95\u770c");
    temp.setDescription("\u798f\u4e95\u770c(Fukui)");
    temp.save();
    // Yamanashi
    temp = new MRegion(country, "\u5c71\u68a8\u770c");
    temp.setDescription("\u5c71\u68a8\u770c(Yamanashi)");
    temp.save();
    // Gifu
    temp = new MRegion(country, "\u5c90\u961c\u770c");
    temp.setDescription("\u5c90\u961c\u770c(Gifu)");
    temp.save();
    // Shizuoka
    temp = new MRegion(country, "\u9759\u5ca1\u770c");
    temp.setDescription("\u9759\u5ca1\u770c(Shizuoka)");
    temp.save();
    // Aichi
    temp = new MRegion(country, "\u611b\u77e5\u770c");
    temp.setDescription("\u611b\u77e5\u770c(Aichi)");
    temp.save();
    // Mie
    temp = new MRegion(country, "\u4e09\u91cd\u770c");
    temp.setDescription("\u4e09\u91cd\u770c(Mie)");
    temp.save();
    // Siga
    temp = new MRegion(country, "\u6ecb\u8cc0\u770c");
    temp.setDescription("\u6ecb\u8cc0\u770c(Siga)");
    temp.save();
    // Kyoto
    temp = new MRegion(country, "\u4eac\u90fd\u5e9c");
    temp.setDescription("\u4eac\u90fd\u5e9c(Kyoto)");
    temp.save();
    // Osaka
    temp = new MRegion(country, "\u5927\u962a\u5e9c");
    temp.setDescription("\u5927\u962a\u5e9c(Osaka)");
    temp.save();
    // Hyogo
    temp = new MRegion(country, "\u5175\u5eab\u770c");
    temp.setDescription("\u5175\u5eab\u770c(Hyogo)");
    temp.save();
    // Nara
    temp = new MRegion(country, "\u5948\u826f\u770c");
    temp.setDescription("\u5948\u826f\u770c(Nara)");
    temp.save();
    // Wakayama
    temp = new MRegion(country, "\u548c\u6b4c\u5c71\u770c");
    temp.setDescription("\u548c\u6b4c\u5c71\u770c(Wakayama)");
    temp.save();
    // Tottori
    temp = new MRegion(country, "\u9ce5\u53d6\u770c");
    temp.setDescription("\u9ce5\u53d6\u770c(Tottori)");
    temp.save();
    // Shimane
    temp = new MRegion(country, "\u5cf6\u6839\u770c");
    temp.setDescription("\u5cf6\u6839\u770c(Shimane)");
    temp.save();
    // Okayama
    temp = new MRegion(country, "\u5ca1\u5c71\u770c");
    temp.setDescription("\u5ca1\u5c71\u770c(Okayama)");
    temp.save();
    // Hiroshima
    temp = new MRegion(country, "\u5e83\u5cf6\u770c");
    temp.setDescription("\u5e83\u5cf6\u770c(Hiroshima)");
    temp.save();
    // Yamaguchi
    temp = new MRegion(country, "\u5c71\u53e3\u770c");
    temp.setDescription("\u5c71\u53e3\u770c(Yamaguchi)");
    temp.save();
    // Tokushima
    temp = new MRegion(country, "\u5fb3\u5cf6\u770c");
    temp.setDescription("\u5fb3\u5cf6\u770c(Tokushima)");
    temp.save();
    // Kagawa
    temp = new MRegion(country, "\u9999\u5ddd\u770c");
    temp.setDescription("\u9999\u5ddd\u770c(Kagawa)");
    temp.save();
    // Ehime
    temp = new MRegion(country, "\u611b\u5a9b\u770c");
    temp.setDescription("\u611b\u5a9b\u770c(Ehime)");
    temp.save();
    // Kouchi
    temp = new MRegion(country, "\u9ad8\u77e5\u770c");
    temp.setDescription("\u9ad8\u77e5\u770c(Kouchi)");
    temp.save();
    // Fukuoka
    temp = new MRegion(country, "\u798f\u5ca1\u770c");
    temp.setDescription("\u798f\u5ca1\u770c(Fukuoka)");
    temp.save();
    // Saga
    temp = new MRegion(country, "\u4f50\u8cc0\u770c");
    temp.setDescription("\u4f50\u8cc0\u770c(Saga)");
    temp.save();
    // Nagasaki
    temp = new MRegion(country, "\u9577\u5d0e\u770c");
    temp.setDescription("\u9577\u5d0e\u770c(Nagasaki)");
    temp.save();
    // Kumamoto
    temp = new MRegion(country, "\u718a\u672c\u770c");
    temp.setDescription("\u718a\u672c\u770c(Kumamoto)");
    temp.save();
    // Ohita
    temp = new MRegion(country, "\u5927\u5206\u770c");
    temp.setDescription("\u5927\u5206\u770c(Ohita)");
    temp.save();
    // Miyasaki
    temp = new MRegion(country, "\u5bae\u5d0e\u770c");
    temp.setDescription("\u5bae\u5d0e\u770c(Miyasaki)");
    temp.save();
    // Kagoshima
    temp = new MRegion(country, "\u9e7f\u5150\u5cf6\u770c");
    temp.setDescription("\u9e7f\u5150\u5cf6\u770c(Kagoshima)");
    temp.save();
    // Okinawa
    temp = new MRegion(country, "\u6c96\u7e04\u770c");
    temp.setDescription("\u6c96\u7e04\u770c(Okinawa)");
    temp.save();
  } //	main
} //	MRegion
Ejemplo n.º 25
0
/**
 * Calendar Period Model
 *
 * @author Jorg Janke
 * @version $Id: MPeriod.java,v 1.4 2006/07/30 00:51:05 jjanke Exp $
 */
public class MPeriod extends X_C_Period {
  /** Logger for class MPeriod */
  private static final org.compiere.util.CLogger log =
      org.compiere.util.CLogger.getCLogger(MPeriod.class);
  /** */
  private static final long serialVersionUID = 1L;

  /**
   * Get Period from Cache
   *
   * @param ctx context
   * @param C_Period_ID id
   * @return MPeriod
   */
  public static MPeriod get(Ctx ctx, int C_Period_ID) {
    Integer key = Integer.valueOf(C_Period_ID);
    MPeriod retValue = s_cache.get(ctx, key);
    if (retValue != null) return retValue;
    //
    retValue = new MPeriod(ctx, C_Period_ID, null);
    if (retValue.get_ID() != 0) s_cache.put(key, retValue);
    return retValue;
  } //	get

  /**
   * Find standard Period of DateAcct based on Client Calendar
   *
   * @param ctx context
   * @param DateAcct date
   * @return active Period or null
   */
  public static MPeriod getOfOrg(Ctx ctx, int AD_Org_ID, Timestamp DateAcct) {
    int C_Calendar_ID = 0;
    if (AD_Org_ID != 0) {
      MOrgInfo info = MOrgInfo.get(ctx, AD_Org_ID, null);
      C_Calendar_ID = info.getC_Calendar_ID();
    }
    if (C_Calendar_ID == 0) {
      MClientInfo cInfo = MClientInfo.get(ctx);
      C_Calendar_ID = cInfo.getC_Calendar_ID();
    }

    return getOfCalendar(ctx, C_Calendar_ID, DateAcct);
  } //	get

  /**
   * 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

  /**
   * Find valid standard Period of DateAcct based on Client Calendar
   *
   * @param ctx context
   * @param DateAcct date
   * @return C_Period_ID or 0
   */
  public static int getC_Period_ID(Ctx ctx, int AD_Org_ID, Timestamp DateAcct) {
    MPeriod period = getOfOrg(ctx, AD_Org_ID, DateAcct);
    if (period == null) return 0;
    return period.getC_Period_ID();
  } //	getC_Period_ID

  /**
   * Is standard Period Open for Document Base Type - does not check Orgs
   *
   * @param ctx context
   * @param DateAcct date
   * @param DocBaseType base type
   * @return true if open
   * @deprecated use new isOpen
   */
  @Deprecated
  public static boolean isOpenOld(Ctx ctx, Timestamp DateAcct, String DocBaseType) {
    if (DateAcct == null) {
      s_log.warning("No DateAcct");
      return false;
    }
    if (DocBaseType == null) {
      s_log.warning("No DocBaseType");
      return false;
    }
    MPeriod period = MPeriod.getOfOrg(ctx, 0, DateAcct);
    if (period == null) {
      s_log.warning("No Period for " + DateAcct + " (" + DocBaseType + ")");
      return false;
    }
    String error = period.isOpen(DocBaseType, DateAcct);
    if (error != null) s_log.warning(error + " - " + period.getName());
    return error == null;
  } //	isOpen

  /**
   * Is standard Period Open for specified orgs for the client. For best performance, ensure that
   * the list of orgs does not contain duplicates.
   *
   * @param ctx
   * @param AD_Client_ID
   * @param orgs
   * @param DateAcct accounting date
   * @param DocBaseType document base type
   * @return error message or null
   */
  public static String isOpen(
      Ctx ctx, int AD_Client_ID, ArrayList<Integer> orgs, Timestamp DateAcct, String DocBaseType) {
    if (DateAcct == null) return "@NotFound@ @DateAcct@";
    if (DocBaseType == null) return "@NotFound@ @DocBaseType@";

    MAcctSchema as = MClient.get(ctx, AD_Client_ID).getAcctSchema();
    if (as == null) return "@NotFound@ @C_AcctSchema_ID@ for AD_Client_ID=" + AD_Client_ID;
    if (as.isAutoPeriodControl()) {
      if (as.isAutoPeriodControlOpen(DateAcct)) return null;
      else return "@PeriodClosed@ - @AutoPeriodControl@";
    }

    //	Get all Calendars in line with Organizations
    MClientInfo clientInfo = MClientInfo.get(ctx, AD_Client_ID, null);
    ArrayList<Integer> orgCalendars = new ArrayList<Integer>();
    ArrayList<Integer> calendars = new ArrayList<Integer>();
    for (int org : orgs) {
      MOrgInfo orgInfo = MOrgInfo.get(ctx, org, null);
      int C_Calendar_ID = orgInfo.getC_Calendar_ID();
      if (C_Calendar_ID == 0) C_Calendar_ID = clientInfo.getC_Calendar_ID();
      orgCalendars.add(C_Calendar_ID);
      if (!calendars.contains(C_Calendar_ID)) calendars.add(C_Calendar_ID);
    }
    //	Should not happen
    if (calendars.size() == 0) return "@NotFound@ @C_Calendar_ID@";

    //	For all Calendars get Periods
    for (int i = 0; i < calendars.size(); i++) {
      int C_Calendar_ID = calendars.get(i);
      MPeriod period = MPeriod.getOfCalendar(ctx, C_Calendar_ID, DateAcct);
      //	First Org for Calendar
      int AD_Org_ID = 0;
      for (int j = 0; j < orgCalendars.size(); j++) {
        if (orgCalendars.get(j) == C_Calendar_ID) {
          AD_Org_ID = orgs.get(j);
          break;
        }
      }
      if (period == null) {
        MCalendar cal = MCalendar.get(ctx, C_Calendar_ID);
        String date = DisplayType.getDateFormat(DisplayTypeConstants.Date).format(DateAcct);
        if (cal != null)
          return "@NotFound@ @C_Period_ID@: "
              + date
              + " - "
              + MOrg.get(ctx, AD_Org_ID).getName()
              + " -> "
              + cal.getName();
        else
          return "@NotFound@ @C_Period_ID@: "
              + date
              + " - "
              + MOrg.get(ctx, AD_Org_ID).getName()
              + " -> C_Calendar_ID="
              + C_Calendar_ID;
      }
      String error = period.isOpen(DocBaseType, DateAcct);
      if (error != null)
        return error
            + " - "
            + MOrg.get(ctx, AD_Org_ID).getName()
            + " -> "
            + MCalendar.get(ctx, C_Calendar_ID).getName();
    }
    return null; //	open
  } //	isOpen

  /**
   * Is standard Period Open for Document Base Type
   *
   * @param header header document record
   * @param lines document lines optional
   * @param DateAcct accounting date
   * @param DocBaseType document base type
   * @return error message or null
   */
  @Deprecated
  public static String isOpen(PO header, PO[] lines, Timestamp DateAcct, String DocBaseType) {

    // Get All Orgs
    ArrayList<Integer> orgs = new ArrayList<Integer>();
    orgs.add(header.getAD_Org_ID());
    if (lines != null) {
      for (PO line : lines) {
        int AD_Org_ID = line.getAD_Org_ID();
        if (!orgs.contains(AD_Org_ID)) orgs.add(AD_Org_ID);
      }
    }

    return isOpen(header.getCtx(), header.getAD_Client_ID(), orgs, DateAcct, DocBaseType);
  } // isOpen

  /**
   * Is standard Period closed for all Document Base Types
   *
   * @param ctx context for AD_Client
   * @param DateAcct accounting date
   * @return true if closed
   */
  public static boolean isClosed(Ctx ctx, Timestamp DateAcct) {
    if (DateAcct == null) return false;
    MAcctSchema as = MClient.get(ctx, ctx.getAD_Client_ID()).getAcctSchema();
    if (as.isAutoPeriodControl()) return !as.isAutoPeriodControlOpen(DateAcct);

    //	Get all Calendars in line with Organizations
    MClientInfo cInfo = MClientInfo.get(ctx, ctx.getAD_Client_ID(), null);
    ArrayList<Integer> calendars = new ArrayList<Integer>();
    MOrg[] orgs = MOrg.getOfClient(cInfo);
    for (MOrg org : orgs) {
      MOrgInfo info = MOrgInfo.get(ctx, org.getAD_Org_ID(), null);
      int C_Calendar_ID = info.getC_Calendar_ID();
      if (C_Calendar_ID == 0) C_Calendar_ID = cInfo.getC_Calendar_ID();
      if (!calendars.contains(C_Calendar_ID)) calendars.add(C_Calendar_ID);
    }
    //	Should not happen
    if (calendars.size() == 0) throw new IllegalArgumentException("@NotFound@ @C_Calendar_ID@");

    //	For all Calendars get Periods
    for (int i = 0; i < calendars.size(); i++) {
      int C_Calendar_ID = calendars.get(i);
      MPeriod period = MPeriod.getOfCalendar(ctx, C_Calendar_ID, DateAcct);
      //	Period not found
      if (period == null) return false;
      if (!period.isClosed()) return false;
    }
    return true; //	closed
  } //	isClosed

  /**
   * 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

  /** Cache */
  private static final CCache<Integer, MPeriod> s_cache =
      new CCache<Integer, MPeriod>("C_Period", 10);

  /** Logger */
  private static final CLogger s_log = CLogger.getCLogger(MPeriod.class);

  /**
   * ************************************************************************ Standard Constructor
   *
   * @param ctx context
   * @param C_Period_ID id
   * @param trx transaction
   */
  public MPeriod(Ctx ctx, int C_Period_ID, Trx trx) {
    super(ctx, C_Period_ID, trx);
    if (C_Period_ID == 0) {
      //	setC_Period_ID (0);		//	PK
      //  setC_Year_ID (0);		//	Parent
      //  setName (null);
      //  setPeriodNo (0);
      //  setStartDate (new Timestamp(System.currentTimeMillis()));
      setPeriodType(PERIODTYPE_StandardCalendarPeriod);
    }
  } //	MPeriod

  /**
   * Load Constructor
   *
   * @param ctx context
   * @param rs result set
   * @param trx transaction
   */
  public MPeriod(Ctx ctx, ResultSet rs, Trx trx) {
    super(ctx, rs, trx);
  } //	MPeriod

  /**
   * Parent constructor
   *
   * @param year year
   * @param PeriodNo no
   * @param name name
   * @param startDate start
   * @param endDate end
   */
  public MPeriod(MYear year, int PeriodNo, String name, Timestamp startDate, Timestamp endDate) {
    this(year.getCtx(), 0, year.get_Trx());
    setClientOrg(year);
    setC_Year_ID(year.getC_Year_ID());
    setPeriodNo(PeriodNo);
    setName(name);
    setStartDate(startDate);
    setEndDate(endDate);
  } //	MPeriod

  /** Period Controls */
  private MPeriodControl[] m_controls = null;
  /** Calendar */
  private int m_C_Calendar_ID = 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

  /**
   * Get Period Control
   *
   * @param DocBaseType Document Base Type
   * @return period control or null
   */
  public MPeriodControl getPeriodControl(String DocBaseType) {
    if (DocBaseType == null) return null;
    getPeriodControls(false);
    for (MPeriodControl element : m_controls) {
      //	log.fine("getPeriodControl - " + 1 + " - " + m_controls[i]);
      if (DocBaseType.equals(element.getDocBaseType())) return element;
    }
    return null;
  } //	getPeriodControl

  /**
   * Date In Period
   *
   * @param date date
   * @return true if in period
   */
  public boolean isInPeriod(Timestamp date) {
    if (date == null) return false;
    Timestamp dateOnly = TimeUtil.getDay(date);
    Timestamp from = TimeUtil.getDay(getStartDate());
    if (dateOnly.before(from)) return false;
    Timestamp to = TimeUtil.getDay(getEndDate());
    if (dateOnly.after(to)) return false;
    return true;
  } //	isInPeriod

  /**
   * Is Period Open for Doc Base Type
   *
   * @param DocBaseType document base type
   * @param dateAcct accounting date
   * @return error message or null
   */
  public String isOpen(String DocBaseType, Timestamp dateAcct) {
    if (!isActive()) {
      s_log.warning("Period not active: " + getName());
      return "@C_Period_ID@ <> @IsActive@";
    }

    MAcctSchema as = MClient.get(getCtx(), getAD_Client_ID()).getAcctSchema();
    if (as != null && as.isAutoPeriodControl()) {
      if (!as.isAutoPeriodControlOpen(dateAcct)) return "@PeriodClosed@ - @AutoPeriodControl@";
      //	We are OK
      Timestamp today = new Timestamp(System.currentTimeMillis());
      if (isInPeriod(today) && as.getC_Period_ID() != getC_Period_ID()) {
        as.setC_Period_ID(getC_Period_ID());
        as.save();
      }
      return null;
    }

    //	Standard Period Control
    if (DocBaseType == null) {
      log.warning(getName() + " - No DocBaseType");
      return "@NotFound@ @DocBaseType@";
    }
    MPeriodControl pc = getPeriodControl(DocBaseType);
    if (pc == null) {
      log.warning(getName() + " - Period Control not found for " + DocBaseType);
      return "@NotFound@ @C_PeriodControl_ID@: " + DocBaseType;
    }
    log.fine(getName() + ": " + DocBaseType);
    if (pc.isOpen()) return null;
    return "@PeriodClosed@ - @C_PeriodControl_ID@ (" + DocBaseType + ", " + dateAcct + ")";
  } //	isOpen

  /**
   * Return true if all PC are closed
   *
   * @return true if closed
   */
  public boolean isClosed() {
    MPeriodControl[] pcs = getPeriodControls(false);
    for (MPeriodControl pc : pcs) {
      if (!pc.isClosed()) return false;
    }
    return true;
  } //	isClosed

  /**
   * Standard Period
   *
   * @return true if standard calendar period
   */
  public boolean isStandardPeriod() {
    return PERIODTYPE_StandardCalendarPeriod.equals(getPeriodType());
  } //	isStandardPeriod

  /**
   * Get Calendar of Period
   *
   * @return calendar
   */
  public int getC_Calendar_ID() {
    if (m_C_Calendar_ID == 0) {
      MYear year = MYear.get(getCtx(), getC_Year_ID());
      if (year != null) m_C_Calendar_ID = year.getC_Calendar_ID();
      else log.severe("@NotFound@ C_Year_ID=" + getC_Year_ID());
    }
    return m_C_Calendar_ID;
  } //	getC_Calendar_ID

  /**
   * Before Save. Truncate Dates
   *
   * @param newRecord new
   * @return true
   */
  @Override
  protected boolean beforeSave(boolean newRecord) {
    Timestamp startdate = getStartDate();
    Timestamp enddate = getEndDate();

    if (enddate != null && startdate.after(enddate)) {

      s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodInvalidDate"));
      return false;
    }
    //	Truncate Dates
    startdate = TimeUtil.getDay(startdate);
    setStartDate(startdate);

    if (enddate != null) enddate = TimeUtil.getDay(enddate);
    else enddate = TimeUtil.getMonthLastDay(getStartDate());

    //		Adding the time component of 23:59:59 to the end date
    enddate = new Timestamp(enddate.getTime() + 86399000);
    setEndDate(enddate);

    MPeriod[] periods = getAllPeriodsInYear(getC_Year_ID(), "S", getCtx(), get_Trx());
    MPeriod[] allperiods = getAllPeriodsInCalendar(getC_Calendar_ID(), "S", getCtx(), get_Trx());
    //		Check for non-negative period number
    if (getPeriodNo() < 0) {
      s_log.saveError("Error", Msg.getMsg(getCtx(), "CalNegPeriodNo"));
      return false;
    }

    //		Check for standard period
    if (isStandardPeriod() == true) {
      // Check Period number is in ascending order

      Timestamp nextPeriodStartDate = null;
      Timestamp prevPeriodStartDate = null;

      // Get the next standard period number Start Date in this year
      String sql =
          "SELECT StartDate FROM C_Period WHERE "
              + "C_Period.IsActive='Y' AND PeriodType='S' "
              + "AND C_Period.C_Year_ID =? "
              + "AND C_Period.C_Period_ID <> ?"
              + "AND  C_Period.PeriodNo "
              + " >  ?  ORDER BY  C_Period.PeriodNo ASC";
      Object[][] result = null;
      result =
          QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo());

      if (result.length != 0) nextPeriodStartDate = (Timestamp) result[0][0];

      // Get the previous standard period number Start Date in this year
      sql =
          "SELECT StartDate FROM C_Period WHERE "
              + "C_Period.IsActive='Y' AND PeriodType='S'  "
              + "AND C_Period.C_Year_ID =? "
              + "AND C_Period.C_Period_ID <> ?"
              + "AND C_Period.PeriodNo "
              + "< ?  ORDER BY  C_Period.PeriodNo DESC";

      result =
          QueryUtil.executeQuery(get_Trx(), sql, getC_Year_ID(), getC_Period_ID(), getPeriodNo());
      if (result.length != 0) prevPeriodStartDate = (Timestamp) result[0][0];

      if ((prevPeriodStartDate != null
          && TimeUtil.max(prevPeriodStartDate, startdate) == prevPeriodStartDate)) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc"));
        return false;
      }

      if ((nextPeriodStartDate != null
          && TimeUtil.max(nextPeriodStartDate, startdate) == startdate)) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodAsc"));
        return false;
      }

      //  Check if the Standard Period is overlapping other periods.

      for (MPeriod period : allperiods) {
        if ((TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true
                || TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true)
            && period.getC_Period_ID() != getC_Period_ID()) {
          s_log.saveError("Error", Msg.getMsg(getCtx(), "CalPeriodOverlap"));
          return false;
        }
      }

    }
    //		Check for adjusting period
    else {
      boolean startflag = false;
      boolean endflag = false;
      for (MPeriod period : periods) {
        if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), startdate) == true)
          startflag = true;
        if (TimeUtil.isValid(period.getStartDate(), period.getEndDate(), enddate) == true)
          endflag = true;
        if (startflag == true && endflag == true) break;
      }
      if (startflag == false || endflag == false) {
        s_log.saveError("Error", Msg.getMsg(getCtx(), "CalAdjPeriod"));
        return false;
      }
    }
    return true;
  } //	beforeSave

  /**
   * After Save
   *
   * @param newRecord new
   * @param success success
   * @return success
   */
  @Override
  protected boolean afterSave(boolean newRecord, boolean success) {
    if (newRecord) {
      //	SELECT Value FROM AD_Ref_List WHERE AD_Reference_ID=183
      MDocType[] types = MDocType.getOfClient(getCtx());
      int count = 0;
      ArrayList<String> baseTypes = new ArrayList<String>();
      for (MDocType type : types) {
        String DocBaseType = type.getDocBaseType();
        if (baseTypes.contains(DocBaseType)) continue;
        MPeriodControl pc = new MPeriodControl(this, DocBaseType);
        if (pc.save()) count++;
        baseTypes.add(DocBaseType);
      }
      log.fine("PeriodControl #" + count);
    }
    return success;
  } //	afterSave

  /**
   * String Representation
   *
   * @return info
   */
  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer("MPeriod[");
    sb.append(get_ID())
        .append("-")
        .append(getName())
        .append(", ")
        .append(getStartDate())
        .append("-")
        .append(getEndDate())
        .append("]");
    return sb.toString();
  } //	toString

  /**
   * Returns the next period forward
   *
   * @param period MPeriod
   * @param trx trx
   * @param ctx Ctx
   * @return MPeriod
   */
  public static MPeriod getNextPeriod(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 ASC, C_Period.PeriodNo ASC";

    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;
  }

  /**
   * 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;
  }

  /**
   * 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;
  }

  /**
   * 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

  /**
   * Find the periods in a calendar it need not be a standard period (used in MRP)
   *
   * @param C_Calendar_ID calendar
   * @param periodType Period Type
   * @param ctx context
   * @param trx trx
   * @return MPeriod[]
   */
  public static MPeriod[] getAllPeriodsInCalendar(
      int C_Calendar_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 IN ( SELECT C_Year_ID FROM C_Year WHERE C_Calendar_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_Calendar_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;
  }

  /**
   * 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;
  }

  /**
   * 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;
  }
} //	MPeriod
Ejemplo n.º 26
0
/**
 * Script Model
 *
 * @author Jorg Janke
 * @version $Id: Scriptlet.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
 */
public class Scriptlet {
  /**
   * Run Script
   *
   * @param variable
   * @param script
   * @param ctx
   * @param WindowNo Included Window variables
   * @return result
   */
  static Object run(String variable, String script, Ctx ctx, int WindowNo) {
    Scriptlet scr = new Scriptlet(variable, script, ctx, WindowNo);
    scr.execute();
    return scr.getResult(false);
  } //  run

  /** Constructor */
  public Scriptlet() {
    this(VARIABLE, "", Env.getCtx(), 0);
  } //  Scriptlet

  /** Default Result Variable Name */
  public static final String VARIABLE = "result";

  /** Logger */
  private static CLogger log = CLogger.getCLogger(Scriptlet.class);

  /**
   * Full Constructor
   *
   * @param variable Variable Name
   * @param script The Script
   * @param ctx Context
   * @param WindowNo Included Window variables
   */
  public Scriptlet(String variable, String script, Ctx ctx, int WindowNo) {
    setVariable(variable);
    setScript(script);
    setEnvironment(ctx, WindowNo);
  } //  Scriptlet

  /**
   * Full Constructor
   *
   * @param variable Variable Name
   * @param script The Script
   * @param ctx Environment
   */
  public Scriptlet(String variable, String script, HashMap<String, Object> ctx) {
    setVariable(variable);
    setScript(script);
    setEnvironment(ctx);
  } //  Scriptlet

  /** Variable */
  private String m_variable;
  /** Script */
  private String m_script;
  /** Context */
  private HashMap<String, Object> m_ctx;
  /** Result */
  private Object m_result;

  /** ********************************************************************** */

  /**
   * Execute Script Loads environment and saves result
   *
   * @return null or Exception
   */
  public Exception execute() {
    m_result = null;
    if (m_variable == null
        || m_variable.length() == 0
        || m_script == null
        || m_script.length() == 0) {
      IllegalArgumentException e = new IllegalArgumentException("No variable/script");
      log.config(e.toString());
      return e;
    }
    Interpreter i = new Interpreter();
    loadEnvironment(i);
    try {
      log.config(m_script);
      i.eval(m_script);
    } catch (Exception e) {
      log.config(e.toString());
      return e;
    }
    try {
      m_result = i.get(m_variable);
      log.config("Result (" + m_result.getClass().getName() + ") " + m_result);
    } catch (Exception e) {
      log.config("Result - " + e);
      if (e instanceof NullPointerException)
        e = new IllegalArgumentException("Result Variable not found - " + m_variable);
      return e;
    }
    return null;
  } //  execute

  /**
   * Set Environment for Interpreter
   *
   * @param i Interpreter
   */
  private void loadEnvironment(Interpreter i) {
    if (m_ctx == null) return;
    Iterator<String> it = m_ctx.keySet().iterator();
    while (it.hasNext()) {
      String key = it.next();
      Object value = m_ctx.get(key);
      try {
        if (value instanceof Boolean) i.set(key, ((Boolean) value).booleanValue());
        else if (value instanceof Integer) i.set(key, ((Integer) value).intValue());
        else if (value instanceof Double) i.set(key, ((Double) value).doubleValue());
        else i.set(key, value);
      } catch (EvalError ee) {
        log.log(Level.SEVERE, "", ee);
      }
    }
  } //  setEnvironment

  /** ********************************************************************** */

  /**
   * Get Variable
   *
   * @return variable
   */
  public String getVariable() {
    return m_variable;
  } //  getVariable

  /**
   * Set Variable
   *
   * @param variable - if null set to VARIABLE
   */
  public void setVariable(String variable) {
    if (variable == null || variable.length() == 0) m_variable = VARIABLE;
    else m_variable = variable;
  }

  /**
   * Set Script
   *
   * @param script
   */
  public void setScript(String script) {
    if (script == null) m_script = "";
    else m_script = script;
  } //  setScript

  /**
   * Get Script
   *
   * @return script
   */
  public String getScript() {
    return m_script;
  } //  getScript

  /**
   * Set Environment
   *
   * @param prop
   * @param WindowNo included Window variables
   */
  public void setEnvironment(Ctx prop, int WindowNo) {
    if (prop == null) prop = Env.getCtx();

    m_ctx = new HashMap<String, Object>();
    //  Convert properties to HashMap
    Iterator<String> it = prop.keySet().iterator();
    while (it.hasNext()) {
      String key = it.next();
      //  filter
      if (key == null
          || key.length() == 0
          || key.startsWith("P") //  Preferences
          || (key.indexOf("|") != -1
              && !key.startsWith(String.valueOf(WindowNo))) //  other Window Settings
      ) continue;

      String value = prop.getContext(key);
      setEnvironment(key, value);
    }
  } //  setEnvironment

  /**
   * Set Environment key to value
   *
   * @param key variable name ('#' will be converted to '_')
   * @param stringValue try to convert to Object
   */
  public void setEnvironment(String key, String stringValue) {
    if (key == null || key.length() == 0) return;
    //	log.fine( "Scriptlet.setEnvironment " + key, stringValue);
    if (stringValue == null) {
      m_ctx.remove(key);
      return;
    }

    //  Boolean
    if (stringValue.equals("Y")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(true));
      return;
    }
    if (stringValue.equals("N")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(false));
      return;
    }

    //  Timestamp
    Timestamp timeValue = null;
    try {
      timeValue = Timestamp.valueOf(stringValue);
      m_ctx.put(convertKey(key), timeValue);
      return;
    } catch (Exception e) {
    }

    //  Numeric
    Integer intValue = null;
    try {
      intValue = Integer.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    Double doubleValue = null;
    try {
      doubleValue = Double.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    if (doubleValue != null) {
      if (intValue != null) {
        double di = Double.parseDouble(intValue.toString());
        //  the numbers are the same -> integer
        if (Double.compare(di, doubleValue.doubleValue()) == 0) {
          m_ctx.put(convertKey(key), intValue);
          return;
        }
      }
      m_ctx.put(convertKey(key), doubleValue);
      return;
    }
    if (intValue != null) {
      m_ctx.put(convertKey(key), intValue);
      return;
    }
    m_ctx.put(convertKey(key), stringValue);
  } //  SetEnvironment

  /**
   * Set Environment key to value
   *
   * @param key variable name ('#' will be vonverted to '_')
   * @param value
   */
  public void setEnvironment(String key, Object value) {
    if (key != null && key.length() > 0) {
      //	log.fine( "Scriptlet.setEnvironment " + key, value);
      if (value == null) m_ctx.remove(key);
      else m_ctx.put(convertKey(key), value);
    }
  } //  SetEnvironment

  /**
   * Convert Key # -> _
   *
   * @param key
   * @return converted key
   */
  private String convertKey(String key) {
    String retValue = Util.replace(key, "#", "_");
    return retValue;
  } //  convertKey

  /**
   * Set Environment
   *
   * @param ctx
   */
  public void setEnvironment(HashMap<String, Object> ctx) {
    if (ctx == null) m_ctx = new HashMap<String, Object>();
    else m_ctx = ctx;
  } //  setEnvironment

  /**
   * Get Environment
   *
   * @return environment
   */
  public HashMap<String, Object> getEnvironment() {
    return m_ctx;
  } //  getEnvironment

  /**
   * ************************************************************************ Get Result
   *
   * @param runIt if true, execute script
   * @return result or null
   */
  public Object getResult(boolean runIt) {
    if (runIt) execute();
    return m_result;
  } //  getResult

  /**
   * String Representation incl. Result
   *
   * @return Scipt
   */
  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer(m_variable);
    sb.append(" { ").append(m_script).append(" } = ").append(getResult(true));
    return sb.toString();
  } //  toString
} //  Scriptlet
Ejemplo n.º 27
0
/**
 * Performance Goal
 *
 * @author Jorg Janke
 * @version $Id: MGoal.java,v 1.2 2006/07/30 00:51:03 jjanke Exp $
 */
public class MGoal extends X_PA_Goal {
  /** Logger for class MGoal */
  private static final org.compiere.util.CLogger log =
      org.compiere.util.CLogger.getCLogger(MGoal.class);
  /** */
  private static final long serialVersionUID = 1L;

  /**
   * 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

  /**
   * 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

  /**
   * Create Test Goals
   *
   * @param ctx context
   * @return array of goals
   */
  public static MGoal[] getTestGoals(Ctx ctx) {
    MGoal[] retValue = new MGoal[4];
    retValue[0] = new MGoal(ctx, "Test 1", "Description 1", new BigDecimal(1000), null);
    retValue[0].setMeasureActual(new BigDecimal(200));
    retValue[1] = new MGoal(ctx, "Test 2", "Description 2", new BigDecimal(1000), null);
    retValue[1].setMeasureActual(new BigDecimal(900));
    retValue[2] = new MGoal(ctx, "Test 3", "Description 3", new BigDecimal(1000), null);
    retValue[2].setMeasureActual(new BigDecimal(1200));
    retValue[3] = new MGoal(ctx, "Test 4", "Description 4", new BigDecimal(1000), null);
    retValue[3].setMeasureActual(new BigDecimal(3200));
    return retValue;
  } //	getTestGoals

  /**
   * 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

  /**
   * Get Multiplier from Scope to Display
   *
   * @param goal goal
   * @return null if error or multiplier
   */
  public static BigDecimal getMultiplier(MGoal goal) {
    String MeasureScope = goal.getMeasureScope();
    String MeasureDisplay = goal.getMeasureDisplay();
    if (MeasureDisplay == null || MeasureScope.equals(MeasureDisplay)) return Env.ONE; // 	1:1

    if (MeasureScope.equals(MEASURESCOPE_Total) || MeasureDisplay.equals(MEASUREDISPLAY_Total))
      return null; //	Error

    BigDecimal Multiplier = null;
    if (MeasureScope.equals(MEASURESCOPE_Year)) {
      if (MeasureDisplay.equals(MEASUREDISPLAY_Quarter)) Multiplier = new BigDecimal(1.0 / 4.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Month)) Multiplier = new BigDecimal(1.0 / 12.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Week)) Multiplier = new BigDecimal(1.0 / 52.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Day)) Multiplier = new BigDecimal(1.0 / 364.0);
    } else if (MeasureScope.equals(MEASURESCOPE_Quarter)) {
      if (MeasureDisplay.equals(MEASUREDISPLAY_Year)) Multiplier = new BigDecimal(4.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Month)) Multiplier = new BigDecimal(1.0 / 3.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Week)) Multiplier = new BigDecimal(1.0 / 13.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Day)) Multiplier = new BigDecimal(1.0 / 91.0);
    } else if (MeasureScope.equals(MEASURESCOPE_Month)) {
      if (MeasureDisplay.equals(MEASUREDISPLAY_Year)) Multiplier = new BigDecimal(12.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Quarter)) Multiplier = new BigDecimal(3.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Week)) Multiplier = new BigDecimal(1.0 / 4.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Day)) Multiplier = new BigDecimal(1.0 / 30.0);
    } else if (MeasureScope.equals(MEASURESCOPE_Week)) {
      if (MeasureDisplay.equals(MEASUREDISPLAY_Year)) Multiplier = new BigDecimal(52.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Quarter)) Multiplier = new BigDecimal(13.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Month)) Multiplier = new BigDecimal(4.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Day)) Multiplier = new BigDecimal(1.0 / 7.0);
    } else if (MeasureScope.equals(MEASURESCOPE_Day)) {
      if (MeasureDisplay.equals(MEASUREDISPLAY_Year)) Multiplier = new BigDecimal(364.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Quarter)) Multiplier = new BigDecimal(91.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Month)) Multiplier = new BigDecimal(30.0);
      else if (MeasureDisplay.equals(MEASUREDISPLAY_Week)) Multiplier = new BigDecimal(7.0);
    }
    return Multiplier;
  } //	getMultiplier

  /** Logger */
  private static CLogger s_log = CLogger.getCLogger(MGoal.class);

  /**
   * ************************************************************************ Standard Constructor
   *
   * @param ctx context
   * @param PA_Goal_ID id
   * @param trx p_trx
   */
  public MGoal(Ctx ctx, int PA_Goal_ID, Trx trx) {
    super(ctx, PA_Goal_ID, trx);
    if (PA_Goal_ID == 0) {
      //	setName (null);
      //	setAD_User_ID (0);
      //	setPA_ColorSchema_ID (0);
      setSeqNo(0);
      setIsSummary(false);
      setMeasureScope(MEASUREDISPLAY_Year);
      setGoalPerformance(Env.ZERO);
      setRelativeWeight(Env.ONE);
      setMeasureTarget(Env.ZERO);
      setMeasureActual(Env.ZERO);
    }
  } //	MGoal

  /**
   * Load Constructor
   *
   * @param ctx context
   * @param rs result set
   * @param trx p_trx
   */
  public MGoal(Ctx ctx, ResultSet rs, Trx trx) {
    super(ctx, rs, trx);
  } //	MGoal

  /**
   * Base Constructor
   *
   * @param ctx context
   * @param Name Name
   * @param Description Decsription
   * @param MeasureTarget target
   * @param trx p_trx
   */
  public MGoal(Ctx ctx, String Name, String Description, BigDecimal MeasureTarget, Trx trx) {
    super(ctx, 0, trx);
    setName(Name);
    setDescription(Description);
    setMeasureTarget(MeasureTarget);
  } //	MGoal

  /** Restrictions */
  private MGoalRestriction[] m_restrictions = null;

  /**
   * 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

  /**
   * Get Measure
   *
   * @return measure or null
   */
  public MMeasure getMeasure() {
    if (getPA_Measure_ID() != 0) return MMeasure.get(getCtx(), getPA_Measure_ID());
    return null;
  } //	getMeasure

  /**
   * ************************************************************************ Update/save Goals for
   * the same measure
   *
   * @param force force to update goal (default once per day)
   * @return true if updated
   */
  public boolean updateGoal(boolean force) {
    log.config("Force=" + force);
    MMeasure measure = MMeasure.get(getCtx(), getPA_Measure_ID());
    if (force || getDateLastRun() == null || !TimeUtil.isSameHour(getDateLastRun(), null)) {
      if (measure.updateGoals()) // 	saves
      {
        load(get_ID(), get_Trx());
        return true;
      }
    }
    return false;
  } //	updateGoal

  /**
   * Set Measure Actual
   *
   * @param MeasureActual actual
   */
  @Override
  public void setMeasureActual(BigDecimal MeasureActual) {
    if (MeasureActual == null) return;
    super.setMeasureActual(MeasureActual);
    setDateLastRun(new Timestamp(System.currentTimeMillis()));
    setGoalPerformance();
  } //	setMeasureActual

  /** Calculate Performance Goal as multiplier */
  public void setGoalPerformance() {
    BigDecimal MeasureTarget = getMeasureTarget();
    BigDecimal MeasureActual = getMeasureActual();
    BigDecimal GoalPerformance = Env.ZERO;
    if (MeasureTarget.signum() != 0)
      GoalPerformance = MeasureActual.divide(MeasureTarget, 6, BigDecimal.ROUND_HALF_UP);
    super.setGoalPerformance(GoalPerformance);
  } //	setGoalPerformance

  /**
   * Get Goal Performance as Double
   *
   * @return performance as multipier
   */
  public double getGoalPerformanceDouble() {
    BigDecimal bd = getGoalPerformance();
    return bd.doubleValue();
  } //	getGoalPerformanceDouble

  /**
   * Get Goal Performance in Percent
   *
   * @return performance in percent
   */
  public int getPercent() {
    BigDecimal bd = getGoalPerformance().multiply(Env.ONEHUNDRED);
    return bd.intValue();
  } //	getPercent

  /**
   * Get Color
   *
   * @return color - white if no target
   */
  public Color getColor() {
    if (getMeasureTarget().signum() == 0) return Color.white;
    else return MColorSchema.getColor(getCtx(), getPA_ColorSchema_ID(), getPercent());
  } //	getColor

  /**
   * Get the color schema for this goal.
   *
   * @return the color schema, or null if the measure targer is 0
   */
  public MColorSchema getColorSchema() {
    return (getMeasureTarget().signum() == 0)
        ? null
        : MColorSchema.get(getCtx(), getPA_ColorSchema_ID());
  }

  /**
   * Get Measure Display
   *
   * @return Measure Display
   */
  @Override
  public String getMeasureDisplay() {
    String s = super.getMeasureDisplay();
    if (s == null) {
      if (MEASURESCOPE_Week.equals(getMeasureScope())) s = MEASUREDISPLAY_Week;
      else if (MEASURESCOPE_Day.equals(getMeasureScope())) s = MEASUREDISPLAY_Day;
      else s = MEASUREDISPLAY_Month;
    }
    return s;
  } //	getMeasureDisplay

  /**
   * Get Measure Display Text
   *
   * @return Measure Display Text
   */
  public String getXAxisText() {
    MMeasure measure = getMeasure();
    if (measure != null
        && X_PA_Measure.MEASUREDATATYPE_StatusQtyAmount.equals(measure.getMeasureDataType())) {
      if (X_PA_Measure.MEASURETYPE_Request.equals(measure.getMeasureType()))
        return Msg.getElement(getCtx(), "R_Status_ID");
      if (X_PA_Measure.MEASURETYPE_Project.equals(measure.getMeasureType()))
        return Msg.getElement(getCtx(), "C_Phase_ID");
    }
    String value = getMeasureDisplay();
    String display = MRefList.getListName(getCtx(), X_Ref_PA_Goal_Scope.AD_Reference_ID, value);
    return display == null ? value : display;
  } //	getMeasureDisplayText

  /**
   * Goal has Target
   *
   * @return true if target
   */
  public boolean isTarget() {
    return getMeasureTarget().signum() != 0;
  } //	isTarget

  /**
   * String Representation
   *
   * @return info
   */
  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer("MGoal[");
    sb.append(get_ID())
        .append("-")
        .append(getName())
        .append(",")
        .append(getGoalPerformance())
        .append("]");
    return sb.toString();
  } //	toString

  /**
   * Before Save
   *
   * @param newRecord new
   * @return true
   */
  @Override
  protected boolean beforeSave(boolean newRecord) {
    //	if (getMultiplier(this) == null)	//	error
    //		setMeasureDisplay(getMeasureScope());

    //	Measure required if nor Summary
    if (!isSummary() && getPA_Measure_ID() == 0) {
      log.saveError("FillMandatory", Msg.getElement(getCtx(), "PA_Measure_ID"));
      return false;
    }
    if (isSummary() && getPA_Measure_ID() != 0) setPA_Measure_ID(0);

    //	User/Role Check
    if ((newRecord || is_ValueChanged("AD_User_ID") || is_ValueChanged("AD_Role_ID"))
        && getAD_User_ID() != 0) {
      MUser user = MUser.get(getCtx(), getAD_User_ID());
      MRole[] roles = user.getRoles(getAD_Org_ID());
      if (roles.length == 0) // 	No Role
      setAD_Role_ID(0);
      else if (roles.length == 1) // 	One
      setAD_Role_ID(roles[0].getAD_Role_ID());
      else {
        int AD_Role_ID = getAD_Role_ID();
        if (AD_Role_ID != 0) // 	validate
        {
          boolean found = false;
          for (MRole element : roles) {
            if (AD_Role_ID == element.getAD_Role_ID()) {
              found = true;
              break;
            }
          }
          if (!found) AD_Role_ID = 0;
        }
        if (AD_Role_ID == 0) // 	set to first one
        setAD_Role_ID(roles[0].getAD_Role_ID());
      } //	multiple roles
    } //	user check

    return true;
  } //	beforeSave

  /**
   * After Save
   *
   * @param newRecord new
   * @param success success
   * @return true
   */
  @Override
  protected boolean afterSave(boolean newRecord, boolean success) {
    if (!success) return success;

    //	Update Goal if Target / Scope Changed
    if (newRecord || is_ValueChanged("MeasureTarget") || is_ValueChanged("MeasureScope"))
      updateGoal(true);

    return success;
  }
} //	MGoal
Ejemplo n.º 28
0
/**
 * Verify Document Types. - Make sure that there is a DocumentType for all Document Base Types -
 * Create missing Period Controls for Document Type
 *
 * @author Jorg Janke
 * @version $Id: DocumentTypeVerify.java,v 1.2 2006/07/30 00:51:01 jjanke Exp $
 */
public class DocumentTypeVerify extends SvrProcess {
  /** Static Logger */
  private static CLogger s_log = CLogger.getCLogger(DocumentTypeVerify.class);

  /** No Parameters (Nop) */
  @Override
  protected void prepare() {} // 	prepare

  /**
   * Execute process
   *
   * @return info
   * @throws Exception
   */
  @Override
  protected String doIt() throws Exception {
    createDocumentTypes(getCtx(), getAD_Client_ID(), this, get_TrxName());
    createPeriodControls(getCtx(), getAD_Client_ID(), this, get_TrxName());
    return "OK";
  } //	doIt

  /**
   * ************************************************************************ 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

  /**
   * 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
} //	DocumentTypeVerify