예제 #1
0
public class WHelp extends HttpServlet {
  /** */
  private static final long serialVersionUID = 2586562865823315494L;

  protected CLogger log = CLogger.getCLogger(getClass());

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    if (!WebEnv.initWeb(config)) throw new ServletException("WHelp.init");
  }

  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.fine("doGet");
    WWindowStatus ws = WWindowStatus.get(request);
    WebDoc doc = null;
    if (ws == null) {
      doc = WebDoc.createPopup("No Context");
      doc.addPopupClose(Env.getCtx());
    } else doc = ws.mWindow.getHelpDoc(false);
    WebUtil.createResponse(request, response, this, null, doc, false);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    WebDoc doc = WebDoc.create("Help - Post - Not Implemented");
    WebUtil.createResponse(request, response, this, null, doc, false);
  }
}
/**
 * ComboBox Selection Manager for AuroReduction
 *
 * @author Jorg Janke
 * @version $Id: ComboSelectionManager.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $
 */
public class ComboSelectionManager implements JComboBox.KeySelectionManager {
  /** */
  public ComboSelectionManager() {} //  ComboSelectionManager

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

  /**
   * Given <code>aKey</code> and the model, returns the row that should become selected. Return -1
   * if no match was found.
   *
   * @param key a char value, usually indicating a keyboard key that was pressed
   * @param model a ComboBoxModel -- the component's data model, containing the list of selectable
   *     items
   * @return an int equal to the selected row, where 0 is the first item and -1 is none
   */
  public int selectionForKey(char key, ComboBoxModel model) {
    log.fine("Key=" + key);
    //
    int currentSelection = -1;
    Object selectedItem = model.getSelectedItem();

    return 0;
  } //	selectionForKey
} //  ComboSelectionManager
예제 #3
0
public class Application implements IApplication {
  private static CLogger log = CLogger.getCLogger(Application.class);

  public static Context context = null;

  public Object start(IApplicationContext ctx) throws Exception {
    log.info("Starting client");
    // A HOSTNAME VERIFIER THAT ACCEPTS EVERY HOSTS
    HostnameVerifier myhostnameverifier =
        new HostnameVerifier() {
          @Override
          public boolean verify(String urlHostName, SSLSession session) {
            return true;
          }
        };

    //
    // start restlet context
    context = new Context();
    context.getAttributes().put("sslContextFactory", new ClientSSLContextFactory());
    context.getAttributes().put("hostnameVerifier", myhostnameverifier);
    List<Protocol> list = new ArrayList<Protocol>();
    list.add(Protocol.HTTPS);
    Client client = new Client(context, list, HttpClientHelper.class.getName());
    context.setClientDispatcher(client);
    client.start();

    Adempiere.startup(true);
    org.compiere.AdempiereClient.main(new String[] {});
    return IApplication.EXIT_OK;
  }

  public void stop() {}
}
예제 #4
0
/**
 * Withholding Model
 *
 * @author Jorg Janke
 * @version $Id: MWithholding.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
 */
public class MWithholding extends X_C_Withholding {
  /** Logger for class MWithholding */
  private static final org.compiere.util.CLogger log =
      org.compiere.util.CLogger.getCLogger(MWithholding.class);
  /** */
  private static final long serialVersionUID = 1L;

  /**
   * Standard Constructor
   *
   * @param ctx context
   * @param C_Withholding_ID id
   * @param trx transaction
   */
  public MWithholding(Ctx ctx, int C_Withholding_ID, Trx trx) {
    super(ctx, C_Withholding_ID, trx);
  } //	MWithholding

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

  /**
   * After Save
   *
   * @param newRecord new
   * @param success success
   * @return success
   */
  @Override
  protected boolean afterSave(boolean newRecord, boolean success) {
    if (newRecord & success)
      success = insert_Accounting("C_Withholding_Acct", "C_AcctSchema_Default", null);

    return success;
  } //	afterSave

  /**
   * Before Delete
   *
   * @return true
   */
  @Override
  protected boolean beforeDelete() {
    return delete_Accounting("C_Withholding_Acct");
  } //	beforeDelete
} //	MWithholding
예제 #5
0
 /**
  * ************************************************************************ Start: not started ->
  * running
  *
  * @return true if set to running
  */
 public boolean start() {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isNotStarted()) {
     m_state = STATE_Running;
     log.info("starting ...");
     return true;
   }
   String msg = "start failed: Not Not Started (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	start
예제 #6
0
 /**
  * Complete: running -> completed
  *
  * @return true if set to completed
  */
 public boolean complete() {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isRunning()) {
     m_state = STATE_Completed;
     log.info("completing ...");
     return true;
   }
   String msg = "complete failed: Not Running (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	complete
예제 #7
0
 /**
  * Terminate: open -> terminated
  *
  * @return true if set to terminated
  */
 public boolean terminate() // 	raises CannotStop, NotRunning
     {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isOpen()) {
     m_state = STATE_Terminated;
     log.info("terminating ...");
     return true;
   }
   String msg = "terminate failed: Not Open (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	terminate
예제 #8
0
 /**
  * Resume: suspended -> running
  *
  * @return true if set to sunning
  */
 public boolean resume() // 	raises CannotResume, NotRunning, NotSuspended
     {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isSuspended()) {
     m_state = STATE_Running;
     log.info("resuming ...");
     return true;
   }
   String msg = "resume failed: Not Suspended (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	resume
예제 #9
0
 /**
  * Suspend: running -> suspended
  *
  * @return true if suspended
  */
 public boolean suspend() // 	raises CannotSuspend, NotRunning, AlreadySuspended
     {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isRunning()) {
     m_state = STATE_Suspended;
     log.info("suspending ...");
     return true;
   }
   String msg = "suspend failed: Not Running (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	suspend
예제 #10
0
/**
 * Function Key Sub Panel
 *
 * @author Comunidad de Desarrollo OpenXpertya *Basado en Codigo Original Modificado, Revisado y
 *     Optimizado de: *Copyright (c) Jorg Janke
 * @version $Id: SubFunctionKeys.java,v 1.1 2004/07/12 04:10:04 jjanke Exp $
 */
public class SubFunctionKeys extends PosSubPanel implements PosKeyListener {
  /** */
  private static final long serialVersionUID = -1870924843670214389L;

  /**
   * Constructor
   *
   * @param posPanel POS Panel
   */
  public SubFunctionKeys(PosBasePanel posPanel) {
    super(posPanel);
  } //	PosSubFunctionKeys

  /** Keys */
  // private MPOSKey[] 	m_keys;
  /** Logger */
  @SuppressWarnings("unused")
  private static CLogger log = CLogger.getCLogger(SubFunctionKeys.class);

  /** Initialize */
  public void init() {
    int C_POSKeyLayout_ID = p_pos.getC_POSKeyLayout_ID();
    if (C_POSKeyLayout_ID == 0) return;

    PosKeyPanel panel = new PosKeyPanel(C_POSKeyLayout_ID, this);
    this.setLayout(new MigLayout("fill, ins 0"));
    add(panel, "growx, growy");
  } //	init

  /** Dispose - Free Resources */
  public void dispose() {
    super.dispose();
  } //	dispose

  /** Call back from key panel */
  public void keyReturned(MPOSKey key) {
    // processed order
    if (p_posPanel.m_order != null && p_posPanel.m_order.isProcessed()) return;

    // new line
    p_posPanel.f_curLine.setM_Product_ID(key.getM_Product_ID());
    p_posPanel.f_curLine.setPrice();
    p_posPanel.f_curLine.setQty(key.getQty());
    if (!p_posPanel.f_curLine.saveLine()) {
      ADialog.error(0, this, "Could not save order line");
    }
    p_posPanel.updateInfo();
    return;
  }
} //	PosSubFunctionKeys
public class CompiereUtil {

  private static CLogger log = CLogger.getCLogger(CompiereUtil.class);
  private static boolean s_initOK = false;

  public static boolean initWeb() {
    if (s_initOK) {
      // log.info(context.getServletContextName());
      return true;
    }

    // TODO:
    //  Load Environment Variables (serverApps/src/web/WEB-INF/web.xml)

    try {
      // CLogMgt.setLevel(Level.OFF);

      /* ADEMPIERE/COMPIERE */
      // s_initOK = Compiere.startup(false);
      s_initOK = Adempiere.startup(false);
    } catch (Exception ex) {
      log.log(Level.SEVERE, "startup", ex);
    }
    if (!s_initOK) return false;

    //	Logging now initiated
    // log.info(info.toString());

    //
    Properties ctx = new Properties();
    MClient client = MClient.get(ctx, 0);
    MSystem system = MSystem.get(ctx);

    // Env.setContext( ctx, "#AD_Language", "pl_PL" );
    // client.sendEMail(client.getRequestEMail(),
    //	"Server started: " + system.getName()
    //	,"ServerInfo: " + context.getServerInfo()
    // );

    return s_initOK;
  }
}
예제 #12
0
/**
 * Generate Model Classes extending PO. Base class for CMP interface - will be extended to create
 * byte code directly
 *
 * @author Jorg Janke, Victor Perez (JPA variation)
 * @version $Id$
 */
public class GenerateModelJPA {
  /**
   * Generate PO Class
   *
   * @param AD_Table_ID table id
   * @param directory directory with \ or / at the end.
   * @param packageName package name
   */
  public GenerateModelJPA(int AD_Table_ID, String directory, String packageName) {
    //	create column access methods
    StringBuffer mandatory = new StringBuffer();
    StringBuffer sb = createColumns(AD_Table_ID, mandatory);
    // add header stuff
    String tableName = createHeader(AD_Table_ID, sb, mandatory, packageName);
    //	Save it
    writeToFile(sb, directory + tableName + ".java");
  } //	GenerateModel

  /** File Header */
  public static final String COPY =
      "/******************************************************************************\n"
          + " * Product: Adempiere ERP & CRM Smart Business Solution                       *\n"
          + " * Copyright (C) 2006-2008 Adempiere Bazaar. All Rights Reserved.                *\n"
          + " * This program is free software; you can redistribute it and/or modify it    *\n"
          + " * under the terms version 2 of the GNU General Public License as published   *\n"
          + " * by the Free Software Foundation. This program is distributed in the hope   *\n"
          + " * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *\n"
          + " * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           *\n"
          + " * See the GNU General Public License for more details.                       *\n"
          + " * You should have received a copy of the GNU General Public License along    *\n"
          + " * with this program; if not, write to the Free Software Foundation, Inc.,    *\n"
          // +" * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.                     *\n"
          // +" * For the text or an alternative of this public license, you may reach us    *\n"
          + " * or via www.adempiere.org or http://www.adempiere.org/wiki		           *\n"
          + " * Contributor: Victor Perez Juarez                                           *\n"
          + " *****************************************************************************/\n";

  /** Generated on */
  private Timestamp s_run = new Timestamp(System.currentTimeMillis());

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

  /**
   * Add Header info to buffer
   *
   * @param AD_Table_ID table
   * @param sb buffer
   * @param mandatory init call for mandatory columns
   * @param packageName package name
   * @return class name
   */
  private String createHeader(
      int AD_Table_ID, StringBuffer sb, StringBuffer mandatory, String packageName) {
    String tableName = "";
    int accessLevel = 0;
    String sql = "SELECT TableName, AccessLevel FROM AD_Table WHERE AD_Table_ID=?";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      pstmt.setInt(1, AD_Table_ID);
      rs = pstmt.executeQuery();
      if (rs.next()) {
        tableName = rs.getString(1);
        accessLevel = rs.getInt(2);
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }
    if (tableName == null) throw new RuntimeException("TableName not found for ID=" + AD_Table_ID);
    //
    String accessLevelInfo = accessLevel + " ";
    if (accessLevel >= 4) accessLevelInfo += "- System ";
    if (accessLevel == 2 || accessLevel == 3 || accessLevel == 6 || accessLevel == 7)
      accessLevelInfo += "- Client ";
    if (accessLevel == 1 || accessLevel == 3 || accessLevel == 5 || accessLevel == 7)
      accessLevelInfo += "- Org ";

    String keyColumn = tableName + "_ID";
    // String className = "X_" + tableName;
    String className = "" + tableName;
    //
    StringBuffer start =
        new StringBuffer()
            .append(COPY)
            .append(
                "package " + packageName + ";\n" + "/** Generated Model JPA - DO NOT CHANGE */\n");
    if (!packageName.equals("org.adempiere.model")) start.append("import org.adempiere.model.*;");
    start
        .append(
            "import java.util.*;"
                + "import java.sql.*;"
                + "import java.math.*;"
                + "import javax.persistence.*;"
                + "import org.compiere.util.*;"
                + "import org.adempiere.util.*;"
                //	Class
                + "/** Generated Model for ")
        .append(tableName)
        .append("\n" + " *  @author Victor Perez (generated) \n" + " *  @version ")
        .append(Adempiere.MAIN_VERSION)
        .append(" - ")
        .append(s_run)
        .append(" */\n" + " @Entity" + "@Table(name=\"" + tableName + "\")" + "public class ")
        .append(className)
        .append(
            " extends PO"
                + " implements java.io.Serializable "
                + "{"
                //	Standard Constructor
                + "/** Standard Constructor\n@param ctx context\n@param "
                + keyColumn
                + " id\n@param trxName transaction\n*/\n"
                + "public ")
        .append(className)
        .append(" (Properties ctx, int ")
        .append(keyColumn)
        .append(", String trxName)" + "{" + "super (ctx, ")
        .append(keyColumn)
        .append(", trxName);" + "/** if (")
        .append(keyColumn)
        .append(" == 0)" + "{")
        .append(mandatory)
        .append(
            "} */\n"
                + "}" //	Constructor End
                //	Short Constructor
                //			+ "/** Short Constructor */\n"
                //			+ "public ").append(className).append(" (Properties ctx, int
                // ").append(keyColumn).append(")"
                //			+ "{"
                //			+ "this (ctx, ").append(keyColumn).append(", null);"
                //			+ "}"	//	Constructor End

                //	Load Constructor
                + "/** Load Constructor \n@param ctx context\n@param rs result set \n@param trxName transaction\n*/\n"
                + "public ")
        .append(className)
        .append(
            " (Properties ctx, ResultSet rs, String trxName)"
                + "{"
                + "super (ctx, rs, trxName);"
                + "}" //	Load Constructor End
                //
                + "/** AD_Table_ID=")
        .append(AD_Table_ID)
        .append(" */\n" + "public static final int Table_ID=")
        .append(AD_Table_ID)
        .append(
            ";\n"
                //
                + "/** TableName=")
        .append(tableName)
        .append(" */\n" + "public static final String Table_Name=\"")
        .append(tableName)
        .append("\";\n" + "protected static KeyNamePair Model = new KeyNamePair(")
        .append(AD_Table_ID)
        .append(",\"")
        .append(tableName)
        .append(
            "\");\n"
                //
                + "protected BigDecimal accessLevel = new BigDecimal(")
        .append(accessLevel)
        .append(");" + "/** AccessLevel\n@return ")
        .append(accessLevelInfo)
        .append(
            "\n*/\n"
                + "protected int get_AccessLevel()"
                + "{"
                + "return accessLevel.intValue();"
                + "}"
                //
                + "/** Load Meta Data\n@param ctx context\n@return PO Info\n*/\n"
                + "protected POInfo initPO (Properties ctx)"
                + "{"
                + "POInfo poi = POInfo.getPOInfo (ctx, Table_ID);"
                + "return poi;"
                + "}" //	initPO
                //
                + "/** Info\n@return info\n*/\n"
                + "public String toString()"
                + "{"
                + "StringBuffer sb = new StringBuffer (\"")
        .append(className)
        .append("[\")" + ".append(get_ID()).append(\"]\");" + "return sb.toString();" + "}");

    StringBuffer end = new StringBuffer("}");
    //
    sb.insert(0, start);
    sb.append(end);

    return className;
  } //	createHeader

  /**
   * Create Column access methods
   *
   * @param AD_Table_ID table
   * @param mandatory init call for mandatory columns
   * @return set/get method
   */
  private StringBuffer createColumns(int AD_Table_ID, StringBuffer mandatory) {
    StringBuffer sb = new StringBuffer();
    String sql =
        "SELECT c.ColumnName, c.IsUpdateable, c.IsMandatory," //	1..3
            + " c.AD_Reference_ID, c.AD_Reference_Value_ID, DefaultValue, SeqNo, " //	4..7
            + " c.FieldLength, c.ValueMin, c.ValueMax, c.VFormat, c.Callout, " //	8..12
            + " c.Name, c.Description, c.ColumnSQL, c.IsEncrypted "
            + "FROM AD_Column c "
            + "WHERE c.AD_Table_ID=?"
            + " AND c.IsActive='Y'"
            + " AND c.ColumnName <> 'AD_Client_ID'"
            + " AND c.ColumnName <> 'AD_Org_ID'"
            + " AND c.ColumnName <> 'IsActive'"
            + " AND c.ColumnName NOT LIKE 'Created%'"
            + " AND c.ColumnName NOT LIKE 'Updated%' "
            + "ORDER BY c.ColumnName";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      pstmt.setInt(1, AD_Table_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        String columnName = rs.getString(1);
        boolean isUpdateable = "Y".equals(rs.getString(2));
        boolean isMandatory = "Y".equals(rs.getString(3));
        int displayType = rs.getInt(4);
        int AD_Reference_Value_ID = rs.getInt(5);
        String defaultValue = rs.getString(6);
        int seqNo = rs.getInt(7);
        int fieldLength = rs.getInt(8);
        String ValueMin = rs.getString(9);
        String ValueMax = rs.getString(10);
        String VFormat = rs.getString(11);
        String Callout = rs.getString(12);
        String Name = rs.getString(13);
        String Description = rs.getString(14);
        String ColumnSQL = rs.getString(15);
        boolean virtualColumn = ColumnSQL != null && ColumnSQL.length() > 0;
        boolean IsEncrypted = "Y".equals(rs.getString(16));
        //
        sb.append("@Column(name=\"" + Name + "\") ");
        sb.append(
            createColumnMethods(
                mandatory,
                columnName,
                isUpdateable,
                isMandatory,
                displayType,
                AD_Reference_Value_ID,
                fieldLength,
                defaultValue,
                ValueMin,
                ValueMax,
                VFormat,
                Callout,
                Name,
                Description,
                virtualColumn,
                IsEncrypted));
        //
        if (seqNo == 1) sb.append(createKeyNamePair(columnName, displayType));
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }
    return sb;
  } //	createColumns

  /**
   * Create set/get methods for column
   *
   * @param mandatory init call for mandatory columns
   * @param columnName column name
   * @param isUpdateable updateable
   * @param isMandatory mandatory
   * @param displayType display type
   * @param AD_Reference_ID validation reference
   * @param fieldLength int
   * @param defaultValue default value
   * @param ValueMin String
   * @param ValueMax String
   * @param VFormat String
   * @param Callout String
   * @param Name String
   * @param Description String
   * @param virtualColumn virtual column
   * @param IsEncrypted stored encrypted
   * @return set/get method
   */
  private String createColumnMethods(
      StringBuffer mandatory,
      String columnName,
      boolean isUpdateable,
      boolean isMandatory,
      int displayType,
      int AD_Reference_ID,
      int fieldLength,
      String defaultValue,
      String ValueMin,
      String ValueMax,
      String VFormat,
      String Callout,
      String Name,
      String Description,
      boolean virtualColumn,
      boolean IsEncrypted) {
    //	Clazz
    Class clazz = DisplayType.getClass(displayType, true);
    if (defaultValue == null) defaultValue = "";
    if (DisplayType.isLOB(displayType)) // 	No length check for LOBs
    fieldLength = 0;

    //	Handle Posted
    if (columnName.equalsIgnoreCase("Posted")
        || columnName.equalsIgnoreCase("Processed")
        || columnName.equalsIgnoreCase("Processing")) {
      clazz = Boolean.class;
      AD_Reference_ID = 0;
    }
    //	Record_ID
    else if (columnName.equalsIgnoreCase("Record_ID")) {
      clazz = Integer.class;
      AD_Reference_ID = 0;
    }
    //	String Key
    else if (columnName.equalsIgnoreCase("AD_Language")
        || columnName.equalsIgnoreCase("EntityType")) {
      clazz = String.class;
    }
    //	Data Type
    String dataType = clazz.getName();
    dataType = dataType.substring(dataType.lastIndexOf('.') + 1);
    if (dataType.equals("Boolean")) dataType = "boolean";
    else if (dataType.equals("Integer")) dataType = "int";
    else if (displayType == DisplayType.Binary) dataType = "byte[]";

    StringBuffer sb = new StringBuffer();
    //	****** Set Comment ******
    sb.append("/** Set ").append(Name);
    sb.append(".\n@param ").append(columnName).append(" ");
    if (Description != null && Description.length() > 0) sb.append(Description);
    else sb.append(Name);
    sb.append(" */\n");

    //	Set	********
    String setValue = "set_Value";
    if (IsEncrypted) setValue = "set_ValueE";
    //	public void setColumn (xxx variable)
    sb.append("public ");
    if (!isUpdateable) {
      setValue = "set_ValueNoCheck";
      if (IsEncrypted) setValue = "set_ValueNoCheckE";
    }
    sb.append("void set")
        .append(columnName)
        .append(" (")
        .append(dataType)
        .append(" ")
        .append(columnName)
        .append(")" + "{");
    //	List Validation
    if (AD_Reference_ID != 0) {
      String staticVar = addListValidation(sb, AD_Reference_ID, columnName, !isMandatory);
      sb.insert(0, staticVar); // 	first check
    }
    //	setValue ("ColumnName", xx);
    if (virtualColumn) {
      sb.append("throw new IllegalArgumentException (\"")
          .append(columnName)
          .append(" is virtual column\");");
    } else if (clazz.equals(Integer.class)) {
      if (columnName.endsWith("_ID")) {
        if (isMandatory) //	check mandatory ID
        {
          int firstOK = 1; // 	Valid ID 0
          if (columnName.equals("AD_Client_ID")
              || columnName.equals("AD_Org_ID")
              || columnName.equals("Record_ID")
              || columnName.equals("C_DocType_ID")
              || columnName.equals("Node_ID")
              || columnName.equals("AD_Role_ID")
              || columnName.equals("M_AttributeSet_ID")
              || columnName.equals("M_AttributeSetInstance_ID")) firstOK = 0;
          sb.append("if (")
              .append(columnName)
              .append(" < ")
              .append(firstOK)
              .append(") throw new IllegalArgumentException (\"")
              .append(columnName)
              .append(" is mandatory.\");");
        } else //	set optional _ID to null if 0
        sb.append("if (")
              .append(columnName)
              .append(" <= 0) ")
              .append(setValue)
              .append(" (\"")
              .append(columnName)
              .append("\", null); else \n");
      }
      sb.append(setValue)
          .append(" (\"")
          .append(columnName)
          .append("\", new Integer(")
          .append(columnName)
          .append("));");
    } else if (clazz.equals(Boolean.class))
      sb.append(setValue)
          .append(" (\"")
          .append(columnName)
          .append("\", new Boolean(")
          .append(columnName)
          .append("));");
    else {
      if (isMandatory && AD_Reference_ID == 0) // 	does not apply to int/boolean
      {
        sb.append("if (")
            .append(columnName)
            .append(" == null)" + " throw new IllegalArgumentException (\"")
            .append(columnName)
            .append(" is mandatory.\");");
      }
      // String length check
      if (clazz.equals(String.class) && fieldLength > 0) {
        sb.append("if (");
        if (!isMandatory) sb.append(columnName).append(" != null && ");
        sb.append(columnName)
            .append(".length() > ")
            .append(fieldLength)
            .append("){log.warning(\"Length > ")
            .append(fieldLength)
            .append(" - truncated\");")
            .append(columnName)
            .append(" = ")
            .append(columnName)
            .append(".substring(0,")
            .append(fieldLength - 1)
            .append(");}");
      }

      //
      sb.append(setValue)
          .append(" (\"")
          .append(columnName)
          .append("\", ")
          .append(columnName)
          .append(");");
    }
    sb.append("}");

    //	Mandatory call in constructor
    if (isMandatory) {
      mandatory.append("set").append(columnName).append(" (");
      if (clazz.equals(Integer.class)) mandatory.append("0");
      else if (clazz.equals(Boolean.class)) {
        if (defaultValue.indexOf('Y') != -1) mandatory.append(true);
        else mandatory.append("false");
      } else if (clazz.equals(BigDecimal.class)) mandatory.append("Env.ZERO");
      else if (clazz.equals(Timestamp.class))
        mandatory.append("new Timestamp(System.currentTimeMillis())");
      else mandatory.append("null");
      mandatory.append(");");
      if (defaultValue.length() > 0) mandatory.append("// ").append(defaultValue).append(Env.NL);
    }

    //	****** Get Comment ******
    sb.append("/** Get ").append(Name);
    if (Description != null && Description.length() > 0)
      sb.append(".\n@return ").append(Description);
    else sb.append(".\n@return ").append(Name);
    sb.append(" */\n");

    //	Get	********
    String getValue = "get_Value";
    if (IsEncrypted) getValue = "get_ValueE";
    sb.append("public ").append(dataType);
    if (clazz.equals(Boolean.class)) {
      sb.append(" is");
      if (columnName.toLowerCase().startsWith("is")) sb.append(columnName.substring(2));
      else sb.append(columnName);
    } else sb.append(" get").append(columnName);
    sb.append("() {");
    if (clazz.equals(Integer.class))
      sb.append("Integer ii = (Integer)")
          .append(getValue)
          .append("(\"")
          .append(columnName)
          .append("\");" + "if (ii == null)" + " return 0;" + "return ii.intValue();");
    else if (clazz.equals(BigDecimal.class))
      sb.append("BigDecimal bd = (BigDecimal)")
          .append(getValue)
          .append("(\"")
          .append(columnName)
          .append("\");" + "if (bd == null)" + " return Env.ZERO;" + "return bd;");
    else if (clazz.equals(Boolean.class))
      sb.append("Object oo = ")
          .append(getValue)
          .append("(\"")
          .append(columnName)
          .append(
              "\");"
                  + "if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return \"Y\".equals(oo);}"
                  + "return false;");
    else if (dataType.equals("Object"))
      sb.append("return ").append(getValue).append("(\"").append(columnName).append("\");");
    else
      sb.append("return (")
          .append(dataType)
          .append(")")
          .append(getValue)
          .append("(\"")
          .append(columnName)
          .append("\");");
    sb.append("}");
    //
    return sb.toString();
  } //	createColumnMethods

  /**
   * Add List Validation
   *
   * @param sb buffer - example: if (NextAction.equals("N") || NextAction.equals("F")); else throw
   *     new IllegalArgumentException ("NextAction Invalid value - Reference_ID=219 - N - F");
   * @param AD_Reference_ID reference
   * @param columnName column
   * @param nullable the validation must allow null values
   * @return static parameter - Example: public static final int NEXTACTION_AD_Reference_ID=219;
   *     public static final String NEXTACTION_None = "N"; public static final String
   *     NEXTACTION_FollowUp = "F";
   */
  private String addListValidation(
      StringBuffer sb, int AD_Reference_ID, String columnName, boolean nullable) {
    StringBuffer retValue = new StringBuffer();
    retValue
        .append("\n/** ")
        .append(columnName)
        .append(" AD_Reference_ID=")
        .append(AD_Reference_ID)
        .append(" */\n")
        .append("public static final int ")
        .append(columnName.toUpperCase())
        .append("_AD_Reference_ID=")
        .append(AD_Reference_ID)
        .append(";");
    //
    boolean found = false;
    StringBuffer values = new StringBuffer("Reference_ID=").append(AD_Reference_ID);
    StringBuffer statement = new StringBuffer();
    if (nullable) statement.append("if (").append(columnName).append(" == null");
    //
    String sql = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=?";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      pstmt.setInt(1, AD_Reference_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        String value = rs.getString(1);
        values.append(" - ").append(value);
        if (statement.length() == 0)
          statement
              .append("if (")
              .append(columnName)
              .append(".equals(\"")
              .append(value)
              .append("\")");
        else
          statement
              .append(" || ")
              .append(columnName)
              .append(".equals(\"")
              .append(value)
              .append("\")");
        if (!found) {
          found = true;
          sb.append("if (")
              .append(columnName)
              .append(" == null)" + " throw new IllegalArgumentException (\"")
              .append(columnName)
              .append(" is mandatory\");");
        }
        //	Name (SmallTalkNotation)
        String name = rs.getString(2);
        char[] nameArray = name.toCharArray();
        StringBuffer nameClean = new StringBuffer();
        boolean initCap = true;
        for (int i = 0; i < nameArray.length; i++) {
          char c = nameArray[i];
          if (Character.isJavaIdentifierPart(c)) {
            if (initCap) nameClean.append(Character.toUpperCase(c));
            else nameClean.append(c);
            initCap = false;
          } else {
            if (c == '+') nameClean.append("Plus");
            else if (c == '-') nameClean.append("_");
            else if (c == '>') {
              if (name.indexOf('<') == -1) // 	ignore <xx>
              nameClean.append("Gt");
            } else if (c == '<') {
              if (name.indexOf('>') == -1) // 	ignore <xx>
              nameClean.append("Le");
            } else if (c == '!') nameClean.append("Not");
            else if (c == '=') nameClean.append("Eq");
            else if (c == '~') nameClean.append("Like");
            initCap = true;
          }
        }
        retValue.append("/** ").append(name).append(" = ").append(value).append(" */\n");
        retValue
            .append("public static final String ")
            .append(columnName.toUpperCase())
            .append("_")
            .append(nameClean)
            .append(" = \"")
            .append(value)
            .append("\";");
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
      found = false;
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }
    statement
        .append(")" + "; " + "else " + "throw new IllegalArgumentException (\"")
        .append(columnName)
        .append(" Invalid value - \" + ")
        .append(columnName)
        .append(" + \" - ")
        .append(values)
        .append("\");");
    //
    if (found && !columnName.equals("EntityType")) sb.append(statement);
    return retValue.toString();
  } //	addListValidation

  /**
   * Create getKeyNamePair() method with first identifier
   *
   * @param columnName name * @param displayType int
   * @return method code
   */
  private StringBuffer createKeyNamePair(String columnName, int displayType) {
    String method = "get" + columnName + "()";
    if (displayType != DisplayType.String) method = "String.valueOf(" + method + ")";
    StringBuffer sb =
        new StringBuffer(
                "/** Get Record ID/ColumnName\n@return ID/ColumnName pair\n*/"
                    + "public KeyNamePair getKeyNamePair() "
                    + "{return new KeyNamePair(get_ID(), ")
            .append(method)
            .append(");}");
    return sb;
  } //	createKeyNamePair

  /**
   * ************************************************************************ Write to file
   *
   * @param sb string buffer
   * @param fileName file name
   */
  private void writeToFile(StringBuffer sb, String fileName) {
    try {
      File out = new File(fileName);
      FileWriter fw = new FileWriter(out);
      for (int i = 0; i < sb.length(); i++) {
        char c = sb.charAt(i);
        //	after
        if (c == ';' || c == '}') {
          fw.write(c);
          if (sb.substring(i + 1).startsWith("//")) fw.write('\t');
          else fw.write(Env.NL);
        }
        //	before & after
        else if (c == '{') {
          fw.write(Env.NL);
          fw.write(c);
          fw.write(Env.NL);
        } else fw.write(c);
      }
      fw.flush();
      fw.close();
      float size = out.length();
      size /= 1024;
      log.info(out.getAbsolutePath() + " - " + size + " kB");
    } catch (Exception ex) {
      log.log(Level.SEVERE, fileName, ex);
    }
  } //	writeToFile

  /**
   * String representation
   *
   * @return string representation
   */
  public String toString() {
    StringBuffer sb = new StringBuffer("GenerateModel[").append("]");
    return sb.toString();
  } //	toString

  /**
   * ************************************************************************ Generate PO Model
   * Class.
   *
   * <pre>
   * 	Example: java GenerateModel.class mydirectory myPackage 'U','A'
   * 	would generate entity type User and Application classes into mydirectory.
   * 	Without parameters, the default is used:
   * 	C:\Adempiere\adempiere-all\extend\src\adempiere\model\ adempiere.model 'U','A'
   * 	</pre>
   *
   * @param args directory package entityType - directory where to save the generated file - package
   *     of the classes to be generated - entityType to be generated
   */
  public static void main(String[] args) {
    org.compiere.Adempiere.startupEnvironment(true);
    CLogMgt.setLevel(Level.FINE);
    //	CLogMgt.setLevel(Level.ALL);
    log.info("Generate Model   $Revision: 1.5 $");
    log.info("----------------------------------");
    //	first parameter
    String directory = "/app/adempiere/adempiere_branch_3.1.1/dbPort/src/org/adempiere/model/";
    if (args.length > 0) directory = args[0];
    if (directory == null || directory.length() == 0) {
      System.err.println("No Directory");
      System.exit(1);
    }
    log.info("Directory: " + directory);

    //	second parameter
    String packageName = "adempiere.model";
    if (args.length > 1) packageName = args[1];
    if (packageName == null || packageName.length() == 0) {
      System.err.println("No package");
      System.exit(1);
    }
    log.info("Package:   " + packageName);

    //	third parameter
    String entityType = "'U','A','D'"; // 	User, Application
    if (args.length > 2) entityType = args[2];
    if (entityType == null || entityType.length() == 0) {
      System.err.println("No EntityType");
      System.exit(1);
    }
    StringBuffer sql = new StringBuffer("EntityType IN (").append(entityType).append(")");
    log.info(sql.toString());
    log.info("----------------------------------");

    //	complete sql
    sql.insert(
        0,
        "SELECT AD_Table_ID "
            + "FROM AD_Table "
            + "WHERE (TableName IN ('RV_WarehousePrice','RV_BPartner')" //	special views
            + " OR IsView='N')"
            + " AND TableName NOT LIKE '%_Trl' AND ");
    sql.append(" ORDER BY TableName");

    //
    int count = 0;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql.toString(), null);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        new GenerateModelJPA(rs.getInt(1), directory, packageName);
        count++;
      }
    } catch (Exception e) {
      log.severe("main - " + e);
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }

    log.info("Generated = " + count);
  } //	main
} //	GenerateModel
예제 #13
0
/**
 * Dialog to enter Account Info
 *
 * @author Jorg Janke
 * @version $Id: VAccountDialog.java,v 1.3 2006/07/30 00:51:28 jjanke Exp $
 */
public final class VAccountDialog extends CDialog
    implements ActionListener, DataStatusListener, VetoableChangeListener {
  /** */
  private static final long serialVersionUID = -1980622319541357651L;

  /** Mouse Listener */
  class VAccountDialog_mouseAdapter extends java.awt.event.MouseAdapter {
    VAccountDialog_mouseAdapter(VAccountDialog adaptee) {
      this.adaptee = adaptee;
    }

    VAccountDialog adaptee;

    public void mouseClicked(MouseEvent e) {
      //	Table => select
      if (e.getSource() instanceof JTable && e.getClickCount() > 1) {
        adaptee.m_changed = true;
        adaptee.dispose();
      }
    }
  } //	VAccountDialog_mouseListener

  /**
   * Constructor
   *
   * @param frame frame
   * @param title title
   * @param mAccount account info
   * @param C_AcctSchema_ID as
   */
  public VAccountDialog(Frame frame, String title, MAccountLookup mAccount, int C_AcctSchema_ID) {
    super(frame, title, true);
    log.config(
        "C_AcctSchema_ID="
            + C_AcctSchema_ID
            + ", C_ValidCombination_ID="
            + mAccount.C_ValidCombination_ID);
    m_mAccount = mAccount;
    m_C_AcctSchema_ID = C_AcctSchema_ID;
    m_WindowNo = Env.createWindowNo(this);
    setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    try {
      jbInit();
    } catch (Exception ex) {
      log.log(Level.SEVERE, ex.toString());
    }
    if (initAccount()) AEnv.showCenterWindow(frame, this);
    else dispose();
  } //	VLocationDialog

  /** Window No */
  private int m_WindowNo;
  /** Journal Entry * private boolean m_onlyNonDocControlled = false; /** Selection changed */
  protected boolean m_changed = false;

  /** Accounting Schema */
  private static MAcctSchema s_AcctSchema = null;
  /** MWindow for AccountCombination */
  private GridWindow m_mWindow = null;
  /** MTab for AccountCombination */
  private GridTab m_mTab = null;
  /** GridController */
  private GridController m_gridController = null;

  /** Account used */
  private MAccountLookup m_mAccount = null;
  /** Result */
  private int m_C_ValidCombination_ID;
  /** Acct Schema */
  private int m_C_AcctSchema_ID = 0;
  /** Client */
  private int m_AD_Client_ID;
  /** Where clause for combination search */
  private MQuery m_query;
  /** Logger */
  private static CLogger log = CLogger.getCLogger(VAccountDialog.class);

  //  Editors for Query
  private VEditor f_Alias,
      f_Combination,
      f_AD_Org_ID,
      f_Account_ID,
      f_SubAcct_ID,
      f_M_Product_ID,
      f_C_BPartner_ID,
      f_C_Campaign_ID,
      f_C_LocFrom_ID,
      f_C_LocTo_ID,
      f_C_Project_ID,
      f_C_SalesRegion_ID,
      f_AD_OrgTrx_ID,
      f_C_Activity_ID,
      f_User1_ID,
      f_User2_ID;
  //
  private JLabel f_Description = new JLabel("", JLabel.CENTER);

  private GridBagConstraints m_gbc = new GridBagConstraints();
  private Insets m_labelInsets = new Insets(2, 15, 2, 0); // 	top,left,bottom,right
  private Insets m_fieldInsets = new Insets(2, 5, 2, 10);
  private int m_line = 0;
  private boolean m_newRow = true;
  //
  private CPanel panel = new CPanel();
  private BorderLayout panelLayout = new BorderLayout();
  private ConfirmPanel confirmPanel = new ConfirmPanel(true);
  private TitledBorder titledBorder;
  private StatusBar statusBar = new StatusBar();
  private CPanel northPanel = new CPanel();
  private CPanel parameterPanel = new CPanel();
  private GridBagLayout parameterLayout = new GridBagLayout();
  private BorderLayout northLayout = new BorderLayout();
  private JToolBar toolBar = new JToolBar();
  private CButton bRefresh = new CButton();
  private CButton bSave = new CButton();
  private CButton bIgnore = new CButton();

  /**
   * Static component init.
   *
   * <pre>
   *  - panel
   *      - northPanel
   *          - parameterPanel
   *          - toolBar
   *      - gridController
   *      - confirmPanel
   *  - statusBar
   *  </pre>
   *
   * @throws Exception
   */
  void jbInit() throws Exception {
    // [ 1707303 ] Account Combination Form(VAccountDialog) translation issue
    titledBorder =
        new TitledBorder(
            BorderFactory.createEtchedBorder(Color.white, new Color(134, 134, 134)),
            Msg.getMsg(Env.getCtx(), "Parameter"));
    //
    panelLayout.setHgap(5);
    panelLayout.setVgap(5);
    northLayout.setHgap(5);
    northLayout.setVgap(5);
    //
    parameterPanel.setLayout(parameterLayout);
    parameterPanel.setBorder(titledBorder);
    northPanel.setLayout(northLayout);
    toolBar.setOrientation(JToolBar.VERTICAL);
    toolBar.setBorder(null);
    toolBar.setRequestFocusEnabled(false);
    toolBar.setBorderPainted(false);
    toolBar.setMargin(new Insets(5, 5, 5, 5));
    bSave.setIcon(new ImageIcon(ResourceFinder.getResource("images/Save24.gif")));
    bSave.setMargin(new Insets(2, 2, 2, 2));
    bSave.setToolTipText(Msg.getMsg(Env.getCtx(), "AccountNewUpdate"));
    bSave.addActionListener(this);
    bRefresh.setIcon(new ImageIcon(ResourceFinder.getResource("images/Refresh24.gif")));
    bRefresh.setMargin(new Insets(2, 2, 2, 2));
    bRefresh.setToolTipText(Msg.getMsg(Env.getCtx(), "Refresh"));
    bRefresh.addActionListener(this);
    bIgnore.setIcon(new ImageIcon(ResourceFinder.getResource("images/Ignore24.gif")));
    bIgnore.setMargin(new Insets(2, 2, 2, 2));
    bIgnore.setToolTipText(Msg.getMsg(Env.getCtx(), "Ignore"));
    bIgnore.addActionListener(this);
    //
    toolBar.addSeparator();
    toolBar.add(bRefresh, null);
    toolBar.add(bIgnore, null);
    toolBar.add(bSave, null);
    //
    getContentPane().add(panel);
    panel.setLayout(panelLayout);
    panel.add(confirmPanel, BorderLayout.SOUTH);
    panel.add(northPanel, BorderLayout.NORTH);
    northPanel.add(parameterPanel, BorderLayout.CENTER);
    northPanel.add(toolBar, BorderLayout.EAST);
    //
    this.getContentPane().add(statusBar, BorderLayout.SOUTH);
    confirmPanel.addActionListener(this);
  } //	jbInit

  /**
   * Dyanmic Init. When a row is selected, the editor values are set (editors do not change grid)
   *
   * @return true if initialized
   */
  private boolean initAccount() {
    m_AD_Client_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "AD_Client_ID");
    //	Get AcctSchema Info
    if (s_AcctSchema == null || s_AcctSchema.getC_AcctSchema_ID() != m_C_AcctSchema_ID)
      s_AcctSchema = new MAcctSchema(Env.getCtx(), m_C_AcctSchema_ID, null);
    log.config(s_AcctSchema.toString() + ", #" + s_AcctSchema.getAcctSchemaElements().length);
    Env.setContext(Env.getCtx(), m_WindowNo, "C_AcctSchema_ID", m_C_AcctSchema_ID);

    //  Model
    int AD_Window_ID = 153; // 	Maintain Account Combinations
    GridWindowVO wVO = AEnv.getMWindowVO(m_WindowNo, AD_Window_ID, 0);
    if (wVO == null) return false;
    m_mWindow = new GridWindow(wVO);
    m_mTab = m_mWindow.getTab(0);
    // Make sure is the tab is loaded - teo_sarca [ 1659124 ]
    if (!m_mTab.isLoadComplete()) m_mWindow.initTab(0);

    //  ParameterPanel restrictions
    m_mTab.getField("Alias").setDisplayLength(15);
    m_mTab.getField("Combination").setDisplayLength(15);
    //  Grid restrictions
    m_mTab.getField("AD_Client_ID").setDisplayed(false);
    m_mTab.getField("C_AcctSchema_ID").setDisplayed(false);
    m_mTab.getField("IsActive").setDisplayed(false);
    m_mTab.getField("IsFullyQualified").setDisplayed(false);
    //  don't show fields not being displayed in this environment
    for (int i = 0; i < m_mTab.getFieldCount(); i++) {
      GridField field = m_mTab.getField(i);
      if (!field.isDisplayed(true)) //  check context
      field.setDisplayed(false);
    }

    //  GridController
    m_gridController = new GridController();
    m_gridController.initGrid(m_mTab, true, m_WindowNo, null, null);
    m_gridController.setPreferredSize(new Dimension(300, 100));
    panel.add(m_gridController, BorderLayout.CENTER);

    //  Prepare Parameter
    m_gbc.anchor = GridBagConstraints.NORTHWEST;
    m_gbc.gridy = 0; // 	line
    m_gbc.gridx = 0;
    m_gbc.gridwidth = 1;
    m_gbc.insets = m_fieldInsets;
    m_gbc.fill = GridBagConstraints.HORIZONTAL;
    m_gbc.weightx = 0;
    m_gbc.weighty = 0;

    int TabNo = 0;

    //	Alias
    if (s_AcctSchema.isHasAlias()) {
      GridField alias = m_mTab.getField("Alias");
      f_Alias = VEditorFactory.getEditor(m_mTab, alias, false);
      addLine(alias, f_Alias, false);
    } //	Alias

    //	Combination
    GridField combination = m_mTab.getField("Combination");
    f_Combination = VEditorFactory.getEditor(m_mTab, combination, false);
    addLine(combination, f_Combination, false);
    m_newRow = true;

    /** Create Fields in Element Order */
    MAcctSchemaElement[] elements = s_AcctSchema.getAcctSchemaElements();
    for (int i = 0; i < elements.length; i++) {
      MAcctSchemaElement ase = elements[i];
      String type = ase.getElementType();
      boolean isMandatory = ase.isMandatory();
      //
      if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Organization)) {
        GridField field = m_mTab.getField("AD_Org_ID");
        f_AD_Org_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_AD_Org_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Account)) {
        GridField field = m_mTab.getField("Account_ID");
        f_Account_ID = VEditorFactory.getEditor(m_mTab, field, false);
        //	((VLookup)f_Account_ID).setWidth(400);
        addLine(field, f_Account_ID, isMandatory);
        f_Account_ID.addVetoableChangeListener(this);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_SubAccount)) {
        GridField field = m_mTab.getField("C_SubAcct_ID");
        f_SubAcct_ID = VEditorFactory.getEditor(m_mTab, field, false);
        //	((VLookup)f_SubAcct_ID).setWidth(400);
        addLine(field, f_SubAcct_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Product)) {
        GridField field = m_mTab.getField("M_Product_ID");
        f_M_Product_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_M_Product_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_BPartner)) {
        GridField field = m_mTab.getField("C_BPartner_ID");
        f_C_BPartner_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_BPartner_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Campaign)) {
        GridField field = m_mTab.getField("C_Campaign_ID");
        f_C_Campaign_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_Campaign_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_LocationFrom)) {
        GridField field = m_mTab.getField("C_LocFrom_ID");
        f_C_LocFrom_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_LocFrom_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_LocationTo)) {
        GridField field = m_mTab.getField("C_LocTo_ID");
        f_C_LocTo_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_LocTo_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Project)) {
        GridField field = m_mTab.getField("C_Project_ID");
        f_C_Project_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_Project_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_SalesRegion)) {
        GridField field = m_mTab.getField("C_SalesRegion_ID");
        f_C_SalesRegion_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_SalesRegion_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_OrgTrx)) {
        GridField field = m_mTab.getField("AD_OrgTrx_ID");
        f_AD_OrgTrx_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_AD_OrgTrx_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Activity)) {
        GridField field = m_mTab.getField("C_Activity_ID");
        f_C_Activity_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_C_Activity_ID, isMandatory);
      }
      //	User1
      else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_UserList1)) {
        GridField field = m_mTab.getField("User1_ID");
        f_User1_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_User1_ID, isMandatory);
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_UserList2)) {
        GridField field = m_mTab.getField("User2_ID");
        f_User2_ID = VEditorFactory.getEditor(m_mTab, field, false);
        addLine(field, f_User2_ID, isMandatory);
      }
    } //	Create Fields in Element Order

    //	Add description
    m_newRow = true;
    m_gbc.gridy = m_line++;
    m_gbc.gridx = 0;
    m_gbc.gridwidth = 4;
    m_gbc.insets = new Insets(5, 15, 2, 0); // 	top,left,bottom,right
    m_gbc.fill = GridBagConstraints.HORIZONTAL;
    f_Description.setFont(f_Description.getFont().deriveFont(Font.ITALIC));
    parameterPanel.add(f_Description, m_gbc);

    //	Finish
    m_query = new MQuery();
    m_query.addRestriction("C_AcctSchema_ID", MQuery.EQUAL, m_C_AcctSchema_ID);
    m_query.addRestriction("IsFullyQualified", MQuery.EQUAL, "Y");
    if (m_mAccount.C_ValidCombination_ID == 0) m_mTab.setQuery(MQuery.getEqualQuery("1", "2"));
    else {
      MQuery query = new MQuery();
      query.addRestriction("C_AcctSchema_ID", MQuery.EQUAL, m_C_AcctSchema_ID);
      query.addRestriction("C_ValidCombination_ID", MQuery.EQUAL, m_mAccount.C_ValidCombination_ID);
      m_mTab.setQuery(query);
    }
    m_mTab.query(false);
    m_gridController.getTable().addMouseListener(new VAccountDialog_mouseAdapter(this));
    m_gridController.addDataStatusListener(this);

    statusBar.setStatusLine(s_AcctSchema.toString());
    statusBar.setStatusDB("?");

    //	Initial value
    if (m_mAccount.C_ValidCombination_ID != 0) m_mTab.navigate(0);

    log.config("fini");
    return true;
  } //	initAccount

  /**
   * Add Editor to parameterPanel alernative right/left depending on m_newRow. Field Value changes
   * update Editors
   *
   * @param field field
   * @param editor editor
   * @param mandatory mandatory
   */
  private void addLine(GridField field, VEditor editor, boolean mandatory) {
    log.fine("Field=" + field);
    JLabel label = VEditorFactory.getLabel(field);
    label.setLabelFor((Component) editor);
    editor.setReadWrite(true);
    editor.setMandatory(mandatory);
    //  MField => VEditor
    field.addPropertyChangeListener(editor);

    //	label
    if (m_newRow) {
      m_gbc.gridy = m_line++;
      m_gbc.gridx = 0;
    } else m_gbc.gridx = 2;
    m_gbc.insets = m_labelInsets;
    m_gbc.fill = GridBagConstraints.HORIZONTAL;
    m_gbc.weightx = 0;
    parameterPanel.add(label, m_gbc);

    //	Field
    if (m_newRow) m_gbc.gridx = 1;
    else m_gbc.gridx = 3;
    m_gbc.insets = m_fieldInsets;
    m_gbc.fill = GridBagConstraints.HORIZONTAL;
    m_gbc.weightx = 1;
    parameterPanel.add((Component) editor, m_gbc);
    //
    m_newRow = !m_newRow;
  } //	addLine

  /**
   * Load Information
   *
   * @param C_ValidCombination_ID valid combination
   * @param C_AcctSchema_ID acct schema
   */
  private void loadInfo(int C_ValidCombination_ID, int C_AcctSchema_ID) {
    log.fine("C_ValidCombination_ID=" + C_ValidCombination_ID);
    String sql =
        "SELECT * FROM C_ValidCombination WHERE C_ValidCombination_ID=? AND C_AcctSchema_ID=?";
    try {
      PreparedStatement pstmt = DB.prepareStatement(sql, null);
      pstmt.setInt(1, C_ValidCombination_ID);
      pstmt.setInt(2, C_AcctSchema_ID);
      ResultSet rs = pstmt.executeQuery();
      if (rs.next()) {
        if (f_Alias != null) f_Alias.setValue(rs.getString("Alias"));
        f_Combination.setValue(rs.getString("Combination"));
        //
        loadInfoOf(rs, f_AD_Org_ID, "AD_Org_ID");
        loadInfoOf(rs, f_Account_ID, "Account_ID");
        loadInfoOf(rs, f_SubAcct_ID, "C_SubAcct_ID");
        //
        loadInfoOf(rs, f_M_Product_ID, "M_Product_ID");
        loadInfoOf(rs, f_C_BPartner_ID, "C_BPartner_ID");
        loadInfoOf(rs, f_C_Campaign_ID, "C_Campaign_ID");
        loadInfoOf(rs, f_C_LocFrom_ID, "C_LocFrom_ID");
        loadInfoOf(rs, f_C_LocTo_ID, "C_LocTo_ID");
        loadInfoOf(rs, f_C_Project_ID, "C_Project_ID");
        loadInfoOf(rs, f_C_SalesRegion_ID, "C_SalesRegion_ID");
        loadInfoOf(rs, f_AD_OrgTrx_ID, "AD_OrgTrx_ID");
        loadInfoOf(rs, f_C_Activity_ID, "C_Activity_ID");
        loadInfoOf(rs, f_User1_ID, "User1_ID");
        loadInfoOf(rs, f_User2_ID, "User2_ID");
        //
        f_Description.setText(rs.getString("Description"));
      }
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    }
  } //	loadInfo

  /**
   * Set Value of Editor
   *
   * @param rs result set
   * @param editor editor
   * @param name name
   * @throws SQLException
   */
  private void loadInfoOf(ResultSet rs, VEditor editor, String name) throws SQLException {
    if (editor == null) return;
    int intValue = rs.getInt(name);
    if (rs.wasNull()) editor.setValue(null);
    else editor.setValue(new Integer(intValue));
  } //	loadInfoOf

  /** dispose */
  public void dispose() {
    saveSelection();
    //  GridController
    if (m_gridController != null) m_gridController.dispose();
    m_gridController = null;
    //  Model
    m_mTab = null;
    if (m_mWindow != null) m_mWindow.dispose();
    m_mWindow = null;

    removeAll();
    Env.clearWinContext(m_WindowNo);
    super.dispose();
  } //	dispose

  /** Save Selection */
  private void saveSelection() {
    if (m_changed && m_gridController != null) {
      int row = m_gridController.getTable().getSelectedRow();
      if (row >= 0)
        m_C_ValidCombination_ID =
            ((Integer) m_mTab.getValue(row, "C_ValidCombination_ID")).intValue();
      log.config("(" + row + ") - " + m_C_ValidCombination_ID);
    }
  } //	saveSelection

  /**
   * ActionListener
   *
   * @param e event
   */
  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals(ConfirmPanel.A_OK)) {
      m_changed = true;
      dispose();
    } else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) {
      m_changed = false;
      dispose();
    }
    //
    else if (e.getSource() == bSave) action_Save();
    else if (e.getSource() == bIgnore) action_Ignore();
    //	all other
    else action_Find(true);
  } //	actionPerformed

  /**
   * Status Change Listener
   *
   * @param e event
   */
  public void dataStatusChanged(DataStatusEvent e) {
    log.config(e.toString());
    String info = (String) m_mTab.getValue("Description");
    f_Description.setText(info);
    //
    //	log.info( ">> Field=" + m_mTab.getValue("AD_Org_ID"),
    //		"Editor=" + f_AD_Org_ID.getValue());
    //	if (f_AD_Org_ID.getValue() == null)
    //		f_AD_Org_ID.setValue(m_mTab.getValue("AD_Org_ID"));
  } //	statusChanged

  /**
   * Action Find. - create where clause - query database
   *
   * @param includeAliasCombination include alias combination
   */
  private void action_Find(boolean includeAliasCombination) {
    log.info("");
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    //	Create where Clause
    MQuery query = null;
    if (m_query != null) query = m_query.deepCopy();
    else query = new MQuery();
    //	Alias
    if (includeAliasCombination && f_Alias != null && f_Alias.getValue().toString().length() > 0) {
      String value = f_Alias.getValue().toString().toUpperCase();
      if (!value.endsWith("%")) value += "%";
      query.addRestriction("UPPER(Alias)", MQuery.LIKE, value);
    }
    //	Combination (mandatory)
    if (includeAliasCombination && f_Combination.getValue().toString().length() > 0) {
      String value = f_Combination.getValue().toString().toUpperCase();
      if (!value.endsWith("%")) value += "%";
      query.addRestriction("UPPER(Combination)", MQuery.LIKE, value);
    }
    //	Org (mandatory)
    if (f_AD_Org_ID != null && f_AD_Org_ID.getValue() != null)
      query.addRestriction("AD_Org_ID", MQuery.EQUAL, f_AD_Org_ID.getValue());
    //	Account (mandatory)
    if (f_Account_ID != null && f_Account_ID.getValue() != null)
      query.addRestriction("Account_ID", MQuery.EQUAL, f_Account_ID.getValue());
    if (f_SubAcct_ID != null && f_SubAcct_ID.getValue() != null)
      query.addRestriction("C_SubAcct_ID", MQuery.EQUAL, f_SubAcct_ID.getValue());

    //	Product
    if (f_M_Product_ID != null && f_M_Product_ID.getValue() != null)
      query.addRestriction("M_Product_ID", MQuery.EQUAL, f_M_Product_ID.getValue());
    //	BPartner
    if (f_C_BPartner_ID != null && f_C_BPartner_ID.getValue() != null)
      query.addRestriction("C_BPartner_ID", MQuery.EQUAL, f_C_BPartner_ID.getValue());
    //	Campaign
    if (f_C_Campaign_ID != null && f_C_Campaign_ID.getValue() != null)
      query.addRestriction("C_Campaign_ID", MQuery.EQUAL, f_C_Campaign_ID.getValue());
    //	Loc From
    if (f_C_LocFrom_ID != null && f_C_LocFrom_ID.getValue() != null)
      query.addRestriction("C_LocFrom_ID", MQuery.EQUAL, f_C_LocFrom_ID.getValue());
    //	Loc To
    if (f_C_LocTo_ID != null && f_C_LocTo_ID.getValue() != null)
      query.addRestriction("C_LocTo_ID", MQuery.EQUAL, f_C_LocTo_ID.getValue());
    //	Project
    if (f_C_Project_ID != null && f_C_Project_ID.getValue() != null)
      query.addRestriction("C_Project_ID", MQuery.EQUAL, f_C_Project_ID.getValue());
    //	SRegion
    if (f_C_SalesRegion_ID != null && f_C_SalesRegion_ID.getValue() != null)
      query.addRestriction("C_SalesRegion_ID", MQuery.EQUAL, f_C_SalesRegion_ID.getValue());
    //	Org Trx
    if (f_AD_OrgTrx_ID != null && f_AD_OrgTrx_ID.getValue() != null)
      query.addRestriction("AD_OrgTrx_ID", MQuery.EQUAL, f_AD_OrgTrx_ID.getValue());
    //	Activity
    if (f_C_Activity_ID != null && f_C_Activity_ID.getValue() != null)
      query.addRestriction("C_Activity_ID", MQuery.EQUAL, f_C_Activity_ID.getValue());
    //	User 1
    if (f_User1_ID != null && f_User1_ID.getValue() != null)
      query.addRestriction("User1_ID", MQuery.EQUAL, f_User1_ID.getValue());
    //	User 2
    if (f_User2_ID != null && f_User2_ID.getValue() != null)
      query.addRestriction("User2_ID", MQuery.EQUAL, f_User2_ID.getValue());

    //	Query
    m_mTab.setQuery(query);
    m_mTab.query(false);
    statusBar.setStatusDB(String.valueOf(m_mTab.getRowCount()));
    setCursor(Cursor.getDefaultCursor());
  } //	action_Find

  /** Create/Save Account */
  private void action_Save() {
    log.info("");
    /** Check completeness (mandatory fields) ... and for duplicates */
    StringBuffer sb = new StringBuffer();
    StringBuffer sql =
        new StringBuffer("SELECT C_ValidCombination_ID, Alias FROM C_ValidCombination WHERE ");
    Object value = null;
    if (s_AcctSchema.isHasAlias()) {
      value = f_Alias.getValue().toString();
      if (value == null) sb.append(Msg.translate(Env.getCtx(), "Alias")).append(", ");
    }
    MAcctSchemaElement[] elements = s_AcctSchema.getAcctSchemaElements();
    for (int i = 0; i < elements.length; i++) {
      MAcctSchemaElement ase = elements[i];
      String type = ase.getElementType();
      //
      if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Organization)) {
        value = f_AD_Org_ID.getValue();
        sql.append("AD_Org_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Account)) {
        value = f_Account_ID.getValue();
        sql.append("Account_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_SubAccount)) {
        value = f_SubAcct_ID.getValue();
        sql.append("C_SubAcct_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Product)) {
        value = f_M_Product_ID.getValue();
        sql.append("M_Product_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_BPartner)) {
        value = f_C_BPartner_ID.getValue();
        sql.append("C_BPartner_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Campaign)) {
        value = f_C_Campaign_ID.getValue();
        sql.append("C_Campaign_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_LocationFrom)) {
        value = f_C_LocFrom_ID.getValue();
        sql.append("C_LocFrom_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_LocationTo)) {
        value = f_C_LocTo_ID.getValue();
        sql.append("C_LocTo_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Project)) {
        value = f_C_Project_ID.getValue();
        sql.append("C_Project_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_SalesRegion)) {
        value = f_C_SalesRegion_ID.getValue();
        sql.append("C_SalesRegion_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_OrgTrx)) {
        value = f_AD_OrgTrx_ID.getValue();
        sql.append("AD_OrgTrx_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_Activity)) {
        value = f_C_Activity_ID.getValue();
        sql.append("C_Activity_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_UserList1)) {
        value = f_User1_ID.getValue();
        sql.append("User1_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      } else if (type.equals(MAcctSchemaElement.ELEMENTTYPE_UserList2)) {
        value = f_User2_ID.getValue();
        sql.append("User2_ID");
        if (value == null) sql.append(" IS NULL AND ");
        else sql.append("=").append(value).append(" AND ");
      }
      //
      if (ase.isMandatory() && value == null) sb.append(ase.getName()).append(", ");
    } //	Fields in Element Order

    if (sb.length() != 0) {
      ADialog.error(m_WindowNo, this, "FillMandatory", sb.substring(0, sb.length() - 2));
      return;
    }
    if (f_AD_Org_ID == null || f_AD_Org_ID.getValue() == null) {
      ADialog.error(m_WindowNo, this, "FillMandatory", Msg.getElement(Env.getCtx(), "AD_Org_ID"));
      return;
    }
    if (f_Account_ID == null || f_Account_ID.getValue() == null) {
      ADialog.error(m_WindowNo, this, "FillMandatory", Msg.getElement(Env.getCtx(), "Account_ID"));
      return;
    }

    /** Check if already exists */
    sql.append("AD_Client_ID=? AND C_AcctSchema_ID=?");
    log.fine("Check = " + sql.toString());
    int IDvalue = 0;
    String Alias = null;
    try {
      PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
      pstmt.setInt(1, m_AD_Client_ID);
      pstmt.setInt(2, s_AcctSchema.getC_AcctSchema_ID());
      ResultSet rs = pstmt.executeQuery();
      if (rs.next()) {
        IDvalue = rs.getInt(1);
        Alias = rs.getString(2);
      }
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql.toString(), e);
      IDvalue = 0;
    }
    log.fine("ID=" + IDvalue + ", Alias=" + Alias);

    if (Alias == null) Alias = "";

    //	We have an account like this already - check alias
    if (IDvalue != 0 && s_AcctSchema.isHasAlias() && !f_Alias.getValue().toString().equals(Alias)) {
      sql = new StringBuffer("UPDATE C_ValidCombination SET Alias=");
      if (f_Alias.getValue().toString().length() == 0) sql.append("NULL");
      else sql.append("'").append(f_Alias.getValue()).append("'");
      sql.append(" WHERE C_ValidCombination_ID=").append(IDvalue);
      int i = 0;
      try {
        java.sql.PreparedStatement stmt =
            DB.prepareStatement(
                sql.toString(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE, null);
        i = stmt.executeUpdate();
        stmt.close();
      } catch (SQLException e) {
        log.log(Level.SEVERE, sql.toString(), e);
      }
      if (i == 0) ADialog.error(m_WindowNo, this, "AccountNotUpdated");
    }

    //	load and display
    if (IDvalue != 0) {
      loadInfo(IDvalue, s_AcctSchema.getC_AcctSchema_ID());
      action_Find(false);
      return;
    }

    log.config("New");
    Alias = null;
    if (f_Alias != null) Alias = f_Alias.getValue().toString();
    int C_SubAcct_ID = 0;
    if (f_SubAcct_ID != null && f_SubAcct_ID.getValue() != null)
      C_SubAcct_ID = ((Integer) f_SubAcct_ID.getValue()).intValue();
    int M_Product_ID = 0;
    if (f_M_Product_ID != null && f_M_Product_ID.getValue() != null)
      M_Product_ID = ((Integer) f_M_Product_ID.getValue()).intValue();
    int C_BPartner_ID = 0;
    if (f_C_BPartner_ID != null && f_C_BPartner_ID.getValue() != null)
      C_BPartner_ID = ((Integer) f_C_BPartner_ID.getValue()).intValue();
    int AD_OrgTrx_ID = 0;
    if (f_AD_OrgTrx_ID != null && f_AD_OrgTrx_ID.getValue() != null)
      AD_OrgTrx_ID = ((Integer) f_AD_OrgTrx_ID.getValue()).intValue();
    int C_LocFrom_ID = 0;
    if (f_C_LocFrom_ID != null && f_C_LocFrom_ID.getValue() != null)
      C_LocFrom_ID = ((Integer) f_C_LocFrom_ID.getValue()).intValue();
    int C_LocTo_ID = 0;
    if (f_C_LocTo_ID != null && f_C_LocTo_ID.getValue() != null)
      C_LocTo_ID = ((Integer) f_C_LocTo_ID.getValue()).intValue();
    int C_SRegion_ID = 0;
    if (f_C_SalesRegion_ID != null && f_C_SalesRegion_ID.getValue() != null)
      C_SRegion_ID = ((Integer) f_C_SalesRegion_ID.getValue()).intValue();
    int C_Project_ID = 0;
    if (f_C_Project_ID != null && f_C_Project_ID.getValue() != null)
      C_Project_ID = ((Integer) f_C_Project_ID.getValue()).intValue();
    int C_Campaign_ID = 0;
    if (f_C_Campaign_ID != null && f_C_Campaign_ID.getValue() != null)
      C_Campaign_ID = ((Integer) f_C_Campaign_ID.getValue()).intValue();
    int C_Activity_ID = 0;
    if (f_C_Activity_ID != null && f_C_Activity_ID.getValue() != null)
      C_Activity_ID = ((Integer) f_C_Activity_ID.getValue()).intValue();
    int User1_ID = 0;
    if (f_User1_ID != null && f_User1_ID.getValue() != null)
      User1_ID = ((Integer) f_User1_ID.getValue()).intValue();
    int User2_ID = 0;
    if (f_User2_ID != null && f_User2_ID.getValue() != null)
      User2_ID = ((Integer) f_User2_ID.getValue()).intValue();

    MAccount acct =
        MAccount.get(
            Env.getCtx(),
            m_AD_Client_ID,
            ((Integer) f_AD_Org_ID.getValue()).intValue(),
            s_AcctSchema.getC_AcctSchema_ID(),
            ((Integer) f_Account_ID.getValue()).intValue(),
            C_SubAcct_ID,
            M_Product_ID,
            C_BPartner_ID,
            AD_OrgTrx_ID,
            C_LocFrom_ID,
            C_LocTo_ID,
            C_SRegion_ID,
            C_Project_ID,
            C_Campaign_ID,
            C_Activity_ID,
            User1_ID,
            User2_ID,
            0,
            0);
    if (acct != null && acct.get_ID() == 0) acct.save();

    //  Show Info
    if (acct == null || acct.get_ID() == 0) loadInfo(0, 0);
    else {
      //	Update Account with optional Alias
      if (Alias != null && Alias.length() > 0) {
        acct.setAlias(Alias);
        acct.save();
      }
      loadInfo(acct.get_ID(), s_AcctSchema.getC_AcctSchema_ID());
    }
    action_Find(false);
  } //	action_Save

  /** Ignore */
  private void action_Ignore() {
    if (f_Alias != null) f_Alias.setValue("");
    f_Combination.setValue("");
    f_Description.setText("");
    //
    //	Org (mandatory)
    f_AD_Org_ID.setValue(null);
    //	Account (mandatory)
    f_Account_ID.setValue(null);
    if (f_SubAcct_ID != null) f_SubAcct_ID.setValue(null);

    //	Product
    if (f_M_Product_ID != null) f_M_Product_ID.setValue(null);
    //	BPartner
    if (f_C_BPartner_ID != null) f_C_BPartner_ID.setValue(null);
    //	Campaign
    if (f_C_Campaign_ID != null) f_C_Campaign_ID.setValue(null);
    //	Loc From
    if (f_C_LocFrom_ID != null) f_C_LocFrom_ID.setValue(null);
    //	Loc To
    if (f_C_LocTo_ID != null) f_C_LocTo_ID.setValue(null);
    //	Project
    if (f_C_Project_ID != null) f_C_Project_ID.setValue(null);
    //	SRegion
    if (f_C_SalesRegion_ID != null) f_C_SalesRegion_ID.setValue(null);
    //	Org Trx
    if (f_AD_OrgTrx_ID != null) f_AD_OrgTrx_ID.setValue(null);
    //	Activity
    if (f_C_Activity_ID != null) f_C_Activity_ID.setValue(null);
    //	User 1
    if (f_User1_ID != null) f_User1_ID.setValue(null);
    //	User 2
    if (f_User2_ID != null) f_User2_ID.setValue(null);
  } //	action_Ignore

  /**
   * Get selected account
   *
   * @return account
   */
  public Integer getValue() {
    log.config("C_ValidCombination_ID=" + m_C_ValidCombination_ID + ", Changed=" + m_changed);
    if (!m_changed || m_C_ValidCombination_ID == 0) return null;
    return new Integer(m_C_ValidCombination_ID);
  }

  /**
   * VetoableChange - Account Changed
   *
   * @param evt event
   * @throws PropertyVetoException
   */
  public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
    Object newValue = evt.getNewValue();
    if (newValue instanceof Integer)
      Env.setContext(Env.getCtx(), m_WindowNo, "Account_ID", ((Integer) newValue).intValue());
  } //	vetoableChange
} //	VAccountDialog
/**
 * Libero Validator
 *
 * @author Victor Perez
 */
public class LiberoWMValidator implements ModelValidator {
  /** Context variable which says if libero manufacturing is enabled */
  public static final String CTX_IsLiberoWMEnabled = "#IsLiberoWMEnabled";

  /** Logger */
  private CLogger log = CLogger.getCLogger(getClass());
  /** Client */
  private int m_AD_Client_ID = -1;

  public void initialize(ModelValidationEngine engine, MClient client) {
    if (client != null) {
      m_AD_Client_ID = client.getAD_Client_ID();
    }
    engine.addModelChange(MDDOrderLine.Table_Name, this);
    // engine.addDocValidate(MDDOrderLine.Table_Name, this);
    // engine.addDocValidate(MMovement.Table_Name, this);
  } //	initialize

  public String modelChange(PO po, int type) throws Exception {
    boolean IsLiberoEnabled = "Y".equals(Env.getContext(po.getCtx(), "#IsLiberoEnabled"));
    log.info(po.get_TableName() + " Type: " + type);
    if (!IsLiberoEnabled) return null;

    if (po instanceof MDDOrderLine
        && (TYPE_AFTER_CHANGE == type
            && po.is_ValueChanged(MDDOrderLine.COLUMNNAME_QtyDelivered))) {
      MDDOrderLine oline = (MDDOrderLine) po;
      Integer WM_InOutBoundLine_ID =
          (Integer) oline.get_Value(MWMInOutBoundLine.COLUMNNAME_WM_InOutBoundLine_ID);
      if (WM_InOutBoundLine_ID != null
          && WM_InOutBoundLine_ID.intValue() > 0
          && oline.getQtyOrdered().compareTo(oline.getQtyDelivered()) >= 0) {

        MWMInOutBoundLine obline =
            new MWMInOutBoundLine(oline.getCtx(), WM_InOutBoundLine_ID, oline.get_TrxName());
        obline.setPickedQty(oline.getQtyDelivered());
        obline.saveEx();
      }
    }
    return null;
  } //	modelChange

  public String docValidate(PO po, int timing) {
    log.info(po.get_TableName() + " Timing: " + timing);
    return null;
  } //	docValidate

  /**
   * User Login. Called when preferences are set
   *
   * @param AD_Org_ID org
   * @param AD_Role_ID role
   * @param AD_User_ID user
   * @return error message or null
   */
  public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) {
    Env.setContext(Env.getCtx(), CTX_IsLiberoWMEnabled, true);
    return null;
  } //	login

  /**
   * Get Client to be monitored
   *
   * @return AD_Client_ID client
   */
  public int getAD_Client_ID() {
    return m_AD_Client_ID;
  } //	getAD_Client_ID
} //	LiberoValidator
예제 #15
0
/**
 * IntPackIn Tool.
 *
 * @author: Robert KLEIN. [email protected]
 */
public class PackIn extends SvrProcess {

  /** Logger */
  private CLogger log = CLogger.getCLogger("PackIn");
  // update system maintain dictionary, default to true
  public static String m_UpdateMode = "true";
  public static String m_Database = "Oracle";
  public static String m_Package_Dir = null;
  public int p_PackIn_ID = 0;

  private Map<String, Integer> tableCache = new HashMap<String, Integer>();
  private Map<String, Integer> columnCache = new HashMap<String, Integer>();

  /**
   * add to table id cache
   *
   * @param tableName
   * @param tableId
   */
  public void addTable(String tableName, int tableId) {
    tableCache.put(tableName, tableId);
  }

  /**
   * Find table id from cache
   *
   * @param tableName
   * @return tableId
   */
  public int getTableId(String tableName) {
    if (tableCache.containsKey(tableName)) return tableCache.get(tableName).intValue();
    else return 0;
  }

  /**
   * add to column id cache
   *
   * @param tableName
   * @param columnName
   * @param columnId
   */
  public void addColumn(String tableName, String columnName, int columnId) {
    columnCache.put(tableName + "." + columnName, columnId);
  }

  /**
   * find column id from cache
   *
   * @param tableName
   * @param columnName
   * @return column id
   */
  public int getColumnId(String tableName, String columnName) {
    String key = tableName + "." + columnName;
    if (columnCache.containsKey(key)) return columnCache.get(key).intValue();
    else return 0;
  }

  @Override
  protected void prepare() {
    p_PackIn_ID = getRecord_ID();
    ProcessInfoParameter[] para = getParameter();
    for (int i = 0; i < para.length; i++) {}
  } // prepare

  /**
   * Uses PackInHandler to update AD.
   *
   * @param fileName xml file to read
   * @return status message
   */
  public String importXML(String fileName, Properties ctx, String trxName) throws Exception {
    log.info("importXML:" + fileName);
    File in = new File(fileName);
    if (!in.exists()) {
      String msg = "File does not exist: " + fileName;
      log.info("importXML:" + msg);
      return msg;
    }
    try {
      log.info("starting");
      System.setProperty(
          "javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
      PackInHandler handler = new PackInHandler();
      handler.set_TrxName(trxName);
      handler.setCtx(ctx);
      handler.setProcess(this);
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser parser = factory.newSAXParser();
      String msg = "Start Parser";
      log.info(msg);
      parser.parse(in, handler);
      msg = "End Parser";
      log.info(msg);
      return "OK.";
    } catch (Exception e) {
      log.log(Level.SEVERE, "importXML:", e);
      throw e;
    }
  }

  /**
   * Doit
   *
   * @return ""
   */
  @Override
  protected String doIt() throws Exception {

    X_AD_Package_Imp_Proc adPackageImp = new X_AD_Package_Imp_Proc(getCtx(), p_PackIn_ID, null);

    // clear cache of previous runs
    IDFinder.clearIDCache();

    // Create Target directory if required
    String packageDirectory = adPackageImp.getAD_Package_Dir();
    if (packageDirectory == null || packageDirectory.trim().length() == 0) {
      packageDirectory = Adempiere.getAdempiereHome();
    }
    File targetDir = new File(packageDirectory + File.separator + "packages");

    if (!targetDir.exists()) {
      boolean success = (new File(packageDirectory + File.separator + "packages")).mkdirs();
      if (!success) {
        log.info("Target directory creation failed");
      }
    }

    // Unzip package
    File zipFilepath = new File(adPackageImp.getAD_Package_Source());
    log.info("zipFilepath->" + zipFilepath);
    String PackageName = CreateZipFile.getParentDir(zipFilepath);
    CreateZipFile.unpackFile(zipFilepath, targetDir);

    String dict_file =
        packageDirectory
            + File.separator
            + "packages"
            + File.separator
            + PackageName
            + File.separator
            + "dict"
            + File.separator
            + "PackOut.xml";
    log.info("dict file->" + dict_file);
    PackIn packIn = new PackIn();

    if (adPackageImp.isAD_Override_Dict() == true) PackIn.m_UpdateMode = "true";
    else PackIn.m_UpdateMode = "false";

    PackIn.m_Package_Dir =
        packageDirectory
            + File.separator
            + "packages"
            + File.separator
            + PackageName
            + File.separator;
    if (DB.isOracle()) PackIn.m_Database = "Oracle";
    else if (DB.isPostgreSQL()) PackIn.m_Database = "PostgreSQL";

    // call XML Handler
    String msg = packIn.importXML(dict_file, getCtx(), get_TrxName());

    // Generate Model Classes
    // globalqss - don't call Generate Model must be done manual
    // String args[] =
    // {IntPackIn.getAD_Package_Dir()+"/dbPort/src/org/compiere/model/",
    // "org.compiere.model","'U'"};
    // org.compiere.util.GenerateModel.main(args) ;

    return msg;
  } // doIt
} // PackIn
예제 #16
0
/**
 * Transfer data from editor to GridTab
 *
 * @author hengsin
 */
public class GridTabDataBinder implements ValueChangeListener {

  private static final CLogger logger = CLogger.getCLogger(GridTabDataBinder.class);

  private GridTab gridTab;

  /** @param gridTab */
  public GridTabDataBinder(GridTab gridTab) {
    this.gridTab = gridTab;
  }

  /** @param e */
  public void valueChange(ValueChangeEvent e) {
    if (gridTab.isProcessed()) //  only active records
    {
      Object source = e.getSource();
      if (source instanceof WEditor) {
        // Elaine 2009/05/06
        WEditor editor = (WEditor) source;
        GridField gridField = editor.getGridField();

        if (gridField != null) {
          if (!gridField.isEditable(true)) {
            logger.config("(" + gridTab.toString() + ") " + e.getPropertyName());
            return;
          }
        } else if (!editor.isReadWrite()) {
          logger.config("(" + gridTab.toString() + ") " + e.getPropertyName());
          return;
        }
      } else {
        logger.config("(" + gridTab.toString() + ") " + e.getPropertyName());
        return;
      }
    } //  processed
    logger.config(
        "("
            + gridTab.toString()
            + ") "
            + e.getPropertyName()
            + "="
            + e.getNewValue()
            + " ("
            + e.getOldValue()
            + ") "
            + (e.getOldValue() == null ? "" : e.getOldValue().getClass().getName()));

    //  Get Row/Col Info
    GridTable mTable = gridTab.getTableModel();
    int row = gridTab.getCurrentRow();
    int col = mTable.findColumn(e.getPropertyName());
    //
    if (e.getNewValue() == null
        && e.getOldValue() != null
        && e.getOldValue().toString().length() > 0) //  some editors return "" instead of null
      //        	  this is the original code from GridController, don't know what it does there but
      // it breaks ignore button for web ui
      //            mTable.setChanged (true);
      mTable.setValueAt(e.getNewValue(), row, col);
    else {

      Object newValue = e.getNewValue();
      Integer newValues[] = null;

      if (newValue instanceof Integer[]) {
        newValues = ((Integer[]) newValue);
        newValue = newValues[0];

        if (newValues.length > 1) {
          Integer valuesCopy[] = new Integer[newValues.length - 1];
          System.arraycopy(newValues, 1, valuesCopy, 0, valuesCopy.length);
          newValues = valuesCopy;
        } else {
          newValues = null;
        }
      } else if (newValue instanceof Object[]) {
        logger.severe("Multiple values can only be processed for IDs (Integer)");
        throw new IllegalArgumentException(
            "Multiple Selection values not available for this field. " + e.getPropertyName());
      }

      mTable.setValueAt(newValue, row, col);
      //  Force Callout
      if (e.getPropertyName().equals("S_ResourceAssignment_ID")) {
        GridField mField = gridTab.getField(col);
        if (mField != null && mField.getCallout().length() > 0) {
          gridTab.processFieldChange(mField); //  Dependencies & Callout
        }
      }

      if (newValues != null && newValues.length > 0) {
        // Save data, since record need to be used for generating clones.
        if (!gridTab.dataSave(false)) {
          throw new AdempiereException("SaveError");
        }

        // Retrieve the current record ID
        int recordId = gridTab.getKeyID(gridTab.getCurrentRow());

        Trx trx = Trx.get(Trx.createTrxName(), true);
        trx.start();
        try {
          saveMultipleRecords(
              Env.getCtx(),
              gridTab.getTableName(),
              e.getPropertyName(),
              recordId,
              newValues,
              trx.getTrxName());
          trx.commit();
          gridTab.dataRefreshAll();
        } catch (Exception ex) {
          trx.rollback();
          logger.severe(ex.getMessage());
          throw new AdempiereException("SaveError");
        } finally {
          trx.close();
        }
      }
    }
  } // ValueChange

  /**
   * ************************************************************************ Save Multiple records
   * - Clone a record and assign new values to each clone for a specific column.
   *
   * @param ctx context
   * @param tableName Table Name
   * @param columnName Column for which value need to be changed
   * @param recordId Record to clone
   * @param values Values to be assigned to clones for the specified column
   * @param trxName Transaction
   * @throws Exception If error is occured when loading the PO or saving clones
   * @author ashley
   */
  protected void saveMultipleRecords(
      Properties ctx,
      String tableName,
      String columnName,
      int recordId,
      Integer[] values,
      String trxName)
      throws Exception {
    if (values == null) {
      return;
    }

    int oldRow = gridTab.getCurrentRow();
    GridField lineField = gridTab.getField("Line");

    for (int i = 0; i < values.length; i++) {
      if (!gridTab.dataNew(true)) {
        throw new IllegalStateException("Could not clone tab");
      }

      gridTab.setValue(columnName, values[i]);

      if (lineField != null) {
        gridTab.setValue(lineField, 0);
      }

      if (!gridTab.dataSave(false)) {
        throw new IllegalStateException("Could not update tab");
      }

      gridTab.setCurrentRow(oldRow);
    }
  }
}
/* package */ class MRPNoteBuilder implements IMRPNoteBuilder {
  public static final MRPNoteBuilder cast(final IMRPNoteBuilder builder) {
    return (MRPNoteBuilder) builder;
  }

  // Services
  private static final transient CLogger logger = CLogger.getCLogger(MRPNoteBuilder.class);
  private final transient IMsgBL messagesBL = Services.get(IMsgBL.class);
  private final transient IADMessageDAO adMessageDAO = Services.get(IADMessageDAO.class);
  private final transient IMRPDAO mrpDAO = Services.get(IMRPDAO.class);
  private final transient IMsgBL msgBL = Services.get(IMsgBL.class);
  private final transient IProductPlanningBL productPlanningBL =
      Services.get(IProductPlanningBL.class);

  //
  // Parameters: context
  private IMRPContext _mrpContext;
  private final IMRPNotesCollector _mrpNotesCollector;
  // private IMRPExecutor _mrpExecutor;
  // Parameters: MRP Code
  private String _mrpCode;
  // Parameters: MRP segment
  private I_AD_Org _org;
  private I_M_Warehouse _warehouse;
  private I_S_Resource _plant;
  private I_M_Product _product;
  // Others
  private final Map<String, Object> _parameters = new LinkedHashMap<>();
  private final List<I_PP_MRP> _mrps = new ArrayList<>();
  private Exception _exception;
  private String _comment;
  private boolean _duplicate = false;

  public MRPNoteBuilder(final IMRPNotesCollector mrpNotesCollector) {
    super();
    Check.assumeNotNull(mrpNotesCollector, "mrpNotesCollector not null");
    _mrpNotesCollector = mrpNotesCollector;
  }

  @Override
  public void collect() {
    _mrpNotesCollector.collectNote(this);
  }

  @Override
  public I_AD_Note createMRPNote() {
    final Properties ctx = getCtx();
    final I_AD_Org org = getAD_Org_ToUse();
    final int AD_Org_ID = org == null ? 0 : org.getAD_Org_ID();
    final I_M_Warehouse warehouse = getM_Warehouse_ToUse();
    final I_S_Resource plant = getPlant_ToUse();
    final I_M_Product product = getM_Product_ToUse();
    final int productPlanningId = getPP_Product_Planning_ID_ToUse();
    final int panner_AD_User_ID = getPlanner_AD_Use_ID_ToUse();

    //
    // Note's TextMsg
    final I_AD_Message adMessageToUse = getMRPCode_AD_Message_ToUse();
    final StringBuilder noteTextMsg = new StringBuilder();
    noteTextMsg
        .append(adMessageToUse.getValue())
        .append(" - ")
        .append(messagesBL.getMsg(ctx, adMessageToUse.getValue()));

    //
    // Note's Reference text
    final String noteReference;
    if (product != null) {
      noteReference =
          messagesBL.translate(ctx, "M_Product_ID")
              + ": "
              + product.getValue()
              + " "
              + product.getName();
    } else {
      noteReference = "";
    }

    //
    // Append DocumentNos to note's TextMsg
    final Set<String> documentNos = getDocumentNos_ToUse();
    if (documentNos != null && !documentNos.isEmpty()) {
      final String documentNoPropertyName =
          messagesBL.translate(ctx, I_PP_Order.COLUMNNAME_DocumentNo);
      for (final String documentNo : documentNos) {
        noteTextMsg.append("\n" + documentNoPropertyName + ":" + documentNo);
      }
    }

    //
    // Append additional parameters to TextMsg
    final String parametersStr = getParametersAsString();
    if (!Check.isEmpty(parametersStr, true)) {
      noteTextMsg.append("\n").append(parametersStr);
    }

    //
    // Apppend Comment (if any) to note's TextMsg
    final String comment = getComment_ToUse();
    if (!Check.isEmpty(comment, true)) {
      noteTextMsg.append("\n").append(comment);
    }

    //
    // Append Exception (if any)
    final Exception exception = getException_ToUse();
    if (exception != null) {
      String exceptionStr = exception.getLocalizedMessage();
      if (exceptionStr == null || exceptionStr.length() <= 5) {
        // comment to small, better use whole exception string
        exceptionStr = exception.toString();
      }

      noteTextMsg.append("\nException: ").append(exceptionStr);

      // NOTE: since the exception is not logged anywhere, we are printing here to console
      // FIXME: create an AD_Issue and link it to create AD_Note.
      logger.log(Level.WARNING, exception.getLocalizedMessage(), exception);
    }

    //
    // Create AD_Note and return it
    {
      final I_PP_MRP mrp = getPP_MRP_ToUse();
      final int mrpId = mrp == null ? 0 : mrp.getPP_MRP_ID();

      final I_AD_Note note =
          InterfaceWrapperHelper.create(ctx, I_AD_Note.class, ITrx.TRXNAME_ThreadInherited);
      note.setAD_Org_ID(AD_Org_ID);
      note.setAD_Message_ID(adMessageToUse.getAD_Message_ID());
      note.setAD_User_ID(panner_AD_User_ID);

      // NOTE: we always shall set the AD_Table_ID=PP_MRP because else the MRP cleanup won't delete
      // this note (see org.eevolution.mrp.api.impl.MRPNoteDAO.deleteMRPNotes(IMRPContext))
      note.setAD_Table_ID(InterfaceWrapperHelper.getTableId(I_PP_MRP.class));

      if (mrpId > 0) {
        note.setRecord_ID(mrpId);
      }
      note.setM_Warehouse(warehouse);
      note.setPP_Plant(plant);
      note.setM_Product(product);
      note.setPP_Product_Planning_ID(productPlanningId);
      note.setReference(noteReference);
      note.setTextMsg(noteTextMsg.toString());
      InterfaceWrapperHelper.save(note);
      return note;
    }
  }

  @Override
  public IMRPNoteBuilder setMRPContext(final IMRPContext mrpContext) {
    _mrpContext = mrpContext;
    return this;
  }

  @Override
  public IMRPContext getMRPContext() {
    // null is allowed
    return _mrpContext;
  }

  private final Properties getCtx() {
    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      return mrpContext.getCtx();
    }

    return Env.getCtx();
  }

  @Override
  public IMRPNoteBuilder setMRPCode(final String mrpCode) {
    _mrpCode = mrpCode;
    return this;
  }

  /* package */ String getMRPCode_ToUse() {
    Check.assumeNotEmpty(_mrpCode, "mrpCode not empty");
    return _mrpCode;
  }

  private I_AD_Message getMRPCode_AD_Message_ToUse() {
    final Properties ctx = getCtx();
    final String mrpCode = getMRPCode_ToUse();
    I_AD_Message adMessage = adMessageDAO.retrieveByValue(ctx, mrpCode);
    if (adMessage == null) {
      // If MRP code not found, use MRP-999 - unknown error
      adMessage = adMessageDAO.retrieveByValue(ctx, IMRPExecutor.MRP_ERROR_999_Unknown);
    }
    Check.assumeNotNull(
        adMessage, LiberoException.class, "adMessage not null (MRPCode: {0})", mrpCode);
    return adMessage;
  }

  private I_PP_Product_Planning getProductPlanning_ToUse() {
    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      return mrpContext.getProductPlanning();
    }

    return null;
  }

  private final int getPP_Product_Planning_ID_ToUse() {
    final I_PP_Product_Planning productPlanning = getProductPlanning_ToUse();
    if (productPlanning != null) {
      return productPlanningBL.getBase_Product_Planning_ID(productPlanning);
    }

    return -1;
  }

  private int getPlanner_AD_Use_ID_ToUse() {
    final I_PP_Product_Planning productPlanning = getProductPlanning_ToUse();
    if (productPlanning == null) {
      return 0;
    }
    final int plannerId = productPlanning.getPlanner_ID();
    return plannerId < 0 ? 0 : plannerId;
  }

  @Override
  public IMRPNoteBuilder setAD_Org(final I_AD_Org org) {
    _org = org;
    return this;
  }

  private I_AD_Org getAD_Org_ToUse() {
    if (_org != null) {
      return _org;
    }

    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      return mrpContext.getAD_Org();
    }

    return null;
  }

  @Override
  public IMRPNoteBuilder setM_Product(final I_M_Product product) {
    _product = product;
    return this;
  }

  private I_M_Product getM_Product_ToUse() {
    if (_product != null) {
      return _product;
    }

    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      return mrpContext.getM_Product();
    }
    return null;
  }

  @Override
  public IMRPNoteBuilder setM_Warehouse(final I_M_Warehouse warehouse) {
    _warehouse = warehouse;
    return this;
  }

  private I_M_Warehouse getM_Warehouse_ToUse() {
    if (_warehouse != null) {
      return _warehouse;
    }

    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      return mrpContext.getM_Warehouse();
    }

    return null;
  }

  @Override
  public IMRPNoteBuilder setPlant(final I_S_Resource plant) {
    _plant = plant;
    return this;
  }

  private I_S_Resource getPlant_ToUse() {
    if (_plant != null) {
      return _plant;
    }

    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      return mrpContext.getPlant();
    }

    return null;
  }

  @Override
  public IMRPNoteBuilder addMRPRecord(final I_PP_MRP mrp) {
    if (mrp == null) {
      return this;
    }

    _mrps.add(mrp);

    return this;
  }

  @Override
  public IMRPNoteBuilder addMRPRecords(final List<I_PP_MRP> mrps) {
    if (mrps == null || mrps.isEmpty()) {
      return this;
    }

    for (final I_PP_MRP mrp : mrps) {
      addMRPRecord(mrp);
    }

    return this;
  }

  @Override
  public IMRPNoteBuilder addParameter(final String parameterName, final Object parameterValue) {
    Check.assumeNotEmpty(parameterName, "parameterName not empty");
    _parameters.put(parameterName, parameterValue);
    return this;
  }

  /* package */ String getParametersAsString() {
    if (_parameters == null || _parameters.isEmpty()) {
      return "";
    }

    final StringBuilder parametersStr = new StringBuilder();
    final Properties ctx = getCtx();
    for (final Map.Entry<String, Object> param : _parameters.entrySet()) {
      final String parameterName = param.getKey();
      String parameterDisplayName = messagesBL.translate(ctx, parameterName);
      if (Check.isEmpty(parameterDisplayName, true)) {
        parameterDisplayName = parameterName;
      }
      final Object parameterValue = param.getValue();
      final String parameterValueStr = toParameterValueString(parameterValue);

      //
      if (parametersStr.length() > 0) {
        parametersStr.append("\n");
      }
      parametersStr.append(parameterDisplayName).append(": ").append(parameterValueStr);
    }

    return parametersStr.toString();
  }

  private String toParameterValueString(final Object parameterValue) {
    return parameterValue == null ? "" : parameterValue.toString();
  }

  @Override
  public IMRPNoteBuilder setException(final Exception exception) {
    _exception = exception;
    return this;
  }

  /* package */ Exception getException_ToUse() {
    return _exception;
  }

  private Collection<I_PP_MRP> getPP_MRPs_ToUse() {
    final Map<Integer, I_PP_MRP> mrps = new LinkedHashMap<>();

    //
    // Get MRP records that were explicitelly set
    for (final I_PP_MRP mrp : _mrps) {
      mrps.put(mrp.getPP_MRP_ID(), mrp);
    }
    // If we have MRP records explicitelly assigned, there is no point checking the MRP Context
    // because developer specified them and the ones from MRP context could be not relevant
    if (!mrps.isEmpty()) {
      return mrps.values();
    }

    //
    // Get MRP records from context
    final IMRPContext mrpContext = getMRPContext();
    if (mrpContext != null) {
      final I_PP_MRP mrp = mrpContext.getPP_MRP();
      if (mrp != null) {
        mrps.put(mrp.getPP_MRP_ID(), mrp);
      }
    }

    return mrps.values();
  }

  /**
   * Facade for {@link #getPP_MRPs_ToUse()}. It will return the first {@link I_PP_MRP} record from
   * there or <code>null</code> if there are no MRP records.
   *
   * @return first MRP record or <code>null</code>
   */
  /* package */ I_PP_MRP getPP_MRP_ToUse() {
    final Collection<I_PP_MRP> mrps = getPP_MRPs_ToUse();
    if (mrps == null || mrps.isEmpty()) {
      return null;
    }

    final I_PP_MRP mrp = mrps.iterator().next();
    return mrp;
  }

  private Set<String> getDocumentNos_ToUse() {
    final Set<String> documentNos = new HashSet<String>();
    final Collection<I_PP_MRP> mrps = getPP_MRPs_ToUse();

    for (final I_PP_MRP mrp : mrps) {
      if (mrp == null) {
        // shall not happen
        continue;
      }
      final int ppMRPId = mrp.getPP_MRP_ID();
      final String documentNo = ppMRPId > 0 ? mrpDAO.getDocumentNo(ppMRPId) : null;
      documentNos.add(documentNo);
    }

    return documentNos;
  }

  @Override
  public IMRPNoteBuilder setComment(final String comment) {
    _comment = comment;
    return this;
  }

  /* package */ String getComment_ToUse() {
    if (Check.isEmpty(_comment, true)) {
      return "";
    }

    String commentTrl = msgBL.parseTranslation(getCtx(), _comment);
    if (Check.isEmpty(commentTrl, true)) {
      commentTrl = _comment;
    }
    return commentTrl;
  }

  @Override
  public IMRPNoteBuilder setQtyPlan(final BigDecimal qtyPlan) {
    addParameter("QtyPlan", qtyPlan);
    return this;
  }

  @Override
  public boolean isDuplicate() {
    return _duplicate;
  }

  @Override
  public void setDuplicate() {
    _duplicate = true;
  }
}
예제 #18
0
/**
 * Validator Example Implementation
 *
 * @author Jorg Janke
 * @version $Id: MyValidator.java,v 1.2 2006/07/30 00:51:57 jjanke Exp $
 */
public class MyValidator implements ModelValidator {
  /** Constructor. */
  public MyValidator() {
    super();
  } //	MyValidator

  /** Logger */
  private static CLogger log = CLogger.getCLogger(MyValidator.class);
  /** Client */
  private int m_AD_Client_ID = -1;
  /** User */
  private int m_AD_User_ID = -1;
  /** Role */
  private int m_AD_Role_ID = -1;

  /**
   * Initialize Validation
   *
   * @param engine validation engine
   * @param client client
   */
  public void initialize(ModelValidationEngine engine, MClient client) {
    // client = null for global validator
    if (client != null) {
      m_AD_Client_ID = client.getAD_Client_ID();
      if (log.isLoggable(Level.INFO)) log.info(client.toString());
    } else {
      if (log.isLoggable(Level.INFO)) log.info("Initializing global validator: " + this.toString());
    }

    //	We want to be informed when C_Order is created/changed
    engine.addModelChange(MOrder.Table_Name, this);
    //	We want to validate Order before preparing
    engine.addDocValidate(MOrder.Table_Name, this);
  } //	initialize

  /**
   * Model Change of a monitored Table. Called after PO.beforeSave/PO.beforeDelete when you called
   * addModelChange for the table
   *
   * @param po persistent object
   * @param type TYPE_
   * @return error message or null
   * @exception Exception if the recipient wishes the change to be not accept.
   */
  public String modelChange(PO po, int type) throws Exception {
    if (po.get_TableName().equals("C_Order") && type == TYPE_CHANGE) {
      @SuppressWarnings("unused")
      MOrder order = (MOrder) po;
      if (log.isLoggable(Level.INFO)) log.info(po.toString());
    }
    return null;
  } //	modelChange

  /**
   * Validate Document. Called as first step of DocAction.prepareIt when you called addDocValidate
   * for the table. Note that totals, etc. may not be correct.
   *
   * @param po persistent object
   * @param timing see TIMING_ constants
   * @return error message or null
   */
  public String docValidate(PO po, int timing) {
    if (log.isLoggable(Level.INFO)) log.info(po.get_TableName() + " Timing: " + timing);

    //	Ignore all after Complete events
    if (timing == TIMING_AFTER_COMPLETE) return null;

    if (timing == TIMING_BEFORE_PREPARE) {
      if (po.get_TableName().equals(MOrder.Table_Name)) {
        /**
         * Order Discount Example * MOrder order = (MOrder)po; String error = orderDiscount(order);
         * if (error != null) return error; /** Order Discount Example
         */
        if (log.isLoggable(Level.INFO)) log.info(po.toString());
      }
    }

    return null;
  } //	docValidate

  /**
   * Order Discount. Make sure that last line is discount and check correctness
   *
   * @param order order
   * @return error message or null
   */
  /*private String orderDiscount (MOrder order)
  {
  	String DISCOUNT = "Discount";
  	int C_Tax_ID = 0;
  	BigDecimal totalLines = Env.ZERO;
  	MOrderLine discountLine = null;
  	//
  	MOrderLine[] lines = order.getLines();
  	for (int i = 0; i < lines.length; i++)
  	{
  		MOrderLine oLine = lines[i];
  		String description = oLine.getDescription();
  		if (description != null && description.equals(DISCOUNT))
  			discountLine = oLine;
  		else
  		{
  			totalLines = totalLines.add(oLine.getLineNetAmt());
  			if (C_Tax_ID == 0)
  				C_Tax_ID = oLine.getC_Tax_ID();
  			else if (C_Tax_ID != oLine.getC_Tax_ID())
  				return "Order has more then one Tax, cannot add discount";
  		}
  	}
  	if (discountLine == null)
  	{
  		discountLine = new MOrderLine(order);
  		discountLine.setDescription(DISCOUNT);
  		discountLine.setQty(Env.ONE);
  		discountLine.setC_Tax_ID(C_Tax_ID);
  		discountLine.setLine(9999);
  	}
  	//	Calculate Discount
  	BigDecimal discountPercent = new BigDecimal(3);	//	3% example
  	BigDecimal discountAmt = totalLines.multiply(discountPercent);
  	discountAmt = discountAmt.divide(Env.ONEHUNDRED, order.getPrecision(), BigDecimal.ROUND_HALF_UP);
  	discountLine.setPrice(discountAmt.negate());
  	if (!discountLine.save())
  		return "Could not save discount line";

  	if (log.isLoggable(Level.INFO)) log.info(discountLine.toString());
  	order.getLines(true, null);
  	return null;
  }	//	orderDiscount*/

  /**
   * User Login. Called when preferences are set
   *
   * @param AD_Org_ID org
   * @param AD_Role_ID role
   * @param AD_User_ID user
   * @return error message or null
   */
  public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) {
    if (log.isLoggable(Level.INFO)) log.info("AD_User_ID=" + AD_User_ID);
    m_AD_User_ID = AD_User_ID;
    m_AD_Role_ID = AD_Role_ID;
    return null;
  } //	login

  /**
   * Get Client to be monitored
   *
   * @return AD_Client_ID client
   */
  public int getAD_Client_ID() {
    return m_AD_Client_ID;
  } //	getAD_Client_ID

  /**
   * String Representation
   *
   * @return info
   */
  public String toString() {
    StringBuilder sb = new StringBuilder("MyValidator[Order@Gardenworld");
    sb.append("]");
    return sb.toString();
  } //	toString

  /**
   * Sample Validator BefoMRolere Save Properties - to set mandatory properties on users avoid users
   * changing properties
   */
  public void beforeSaveProperties() {
    // not for SuperUser or role SysAdmin
    if (m_AD_User_ID == 0 // System
        || m_AD_User_ID == 100 // SuperUser
        || m_AD_Role_ID == 0) // System Administrator
    return;

    log.info("Setting default Properties");

    @SuppressWarnings("unused")
    MRole role = MRole.get(Env.getCtx(), m_AD_Role_ID);

    // Example - if you don't want user to select auto commit property
    // Ini.setProperty(Ini.P_A_COMMIT, false);

    // Example - if you don't want user to select auto login
    // Ini.setProperty(Ini.P_A_LOGIN, false);

    // Example - if you don't want user to select store password
    // Ini.setProperty(Ini.P_STORE_PWD, false);

    // Example - if you want your user inherit ALWAYS the show accounting from role
    // Ini.setProperty(Ini.P_SHOW_ACCT, role.isShowAcct());

    // Example - if you want to avoid your user from changing the working date
    /*
    Timestamp DEFAULT_TODAY =	new Timestamp(System.currentTimeMillis());
    //  Date (remove seconds)
    DEFAULT_TODAY.setHours(0);
    DEFAULT_TODAY.setMinutes(0);
    DEFAULT_TODAY.setSeconds(0);
    DEFAULT_TODAY.setNanos(0);
    Ini.setProperty(Ini.P_TODAY, DEFAULT_TODAY.toString());
    Env.setContext(Env.getCtx(), "#Date", DEFAULT_TODAY);
    */

  } // beforeSaveProperties
} //	MyValidator
예제 #19
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
예제 #20
0
/**
 * Attribute Use Model
 *
 * @author Jorg Janke
 * @version $Id: MAttributeUse.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $
 */
public class MAttributeUse extends X_M_AttributeUse {
  /** Logger for class MAttributeUse */
  private static final org.compiere.util.CLogger log =
      org.compiere.util.CLogger.getCLogger(MAttributeUse.class);
  /** */
  private static final long serialVersionUID = 1L;

  /**
   * Persistency Constructor
   *
   * @param ctx context
   * @param ignored ignored
   * @param trx transaction
   */
  public MAttributeUse(Ctx ctx, int ignored, Trx trx) {
    super(ctx, ignored, trx);
    if (ignored != 0) throw new IllegalArgumentException("Multi-Key");
  } //	MAttributeUse

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

  /**
   * After Save
   *
   * @param newRecord new
   * @param success success
   * @return success
   */
  @Override
  protected boolean afterSave(boolean newRecord, boolean success) {
    //	also used for afterDelete
    String sql =
        "UPDATE M_AttributeSet mas"
            + " SET IsInstanceAttribute='Y' "
            + "WHERE M_AttributeSet_ID= ? "
            + " AND IsInstanceAttribute='N'"
            + " AND (IsSerNo='Y' OR IsLot='Y' OR IsGuaranteeDate='Y'"
            + " OR EXISTS (SELECT * FROM M_AttributeUse mau"
            + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
            + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
            + " AND mau.IsActive='Y' AND ma.IsActive='Y'"
            + " AND ma.IsInstanceAttribute='Y')"
            + ")";
    int no = DB.executeUpdate(get_Trx(), sql, getM_AttributeSet_ID());
    if (no != 0) log.fine("afterSave - Set Instance Attribute");
    //
    sql =
        "UPDATE M_AttributeSet mas"
            + " SET IsInstanceAttribute='N' "
            + "WHERE M_AttributeSet_ID=? "
            + " AND IsInstanceAttribute='Y'"
            + "	AND IsSerNo='N' AND IsLot='N' AND IsGuaranteeDate='N'"
            + " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau"
            + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) "
            + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID"
            + " AND mau.IsActive='Y' AND ma.IsActive='Y'"
            + " AND ma.IsInstanceAttribute='Y')";
    no = DB.executeUpdate(get_Trx(), sql, getM_AttributeSet_ID());
    if (no != 0) log.fine("afterSave - Reset Instance Attribute");

    return success;
  } //	afterSave

  /**
   * After Delete
   *
   * @param success success
   * @return success
   */
  @Override
  protected boolean afterDelete(boolean success) {
    afterSave(false, success);
    return success;
  } //	afterDelete
} //	MAttributeUse
/**
 * Payment Header
 *
 * @author Wagner Germán
 * @contributor Marcos Zuñiga - http://www.ergio.com.ar
 */
public class MLARPaymentHeader extends X_LAR_PaymentHeader {
  /** */
  private static final long serialVersionUID = -2698873064570244615L;

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

  /**
   * ************************************************************************ Payment Header
   * Constructor
   *
   * @param ctx context
   * @param A_Asset_ID asset
   * @param trxName transaction name
   */
  public MLARPaymentHeader(Properties ctx, int LAR_PaymentHeader_ID, String trxName) {
    super(ctx, LAR_PaymentHeader_ID, trxName);
  } //	MLARPaymentHeader

  /**
   * Load Constructor
   *
   * @param ctx context
   * @param rs result set record
   * @param trxName transaction
   */
  public MLARPaymentHeader(Properties ctx, ResultSet rs, String trxName) {
    super(ctx, rs, trxName);
  } //	MLARPaymentHeader

  protected boolean beforeSave(boolean newRecord) {
    // TODO - Think about implement a determination of DocType similar to in MPayment.beforeSave()
    if (!newRecord) {
      MPayment[] pays;
      try {
        pays = getPayments(get_TrxName());
      } catch (SQLException e) {
        s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        return false;
      }
      for (int i = 0; i < pays.length; i++) {
        pays[i].setC_DocType_ID(getC_DocType_ID());
        pays[i].setDocumentNo(getDocumentNo());
        pays[i].setDateTrx(getDateTrx());
        pays[i].setDateAcct(getDateTrx());
        pays[i].setC_BPartner_ID(getC_BPartner_ID());
        pays[i].setIsReceipt(isReceipt());
        pays[i].setIsActive(isActive());
        if (!pays[i].save(get_TrxName())) {
          try {
            DB.rollback(false, get_TrxName());
          } catch (SQLException e) {
            s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
          }
          return false;
        }
      }
    }
    return true;
  }

  /** @param success */
  protected boolean afterDelete(boolean success) {
    if (success) {
      try {
        MPayment[] pays = getPayments(get_TrxName());
        for (int i = 0; i < pays.length; i++) {
          if (!pays[i].delete(false, get_TrxName())) {
            String msg =
                "No se pudo eliminar alguno de los pagos vinculados al documento que"
                    + "se está eliminando. Se cancelará la operación";
            s_log.severe(msg);
            ADialog.error(0, null, msg);
            return false;
          }
        }
      } catch (SQLException e) {
        s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        return false;
      }
    }
    return success;
  }

  /**
   * Devuelve un array con todos los payments vinculados a la cabecera
   *
   * @param trxName
   * @return MPayment[] array con los pagos vinculados al documento
   * @throws SQLException
   */
  public MPayment[] getPayments(String trxName) throws SQLException {
    // TODO - Analize genereate a cache for this payments
    List<MPayment> pays = new ArrayList<MPayment>();

    String sql = "SELECT * FROM C_Payment WHERE LAR_PaymentHeader_ID = ?";

    PreparedStatement pstmt;
    pstmt = DB.prepareStatement(sql, trxName);
    ResultSet rs = null;

    try {
      pstmt.setInt(1, getLAR_PaymentHeader_ID());
      rs = pstmt.executeQuery();
      while (rs.next()) pays.add(new MPayment(getCtx(), rs, trxName));
    } catch (SQLException e) {
      DB.close(rs, pstmt);
      throw e;
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }

    return pays.toArray(new MPayment[pays.size()]);
  }

  /**
   * Process document
   *
   * @param processAction document action
   * @return true if performed
   */
  public boolean processIt(String processAction) {
    s_log.info(toString());
    MPayment[] pays;
    try {
      pays = getPayments(get_TrxName());
    } catch (SQLException e) {
      s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
      return false;
    }

    for (int i = 0; i < pays.length; i++) {
      if (!pays[i].processIt(processAction)) {
        try {
          DB.rollback(false, get_TrxName());
        } catch (SQLException e) {
          s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        return false;
      }
      if (!pays[i].save(get_TrxName())) {
        try {
          DB.rollback(false, get_TrxName());
        } catch (SQLException e) {
          s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        return false;
      }
    }

    if (!isProcessed()) setProcessed(true);

    setDocStatus(processAction);

    if (!save()) {
      try {
        DB.rollback(false, get_TrxName());
      } catch (SQLException e) {
        s_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
      }
      return false;
    }
    return true;
  } //	process

  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer("MLARPaymentHeader[");
    sb.append(get_ID())
        .append("-")
        .append(getDocumentNo())
        .append(",Receipt=")
        .append(isReceipt())
        .append(",DocStatus=")
        .append(getDocStatus())
        .append("]");
    return sb.toString();
  }
} //	MLARPaymentHeader
예제 #22
0
 /** Default Constructor (not started) */
 public StateEngine() {
   this(STATE_NotStarted);
   log = CLogger.getCLogger(getClass());
 } //	State
예제 #23
0
/**
 * Movement Material Allocation
 *
 * @author Jorg Janke
 * @version $Id: MMovementLineMA.java,v 1.3 2006/07/30 00:51:05 jjanke Exp $
 */
public class MMovementLineMA extends X_M_MovementLineMA {
  /** */
  private static final long serialVersionUID = -155379485409000271L;

  /**
   * Get Material Allocations for Line
   *
   * @param ctx context
   * @param M_MovementLine_ID line
   * @param trxName trx
   * @return allocations
   */
  public static MMovementLineMA[] get(Properties ctx, int M_MovementLine_ID, String trxName) {
    ArrayList<MMovementLineMA> list = new ArrayList<MMovementLineMA>();
    String sql = "SELECT * FROM M_MovementLineMA WHERE M_MovementLine_ID=?";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, trxName);
      pstmt.setInt(1, M_MovementLine_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        list.add(new MMovementLineMA(ctx, rs, trxName));
      }
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }

    MMovementLineMA[] retValue = new MMovementLineMA[list.size()];
    list.toArray(retValue);
    return retValue;
  } //	get

  /**
   * Delete all Material Allocation for Movement
   *
   * @param M_Movement_ID movement
   * @param trxName transaction
   * @return number of rows deleted or -1 for error
   */
  public static int deleteMovementMA(int M_Movement_ID, String trxName) {
    String sql =
        "DELETE FROM M_MovementLineMA ma WHERE EXISTS "
            + "(SELECT * FROM M_MovementLine l WHERE l.M_MovementLine_ID=ma.M_MovementLine_ID"
            + " AND M_Movement_ID="
            + M_Movement_ID
            + ")";
    return DB.executeUpdate(sql, trxName);
  } //	deleteInOutMA

  /**
   * Delete all Material Allocation for Movement Line
   *
   * @param M_MovementLine_ID movement line
   * @param trxName transaction
   * @return number of rows deleted or -1 for error
   */
  public static int deleteMovementLineMA(int M_MovementLine_ID, String trxName) {
    String sql = "DELETE FROM M_MovementLineMA WHERE M_MovementLine_ID=? AND IsAutoGenerated='Y' ";
    return DB.executeUpdate(sql, M_MovementLine_ID, trxName);
  } //	deleteMovementLineMA

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

  /**
   * ************************************************************************ Standard Constructor
   *
   * @param ctx context
   * @param M_MovementLineMA_ID ignored
   * @param trxName trx
   */
  public MMovementLineMA(Properties ctx, int M_MovementLineMA_ID, String trxName) {
    super(ctx, M_MovementLineMA_ID, trxName);
    if (M_MovementLineMA_ID != 0) throw new IllegalArgumentException("Multi-Key");
  } //	MMovementLineMA

  /**
   * Load Constructor
   *
   * @param ctx context
   * @param rs result ser
   * @param trxName trx
   */
  public MMovementLineMA(Properties ctx, ResultSet rs, String trxName) {
    super(ctx, rs, trxName);
  } //	MMovementLineMA

  /**
   * Parent Constructor
   *
   * @param parent parent
   * @param M_AttributeSetInstance_ID asi
   * @param MovementQty qty
   * @param DateMaterialPolicy
   */
  public MMovementLineMA(
      MMovementLine parent,
      int M_AttributeSetInstance_ID,
      BigDecimal MovementQty,
      Timestamp DateMaterialPolicy) {
    this(parent, M_AttributeSetInstance_ID, MovementQty, DateMaterialPolicy, true);
  }

  /**
   * @param parent
   * @param M_AttributeSetInstance_ID
   * @param MovementQty
   * @param DateMaterialPolicy
   * @param isAutoGenerated
   */
  public MMovementLineMA(
      MMovementLine parent,
      int M_AttributeSetInstance_ID,
      BigDecimal MovementQty,
      Timestamp DateMaterialPolicy,
      boolean isAutoGenerated) {
    this(parent.getCtx(), 0, parent.get_TrxName());
    setClientOrg(parent);
    setM_MovementLine_ID(parent.getM_MovementLine_ID());
    //
    setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
    setMovementQty(MovementQty);
    if (DateMaterialPolicy == null) {
      if (M_AttributeSetInstance_ID > 0) {
        MAttributeSetInstance asi =
            new MAttributeSetInstance(
                parent.getCtx(), M_AttributeSetInstance_ID, parent.get_TrxName());
        DateMaterialPolicy = asi.getCreated();
      } else {
        DateMaterialPolicy = parent.getParent().getMovementDate();
      }
    }
    setDateMaterialPolicy(DateMaterialPolicy);
    setIsAutoGenerated(isAutoGenerated);
  } //	MMovementLineMA

  @Override
  public void setDateMaterialPolicy(Timestamp DateMaterialPolicy) {
    if (DateMaterialPolicy != null) DateMaterialPolicy = Util.removeTime(DateMaterialPolicy);
    super.setDateMaterialPolicy(DateMaterialPolicy);
  }

  /**
   * String Representation
   *
   * @return info
   */
  public String toString() {
    StringBuilder sb = new StringBuilder("MMovementLineMA[");
    sb.append("M_MovementLine_ID=")
        .append(getM_MovementLine_ID())
        .append(",M_AttributeSetInstance_ID=")
        .append(getM_AttributeSetInstance_ID())
        .append(", Qty=")
        .append(getMovementQty())
        .append("]");
    return sb.toString();
  } //	toString

  public static MMovementLineMA addOrCreate(
      MMovementLine line,
      int M_AttributeSetInstance_ID,
      BigDecimal MovementQty,
      Timestamp DateMaterialPolicy) {
    return addOrCreate(line, M_AttributeSetInstance_ID, MovementQty, DateMaterialPolicy, true);
  }

  public static MMovementLineMA addOrCreate(
      MMovementLine line,
      int M_AttributeSetInstance_ID,
      BigDecimal MovementQty,
      Timestamp DateMaterialPolicy,
      boolean isAutoGenerated) {
    Query query =
        new Query(
            Env.getCtx(),
            I_M_MovementLineMA.Table_Name,
            "M_MovementLine_ID=? AND M_AttributeSetInstance_ID=? AND DateMaterialPolicy=trunc(cast(? as date))",
            line.get_TrxName());
    MMovementLineMA po =
        query
            .setParameters(
                line.getM_MovementLine_ID(), M_AttributeSetInstance_ID, DateMaterialPolicy)
            .first();
    if (po == null)
      po =
          new MMovementLineMA(
              line, M_AttributeSetInstance_ID, MovementQty, DateMaterialPolicy, isAutoGenerated);
    else po.setMovementQty(po.getMovementQty().add(MovementQty));
    return po;
  }

  /**
   * @param M_MovementLine_ID
   * @param trxName
   * @return
   */
  public static BigDecimal getManualQty(int M_MovementLine_ID, String trxName) {
    String sql =
        "SELECT SUM(movementqty) FROM M_MovementLineMA ma WHERE ma.M_MovementLine_ID=?  AND ma.IsAutoGenerated='N'";
    BigDecimal totalQty = DB.getSQLValueBD(trxName, sql, M_MovementLine_ID);
    return totalQty == null ? Env.ZERO : totalQty;
  } // totalLineQty

  /**
   * ************************************************************************ Before Save
   *
   * @param newRecord new
   * @return save
   */
  protected boolean beforeSave(boolean newRecord) {
    // Set DateMaterialPolicy
    if (!newRecord && is_ValueChanged(COLUMNNAME_M_AttributeSetInstance_ID)) {
      I_M_MovementLine line = getM_MovementLine();

      Timestamp dateMPolicy = null;
      if (getM_AttributeSetInstance_ID() > 0) {
        dateMPolicy = getM_AttributeSetInstance().getCreated();
      }

      if (dateMPolicy == null) {
        I_M_Movement movement = line.getM_Movement();
        dateMPolicy = movement.getMovementDate();
      }

      setDateMaterialPolicy(dateMPolicy);
    }

    return true;
  } // beforeSave
} //	MMovementLineMA
예제 #24
0
/** @author [email protected] , eEvolution Consultants */
public class WBrowserSearch extends Grid implements ValueChangeListener {

  /** */
  private static final long serialVersionUID = 7952373172724992710L;

  private int p_WindowNo;
  private ArrayList<WEditor> m_wEditors = new ArrayList<WEditor>();
  private ArrayList<WEditor> m_wEditors2 = new ArrayList<WEditor>(); // for ranges
  private ArrayList<GridField> m_mFields = new ArrayList<GridField>();
  private ArrayList<GridField> m_mFields2 = new ArrayList<GridField>();
  /** Logger */
  private static CLogger log = CLogger.getCLogger(ProcessParameterPanel.class);

  /** Parameters */
  protected LinkedHashMap<Object, Object> m_search = new LinkedHashMap<Object, Object>();

  /** */
  public WBrowserSearch() {
    // TODO Auto-generated constructor stub
  }

  /** */
  public WBrowserSearch(int windowNo) {
    p_WindowNo = windowNo;
    makeNoStrip();
  }

  public void addField(MBrowseField field, Row row, String name, String title) {
    GridFieldVO voBase =
        GridFieldVO.createStdField(field.getCtx(), p_WindowNo, 0, 0, 0, false, false, false);

    String uniqueName = field.getAD_View_Column().getColumnSQL();

    voBase.isProcess = true;
    voBase.IsDisplayed = true;
    voBase.IsReadOnly = false;
    voBase.IsUpdateable = true;
    voBase.WindowNo = p_WindowNo;

    voBase.AD_Column_ID = field.getAD_View_Column().getAD_Column_ID();
    voBase.AD_Table_ID = field.getAD_View_Column().getAD_Column().getAD_Table_ID();
    voBase.ColumnName = field.getAD_View_Column().getAD_Column().getColumnName();
    voBase.displayType = field.getAD_Reference_ID();
    voBase.AD_Reference_Value_ID = field.getAD_Reference_Value_ID();
    voBase.IsMandatory = field.isMandatory();
    voBase.IsAlwaysUpdateable = false;
    voBase.IsKey = field.isKey();

    voBase.DefaultValue = field.getDefaultValue();
    voBase.DefaultValue2 = field.getDefaultValue2();
    voBase.InfoFactoryClass = field.getInfoFactoryClass();
    voBase.FieldLength = field.getFieldLength();
    voBase.ReadOnlyLogic = field.getReadOnlyLogic();
    voBase.DisplayLogic = field.getDisplayLogic();
    voBase.VFormat = field.getVFormat();
    voBase.ValueMin = field.getValueMin();
    voBase.ValueMax = field.getValueMax();
    voBase.ValidationCode = field.getAD_Val_Rule().getCode();

    voBase.isRange = field.isRange();
    voBase.Description = field.getDescription();
    voBase.Help = uniqueName;
    voBase.Header = title;

    GridField gField = new GridField(GridFieldVO.createParameter(voBase));
    GridField gField2 = null;

    WEditor editor = WebEditorFactory.getEditor(gField, false);
    editor.setReadWrite(true);
    editor.addValueChangeListener(this);
    editor.dynamicDisplay();
    gField.addPropertyChangeListener(editor);

    Object defaultObject = null;
    Object defaultObject2 = null;

    //  Set Default
    if (field.getAD_View_Column().getAD_Column_ID() > 0) {
      defaultObject = gField.getDefault();
      if (defaultObject != null && field.getDefaultValue() != null) {
        gField.setValue(defaultObject, true);
        editor.setValue(defaultObject);
      }
    }

    gField.lookupLoadComplete();
    m_mFields.add(gField);
    m_wEditors.add(editor);

    if (DisplayType.YesNo != field.getAD_Reference_ID()) {
      Div div = new Div();
      div.setAlign("right");
      org.adempiere.webui.component.Label label = editor.getLabel();
      label.setValue(title);
      div.appendChild(label);
      if (label.getDecorator() != null) div.appendChild(label.getDecorator());
      row.appendChild(div);
    }
    row.appendChild(editor.getComponent());
    setParameter(name, editor);

    if (field.isRange()) {
      title = Msg.getMsg(Env.getCtx(), "To");
      name = name + "_To";
      voBase.Header = title;
      voBase.DefaultValue = field.getDefaultValue2();
      gField2 = new GridField(GridFieldVO.createParameter(voBase));
      gField2.lookupLoadComplete();

      WEditor editor2 = WebEditorFactory.getEditor(gField2, false);
      editor2.setReadWrite(true);
      editor2.addValueChangeListener(this);
      editor2.dynamicDisplay();
      //  Set Default
      if (field.getAD_View_Column().getAD_Column_ID() > 0) {
        defaultObject2 = gField2.getDefault();
        if (defaultObject2 != null && field.getDefaultValue2() != null) {
          gField2.setValue(defaultObject2, true);
          editor2.setValue(defaultObject2);
        }
      }
      m_mFields2.add(gField2);
      m_wEditors2.add(editor2);

      Div div = new Div();
      div.setAlign("right");
      org.adempiere.webui.component.Label label = editor2.getLabel();
      label.setValue(title);
      div.appendChild(label);
      if (label.getDecorator() != null) div.appendChild(label.getDecorator());
      row.appendChild(div);

      row.appendChild(editor2.getComponent());
      setParameter(name, editor2);
    } else {
      m_mFields2.add(null);
      m_wEditors2.add(null);
    }

    if (gField != null) processNewValue(defaultObject, gField.getVO().Help);
    if (gField2 != null) processNewValue(defaultObject2, gField2.getVO().Help);
  }

  /**
   * Editor Listener
   *
   * @param evt Event
   * @exception ValueChangeEvent if the recipient wishes to roll back.
   */
  public void valueChange(ValueChangeEvent evt) {
    if (evt.getSource() instanceof WEditor) {
      GridField changedField = ((WEditor) evt.getSource()).getGridField();
      if (changedField != null) {
        processDependencies(changedField);
        // future processCallout (changedField);
      }
    }
    String columnName = "";
    if (evt.getSource() instanceof WEditor) {
      WEditor wEditor = (WEditor) evt.getSource();
      columnName = wEditor.getGridField().getVO().Help;
    }
    processNewValue(evt.getNewValue(), columnName);
  } // valueChange

  public void setParameter(Object name, Object value) {
    if (value != null) {
      m_search.put(name, value);
    }
  }

  public LinkedHashMap<Object, Object> getParameters() {
    return m_search;
  }

  /**
   * get Parameter Value
   *
   * @param id
   * @return Object Value
   */
  public Object getParamenterValue(Object key) {
    WEditor editor = (WEditor) m_search.get(key);
    if (editor != null) return editor.getValue();
    else return null;
  }

  /**
   * Evaluate Dependencies
   *
   * @param changedField changed field
   */
  private void processDependencies(GridField changedField) {
    String columnName = changedField.getVO().Help;
    ;

    for (GridField field : m_mFields) {
      if (field == null || field == changedField) continue;
      verifyChangedField(field, columnName);
    }
    for (GridField field : m_mFields2) {
      if (field == null || field == changedField) continue;
      verifyChangedField(field, columnName);
    }
  } // processDependencies

  private void verifyChangedField(GridField field, String columnName) {
    ArrayList<String> list = field.getDependentOn();
    if (list.contains(columnName)) {
      if (field.getLookup() instanceof MLookup) {
        MLookup mLookup = (MLookup) field.getLookup();
        // if the lookup is dynamic (i.e. contains this columnName as variable)
        if (mLookup.getValidation().indexOf("@" + columnName + "@") != -1) {
          log.fine(columnName + " changed - " + field.getColumnName() + " set to null");
          // invalidate current selection
          field.setValue(null, true);
        }
      }
    }
  }

  private void processNewValue(Object value, String name) {
    if (value == null) value = new String("");

    if (value instanceof String) Env.setContext(Env.getCtx(), p_WindowNo, name, (String) value);
    else if (value instanceof Integer)
      Env.setContext(Env.getCtx(), p_WindowNo, name, ((Integer) value).intValue());
    else if (value instanceof Boolean)
      Env.setContext(Env.getCtx(), p_WindowNo, name, ((Boolean) value).booleanValue());
    else if (value instanceof Timestamp)
      Env.setContext(Env.getCtx(), p_WindowNo, name, (Timestamp) value);
    else Env.setContext(Env.getCtx(), p_WindowNo, name, value.toString());

    dynamicDisplay();
  }

  /** Dynamic Display. */
  public void dynamicDisplay() {
    for (int i = 0; i < m_wEditors.size(); i++) {
      WEditor editor = m_wEditors.get(i);
      GridField mField = editor.getGridField();
      if (mField.isDisplayed(true)) {
        if (!editor.isVisible()) {
          editor.setVisible(true);
          if (mField.getVO().isRange) {
            // m_separators.get(i).setVisible(true);
            m_wEditors2.get(i).setVisible(true);
          }
        }
        boolean rw = mField.isEditablePara(true); // r/w - check if
        // field is Editable
        editor.setReadWrite(rw);
        editor.dynamicDisplay();
        if (mField.getVO().isRange) {
          WEditor editorRange = m_wEditors2.get(i);
          if (editorRange != null) {
            editorRange.setReadWrite(rw);
            editorRange.dynamicDisplay();
          }
        }
      } else if (editor.isVisible()) {
        editor.setVisible(false);
        if (mField.getVO().isRange) {
          // m_separators.get(i).setVisible(false);
          m_wEditors2.get(i).setVisible(false);
        }
      }
    }
  }

  /** Dispose */
  public void dispose() {
    cleanContext();
    m_wEditors.clear();
    m_wEditors2.clear();
    m_mFields.clear();
    m_mFields2.clear();
  } //  dispose

  /**
   * Restore window context.
   *
   * @author teo_sarca [ 1699826 ]
   * @see org.compiere.model.GridField#restoreValue()
   */
  protected void cleanContext() {
    for (GridField f : m_mFields) {
      if (f != null) {
        f.restoreValue();
        Env.setContext(f.getVO().ctx, p_WindowNo, f.getVO().Help, "");
      }
    }
    for (GridField f : m_mFields2) {
      if (f != null) {
        f.restoreValue();
        Env.setContext(f.getVO().ctx, p_WindowNo, f.getVO().Help, "");
      }
    }
  }
}
예제 #25
0
public class InstallMain {

  private static final String ENTITY_TYPE = "de.metas.commission";

  private static final String C_ADV_COMMISSION_INSTANCE = I_C_AdvCommissionInstance.Table_Name;
  private static final String C_ADV_COMMISSION_FACT = I_C_AdvCommissionFact.Table_Name;
  private static final String C_INCIDENT_LINE = "C_IncidentLine";
  private static final String C_INCIDENT_LINE_FACT = "C_IncidentLineFact";

  private static final CLogger logger = CLogger.getCLogger(InstallMain.class);

  private static final String trxName = null;

  private static void doIt() {

    // commissionIncident();
    //
    // commissionIncidentFact();
    //
    // commissionInstance();
    //
    // commissionInstanceFact();
    //
    // commissionRelevantPO();

    // commissionfact2salesRepFact();

    // commissionFact_SalesRepV();

    specificSponsorParams();

    specificInstanceParams();
  }

  private static void specificSponsorParams() {

    final Properties ctx = Env.getCtx();
    final String tableName = "C_AdvComSponsorParam";

    TableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName)
        .setName("Spezifische sponsorbezogene Parameter")
        .setAccessLevel(X_AD_Table.ACCESSLEVEL_Organization)
        .save()
        .standardColumns();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "C_AdvCommissionTerm_ID")
        .setReference(TableDir)
        .setUpdatable(false)
        .setMandatory(true)
        .setParent(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "Description")
        .setReference(String)
        .setFieldLength(1024)
        .setUpdatable(true)
        .setMandatory(false)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "Name")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "ParamName")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "ParamValue")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "SeqNo")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "AD_Reference_ID")
        .setReference(TableDir)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "AD_Reference_Value_ID")
        .setReference(Table)
        .setReferenceValue(4)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    IndexTableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "Name_SponsorParam_Idx")
        .setUnique(true)
        .save()
        .addIndexColumns("Name", "C_AdvCommissionTerm_ID")
        .syncIndexTable();

    IndexTableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "ParamName_SponsorParam_Idx")
        .setUnique(true)
        .save()
        .addIndexColumns("ParamName", "C_AdvCommissionTerm_ID")
        .syncIndexTable();
  }

  private static void specificInstanceParams() {

    final Properties ctx = Env.getCtx();
    final String tableName = "C_AdvComInstanceParam";

    TableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName)
        .setName("Spezifische vorgangsbezogene Parameter")
        .setAccessLevel(X_AD_Table.ACCESSLEVEL_Organization)
        .save()
        .standardColumns();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "C_AdvCommissionType_ID")
        .setReference(TableDir)
        .setUpdatable(false)
        .setMandatory(true)
        .setParent(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "Description")
        .setReference(String)
        .setFieldLength(1024)
        .setUpdatable(true)
        .setMandatory(false)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "Name")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "ParamName")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "ParamValue")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "SeqNo")
        .setReference(String)
        .setFieldLength(255)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "AD_Reference_ID")
        .setReference(TableDir)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "AD_Reference_Value_ID")
        .setReference(Table)
        .setReferenceValue(4)
        .setUpdatable(true)
        .setMandatory(true)
        .save()
        .syncColumn();

    IndexTableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "Name_InstanceParam_Idx")
        .setUnique(true)
        .save()
        .addIndexColumns("Name", "C_AdvCommissionType_ID")
        .syncIndexTable();

    IndexTableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, "ParamName_InstanceParam_Idx")
        .setUnique(true)
        .save()
        .addIndexColumns("ParamName", "C_AdvCommissionType_ID")
        .syncIndexTable();
  }

  private static void commissionFact_SalesRepV() {

    final Properties ctx = Env.getCtx();
    final String tableName = "C_AdvComFact_SalesRepFact_V";

    TableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName)
        .setName("Sponsor-Umsatzdatensatz")
        .setAccessLevel(X_AD_Table.ACCESSLEVEL_ClientPlusOrganization)
        .setView(true)
        .save()
        .standardColumns();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_AD_Table_ID)
        .setReference(TableDir)
        .setMandatory(true)
        .save();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_Record_ID)
        .setReference(TableDir)
        .setMandatory(true)
        .save();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_DateDoc)
        .setReference(TableDir)
        .setMandatory(true)
        .save();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_Status)
        .setReference(TableDir)
        .setMandatory(true)
        .save();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(
            ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_CommissionPointsBase)
        .setReference(TableDir)
        .setMandatory(true)
        .save();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_Qty)
        .setReference(TableDir)
        .setMandatory(true)
        .save();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(
            ENTITY_TYPE, tableName, I_C_AdvCommissionFact.COLUMNNAME_CommissionPointsSum)
        .setReference(TableDir)
        .setMandatory(true)
        .save();
  }

  private static void commissionRelevantPO() {

    final Properties ctx = Env.getCtx();
    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(
            ENTITY_TYPE,
            I_C_AdvCommissionRelevantPO.Table_Name,
            I_C_AdvCommissionRelevantPO.COLUMNNAME_DateDocColumn_ID)
        .setMandatory(true)
        .save()
        .syncColumn();
  }

  private static void commissionInstanceFact() {

    final Properties ctx = Env.getCtx();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_FACT, "DateDoc")
        .setReference(DateTime)
        .save()
        .syncColumn()
        .replacesOldCol("DateAcct");

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_FACT, C_INCIDENT_LINE_FACT + "_ID")
        .setReference(TableDir)
        .setParent(true)
        .setUpdatable(false)
        .setMandatory(false)
        .setDefaultValue("-1")
        .save()
        .syncColumn();
  }

  private static void commissionInstance() {

    final Properties ctx = Env.getCtx();

    logger.info("Column 'C_IncidentLine_ID'");
    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, C_INCIDENT_LINE + "_ID")
        .setReference(TableDir)
        .setParent(true)
        .setUpdatable(false)
        .setMandatory(false)
        .setDefaultValue("-1")
        .save()
        .syncColumn();

    logger.info("Column 'LevelForecast'");
    final MColumn levelForecastCol =
        ColumnInstaller.mkInst(ctx, trxName)
            .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, "LevelForecast")
            .setReference(Integer)
            .save()
            .syncColumn()
            .getColumn();

    logger.info("Field for column 'LevelForecast'");
    FieldInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, levelForecastCol)
        .setWindowAndTab("Buchauszug", "Vorgang")
        .setVisible(true)
        .save();

    logger.info("Column 'LevelCalculation'");

    final MColumn levelCalculationCol =
        ColumnInstaller.mkInst(ctx, trxName)
            .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, "LevelCalculation")
            .setReference(Integer)
            .save()
            .syncColumn()
            .replacesOldCol("LevelCommission")
            .getColumn();

    logger.info("Field for column 'LevelCalculation'");
    FieldInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, levelCalculationCol)
        .setWindowAndTab("Buchauszug", "Vorgang")
        .setVisible(true)
        .save();

    logger.info("Column 'LevelHierarchy'");
    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, "LevelHierarchy")
        .setReference(Integer)
        .save()
        .syncColumn();

    // there is a view c_advcommission_info_v that refers to 'level'
    // so in order to drop the level column, one needs to change that view
    // TODO create an installer that executes generic SQL

    // DROP VIEW c_advcommission_info_v;
    //
    // CREATE OR REPLACE VIEW c_advcommission_info_v AS
    // SELECT max(i.c_advcommissioninstance_id) AS
    // c_advcommission_info_v_id, max(i.ad_client_id) AS ad_client_id,
    // max(i.ad_org_id) AS ad_org_id, max(i.created) AS created,
    // max(i.createdby) AS createdby, max(i.updated) AS updated,
    // max(i.updatedby) AS updatedby, ssr.c_bpartner_id,
    // i.c_advcommissionterm_id, i."levelforecast", p.startdate, p.enddate,
    // sum(pr.commissionpoints) AS points_predicted,
    // sum(ca.commissionpoints) AS points_calculated,
    // sum(pa.commissionpoints) AS points_paid
    // FROM c_advcommissioninstance i
    // LEFT JOIN c_sponsor_salesrep ssr ON i.c_sponsor_salesrep_id =
    // ssr.c_sponsor_id AND ssr.isactive = 'Y'::bpchar AND ssr.c_bpartner_id
    // > 0::numeric
    // LEFT JOIN ( SELECT p.startdate, p.enddate, t.c_advcommissionterm_id
    // FROM c_period p
    // LEFT JOIN c_year y ON y.c_year_id = p.c_year_id
    // LEFT JOIN c_advcommissioncondition c ON c.c_calendar_id =
    // y.c_calendar_id
    // LEFT JOIN c_advcommissionterm t ON t.c_advcommissioncondition_id =
    // c.c_advcommissioncondition_id) p ON p.c_advcommissionterm_id =
    // i.c_advcommissionterm_id
    // LEFT JOIN ( SELECT f.commissionpoints, f.c_advcommissioninstance_id,
    // f.datedoc
    // FROM c_advcommissionfact f
    // WHERE f.commissionpoints > 0::numeric AND f.status::text =
    // 'PR'::text) pr ON pr.c_advcommissioninstance_id =
    // i.c_advcommissioninstance_id AND ssr.validfrom <= pr.datedoc AND
    // ssr.validto >= pr.datedoc AND p.startdate <= pr.datedoc AND p.enddate
    // >= pr.datedoc
    // LEFT JOIN ( SELECT f.commissionpoints, f.c_advcommissioninstance_id,
    // f.datedoc
    // FROM c_advcommissionfact f
    // WHERE f.commissionpoints > 0::numeric AND f.status::text =
    // 'CA'::text) ca ON ca.c_advcommissioninstance_id =
    // i.c_advcommissioninstance_id AND ssr.validfrom <= ca.datedoc AND
    // ssr.validto >= ca.datedoc AND p.startdate <= ca.datedoc AND p.enddate
    // >= ca.datedoc
    // LEFT JOIN ( SELECT f.commissionpoints, f.c_advcommissioninstance_id,
    // f.datedoc
    // FROM c_advcommissionfact f
    // WHERE f.commissionpoints > 0::numeric AND f.status::text =
    // 'PA'::text) pa ON pa.c_advcommissioninstance_id =
    // i.c_advcommissioninstance_id AND ssr.validfrom <= pa.datedoc AND
    // ssr.validto >= pa.datedoc AND p.startdate <= pa.datedoc AND p.enddate
    // >= pa.datedoc
    // WHERE i.isactive = 'Y'::bpchar AND (pr.commissionpoints > 0::numeric
    // OR ca.commissionpoints > 0::numeric OR pa.commissionpoints >
    // 0::numeric)
    // GROUP BY ssr.c_bpartner_id, i.c_advcommissionterm_id,
    // i."levelforecast", p.startdate, p.enddate
    // ORDER BY ssr.c_bpartner_id, i.c_advcommissionterm_id,
    // i."levelforecast", p.startdate;
    //
    // GRANT ALL ON TABLE c_advcommission_info_v TO adempiere;

    logger.info("Replacing column 'Level' with 'LevelHierarchy'");
    final MColumn levelHierarchyCol =
        ColumnInstaller.mkInst(ctx, trxName)
            .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, "LevelHierarchy")
            .save()
            .replacesOldCol("Level")
            .getColumn();

    logger.info("Field for column 'LevelHierarchy'");
    FieldInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, levelHierarchyCol)
        .setWindowAndTab("Buchauszug", "Vorgang")
        .setVisible(true)
        .save();

    logger.info("Index for table " + C_ADV_COMMISSION_INSTANCE);
    IndexTableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(
            ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, levelHierarchyCol.getColumnName() + "_IDX")
        .setUnique(true)
        .save()
        .addIndexColumns(
            COLUMNNAME_Record_ID,
            COLUMNNAME_AD_Table_ID,
            COLUMNNAME_C_AdvCommissionTerm_ID,
            COLUMNNAME_LevelHierarchy)
        .syncIndexTable();

    logger.info("Column 'Points_ToCalculate'");
    final MColumn PointsToCalcCol =
        ColumnInstaller.mkInst(ctx, trxName)
            .createOrUpdate(ENTITY_TYPE, C_ADV_COMMISSION_INSTANCE, "Points_ToCalculate")
            .setReference(Amount)
            .setColumnSQL(
                "(select sum(CommissionPoints) from C_AdvCommissionFact f where f.C_AdvCommissionInstance_ID=C_AdvCommissionInstance.C_AdvCommissionInstance_ID AND f.Status='CP')")
            .save()
            .getColumn();

    logger.info("Field for column 'Points_ToCalculate'");
    FieldInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, PointsToCalcCol)
        .setWindowAndTab("Buchauszug", "Vorgang")
        .setVisible(true)
        .save();
  }

  private static void commissionIncident() {

    final Properties ctx = Env.getCtx();

    TableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE)
        .setName("Incident Line")
        .setAccessLevel(X_AD_Table.ACCESSLEVEL_ClientPlusOrganization)
        .save()
        .standardColumns();
  }

  private static void commissionIncidentFact() {

    final Properties ctx = Env.getCtx();

    TableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT)
        .setName("Commission Incident Fact")
        .setAccessLevel(X_AD_Table.ACCESSLEVEL_ClientPlusOrganization)
        .save()
        .standardColumns();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, C_INCIDENT_LINE + "_ID")
        .setReference(TableDir)
        .setParent(true)
        .setMandatory(true)
        .setUpdatable(false)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, "AD_Table_ID")
        .setReference(TableDir)
        .setMandatory(true)
        .setUpdatable(false)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, "Record_ID")
        .setReference(Button)
        .setFieldLength(20)
        .setMandatory(true)
        .setUpdatable(false)
        .save()
        .syncColumn();

    IndexTableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, C_INCIDENT_LINE_FACT + "_T_R_IDX")
        .setUnique(true)
        .save()
        .addIndexColumns("AD_Table_ID", "Record_ID")
        .syncIndexTable();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, "C_BPartner_ID")
        .setReference(TableDir)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, "DateDoc")
        .setReference(DateTime)
        .setMandatory(true)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, C_INCIDENT_LINE_FACT, "C_AdvCommissionRelevantPO_ID")
        .setReference(TableDir)
        .setMandatory(true)
        .save()
        .syncColumn();
  }

  private static void commissionfact2salesRepFact() {

    final Properties ctx = Env.getCtx();

    final String tableName = "C_AdvComFact_SalesRepFact";

    TableInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName)
        .setName("Commissionfact to sales rep fact")
        .setAccessLevel(X_AD_Table.ACCESSLEVEL_ClientPlusOrganization)
        .save()
        .standardColumns();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(ENTITY_TYPE, tableName, C_ADV_COMMISSION_FACT + "_ID")
        .setReference(TableDir)
        .setMandatory(true)
        .setUpdatable(false)
        .save()
        .syncColumn();

    ColumnInstaller.mkInst(ctx, trxName)
        .createOrUpdate(
            ENTITY_TYPE, tableName, I_C_AdvComSalesRepFact.COLUMNNAME_C_AdvComSalesRepFact_ID)
        .setReference(TableDir)
        .setMandatory(true)
        .setUpdatable(false)
        .save()
        .syncColumn();
  }

  public static void main(final String[] args) {

    Adempiere.startupEnvironment(false);
    Ini.setAdempiereHome(".");
    Ini.setProperty(Ini.P_LOGMIGRATIONSCRIPT, true);

    doIt();
  }
}
예제 #26
0
/**
 * Web (window) Chat
 *
 * @author Jorg Janke
 * @version $Id: WChat.java,v 1.1 2009/04/15 11:27:15 vinhpt Exp $
 */
public class WChat extends HttpServlet {
  /** */
  private static final long serialVersionUID = 6826855534161342772L;

  /** Logger */
  protected CLogger log = CLogger.getCLogger(getClass());

  private MChat m_chat;
  private boolean m_readOnly;
  private boolean m_hasDependents;
  private boolean m_hasCallout;
  private int m_displayLength;
  private String m_columnName;

  /** Initialize global variables */
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    if (!WebEnv.initWeb(config)) throw new ServletException("WChat.init");
  } //  init

  /** Process the HTTP Get request */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.fine("doGet");
    WebSessionCtx wsc = WebSessionCtx.get(request);
    WWindowStatus ws = WWindowStatus.get(request);
    //
    WebDoc doc = null;
    if (ws == null) {
      doc = WebDoc.createPopup("No Context");
      doc.addPopupClose(wsc.ctx);
    } else {
      doc = CreateChatPage(ws, wsc, doc, 0);
    }
    //
    WebUtil.createResponse(request, response, this, null, doc, false);
  } //  doGet

  /** Process the HTTP Post request */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    WebDoc doc = null;

    WebSessionCtx wsc = WebSessionCtx.get(request);
    WWindowStatus ws = WWindowStatus.get(request);

    String data = WebUtil.getParameter(request, "chatinput");
    int CM_ChatID = WebUtil.getParameterAsInt(request, "CM_ChatID");
    int AD_Table_ID = WebUtil.getParameterAsInt(request, "AD_Table_ID");
    int record_ID = WebUtil.getParameterAsInt(request, "record_ID");
    String description = WebUtil.getParameter(request, "description");

    if (data != null && data.length() > 0) {
      if (CM_ChatID == 0) {
        m_chat = new MChat(wsc.ctx, AD_Table_ID, record_ID, description, null);
        m_chat.save();
      }
      MChatEntry entry = new MChatEntry(m_chat, data);
      entry.save();
    } //	data to be saved

    doc = CreateChatPage(ws, wsc, doc, m_chat.getCM_Chat_ID());
    WebUtil.createResponse(request, response, this, null, doc, false);
  } //  doPost
  /**
   * Create Text Field
   *
   * @param data initial value
   * @param rows no of rows
   * @return td
   */
  private td getTextField(String data, int rows) {
    textarea text =
        new textarea(m_columnName, rows, m_displayLength).addElement(Util.maskHTML(data));
    text.setID(m_columnName + "F");
    text.setName(m_columnName);
    text.setDisabled(m_readOnly);
    //
    if (m_hasDependents || m_hasCallout) text.setOnChange("startUpdate(this);");

    return createTD(text);
  }

  /**
   * Create Left Top aligned TD
   *
   * @param element element
   * @return td table data
   */
  private td createTD(Element element) {
    td td = new td().addElement(element).setAlign(AlignType.LEFT).setVAlign(AlignType.TOP);
    td.setColSpan(3);
    return td;
  } //	createTD

  /**
   * Create Left Top aligned TD
   *
   * @param element element
   * @return td table data
   */
  private WebDoc CreateChatPage(WWindowStatus ws, WebSessionCtx wsc, WebDoc doc, int CM_Chat_ID) {

    doc = WebDoc.createPopup("Chat ");

    td center = doc.addWindowCenter(false);
    int record_ID = ws.curTab.getRecord_ID();
    log.info("Record_ID=" + record_ID);
    if (record_ID == -1) // 	No Key
    {
      log.info("Record does not exist");
      return doc;
    }
    //	Find display
    String infoName = null;
    String infoDisplay = null;
    for (int i = 0; i < ws.curTab.getFieldCount(); i++) {
      GridField field = ws.curTab.getField(i);
      if (field.isKey()) infoName = field.getHeader();
      if ((field.getColumnName().equals("Name") || field.getColumnName().equals("DocumentNo"))
          && field.getValue() != null) infoDisplay = field.getValue().toString();
      if (infoName != null && infoDisplay != null) break;
    }
    String description = infoName + ": " + infoDisplay;
    //

    if (ws.curTab.getCM_ChatID() > 0) m_chat = new MChat(wsc.ctx, ws.curTab.getCM_ChatID(), null);
    else if (CM_Chat_ID > 0) m_chat = new MChat(wsc.ctx, CM_Chat_ID, null);
    else m_chat = new MChat(wsc.ctx, ws.curTab.getAD_Table_ID(), record_ID, description, null);

    String text = m_chat.getHistory(MChat.CONFIDENTIALTYPE_Internal).toString();

    form myForm = new form("WChat").setName("chat");
    myForm.setOnSubmit("this.Submit.disabled=true;return true;");
    if (CM_Chat_ID == 0)
      myForm.addElement(new input(input.TYPE_HIDDEN, "CM_ChatID", ws.curTab.getCM_ChatID()));
    else myForm.addElement(new input(input.TYPE_HIDDEN, "CM_ChatID", CM_Chat_ID));
    myForm.addElement(new input(input.TYPE_HIDDEN, "AD_Table_ID", ws.curTab.getAD_Table_ID()));
    myForm.addElement(new input(input.TYPE_HIDDEN, "record_ID", record_ID));
    myForm.addElement(new input(input.TYPE_HIDDEN, "description", description));

    table myTable = new table("0", "0", "5", "100%", null);
    myTable.setID("WChatParameter");
    m_displayLength = 80;

    // history field
    myTable.addElement(new tr().addElement(new td("History")));
    m_readOnly = true;
    table HistoryTable = new table("1", "0", "5", "100%", null);
    HistoryTable.addElement(
        new tr()
            .addElement(
                new td(text)
                    .setRowSpan(10)
                    .setAlign(AlignType.LEFT)
                    .setVAlign(AlignType.TOP)
                    .setColSpan(4)));
    myTable.addElement(HistoryTable);

    // input field
    myTable.addElement(new tr().addElement(new td("Input")));
    m_readOnly = false;
    m_columnName = "chatinput";
    myTable.addElement(new tr().addElement(getTextField("", 10)));

    //	 Reset
    String textbtn = "Reset";
    if (wsc.ctx != null) text = Msg.getMsg(wsc.ctx, "Reset");
    input restbtn = new input(input.TYPE_RESET, textbtn, "  " + text);
    restbtn.setID(text);
    restbtn.setClass("resetbtn");

    //	Submit
    textbtn = "Submit";
    if (wsc.ctx != null) text = Msg.getMsg(wsc.ctx, "Submit");
    input submitbtn = new input(input.TYPE_SUBMIT, textbtn, "  " + text);
    submitbtn.setID(text);
    submitbtn.setClass("submitbtn");

    //	Close
    textbtn = "Close";
    if (wsc.ctx != null) text = Msg.getMsg(wsc.ctx, "Close");
    input closebtn = new input(input.TYPE_SUBMIT, textbtn, "  " + text);
    closebtn.setID(text);
    closebtn.setClass("closebtn");
    closebtn.setOnClick("self.close();return false;");

    myTable.addElement(
        new tr()
            .addElement(new td(null, AlignType.RIGHT, AlignType.MIDDLE, false, restbtn))
            .addElement(new td(null, AlignType.CENTER, AlignType.MIDDLE, false, submitbtn))
            .addElement(new td(null, AlignType.LEFT, AlignType.MIDDLE, false, closebtn)));
    myForm.addElement(myTable);
    center.addElement(myForm);

    return doc;
  }
} //	WReport
예제 #27
0
public class ElementManager {
  protected static final transient CLogger log = CLogger.getCLogger(ElementManager.class);

  private static ElementBean getUnknownElementBean(Properties ctx, String columnName) {
    ElementBean elementBean = new ElementBean();
    elementBean.setColumnName(columnName);
    elementBean.setDescription("Undefined column with name: " + columnName);
    elementBean.setHelp(elementBean.getDescription());
    elementBean.setName(columnName);
    elementBean.setPrintName(columnName);
    return elementBean;
  }

  private static String getElement_TrlSql(Properties ctx, String columnName) {
    String language = Env.getContext(ctx, UdiConstants.LANGUAGE_CTX_PARAM);

    if (language == null || language.trim().length() == 0) {
      language = Language.AD_Language_en_US;
    }

    String tableName = "AD_Element";
    StringBuffer whereClause = new StringBuffer("ColumnName='");
    whereClause.append(columnName);
    whereClause.append("' ");

    if (!language.equals(Language.AD_Language_en_US)) {
      tableName = "AD_Element_Trl";
      whereClause = new StringBuffer();
      whereClause.append(
          "AD_Element_ID= (select AD_Element_ID from AD_Element where ColumnName='"
              + columnName
              + "')");
      whereClause.append(" and AD_Language='");
      whereClause.append(language);
      whereClause.append("'");
    }

    StringBuffer sql = new StringBuffer();
    sql.append("Select ColumnName, Name, PrintName, Description, Help from ");
    sql.append(tableName);
    sql.append(" where ");
    sql.append(whereClause);

    return sql.toString();
  }

  public static String getMsg_trlSql(Properties ctx, String text) {
    String language = Env.getContext(ctx, UdiConstants.LANGUAGE_CTX_PARAM);

    if (language == null || language.trim().length() == 0) {
      language = Language.AD_Language_en_US;
    }

    String tableName = "AD_Message";
    StringBuffer whereClause = new StringBuffer("value='");
    whereClause.append(text);
    whereClause.append("' ");

    if (!language.equals(Language.AD_Language_en_US)) {
      tableName = "AD_Element_Trl";
      whereClause = new StringBuffer();
      whereClause.append("AD_Message_ID= (select AD_Message_ID from AD_Message where value='");
      whereClause.append(text);
      whereClause.append("')");
      whereClause.append(" and AD_Language='");
      whereClause.append(language);
      whereClause.append("'");
    }

    StringBuffer sql = new StringBuffer();
    sql.append("Select Value, MsgText, MsgText, MsgTip, MsgTip from ");
    sql.append(tableName);
    sql.append(" where ");
    sql.append(whereClause);

    return sql.toString();
  }

  private static ElementBean getTrl(String sql) {
    PreparedStatement pstmt = DB.prepareStatement(sql, null);

    ElementBean retElementBean = null;
    try {
      ResultSet rs = pstmt.executeQuery();
      if (rs.next()) {
        retElementBean = new ElementBean();
        retElementBean.setColumnName(rs.getString(1));
        retElementBean.setName(rs.getString(2));
        retElementBean.setPrintName(rs.getString(3));
        retElementBean.setDescription(rs.getString(4));
        retElementBean.setHelp(rs.getString(5));
      } else {
        return null;
      }
      rs.close();
    } catch (Exception ex) {
      log.severe("Could retrieve element translation with sql: " + sql);
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex) {
      }
    }

    return retElementBean;
  }

  public static ElementBean getMsg1(Properties ctx, String text) {
    ElementBean elementBean = null;

    elementBean = getTrl(getElement_TrlSql(ctx, text));

    if (elementBean == null) {
      elementBean = getTrl(getMsg_trlSql(ctx, text));
    }

    if (elementBean == null) {
      elementBean = getUnknownElementBean(ctx, text);
    }

    return elementBean;
  }

  public static ElementBean getMsg(Properties ctx, String text) {
    String language = Env.getContext(ctx, UdiConstants.LANGUAGE_CTX_PARAM);

    if (language == null || language.trim().length() == 0) {
      language = Language.AD_Language_en_US;
    }

    String msg = Msg.getElement(language, text, true);

    if (msg == null || msg == "") {
      msg = Msg.translate(language, text);
    }

    if (msg == null || msg == "") {
      msg = text;
    }

    int ind = msg.indexOf(Env.NL);
    if (ind != -1) msg = msg.substring(0, ind);

    ElementBean elementBean = new ElementBean();
    elementBean.setColumnName(text);
    elementBean.setDescription(msg);
    elementBean.setHelp(msg);
    elementBean.setName(msg);
    elementBean.setPrintName(msg);

    return elementBean;
  }
}
예제 #28
0
public abstract class FCAQPayment {

  public static CLogger log = CLogger.getCLogger(Allocation.class);

  public MBPartner m_bpartner = null;
  public LinkedHashMap<String, I_C_BPartner> studentList =
      new LinkedHashMap<String, I_C_BPartner>();
  public List<MTimeExpenseLine> paymentSchedules = new ArrayList<MTimeExpenseLine>();
  public List<MDocType> doctypes = new ArrayList<MDocType>();
  public List<MRefList> paymentTypes = new ArrayList<MRefList>();
  public List<MRefList> cardTypes = new ArrayList<MRefList>();

  public MBank bankbox = null;
  public MBankAccount cashbox = null;
  public MBank bankdiners = null;
  public MBank bankvisa = null;
  public List<MBankAccount> bankAccounts = new ArrayList<MBankAccount>();

  public X_CA_Payment caPayment = null;

  protected BigDecimal singleMonth = Env.ZERO;
  protected BigDecimal singleYear = Env.ZERO;
  protected BigDecimal singleTotal = Env.ZERO;
  protected BigDecimal consolidatedMonth = Env.ZERO;
  protected BigDecimal consolidatedYear = Env.ZERO;
  protected BigDecimal consolidatedTotal = Env.ZERO;
  protected BigDecimal paymentValue = Env.ZERO;

  public String message_error = "";
  public MSequence sequence = null;
  public Properties ctx = Env.getCtx();
  public int INDEX_VALUE = 1; // Value
  public IMiniTable paymentTable;
  public IMiniTable studentTable;

  public Vector<String> getStudentColumnNames() {
    Vector<String> columnNames = new Vector<String>();
    columnNames.add(Msg.translate(Env.getCtx(), "IsPaid"));
    columnNames.add(Msg.translate(Env.getCtx(), "Value"));
    columnNames.add(Msg.translate(Env.getCtx(), "Name"));
    columnNames.add(Msg.translate(Env.getCtx(), "Grade"));
    columnNames.add(Msg.translate(Env.getCtx(), "Modality"));
    columnNames.add(Msg.translate(Env.getCtx(), "TransportCode"));
    columnNames.add(Msg.translate(Env.getCtx(), "ChildNo"));

    return columnNames;
  }

  public Vector<String> getPaymentColumnNames() {
    Vector<String> columnNames = new Vector<String>();
    columnNames.add(Msg.getMsg(Env.getCtx(), "PaymentType"));
    columnNames.add(Msg.getMsg(Env.getCtx(), "CardType"));
    columnNames.add(Msg.getMsg(Env.getCtx(), "NoQuotes"));
    columnNames.add(Msg.getMsg(Env.getCtx(), "HasInterests"));
    columnNames.add(Msg.getMsg(Env.getCtx(), "BankAccount"));
    columnNames.add(Msg.getMsg(Env.getCtx(), "ReferenceNo"));
    columnNames.add(Msg.getMsg(Env.getCtx(), "Amount"));

    return columnNames;
  }

  public Vector<Vector<Object>> getStudentData(MCAHolder holder) {
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();

    for (MCAHolderRelation relation : holder.getHolderRelations()) {
      I_C_BPartner bpartner = relation.getC_BPartner();

      Vector<Object> line = new Vector<Object>();
      line.add(true);
      line.add(bpartner.getValue());
      line.add(bpartner.getName());
      line.add("0000"); // replace by SecureCode
      line.add("0000"); // replace by Enrollment
      line.add("0000"); // replace by Transport Code
      line.add(relation.getChildNo());
      data.add(line);
      studentList.put(bpartner.getValue(), bpartner);
      findPaymentSchedule(bpartner);
    }
    return data;
  }

  public Vector<Vector<Object>> getParentData(MBPartner bpartner) {
    Vector<Vector<Object>> data = new Vector<Vector<Object>>();
    Vector<Object> line = new Vector<Object>();

    List<MBPartner> students =
        new Query(
                ctx,
                MBPartner.Table_Name,
                "C_BPartner_ID <> ? AND C_BPartner_ID IN (Select C_BPartner_ID from AD_User where BPartner_Parent_ID=?)",
                null) // missing contact clauses
            .setParameters(bpartner.get_ID(), bpartner.get_ID())
            .list();

    for (MBPartner student : students) {

      studentList.put(student.getValue(), student);
      findPaymentSchedule(student);

      line.add(student.getValue());
      line.add(student.getName());
      line.add("0000"); // replace by SecureCode
      line.add("0000"); // replace by Enrollment
      line.add("0000"); // replace by Transport Code

      String whereClause =
          "AD_User_ID IN (Select AD_User_ID from AD_User where BPartner_Parent_ID=? AND C_BPartner_ID=? AND ISPAYMENTRESPONSIBLE=? )";
      MUser contact =
          new Query(ctx, MUser.Table_Name, whereClause, null)
              .setParameters(bpartner.get_ID(), student.get_ID(), true)
              .first();

      line.add(contact != null ? true : false);

      data.add(line);
      line = new Vector<Object>();
    }

    return data;
  }

  public void findPaymentSchedule(I_C_BPartner student) {
    List<MTimeExpenseLine> changes =
        new Query(
                ctx,
                MTimeExpenseLine.Table_Name,
                I_S_TimeExpenseLine.COLUMNNAME_C_BPartner_ID + "=?",
                null)
            .setParameters(student.getC_BPartner_ID())
            .list();

    if (paymentSchedules != null) {
      paymentSchedules.addAll(changes);
    }
  }

  public void calculateItems(String childValue) {
    singleMonth = Env.ZERO;
    ;
    singleYear = Env.ZERO;
    ;
    singleTotal = Env.ZERO;

    consolidatedMonth = Env.ZERO;
    consolidatedYear = Env.ZERO;
    consolidatedTotal = Env.ZERO;
    paymentValue = Env.ZERO;

    I_C_BPartner student = studentList.get(childValue);

    for (MTimeExpenseLine paymentSchedule : paymentSchedules) {
      if (paymentSchedule.getC_BPartner_ID() == student.getC_BPartner_ID()) {
        if (!(paymentSchedule.get_ValueAsBoolean("IsPaid"))) {
          I_M_Product concept = paymentSchedule.getM_Product();
          MExpenseType conceptType = (MExpenseType) concept.getS_ExpenseType();

          String type = conceptType.get_ValueAsString(MInvoiceSchedule.COLUMNNAME_InvoiceFrequency);
          if (MInvoiceSchedule.INVOICEFREQUENCY_Monthly.equals(type))
            singleMonth = singleMonth.add(paymentSchedule.getApprovalAmt());
          else if ("Y".equals(type)) singleYear = singleYear.add(paymentSchedule.getApprovalAmt());

          singleTotal = singleTotal.add(paymentSchedule.getApprovalAmt());
        }
      }

      if (!(paymentSchedule.get_ValueAsBoolean("IsPaid"))) {
        MProduct concept = (MProduct) paymentSchedule.getM_Product();
        MExpenseType conceptType = (MExpenseType) concept.getS_ExpenseType();
        String type = conceptType.get_ValueAsString(MInvoiceSchedule.COLUMNNAME_InvoiceFrequency);
        if (MInvoiceSchedule.INVOICEFREQUENCY_Monthly.equals(type))
          consolidatedMonth = consolidatedMonth.add(paymentSchedule.getApprovalAmt());
        else if ("Y".equals(type))
          consolidatedYear = consolidatedYear.add(paymentSchedule.getApprovalAmt());

        consolidatedTotal = consolidatedTotal.add(paymentSchedule.getApprovalAmt());
      }
    }
  }

  public void loadStartData() {
    String whereClause = "DocBaseType = ? ";
    doctypes =
        new Query(ctx, MDocType.Table_Name, whereClause, null)
            .setParameters("APP")
            .setClient_ID()
            .setOnlyActiveRecords(true)
            .list();

    sequence =
        new Query(ctx, MSequence.Table_Name, "Name = 'FCAQPayment'", null)
            .setClient_ID()
            .setOnlyActiveRecords(true)
            .first();

    paymentTypes =
        new Query(ctx, MRefList.Table_Name, "AD_Reference_ID=?", null)
            .setOnlyActiveRecords(true)
            .setParameters(214)
            .list();

    cardTypes =
        new Query(ctx, MRefList.Table_Name, "AD_Reference_ID=?", null)
            .setOnlyActiveRecords(true)
            .setParameters(149)
            .list();

    bankAccounts =
        new Query(ctx, MBankAccount.Table_Name, "", null)
            .setClient_ID()
            .setOnlyActiveRecords(true)
            .list();

    bankbox =
        new Query(ctx, MBank.Table_Name, "SwiftCode=?", null)
            .setOnlyActiveRecords(true)
            .setParameters("C")
            .first();

    bankdiners =
        new Query(ctx, MBank.Table_Name, "SwiftCode=?", null)
            .setOnlyActiveRecords(true)
            .setParameters("D")
            .first();

    bankvisa =
        new Query(ctx, MBank.Table_Name, "SwiftCode=?", null)
            .setOnlyActiveRecords(true)
            .setParameters("V")
            .first();

    if (bankbox != null) {
      List<MBankAccount> cashboxes =
          new Query(ctx, MBankAccount.Table_Name, "C_Bank_ID=? AND SalesRep_ID=?", null)
              .setParameters(bankbox.get_ID(), Env.getContext(ctx, "#AD_User_ID"))
              .setOnlyActiveRecords(true)
              .list();

      if (cashboxes.size() > 1) {
        showErrorMessage("Existen mas de 2 cajas asignadas a este usuario");
      } else if (cashboxes.size() == 0) {
        showErrorMessage("Este Usuario no tiene ninguna caja asignada");
      } else {
        cashbox = cashboxes.get(0);
      }
    }
  }

  public void clean() {
    m_bpartner = null;
    studentList = new LinkedHashMap<String, I_C_BPartner>();
    paymentSchedules = new ArrayList<MTimeExpenseLine>();
    caPayment = null;

    cleanComponents();
  }

  public abstract void cleanComponents();

  public abstract void showErrorMessage(String message);

  public abstract String getComboValue(int row, int column);

  public abstract void dinamycRefresh();

  public boolean completePayments(int docType_ID, String documentNo, Timestamp trxDate) {
    boolean success = false;

    message_error = "No se pudo completar los pagos";

    try {

      success = validatePayments();

      // create header

      caPayment = new X_CA_Payment(ctx, 0, null);
      caPayment.setC_BPartner_ID(m_bpartner.get_ID());
      caPayment.setDocumentNo(documentNo);
      caPayment.setC_DocType_ID(docType_ID);
      caPayment.setDateTrx(trxDate);
      caPayment.saveEx();

      // save lines

      // buscar tabla de prioridades
      // List<X_CA_PaymentPreference> priorities = new Query(ctx, X_CA_PaymentPreference.Table_Name,
      // "", null)
      // .setOnlyActiveRecords(true).setOrderBy("SeqNo").list();

      for (int tableRow = 0; tableRow <= paymentTable.getRowCount() - 1; tableRow++) {

        String type = getComboValue(tableRow, 0);

        if (!"AN".equals(type) && !"ME".equals(type))
          throw new AdempiereException("Indicar tipo de pago (Anual/Mensual)");

        String paymentType = getComboValue(tableRow, 1);
        String card = getComboValue(tableRow, 2);
        java.lang.Number quote = (java.lang.Number) paymentTable.getValueAt(tableRow, 3);
        Boolean hasinteres = (Boolean) paymentTable.getValueAt(tableRow, 4);
        String account = getComboValue(tableRow, 5);
        String reference = (String) paymentTable.getValueAt(tableRow, 6);
        java.lang.Number amount = (java.lang.Number) paymentTable.getValueAt(tableRow, 7);

        for (int studentRow = 0; studentRow <= studentTable.getRowCount() - 1; studentRow++) {

          String value = (String) studentTable.getValueAt(studentRow, INDEX_VALUE);
          I_C_BPartner student = studentList.get(value);
          Boolean doPay = (Boolean) studentTable.getValueAt(studentRow, 5);

          if (doPay) {
            MTimeExpenseLine currentSchedule = null;

            for (MTimeExpenseLine schedule : paymentSchedules) {
              if (schedule.getC_BPartner_ID() == student.getC_BPartner_ID()) {
                currentSchedule = schedule;
              }
            }

            if (currentSchedule == null) throw new AdempiereException("No existe programa de Pago");

            // generar nuevo pago
            MPayment payment = new MPayment(ctx, 0, null);

            payment.set_ValueOfColumn("CA_Payment_ID", caPayment.get_ID());
            payment.setC_DocType_ID(1000008); // pago, que siempre no, que es cobro
            payment.setC_BankAccount_ID(Integer.parseInt(account));

            payment.set_ValueOfColumn("SalesRep_ID", Env.getContextAsInt(ctx, "#AD_User_ID"));

            payment.setTenderType(paymentType);

            if ("K".equals(paymentType)
                || "Q".equals(paymentType)) // cheque nacional - internacional
            {
              payment.setCheckNo(reference);
            } else if ("A".equals(paymentType)) // Depósito directo
            {
              payment.setAccountNo(reference);
            } else if ("C".equals(paymentType)) // Tarjeta de Crédito
            {
              payment.setCreditCardType(card);
              payment.setCreditCardNumber(reference);
              payment.set_ValueOfColumn("NumberOfShares", new BigDecimal(String.valueOf(quote)));
              payment.set_ValueOfColumn("HasInterests", hasinteres);
            }

            payment.setC_BPartner_ID(student.getC_BPartner_ID());

            payment.setPayAmt(new BigDecimal(String.valueOf(getAmount(currentSchedule, type))));
            payment.setC_Order_ID(currentSchedule.get_ID());
            payment.setC_Currency_ID(100); // USD

            if (payment.getPayAmt().compareTo(new BigDecimal("0")) > 0) {
              payment.saveEx();
              payment.processIt(DocAction.ACTION_Complete);
            }
          }
        }
      }

      success = true;
    } catch (Exception e) {
      success = false;
      e.printStackTrace();
      message_error = e.getMessage();
    }

    return success;
  }

  private boolean validatePayments() {
    boolean valid = true;

    return valid;
  }

  private BigDecimal getAmount(MTimeExpenseLine schedule, String mode) {
    BigDecimal amount = Env.ZERO;

    if (!(schedule.get_ValueAsBoolean("IsPaid"))) {
      MProduct concept = (MProduct) schedule.getM_Product();
      MExpenseType conceptType = (MExpenseType) concept.getS_ExpenseType();
      String type = concept.get_ValueAsString(MInvoiceSchedule.COLUMNNAME_InvoiceFrequency);
      if (mode.equals(type)) {
        amount = amount.add(schedule.getApprovalAmt());
        schedule.set_ValueOfColumn("IsPaid", true);
        schedule.saveEx();
      }
    }

    return amount;
  }
}
예제 #29
0
public class TerminalTable extends MiniTable implements ITerminalTable, IComponentSwing {

  /** */
  private static final long serialVersionUID = 7884238751207398699L;

  public static final int ROW_SIZE = 50;

  private final CLogger log = CLogger.getCLogger(getClass());

  private final ITerminalContext tc;

  private String sql;

  private int idColumnIndex = -1;

  private final PropertyChangeSupport listeners;

  private final ListSelectionListener selectionListener =
      new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
          if (!fireSelectionEvent || e.getValueIsAdjusting()) return;

          int id = getSelectedId();
          listeners.firePropertyChange(PROPERTY_SelectedId, null, id);
        }
      };

  protected TerminalTable(final ITerminalContext tc) {
    super();

    this.tc = tc;
    this.listeners = tc.createPropertyChangeSupport(this);

    setRowSelectionAllowed(true);
    setColumnSelectionAllowed(false);
    setMultiSelection(false);
    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    setRowHeight(ROW_SIZE);
    setAutoResize(false);
    setFocusable(false);
    setFillsViewportHeight(true); // @Trifon
    growScrollbars();

    getSelectionModel().addListSelectionListener(selectionListener);
  }

  @Override
  public void setAutoResize(boolean autoResize) {
    super.setAutoResize(autoResize);
  }

  @Override
  public void addListener(PropertyChangeListener listener) {
    listeners.addPropertyChangeListener(listener);
  }

  private void growScrollbars() {
    // fatter scroll bars
    Container p = getParent();
    if (p instanceof JViewport) {
      Container gp = p.getParent();
      if (gp instanceof JScrollPane) {
        JScrollPane scrollPane = (JScrollPane) gp;
        scrollPane
            .getVerticalScrollBar()
            .setPreferredSize(new Dimension(SwingTerminalFactory.SCROLL_Size, 0));
        scrollPane
            .getHorizontalScrollBar()
            .setPreferredSize(new Dimension(0, SwingTerminalFactory.SCROLL_Size));
      }
    }
  }

  @Override
  public String prepareTable(
      ColumnInfo[] layout, String from, String where, boolean multiSelection, String tableName) {
    for (int i = 0; i < layout.length; i++) {
      if (layout[i].getColClass() == IDColumn.class) {
        idColumnIndex = i;
        break;
      }
    }
    sql = super.prepareTable(layout, from, where, multiSelection, tableName);
    return sql;
  }

  @Override
  public String getSQL() {
    return sql;
  }

  @Override
  public void prepareTable(Class<?> cl, String[] columnNames, String sqlWhere, String sqlOrderBy) {
    ColumnInfo[] layout = MiniTableUtil.createColumnInfo(cl, columnNames);
    String tableName = MiniTableUtil.getTableName(cl);
    String from = tableName;
    prepareTable(layout, from, sqlWhere, false, tableName);
    if (!Check.isEmpty(sqlOrderBy, true)) {
      sql += " ORDER BY " + sqlOrderBy;
    }
  }

  @Override
  public void loadData(Object... params) {
    if (sql == null)
      throw new IllegalStateException(
          "Table not initialized. Please use prepareTable method first");

    int selectedId = getSelectedId();

    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      DB.setParameters(pstmt, params);
      rs = pstmt.executeQuery();
      this.loadTable(rs);
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }

    selectById(selectedId);
  }

  @Override
  public int getSelectedId() {
    if (idColumnIndex < 0) return -1;

    int row = getSelectedRow();
    if (row != -1) {
      Object data = getModel().getValueAt(row, 0);
      if (data != null) {
        Integer id = (Integer) ((IDColumn) data).getRecord_ID();
        return id == null ? -1 : id.intValue();
      }
    }

    return -1;
  }

  @Override
  public void selectById(int id) {
    selectById(id, true);
  }

  public void selectById(int id, boolean fireEvent) {
    if (idColumnIndex < 0) return;

    boolean fireSelectionEventOld = fireSelectionEvent;
    try {
      fireSelectionEvent = fireEvent;
      if (id < 0) {
        this.getSelectionModel().removeSelectionInterval(0, this.getRowCount());
        return;
      }

      for (int i = 0; i < this.getRowCount(); i++) {
        IDColumn key = (IDColumn) this.getModel().getValueAt(i, idColumnIndex);
        if (key != null && id > 0 && key.getRecord_ID() == id) {
          this.getSelectionModel().setSelectionInterval(i, i);
          break;
        }
      }
    } finally {
      fireSelectionEvent = fireSelectionEventOld;
    }
  }

  private boolean fireSelectionEvent = true;

  @Override
  public Component getComponent() {
    return this;
  }

  @Override
  public ITerminalContext getTerminalContext() {
    return tc;
  }

  @Override
  public void dispose() {
    // TODO Auto-generated method stub

  }
}
예제 #30
0
public class WOrderCompletedTips extends Window implements EventListener, IExceptionTips {

  /** */
  private static final long serialVersionUID = 883114344266765693L;
  /** Tab */
  private GridTab m_mTab;

  private boolean m_initOK = false;
  /** Logger */
  private static CLogger log = CLogger.getCLogger(WExceptionTips.class);

  private Panel mainPanel = new Panel();
  private Borderlayout mainLayout = new Borderlayout();
  private WListbox xTable = ListboxFactory.newDataTable();
  private ConfirmPanel confirmPanel = new ConfirmPanel(true);

  private String errorMessage = "";

  public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
  }

  public WOrderCompletedTips(int WindowNo, GridTab mTab, WButtonEditor button) {
    super();
    this.setTitle(Msg.getMsg(Env.getCtx(), "WT_CantComplete"));
    this.setAttribute("mode", "modal");
    m_mTab = mTab;
    try {
      zkInit();
      m_initOK = dynInit(button); // Null Pointer if order/invoice not
      // saved yet
    } catch (Exception ex) {
      setErrorMessage(ex.getLocalizedMessage());
      log.log(Level.SEVERE, "ExceptionTips", ex);
      m_initOK = false;
    }
    //
    this.setHeight("400px");
    this.setWidth("600px");
    this.setBorder("normal");
  }

  private void zkInit() throws Exception {
    this.appendChild(mainPanel);
    mainPanel.appendChild(mainLayout);
    mainPanel.setStyle("width: 100%; height: 100%; padding: 0; margin: 0");
    mainLayout.setHeight("100%");
    mainLayout.setWidth("100%");
    Center center = new Center();
    mainLayout.appendChild(center);
    Panel p = new Panel();
    p.appendChild(xTable);
    xTable.setWidth("100%");
    xTable.setHeight("100%");
    p.setStyle("width: 100%; height: 100%; padding: 0; margin: 0");
    center.appendChild(p);
    //
    South south = new South();
    south.setStyle("border: none");
    mainLayout.appendChild(south);
    south.appendChild(confirmPanel);
    confirmPanel.addActionListener(this);
  } // jbInit

  private boolean dynInit(WButtonEditor button) throws Exception {
    // 获取海外入库单产生的异常
    Vector<Vector> data = getBExceptionData();
    if (data.size() <= 0) {
      // 当卖家海外仓入库单内所有单品状态都变更为"海外仓上架完成"时,将卖家海外仓入库单状态更新为"海外仓入库完成"
      if (m_mTab.getAD_Table_ID() == MOrder.Table_ID) {
        MOrder order = new MOrder(Env.getCtx(), m_mTab.getRecord_ID(), null);
        order.setStatus(MOrder.STATUS_ForeignWarehouseInboundCompleted);
        order.saveEx();
      } else if (m_mTab.getAD_Table_ID() == MWorkOrder.Table_ID) {
        MWorkOrder order = new MWorkOrder(Env.getCtx(), m_mTab.getRecord_ID(), null);
        order.setStatus(MWorkOrder.STATUS_Completed);
        order.saveEx();
      }

      // 不显示业务异常提示窗口
      return false;
    }

    ColumnInfo[] layout =
        new ColumnInfo[] {
          new ColumnInfo(Msg.translate(Env.getCtx(), "WT_ExceptionType"), ".", String.class),
          new ColumnInfo(Msg.translate(Env.getCtx(), "WT_ExceptionID"), ".", String.class)
        };
    xTable.prepareTable(layout, "", "", false, "");
    xTable.loadTable(data);
    // 显示业务异常提示窗口
    return true;
  } // dynInit

  @Override
  public void onEvent(Event e) {
    // Finish
    if (e.getTarget().getId().equals(ConfirmPanel.A_OK)) {
      dispose();
    } else if (e.getTarget().getId().equals(ConfirmPanel.A_CANCEL)) dispose();
  }

  private Vector<Vector> getBExceptionData() {
    Vector<Vector> data = new Vector<Vector>();

    final String whereClause =
        MBExceptionDetail.COLUMNNAME_Record_ID
            + " = "
            + m_mTab.getRecord_ID()
            + " AND "
            + MBExceptionDetail.COLUMNNAME_Status
            + "<>"
            + DB.TO_STRING(MBExceptionDetail.STATUS_Completed);
    MBExceptionDetail[] bExceptionDetails =
        MBExceptionDetail.getBExceptionDetail(Env.getCtx(), whereClause);
    for (MBExceptionDetail ex : bExceptionDetails) {

      Vector<String> row = new Vector<String>();
      row.add(ex.getWT_BExceptionType().getName());
      row.add(ex.getValue());
      data.add(row);
    }

    return data;
  }

  public boolean isInitOK() {
    return m_initOK;
  } // isInitOK

  @Override
  public boolean needSave() {
    return true;
  }

  @Override
  public String getErrorMessage() {
    return this.errorMessage;
  }
}