Initial Commit

This commit is contained in:
shameem_z 2007-11-22 10:51:54 +00:00
parent 296faf1bb8
commit 9189807a0e
165 changed files with 46242 additions and 0 deletions

View File

@ -0,0 +1,122 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui;
import java.util.Properties;
import org.adempiere.webui.session.SessionManager;
import org.compiere.util.Env;
import org.zkoss.zk.ui.event.ClientInfoEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Window;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class AdempiereWebUI extends Window implements EventListener
{
private static final long serialVersionUID = 1L;
public static final String APP_NAME = "Posterita Ajax UI";
public static final String UID = "0.2";
private WLogin loginDesktop;
private Desktop appDesktop;
private ClientInfo clientInfo;
public AdempiereWebUI()
{
this.addEventListener(Events.ON_CLIENT_INFO, this);
}
public void onCreate()
{
this.getPage().setTitle(APP_NAME);
Properties ctx = Env.getCtx();
SessionManager.setSessionApplication(this);
if (!SessionManager.isUserLoggedIn(ctx))
{
loginDesktop = new WLogin(this);
this.appendChild(loginDesktop);
}
else
{
loginCompleted();
}
}
public void onOk()
{
}
public void onCancel()
{
}
public void loginCompleted()
{
loginDesktop = null;
this.getChildren().clear();
appDesktop = new Desktop();
appDesktop.setParent(this);
appDesktop.setClientInfo(clientInfo);
this.setWidth("100%");
this.setHeight("100%");
this.appendChild(appDesktop);
}
public void logout()
{
SessionManager.clearSession();
super.getChildren().clear();
loginDesktop = new WLogin(this);
super.appendChild(loginDesktop);
}
public Desktop getAppDeskop()
{
return appDesktop;
}
public boolean isAsap() {
return true;
}
public void onEvent(Event event) {
if (event instanceof ClientInfoEvent) {
ClientInfoEvent c = (ClientInfoEvent)event;
clientInfo = new ClientInfo();
clientInfo.colorDepth = c.getColorDepth();
clientInfo.desktopHeight = c.getDesktopHeight();
clientInfo.desktopWidth = c.getDesktopWidth();
clientInfo.desktopXOffset = c.getDesktopXOffset();
clientInfo.desktopYOffset = c.getDesktopYOffset();
clientInfo.timeZone = c.getTimeZone();
if (appDesktop != null)
appDesktop.setClientInfo(clientInfo);
}
}
}

View File

@ -0,0 +1,35 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2007 Adempiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*
* Copyright (C) 2007 Low Heng Sin hengsin@avantz.com
* _____________________________________________
*****************************************************************************/
package org.adempiere.webui;
import java.util.TimeZone;
/**
*
* @author Low Heng Sin
*
*/
public class ClientInfo {
public int colorDepth;
public int desktopWidth;
public int desktopHeight;
public int desktopXOffset;
public int desktopYOffset;
public int screenHeight;
public int screenWidth;
public TimeZone timeZone;
}

View File

@ -0,0 +1,355 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import org.adempiere.webui.apps.ProcessDialog;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.component.Window;
import org.adempiere.webui.event.MenuListener;
import org.adempiere.webui.exception.ApplicationException;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.panel.FooterPanel;
import org.adempiere.webui.panel.HeaderPanel;
import org.adempiere.webui.panel.MainPanel;
import org.adempiere.webui.panel.SidePanel;
import org.adempiere.webui.window.ADWindow;
import org.compiere.model.MClient;
import org.compiere.model.MMenu;
import org.compiere.model.MQuery;
import org.compiere.util.CCache;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.WebDoc;
import org.zkoss.util.media.AMedia;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Iframe;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 2, 2007
* @version $Revision: 0.10 $
*/
public class Desktop extends Window implements MenuListener
{
private static final long serialVersionUID = 1L;
private static final CLogger logger = CLogger.getCLogger(Desktop.class);
private HeaderPanel pnlHead;
private SidePanel pnlSide;
private MainPanel pnlMain;
private FooterPanel pnlFooter;
private ClientInfo clientInfo;
private List<Window> windows;
private CCache<Integer, ADWindow> windowCache;
public Desktop()
{
windows = new ArrayList<Window>();
windowCache = new CCache<Integer, ADWindow>("ZKWindowCache", 20);
windowCache.setExpireMinutes(10); // Remove the cached window after 10 mins
init();
}
private void init()
{
pnlSide = new SidePanel();
pnlMain = new MainPanel();
pnlFooter = new FooterPanel();
pnlHead = new HeaderPanel();
pnlSide.getMenuPanel().addMenuListener(this);
VerticalBox verticalBox = new VerticalBox();
verticalBox.setWidth("1200px");
Hbox hbox = new Hbox();
hbox.setWidth("1200px");
hbox.setWidths("300px, 900px");
hbox.appendChild(pnlSide);
hbox.appendChild(pnlMain);
showURL("http://www.posterita.org/", "Home", false);
verticalBox.appendChild(pnlHead);
verticalBox.appendChild(hbox);
//this.setBorder("normal");
this.setStyle("background-color: #FAFAFA");
//this.setWidth("100%");
//this.setHeight("100%");
this.appendChild(verticalBox);
}
/**
* Retrives the Client website url
* @return website url
*/
private String getClientWebsiteURL()
{
MClient client = MClient.get(Env.getCtx());
String defaultUrl = "http://www.adempiere.com";
String url = (String)client.get_Value("WebSiteURL");
if (url == null)
{
url = defaultUrl;
}
else if (!url.startsWith("http"))
{
logger.log(Level.SEVERE, "Website URL provided for the client is not valid!!!");
url = defaultUrl;
}
return url;
}
/**
* Event listener for menu item selection.
* Identifies the action associated with the selected
* menu item and acts accordingly.
*
* @param menuId Identifier for the selected menu item
*
* @throws ApplicationException If the selected menu action has yet
* to be implemented
*/
public void onMenuSelected(int menuId)
{
MMenu menu = new MMenu(Env.getCtx(), menuId, null);
if(menu == null)
{
return;
}
if(menu.getAction().equals(MMenu.ACTION_Window))
{
Integer wMenuId = Integer.valueOf(menu.getAD_Window_ID());
ADWindow wndMain = windowCache.get(wMenuId);
if (wndMain == null)
{
wndMain = new ADWindow(Env.getCtx(), menu.getAD_Window_ID());
windowCache.put(wMenuId, wndMain);
}
pnlMain.addWindow(wndMain, wndMain.getTitle(), true);
}
else if(menu.getAction().equals(MMenu.ACTION_Process) ||
menu.getAction().equals(MMenu.ACTION_Report))
{
ProcessDialog pd = new ProcessDialog (menu.getAD_Process_ID(), menu.isSOTrx());
if (pd.isValid()) {
pd.setPage(this.getPage());
pd.setClosable(true);
pd.setWidth("500px");
try {
pd.doModal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else if(menu.getAction().equals(MMenu.ACTION_Form))
{
Window form = ADForm.openForm(menu.getAD_Form_ID());
pnlMain.addWindow(form, form.getTitle(), true);
}
else
{
throw new ApplicationException("Menu Action not yet implemented: " + menu.getAction());
}
}
public void showURL(String url, boolean closeable)
{
showURL(url, url, closeable);
}
public void showURL(String url, String title, boolean closeable)
{
Iframe iframe = new Iframe(url);
addWin(iframe, title, closeable);
}
public void showURL(WebDoc webDoc, String title, boolean closeable)
{
Iframe iframe = new Iframe();
AMedia media = new AMedia(title, "html", "text/html", webDoc.toString().getBytes());
iframe.setContent(media);
addWin(iframe, title, closeable);
}
private void addWin(Iframe fr, String title, boolean closeable)
{
fr.setWidth("100%");
fr.setHeight("650px");
Window wndUrl = new Window();
//wndUrl.setHeight("650px");
//wndUrl.setWidth("800px");
wndUrl.appendChild(fr);
pnlMain.addWindow(wndUrl, title, closeable);
}
public void showZoomWindow(int AD_Window_ID, MQuery query)
{
ADWindow wnd = new ADWindow(Env.getCtx(), AD_Window_ID, query);
Window window = new Window();
window.appendChild(wnd);
window.setBorder("normal");
pnlMain.addWindow(window,wnd.getTitle(),true);
}
public void showWindow(Window win)
{
win.setPage(this.getPage());
Object objMode = win.getAttribute("mode");
String pos = win.getPosition();
String mode = "modal";
if (objMode != null)
{
mode = objMode.toString();
}
if ("modal".equals(mode))
{
showModal(win);
}
else if ("popup".equals(mode))
{
showPopup(win, pos);
}
else if ("overlapped".equals(mode))
{
showOverlapped(win, pos);
}
else if ("embedded".equals(mode))
{
showEmbedded(win, pos);
}
else if ("highlighted".equals(mode))
{
showHighlighted(win, pos);
}
win.setVisible(true);
}
public void showModal(Window win)
{
try
{
win.doModal();
}
catch(InterruptedException e)
{
}
}
public void showPopup(Window win, String position)
{
if (position == null)
win.setPosition("center");
else
win.setPosition(position);
win.doPopup();
}
public void showOverlapped(Window win, String position)
{
if (position == null)
win.setPosition("center");
else
win.setPosition(position);
win.doOverlapped();
}
public void showHighlighted(Window win, String position)
{
if (position == null)
win.setPosition("center");
else
win.setPosition(position);
win.doHighlighted();
}
public void showEmbedded(Window win, String position)
{
if (position == null)
win.setPosition("center");
else
win.setPosition(position);
win.doEmbedded();
}
public ClientInfo getClientInfo() {
return clientInfo;
}
public void setClientInfo(ClientInfo clientInfo) {
this.clientInfo = clientInfo;
}
public int registerWindow(Window win) {
int retValue = windows.size();
windows.add(win);
return retValue;
}
public void unregisterWindow(int WindowNo) {
if (WindowNo < windows.size())
windows.set(WindowNo, null);
}
public Window findWindow(int WindowNo) {
if (WindowNo < windows.size())
return windows.get(WindowNo);
else
return null;
}
public void removeWindow()
{
pnlMain.removeWindow();
}
}

View File

@ -0,0 +1,47 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui;
import org.adempiere.webui.component.Window;
import org.adempiere.webui.window.LoginWindow;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 3, 2007
* @version $Revision: 0.10 $
*/
public class WLogin extends Window
{
private static final long serialVersionUID = 1L;
private AdempiereWebUI novita;
private LoginWindow loginWindow;
public WLogin(AdempiereWebUI novita)
{
this.novita = novita;
init();
}
private void init()
{
loginWindow = new LoginWindow(novita);
this.appendChild(loginWindow);
}
}

View File

@ -0,0 +1,58 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2007 Adempiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*
* Copyright (C) 2007 Low Heng Sin hengsin@avantz.com
* _____________________________________________
*****************************************************************************/
package org.adempiere.webui;
import java.awt.Image;
import java.util.Properties;
import javax.swing.ImageIcon;
import org.adempiere.webui.session.SessionManager;
import org.adempiere.webui.session.WebContext;
import org.compiere.util.ContextProvider;
/**
*
* @author Low Heng Sin
*
*/
public class ZkContextProvider implements ContextProvider {
public Properties getContext() {
return WebContext.getCurrentInstance();
}
public void showURL(String url) {
SessionManager.getAppDesktop().showURL(url,true);
}
public Image getImage (String fileNameInImageDir)
{
return null;
}
public ImageIcon getImageIcon (String fileNameInImageDir)
{
return null;
}
public ImageIcon getImageIcon2 (String fileName)
{
return null;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,610 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.acct;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import org.adempiere.webui.component.Listbox;
import org.compiere.model.MAcctSchema;
import org.compiere.model.MAcctSchemaElement;
import org.compiere.model.MFactAcct;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MRefList;
import org.compiere.report.core.RColumn;
import org.compiere.report.core.RModel;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.compiere.util.ValueNamePair;
/**
* Account Viewer State - maintains State information for the Account Viewer
* Based on class AcctViewerData
*
* @author Niraj Sohun
* July 27, 2007
*/
public class WAcctViewerData
{
/** Window */
public int WindowNo;
/** Client */
public int AD_Client_ID;
/** All Acct Schema */
public MAcctSchema[] ASchemas = null;
/** This Acct Schema */
public MAcctSchema ASchema = null;
// Selection Info
/** Document Query */
public boolean documentQuery = false;
/** Acct Schema */
public int C_AcctSchema_ID = 0;
/** Posting Type */
public String PostingType = "";
/** Organization */
public int AD_Org_ID = 0;
/** Date From */
public Timestamp DateFrom = null;
/** Date To */
public Timestamp DateTo = null;
// Document Table Selection Info
/** Table ID */
public int AD_Table_ID;
/** Record */
public int Record_ID;
/** Containing Column and Query */
public HashMap<String,String> whereInfo = new HashMap<String,String>();
/** Containing TableName and AD_Table_ID */
public HashMap<String,Integer> tableInfo = new HashMap<String,Integer>();
// Display Info
/** Display Qty */
boolean displayQty = false;
/** Display Source Surrency */
boolean displaySourceAmt = false;
/** Display Document info */
boolean displayDocumentInfo = false;
String sortBy1 = "";
String sortBy2 = "";
String sortBy3 = "";
String sortBy4 = "";
boolean group1 = false;
boolean group2 = false;
boolean group3 = false;
boolean group4 = false;
/** Leasing Columns */
private int m_leadingColumns = 0;
/** UserElement1 Reference */
private String m_ref1 = null;
/** UserElement2 Reference */
private String m_ref2 = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(WAcctViewerData.class);
/**
* Constructor
* @param ctx context
* @param windowNo window no
* @param ad_Client_ID client
* @param ad_Table_ID table
*/
public WAcctViewerData (Properties ctx, int windowNo, int ad_Client_ID, int ad_Table_ID)
{
WindowNo = windowNo;
AD_Client_ID = ad_Client_ID;
if (AD_Client_ID == 0)
AD_Client_ID = Env.getContextAsInt(Env.getCtx(), WindowNo, "AD_Client_ID");
if (AD_Client_ID == 0)
AD_Client_ID = Env.getContextAsInt(Env.getCtx(), "AD_Client_ID");
AD_Table_ID = ad_Table_ID;
ASchemas = MAcctSchema.getClientAcctSchema(ctx, AD_Client_ID);
ASchema = ASchemas[0];
} // AcctViewerData
/**
* Dispose
*/
public void dispose()
{
ASchemas = null;
ASchema = null;
whereInfo.clear();
whereInfo = null;
Env.clearWinContext(WindowNo);
} // dispose
/**************************************************************************
* Fill Accounting Schema
* @param cb Listbox to be filled
*/
protected void fillAcctSchema (Listbox cb)
{
for (int i = 0; i < ASchemas.length; i++)
{
KeyNamePair key = new KeyNamePair(ASchemas[i].getC_AcctSchema_ID(), ASchemas[i].getName());
cb.appendItem(key.getName(), key);
}
} // fillAcctSchema
/**
* Fill Posting Type
* @param cb Listox to be filled
*/
protected void fillPostingType (Listbox cb)
{
int AD_Reference_ID = 125;
ValueNamePair[] pt = MRefList.getList(Env.getCtx(), AD_Reference_ID, true);
for (int i = 0; i < pt.length; i++)
{
cb.appendItem(pt[i].getName(), pt[i]);
}
} // fillPostingType
/**
* Fill Table with
* ValueNamePair (TableName, translatedKeyColumnName)
* and tableInfo with (TableName, AD_Table_ID)
* and select the entry for AD_Table_ID
*
* @param cb Listbox to be filled
*/
protected void fillTable (Listbox cb)
{
ValueNamePair select = null;
String sql = "SELECT AD_Table_ID, TableName FROM AD_Table t "
+ "WHERE EXISTS (SELECT * FROM AD_Column c"
+ " WHERE t.AD_Table_ID=c.AD_Table_ID AND c.ColumnName='Posted')"
+ " AND IsView='N'";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
int id = rs.getInt(1);
String tableName = rs.getString(2);
String name = Msg.translate(Env.getCtx(), tableName+"_ID");
ValueNamePair pp = new ValueNamePair(tableName, name);
cb.appendItem(pp.getName(),pp);
tableInfo.put (tableName, new Integer(id));
if (id == AD_Table_ID)
select = pp;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
if (select != null)
;//cb.setSelectedItem(select);
} // fillTable
/**
* Fill Org
*
* @param cb Listbox to be filled
*/
protected void fillOrg (Listbox cb)
{
KeyNamePair pp = new KeyNamePair(0, "");
cb.appendItem(pp.getName(), pp);
String sql = "SELECT AD_Org_ID, Name FROM AD_Org WHERE AD_Client_ID=? ORDER BY Value";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
KeyNamePair key = new KeyNamePair(rs.getInt(1), rs.getString(2));
cb.appendItem(key.getName(), key);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
} // fillOrg
/**
* Get Button Text
*
* @param tableName table
* @param columnName column
* @param selectSQL sql
* @return Text on button
*/
protected String getButtonText (String tableName, String columnName, String selectSQL)
{
// SELECT (<embedded>) FROM tableName avd WHERE avd.<selectSQL>
StringBuffer sql = new StringBuffer ("SELECT (");
Language language = Env.getLanguage(Env.getCtx());
sql.append(MLookupFactory.getLookup_TableDirEmbed(language, columnName, "avd"))
.append(") FROM ").append(tableName).append(" avd WHERE avd.").append(selectSQL);
String retValue = "<" + selectSQL + ">";
try
{
Statement stmt = DB.createStatement();
ResultSet rs = stmt.executeQuery(sql.toString());
if (rs.next())
retValue = rs.getString(1);
rs.close();
stmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
return retValue;
} // getButtonText
/**************************************************************************
/**
* Create Query and submit
* @return Report Model
*/
protected RModel query()
{
// Set Where Clause
StringBuffer whereClause = new StringBuffer();
// Add Organization
if (C_AcctSchema_ID != 0)
whereClause.append(RModel.TABLE_ALIAS).append(".C_AcctSchema_ID=").append(C_AcctSchema_ID);
// Posting Type Selected
if (PostingType != null && PostingType.length() > 0)
{
if (whereClause.length() > 0)
whereClause.append(" AND ");
whereClause.append(RModel.TABLE_ALIAS)
.append(".PostingType='").append(PostingType).append("'");
}
if (documentQuery)
{
if (whereClause.length() > 0)
whereClause.append(" AND ");
whereClause.append(RModel.TABLE_ALIAS).append(".AD_Table_ID=").append(AD_Table_ID)
.append(" AND ").append(RModel.TABLE_ALIAS).append(".Record_ID=").append(Record_ID);
}
else
{
// get values (Queries)
Iterator it = whereInfo.values().iterator();
while (it.hasNext())
{
String where = (String)it.next();
if (where != null && where.length() > 0) // add only if not empty
{
if (whereClause.length() > 0)
whereClause.append(" AND ");
whereClause.append(RModel.TABLE_ALIAS).append(".").append(where);
}
}
if (DateFrom != null || DateTo != null)
{
if (whereClause.length() > 0)
whereClause.append(" AND ");
if (DateFrom != null && DateTo != null)
whereClause.append("TRUNC(").append(RModel.TABLE_ALIAS).append(".DateAcct) BETWEEN ")
.append(DB.TO_DATE(DateFrom)).append(" AND ").append(DB.TO_DATE(DateTo));
else if (DateFrom != null)
whereClause.append("TRUNC(").append(RModel.TABLE_ALIAS).append(".DateAcct) >= ")
.append(DB.TO_DATE(DateFrom));
else // DateTo != null
whereClause.append("TRUNC(").append(RModel.TABLE_ALIAS).append(".DateAcct) <= ")
.append(DB.TO_DATE(DateTo));
}
// Add Organization
if (AD_Org_ID != 0)
{
if (whereClause.length() > 0)
whereClause.append(" AND ");
whereClause.append(RModel.TABLE_ALIAS).append(".AD_Org_ID=").append(AD_Org_ID);
}
}
// Set Order By Clause
StringBuffer orderClause = new StringBuffer();
if (sortBy1.length() > 0)
orderClause.append(RModel.TABLE_ALIAS).append(".").append(sortBy1);
if (sortBy2.length() > 0)
{
if (orderClause.length() > 0)
orderClause.append(",");
orderClause.append(RModel.TABLE_ALIAS).append(".").append(sortBy2);
}
if (sortBy3.length() > 0)
{
if (orderClause.length() > 0)
orderClause.append(",");
orderClause.append(RModel.TABLE_ALIAS).append(".").append(sortBy3);
}
if (sortBy4.length() > 0)
{
if (orderClause.length() > 0)
orderClause.append(",");
orderClause.append(RModel.TABLE_ALIAS).append(".").append(sortBy4);
}
if (orderClause.length() == 0)
orderClause.append(RModel.TABLE_ALIAS).append(".Fact_Acct_ID");
RModel rm = getRModel();
// Groups
if (group1 && sortBy1.length() > 0)
rm.setGroup(sortBy1);
if (group2 && sortBy2.length() > 0)
rm.setGroup(sortBy2);
if (group3 && sortBy3.length() > 0)
rm.setGroup(sortBy3);
if (group4 && sortBy4.length() > 0)
rm.setGroup(sortBy4);
// Totals
rm.setFunction("AmtAcctDr", RModel.FUNCTION_SUM);
rm.setFunction("AmtAcctCr", RModel.FUNCTION_SUM);
rm.query (Env.getCtx(), whereClause.toString(), orderClause.toString());
return rm;
} // query
/**
* Create Report Model (Columns)
* @return Report Model
*/
private RModel getRModel()
{
Properties ctx = Env.getCtx();
RModel rm = new RModel("Fact_Acct");
// Add Key (Lookups)
ArrayList keys = createKeyColumns();
int max = m_leadingColumns;
if (max == 0)
max = keys.size();
for (int i = 0; i < max; i++)
{
String column = (String)keys.get(i);
if (column != null && column.startsWith("Date"))
rm.addColumn(new RColumn(ctx, column, DisplayType.Date));
else if (column != null && column.endsWith("_ID"))
rm.addColumn(new RColumn(ctx, column, DisplayType.TableDir));
}
// Main Info
rm.addColumn(new RColumn(ctx, "AmtAcctDr", DisplayType.Amount));
rm.addColumn(new RColumn(ctx, "AmtAcctCr", DisplayType.Amount));
if (displaySourceAmt)
{
if (!keys.contains("DateTrx"))
rm.addColumn(new RColumn(ctx, "DateTrx", DisplayType.Date));
rm.addColumn(new RColumn(ctx, "C_Currency_ID", DisplayType.TableDir));
rm.addColumn(new RColumn(ctx, "AmtSourceDr", DisplayType.Amount));
rm.addColumn(new RColumn(ctx, "AmtSourceCr", DisplayType.Amount));
rm.addColumn(new RColumn(ctx, "Rate", DisplayType.Amount,
"CASE WHEN (AmtSourceDr + AmtSourceCr) = 0 THEN 0"
+ " ELSE (AmtAcctDr + AmtAcctCr) / (AmtSourceDr + AmtSourceCr) END"));
}
// Remaining Keys
for (int i = max; i < keys.size(); i++)
{
String column = (String)keys.get(i);
if (column != null && column.startsWith("Date"))
rm.addColumn(new RColumn(ctx, column, DisplayType.Date));
else if (column.startsWith("UserElement"))
{
if (column.indexOf('1') != -1)
rm.addColumn(new RColumn(ctx, column, DisplayType.TableDir, null, 0, m_ref1));
else
rm.addColumn(new RColumn(ctx, column, DisplayType.TableDir, null, 0, m_ref2));
}
else if (column != null && column.endsWith("_ID"))
rm.addColumn(new RColumn(ctx, column, DisplayType.TableDir));
}
// Info
if (!keys.contains("DateAcct"))
rm.addColumn(new RColumn(ctx, "DateAcct", DisplayType.Date));
if (!keys.contains("C_Period_ID"))
rm.addColumn(new RColumn(ctx, "C_Period_ID", DisplayType.TableDir));
if (displayQty)
{
rm.addColumn(new RColumn(ctx, "C_UOM_ID", DisplayType.TableDir));
rm.addColumn(new RColumn(ctx, "Qty", DisplayType.Quantity));
}
if (displayDocumentInfo)
{
rm.addColumn(new RColumn(ctx, "AD_Table_ID", DisplayType.TableDir));
rm.addColumn(new RColumn(ctx, "Record_ID", DisplayType.ID));
rm.addColumn(new RColumn(ctx, "Description", DisplayType.String));
}
if (PostingType == null || PostingType.length() == 0)
rm.addColumn(new RColumn(ctx, "PostingType", DisplayType.List, // teo_sarca, [ 1664208 ]
RModel.TABLE_ALIAS+".PostingType",
MFactAcct.POSTINGTYPE_AD_Reference_ID,
null));
return rm;
} // createRModel
/**
* Create the key columns in sequence
* @return List of Key Columns
*/
private ArrayList createKeyColumns()
{
ArrayList<String> columns = new ArrayList<String>();
m_leadingColumns = 0;
// Sorting Fields
columns.add(sortBy1); // may add ""
if (!columns.contains(sortBy2))
columns.add(sortBy2);
if (!columns.contains(sortBy3))
columns.add(sortBy3);
if (!columns.contains(sortBy4))
columns.add(sortBy4);
// Add Account Segments
MAcctSchemaElement[] elements = ASchema.getAcctSchemaElements();
for (int i = 0; i < elements.length; i++)
{
if (m_leadingColumns == 0 && columns.contains("AD_Org_ID") && columns.contains("Account_ID"))
m_leadingColumns = columns.size();
MAcctSchemaElement ase = elements[i];
String columnName = ase.getColumnName();
if (columnName.startsWith("UserElement"))
{
if (columnName.indexOf('1') != -1)
m_ref1 = ase.getDisplayColumnName();
else
m_ref2 = ase.getDisplayColumnName();
}
if (!columns.contains(columnName))
columns.add(columnName);
}
if (m_leadingColumns == 0 && columns.contains("AD_Org_ID") && columns.contains("Account_ID"))
m_leadingColumns = columns.size();
return columns;
} // createKeyColumns
}

View File

@ -0,0 +1,896 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.apps;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.rmi.*;
import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.adempiere.webui.session.SessionManager;
import org.adempiere.webui.window.FDialog;
import org.compiere.Adempiere;
import org.compiere.db.*;
import org.compiere.interfaces.*;
import org.compiere.model.*;
import org.compiere.util.*;
import org.adempiere.webui.component.Window;
/**
* Windows Application Environment and utilities
*
* @author Jorg Janke
* @version $Id: AEnv.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $
*
* Colin Rooney (croo) & kstan_79 RFE#1670185
*/
public final class AEnv
{
/**
* Show in the center of the screen.
* (pack, set location and set visibility)
* @param window Window to position
*/
public static void showCenterScreen(Window window)
{
/* positionCenterScreen(window);
window.setVisible(true);
window.toFront();
*/
} // showCenterScreen
/**
* Position window in center of the screen
* @param window Window to position
*/
public static void positionCenterScreen(Window window)
{
// positionScreen (window, SwingConstants.CENTER);
} // positionCenterScreen
/**
* Show in the center of the screen.
* (pack, set location and set visibility)
* @param window Window to position
* @param position SwingConstants
*/
public static void showScreen(Window window, int position)
{
/* positionScreen(window, position);
window.setVisible(true);
window.toFront();
*/
} // showScreen
/**
* Position in center of the parent window.
* (pack, set location and set visibility)
* @param parent Parent Window
* @param window Window to position
*/
public static void showCenterWindow(Window parent, Window window)
{
/*
positionCenterWindow(parent, window);
window.setVisible(true);
window.toFront();
*/
} // showCenterWindow
/**
* Perform action command for common menu items.
* Created in AMenu.createMenu(), APanel.createMenu(), FormFrame.createMenu()
* @param actionCommand known action command
* @param WindowNo window no
* @param c Container parent
* @return true if actionCommand was found and performed
*/
/* public static boolean actionPerformed (String actionCommand, int WindowNo, Container c)
{
MRole role = MRole.getDefault();
// File Menu ------------------------
if (actionCommand.equals("PrintScreen"))
{
PrintScreenPainter.printScreen (Env.getFrame(c));
}
else if (actionCommand.equals("ScreenShot"))
{
ScreenShot.createJPEG(Env.getFrame(c), null);
}
// else if (actionCommand.equals("Report"))
// {
// AEnv.showCenterScreen (new ProcessStart());
// }
else if (actionCommand.equals("Exit"))
{
if (ADialog.ask(WindowNo, c, "ExitApplication?"))
Env.exitEnv(0);
}
else if (actionCommand.equals("Logout"))
{
AMenu aMenu = (AMenu)Env.getWindow(0);
aMenu.logout();
}
// View Menu ------------------------
else if (actionCommand.equals("InfoProduct") && AEnv.canAccessInfo("PRODUCT"))
{
org.compiere.apps.search.Info.showProduct (Env.getFrame(c), WindowNo);
}
else if (actionCommand.equals("InfoBPartner") && AEnv.canAccessInfo("BPARTNER"))
{
org.compiere.apps.search.Info.showBPartner (Env.getFrame(c), WindowNo);
}
else if (actionCommand.equals("InfoAsset") && AEnv.canAccessInfo("ASSET"))
{
org.compiere.apps.search.Info.showAsset (Env.getFrame(c), WindowNo);
}
else if (actionCommand.equals("InfoAccount") &&
MRole.getDefault().isShowAcct() &&
AEnv.canAccessInfo("ACCOUNT"))
{
new org.compiere.acct.AcctViewer();
}
else if (actionCommand.equals("InfoSchedule") && AEnv.canAccessInfo("SCHEDULE"))
{
new org.compiere.apps.search.InfoSchedule (Env.getFrame(c), null, false);
}
else if (actionCommand.equals("InfoOrder") && AEnv.canAccessInfo("ORDER"))
{
org.compiere.apps.search.Info.showOrder (Env.getFrame(c), WindowNo, "");
}
else if (actionCommand.equals("InfoInvoice") && AEnv.canAccessInfo("INVOICE"))
{
org.compiere.apps.search.Info.showInvoice (Env.getFrame(c), WindowNo, "");
}
else if (actionCommand.equals("InfoInOut") && AEnv.canAccessInfo("INOUT"))
{
org.compiere.apps.search.Info.showInOut (Env.getFrame(c), WindowNo, "");
}
else if (actionCommand.equals("InfoPayment") && AEnv.canAccessInfo("PAYMENT"))
{
org.compiere.apps.search.Info.showPayment (Env.getFrame(c), WindowNo, "");
}
else if (actionCommand.equals("InfoCashLine") && AEnv.canAccessInfo("CASHJOURNAL"))
{
org.compiere.apps.search.Info.showCashLine (Env.getFrame(c), WindowNo, "");
}
else if (actionCommand.equals("InfoAssignment") && AEnv.canAccessInfo("RESOURCE"))
{
org.compiere.apps.search.Info.showAssignment (Env.getFrame(c), WindowNo, "");
}
// Go Menu ------------------------
else if (actionCommand.equals("WorkFlow"))
{
startWorkflowProcess(0,0);
}
else if (actionCommand.equals("Home"))
{
Env.getWindow(0).toFront();
}
// Tools Menu ------------------------
else if (actionCommand.equals("Calculator"))
{
Calculator calc = new org.compiere.grid.ed.Calculator(Env.getFrame(c));
calc.setDisposeOnEqual(false);
AEnv.showCenterScreen (calc);
}
else if (actionCommand.equals("Calendar"))
{
AEnv.showCenterScreen (new org.compiere.grid.ed.Calendar(Env.getFrame(c)));
}
else if (actionCommand.equals("Editor"))
{
AEnv.showCenterScreen (new org.compiere.grid.ed.Editor(Env.getFrame(c)));
}
else if (actionCommand.equals("Script"))
{
new ScriptEditor();
}
else if (actionCommand.equals("Preference"))
{
if (role.isShowPreference()) {
AEnv.showCenterScreen(new Preference (Env.getFrame(c), WindowNo));
}
}
// Help Menu ------------------------
else if (actionCommand.equals("Online"))
{
Env.startBrowser(org.compiere.Adempiere.getOnlineHelpURL());
}
else if (actionCommand.equals("EMailSupport"))
{
ADialog.createSupportEMail(Env.getFrame(c), Env.getFrame(c).getTitle(), "\n\n");
}
else if (actionCommand.equals("About"))
{
AEnv.showCenterScreen(new AboutBox(Env.getFrame(c)));
}
else
return false;
//
return true;
} // actionPerformed
*/
/**
* Get Mnemonic character from text.
* @param text text with '&'
* @return Mnemonic or 0
*/
public static char getMnemonic (String text)
{
int pos = text.indexOf('&');
if (pos != -1) // We have a nemonic
return text.charAt(pos+1);
return 0;
} // getMnemonic
/*************************************************************************
* Zoom
* @param AD_Table_ID
* @param Record_ID
*/
public static void zoom (int AD_Table_ID, int Record_ID)
{
/*
String TableName = null;
int AD_Window_ID = 0;
int PO_Window_ID = 0;
String sql = "SELECT TableName, AD_Window_ID, PO_Window_ID FROM AD_Table WHERE AD_Table_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Table_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
TableName = rs.getString(1);
AD_Window_ID = rs.getInt(2);
PO_Window_ID = rs.getInt(3);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
// Nothing to Zoom to
if (TableName == null || AD_Window_ID == 0)
return;
// PO Zoom ?
boolean isSOTrx = true;
if (PO_Window_ID != 0)
{
String whereClause = TableName + "_ID=" + Record_ID;
isSOTrx = DB.isSOTrx(TableName, whereClause);
if (!isSOTrx)
AD_Window_ID = PO_Window_ID;
}
log.config(TableName + " - Record_ID=" + Record_ID + " (IsSOTrx=" + isSOTrx + ")");
AWindow frame = new AWindow();
if (!frame.initWindow(AD_Window_ID, MQuery.getEqualQuery(TableName + "_ID", Record_ID)))
return;
addToWindowManager(frame);
if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED))
{
AEnv.showMaximized(frame);
}
else
{
AEnv.showCenterScreen(frame);
}
frame = null;
*/
} // zoom
/**
* Exit System
* @param status System exit status (usually 0 for no error)
*/
public static void exit (int status)
{
if (s_server != null)
{
try
{
s_server.remove();
}
catch (Exception ex)
{
}
}
Env.exitEnv(status);
} // exit
public static void logout()
{
if (s_server != null)
{
try
{
s_server.remove();
}
catch (Exception ex)
{
}
}
Env.logout();
}
/**
* Is Workflow Process view enabled.
* @return true if enabled
*/
public static boolean isWorkflowProcess ()
{
if (s_workflow == null)
{
s_workflow = Boolean.FALSE;
int AD_Table_ID = 645; // AD_WF_Process
if (MRole.getDefault().isTableAccess (AD_Table_ID, true)) // RO
s_workflow = Boolean.TRUE;
else
{
AD_Table_ID = 644; // AD_WF_Activity
if (MRole.getDefault().isTableAccess (AD_Table_ID, true)) // RO
s_workflow = Boolean.TRUE;
else
log.config(s_workflow.toString());
}
// Get Window
if (s_workflow.booleanValue())
{
s_workflow_Window_ID = DB.getSQLValue (null,
"SELECT AD_Window_ID FROM AD_Table WHERE AD_Table_ID=?", AD_Table_ID);
if (s_workflow_Window_ID == 0)
s_workflow_Window_ID = 297; // fallback HARDCODED
// s_workflow = Boolean.FALSE;
log.config(s_workflow + ", Window=" + s_workflow_Window_ID);
}
}
return s_workflow.booleanValue();
} // isWorkflowProcess
/**
* Start Workflow Process Window
* @param AD_Table_ID optional table
* @param Record_ID optional record
*/
public static void startWorkflowProcess (int AD_Table_ID, int Record_ID)
{
/*
if (s_workflow_Window_ID == 0)
return;
//
MQuery query = null;
if (AD_Table_ID != 0 && Record_ID != 0)
{
query = new MQuery("AD_WF_Process");
query.addRestriction("AD_Table_ID", MQuery.EQUAL, AD_Table_ID);
query.addRestriction("Record_ID", MQuery.EQUAL, Record_ID);
}
//
AWindow frame = new AWindow();
if (!frame.initWindow(s_workflow_Window_ID, query))
return;
addToWindowManager(frame);
if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED) ) {
frame.pack();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.toFront();
} else
AEnv.showCenterScreen(frame);
frame = null;
*/
} // startWorkflowProcess
/*************************************************************************/
/** Workflow Menu */
private static Boolean s_workflow = null;
/** Workflow Menu */
private static int s_workflow_Window_ID = 0;
/** Server Re-tries */
private static int s_serverTries = 0;
/** Server Session */
private static Server s_server = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(AEnv.class);
/**
* Is AppsServer Active ?
* @return true if active
*/
public static boolean isServerActive()
{
boolean contactAgain = s_server == null && s_serverTries == 0;
boolean ok = CConnection.get().isAppsServerOK(contactAgain);
if (ok)
{
s_serverTries = 0;
return true;
}
if (s_serverTries > 1) // try twice
return false;
// Try to connect
CLogMgt.enable(false);
try
{
s_serverTries++;
log.config("try #" + s_serverTries);
ok = CConnection.get().isAppsServerOK(true);
if (ok)
s_serverTries = 0;
}
catch (Exception ex)
{
ok = false;
s_server = null;
}
CLogMgt.enable(true);
//
return ok;
} // isServerActive
/**
* Get Server Version
* @return Apps Server Version
* @see ALogin#checkVersion
*/
public static String getServerVersion ()
{
return CConnection.get().getServerVersion();
} // getServerVersion
/** Window Cache */
private static CCache<Integer,GridWindowVO> s_windows
= new CCache<Integer,GridWindowVO>("AD_Window", 10);
/**
* Get Window Model
*
* @param WindowNo Window No
* @param AD_Window_ID window
* @param AD_Menu_ID menu
* @return Model Window Value Obkect
*/
public static GridWindowVO getMWindowVO (int WindowNo, int AD_Window_ID, int AD_Menu_ID)
{
log.config("Window=" + WindowNo + ", AD_Window_ID=" + AD_Window_ID);
GridWindowVO mWindowVO = null;
if (AD_Window_ID != 0 && Ini.isCacheWindow()) // try cache
{
mWindowVO = s_windows.get(AD_Window_ID);
if (mWindowVO != null)
{
mWindowVO = mWindowVO.clone(WindowNo);
log.info("Cached=" + mWindowVO);
}
}
// try to get from Server when enabled
if (mWindowVO == null && DB.isRemoteObjects() && isServerActive())
{
log.config("trying server");
try
{
s_server = CConnection.get().getServer();
if (s_server != null)
{
mWindowVO = s_server.getWindowVO(Env.getCtx(), WindowNo, AD_Window_ID, AD_Menu_ID);
log.config("from Server: success");
}
}
catch (RemoteException e)
{
log.log(Level.SEVERE, "(RE)", e);
mWindowVO = null;
s_server = null;
}
catch (Exception e)
{
Throwable tt = e.getCause();
if (tt != null && tt instanceof InvalidClassException)
log.log(Level.SEVERE, "(Server<>Client class) " + tt);
else if (tt != null && tt instanceof NotSerializableException)
log.log(Level.SEVERE, "Serialization: " + tt.getMessage(), e);
else
log.log(Level.SEVERE, "ex", e);
mWindowVO = null;
s_server = null;
}
catch (Throwable t)
{
log.log(Level.SEVERE, t.toString());
mWindowVO = null;
s_server = null;
}
if (mWindowVO != null)
s_windows.put(AD_Window_ID, mWindowVO);
} // from Server
// Create Window Model on Client
if (mWindowVO == null)
{
log.config("create local");
mWindowVO = GridWindowVO.create (Env.getCtx(), WindowNo, AD_Window_ID, AD_Menu_ID);
if (mWindowVO != null)
s_windows.put(AD_Window_ID, mWindowVO);
} // from Client
if (mWindowVO == null)
return null;
// Check (remote) context
if (!mWindowVO.ctx.equals(Env.getCtx()))
{
// Remote Context is called by value, not reference
// Add Window properties to context
Enumeration keyEnum = mWindowVO.ctx.keys();
while (keyEnum.hasMoreElements())
{
String key = (String)keyEnum.nextElement();
if (key.startsWith(WindowNo+"|"))
{
String value = mWindowVO.ctx.getProperty (key);
Env.setContext(Env.getCtx(), key, value);
}
}
// Sync Context
mWindowVO.setCtx(Env.getCtx());
}
return mWindowVO;
} // getWindow
/**
* Post Immediate
* @param WindowNo window
* @param AD_Table_ID Table ID of Document
* @param AD_Client_ID Client ID of Document
* @param Record_ID Record ID of this document
* @param force force posting
* @return null if success, otherwise error
*/
public static String postImmediate (int WindowNo, int AD_Client_ID,
int AD_Table_ID, int Record_ID, boolean force)
{
log.config("Window=" + WindowNo
+ ", AD_Table_ID=" + AD_Table_ID + "/" + Record_ID
+ ", Force=" + force);
String error = null;
// try to get from Server when enabled
if (isServerActive())
{
log.config("trying server");
try
{
s_server = CConnection.get().getServer();
if (s_server != null)
{
error = s_server.postImmediate(Env.getCtx(), AD_Client_ID,
AD_Table_ID, Record_ID, force, null);
log.config("from Server: " + error== null ? "OK" : error);
}
else
{
FDialog.error(WindowNo, "", "NoApps Server");
return "NoAppsServer";
}
}
catch (RemoteException e)
{
log.log(Level.WARNING, "(RE)", e);
error = e.getMessage();
s_server = null;
}
catch (Exception e)
{
log.log(Level.WARNING, "ex", e);
error = e.getMessage();
s_server = null;
}
}
else
{
FDialog.error(WindowNo, "", "NoAppsServer");
return "NoAppsServer";
}
return error;
} // postImmediate
/**
* Cache Reset
* @param tableName table name
* @param Record_ID record id
*/
public static void cacheReset (String tableName, int Record_ID)
{
log.config("TableName=" + tableName + ", Record_ID=" + Record_ID);
// try to get from Server when enabled
if (isServerActive())
{
log.config("trying server");
try
{
Server server = CConnection.get().getServer();
if (server != null)
{
server.cacheReset(tableName, Record_ID);
}
}
catch (RemoteException e)
{
log.log(Level.SEVERE, "(RE)", e);
s_server = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, "ex", e);
s_server = null;
}
}
} // cacheReset
/**
* Validate permissions to access Info queries on the view menu
* @author kstan_79
* @return true if access is allowed
*/
public static boolean canAccessInfo(String infoWindowName)
{
boolean result=false;
int roleid= Env.getAD_Role_ID(Env.getCtx());
String sqlRolePermission="Select COUNT(AD_ROLE_ID) AS ROWCOUNT FROM AD_ROLE WHERE AD_ROLE_ID=" + roleid
+ " AND ALLOW_INFO_" + infoWindowName + "='Y'";
log.config(sqlRolePermission);
PreparedStatement prolestmt = null;
try
{
prolestmt = DB.prepareStatement (sqlRolePermission, null);
ResultSet rs = prolestmt.executeQuery ();
rs.next();
if (rs.getInt("ROWCOUNT")>0)
{
result=true;
}
else
{
return false;
}
rs.close ();
prolestmt.close ();
prolestmt = null;
}
catch (Exception e)
{
System.out.println(e);
log.log(Level.SEVERE, "(1)", e);
}
try
{
if (prolestmt != null)
{
prolestmt.close ();
}
prolestmt = null;
}
catch (Exception e)
{
prolestmt = null;
}
return result;
} // canAccessInfo
public static void actionRefresh(Lookup lookup, Object value, boolean mandatory)
{
if (lookup == null)
return;
lookup.refresh();
if (lookup.isValidated())
lookup.fillComboBox(mandatory, false, false, false);
else
lookup.fillComboBox(mandatory, true, false, false);
}
/**
*
* @param lookup
* @param value
*/
public static void actionZoom(Lookup lookup, Object value)
{
if (lookup == null)
return;
//
MQuery zoomQuery = lookup.getZoomQuery();
// If not already exist or exact value
if (zoomQuery == null || value != null)
{
zoomQuery = new MQuery(); // ColumnName might be changed in MTab.validateQuery
zoomQuery.addRestriction(lookup.getColumnName(), MQuery.EQUAL, value);
zoomQuery.setRecordCount(1); // guess
}
int windowId = lookup.getZoom(zoomQuery);
zoom(windowId, zoomQuery);
}
/**
* Zoom to a window with the provided window id and filters according to the
* query
* @param AD_Window_ID Window on which to zoom
* @param query Filter to be applied on the records.
*/
public static void zoom(int AD_Window_ID, MQuery query)
{
SessionManager.getAppDesktop().showZoomWindow(AD_Window_ID, query);
}
public static void showWindow(Window win)
{
SessionManager.getAppDesktop().showWindow(win);
}
/**
* Zoom
* @param query query
*/
public static void zoom (MQuery query)
{
if (query == null || query.getTableName() == null || query.getTableName().length() == 0)
return;
String TableName = query.getTableName();
int AD_Window_ID = 0;
int PO_Window_ID = 0;
String sql = "SELECT AD_Window_ID, PO_Window_ID FROM AD_Table WHERE TableName=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setString(1, TableName);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
AD_Window_ID = rs.getInt(1);
PO_Window_ID = rs.getInt(2);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
// Nothing to Zoom to
if (AD_Window_ID == 0)
return;
// PO Zoom ?
boolean isSOTrx = true;
if (PO_Window_ID != 0)
{
isSOTrx = DB.isSOTrx(TableName, query.getWhereClause(false));
if (!isSOTrx)
AD_Window_ID = PO_Window_ID;
}
log.config(query + " (IsSOTrx=" + isSOTrx + ")");
zoom(AD_Window_ID, query);
}
/**
* Get ImageIcon.
*
* @param fileNameInImageDir full file name in imgaes folder (e.g. Bean16.gif)
* @return image
*/
public static URI getImage(String fileNameInImageDir)
{
URI uri = null;
try
{
uri = new URI("/images/" + fileNameInImageDir);
}
catch (URISyntaxException exception)
{
log.log(Level.SEVERE, "Not found: " + fileNameInImageDir);
return null;
}
return uri;
} // getImageIcon
/**
* Get ImageIcon. This method different from getImageIcon
* where the fileName parameter is without extension. The
* method will first try .gif and then .png if .gif does not
* exists.
*
* @param fileName file name in imgaes folder without the extension(e.g. Bean16)
* @return image
*/
public static URI getImage2 (String fileName)
{
String relativePath;
URI uri = null;
URL absoluteUrl = null;
final String imageDir = "images/";
relativePath = imageDir + fileName + ".png";
uri = URI.create("/" + relativePath);
absoluteUrl = Adempiere.class.getResource(relativePath);
if (absoluteUrl == null)
{
relativePath = imageDir + fileName + ".gif";
uri = URI.create("/" + relativePath);
absoluteUrl = Adempiere.class.getResource(relativePath);
if (absoluteUrl == null)
{
log.log(Level.WARNING, "GIF/PNG Not found: " + fileName);
return null;
}
}
return uri;
} // getImageIcon2
} // AEnv

View File

@ -0,0 +1,397 @@
package org.adempiere.webui.apps;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.component.Window;
import org.adempiere.webui.session.SessionManager;
import org.compiere.apps.ProcessCtl;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoUtil;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Div;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Html;
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2007 Low Heng Sin *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*****************************************************************************/
/**
* Dialog to Start process or report.
* Displays information about the process
* and lets the user decide to start it
* and displays results (optionally print them).
* Calls ProcessCtl to execute.
* @author Low Heng Sin
* @author arboleda - globalqss
* - Implement ShowHelp option on processes and reports
*/
public class ProcessDialog extends Window implements EventListener
{
/**
* Dialog to start a process/report
* @param ctx
* @param parent
* @param title
* @param aProcess
* @param WindowNo
* @param AD_Process_ID
* @param tableId
* @param recordId
* @param autoStart
*/
public ProcessDialog (int AD_Process_ID, boolean isSOTrx)
{
log.info("Process=" + AD_Process_ID );
m_ctx = Env.getCtx();;
m_WindowNo = SessionManager.getAppDesktop().registerWindow(this);
m_AD_Process_ID = AD_Process_ID;
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", isSOTrx ? "Y" : "N");
try
{
initComponents();
init();
}
catch(Exception ex)
{
log.log(Level.SEVERE, "", ex);
}
} // ProcessDialog
private void initComponents() {
VerticalBox vbox = new VerticalBox();
vbox.setWidth("100%");
vbox.setSpacing("10px");
Div div = new Div();
message = new Html();
div.appendChild(message);
vbox.appendChild(div);
centerPanel = new Panel();
vbox.appendChild(centerPanel);
div = new Div();
div.setAlign("right");
Hbox hbox = new Hbox();
String label = Msg.getMsg(Env.getCtx(), "Ok");
bOK = new Button(label.replaceAll("&", ""));
bOK.setImage("/images/Ok16.gif");
bOK.setName("ok");
bOK.addEventListener(Events.ON_CLICK, this);
hbox.appendChild(bOK);
label = Msg.getMsg(Env.getCtx(), "Cancel");
Button btn = new Button(label.replaceAll("&", ""));
btn.setImage("/images/Cancel16.gif");
btn.setName("cancel");
btn.addEventListener(Events.ON_CLICK, this);
hbox.appendChild(btn);
div.appendChild(hbox);
vbox.appendChild(div);
this.appendChild(vbox);
this.setBorder("normal");
}
private int m_WindowNo;
private Properties m_ctx;
private int m_AD_Process_ID;
private String m_Name = null;
private boolean m_IsReport = false;
private int[] m_ids = null;
private StringBuffer m_messageText = new StringBuffer();
private String m_ShowHelp = null; // Determine if a Help Process Window is shown
private Panel centerPanel = null;
private Html message = null;
private Button bOK = null;
private boolean valid = true;
/** Logger */
private static CLogger log = CLogger.getCLogger(ProcessDialog.class);
//
private ProcessParameterPanel parameterPanel = null;
private ProcessInfo m_pi = null;
/**
* Set Visible
* (set focus to OK if visible)
* @param visible true if visible
*/
public boolean setVisible (boolean visible)
{
return super.setVisible(visible);
} // setVisible
/**
* Dispose
*/
public void dispose()
{
Env.clearWinContext(m_WindowNo);
SessionManager.getAppDesktop().unregisterWindow(m_WindowNo);
valid = false;
this.detach();
}// dispose
/**
* Dynamic Init
* @return true, if there is something to process (start from menu)
*/
public boolean init()
{
log.config("");
//
boolean trl = !Env.isBaseLanguage(m_ctx, "AD_Process");
String sql = "SELECT Name, Description, Help, IsReport, ShowHelp "
+ "FROM AD_Process "
+ "WHERE AD_Process_ID=?";
if (trl)
sql = "SELECT t.Name, t.Description, t.Help, p.IsReport, p.ShowHelp "
+ "FROM AD_Process p, AD_Process_Trl t "
+ "WHERE p.AD_Process_ID=t.AD_Process_ID"
+ " AND p.AD_Process_ID=? AND t.AD_Language=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_AD_Process_ID);
if (trl)
pstmt.setString(2, Env.getAD_Language(m_ctx));
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_Name = rs.getString(1);
m_IsReport = rs.getString(4).equals("Y");
m_ShowHelp = rs.getString(5);
//
m_messageText.append("<b>");
String s = rs.getString(2); // Description
if (rs.wasNull())
m_messageText.append(Msg.getMsg(m_ctx, "StartProcess?"));
else
m_messageText.append(s);
m_messageText.append("</b>");
s = rs.getString(3); // Help
if (!rs.wasNull())
m_messageText.append("<p>").append(s).append("</p>");
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return false;
}
if (m_Name == null)
return false;
//
this.setTitle(m_Name);
message.setContent(m_messageText.toString());
bOK.setLabel(Msg.getMsg(Env.getCtx(), "Start"));
// Move from APanel.actionButton
m_pi = new ProcessInfo(m_Name, m_AD_Process_ID);
m_pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx()));
m_pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));
parameterPanel = new ProcessParameterPanel(m_WindowNo, m_pi);
centerPanel.getChildren().clear();
if ( parameterPanel.init() ) {
centerPanel.appendChild(parameterPanel);
} else {
if (m_ShowHelp != null && m_ShowHelp.equals("N")) {
startProcess();
}
}
// Check if the process is a silent one
if(m_ShowHelp != null && m_ShowHelp.equals("S"))
{
startProcess();
}
return true;
} // init
public void startProcess()
{
m_pi.setPrintPreview(true);
//can't use asyncprocess, zk ui threading issue
this.lockUI(m_pi);
try {
ProcessCtl.process(null, m_WindowNo, parameterPanel, m_pi, null);
} finally {
this.unlockUI(m_pi);
}
}
public boolean isAsap() {
return true;
}
public void onEvent(Event event) {
Component component = event.getTarget();
if (component instanceof Button) {
Button element = (Button)component;
if ("ok".equalsIgnoreCase(element.getName())) {
if (element.getLabel().length() > 0)
this.startProcess();
else
this.dispose();
} else if ("cancel".equalsIgnoreCase(element.getName())) {
this.dispose();
}
}
}
public void lockUI(ProcessInfo pi) {
bOK.setLabel("");
bOK.setEnabled(false);
}
public void unlockUI(ProcessInfo pi) {
ProcessInfoUtil.setLogFromDB(pi);
m_messageText.append("<p><font color=\"").append(pi.isError() ? "#FF0000" : "#0000FF").append("\">** ")
.append(pi.getSummary())
.append("</font></p>");
m_messageText.append(pi.getLogInfo(true));
message.setContent(m_messageText.toString());
//message.setCaretPosition(message.getDocument().getLength()); // scroll down
m_ids = pi.getIDs();
//
bOK.setEnabled(true);
//no longer needed, hide to give more space to display log
centerPanel.detach();
invalidate();
//
afterProcessTask();
// Close automatically
if (m_IsReport && !pi.isError())
this.dispose();
// If the process is a silent one and no errors occured, close the dialog
if(m_ShowHelp != null && m_ShowHelp.equals("S"))
this.dispose();
}
/**************************************************************************
* Optional Processing Task
*/
private void afterProcessTask()
{
// something to do?
if (m_ids != null && m_ids.length > 0)
{
log.config("");
// Print invoices
if (m_AD_Process_ID == 119)
printInvoices();
else if (m_AD_Process_ID == 118)
printShipments();
}
} // afterProcessTask
/**************************************************************************
* Print Shipments
*/
private void printShipments()
{
/*
if (m_ids == null)
return;
if (!ADialog.ask(m_WindowNo, this, "PrintShipments"))
return;
m_messageText.append("<p>").append(Msg.getMsg(Env.getCtx(), "PrintShipments")).append("</p>");
message.setText(m_messageText.toString());
int retValue = ADialogDialog.A_CANCEL;
do
{
// Loop through all items
for (int i = 0; i < m_ids.length; i++)
{
int M_InOut_ID = m_ids[i];
ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, Env.getWindowNo(this), true);
}
ADialogDialog d = new ADialogDialog (this,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
*/
} // printInvoices
/**
* Print Invoices
*/
private void printInvoices()
{
/*
if (m_ids == null)
return;
if (!ADialog.ask(m_WindowNo, this, "PrintInvoices"))
return;
m_messageText.append("<p>").append(Msg.getMsg(Env.getCtx(), "PrintInvoices")).append("</p>");
message.setText(m_messageText.toString());
int retValue = ADialogDialog.A_CANCEL;
do
{
// Loop through all items
for (int i = 0; i < m_ids.length; i++)
{
int AD_Invoice_ID = m_ids[i];
ReportCtl.startDocumentPrint(ReportEngine.INVOICE, AD_Invoice_ID, this, Env.getWindowNo(this), true);
}
ADialogDialog d = new ADialogDialog (this,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
*/
} // printInvoices
public boolean isValid() {
return valid;
}
} // ProcessDialog

View File

@ -0,0 +1,281 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2007 Adempiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*
* Copyright (C) 2007 Low Heng Sin hengsin@avantz.com
* _____________________________________________
*****************************************************************************/
package org.adempiere.webui.apps;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.component.Window;
import org.compiere.apps.ProcessCtl;
import org.compiere.apps.ProcessDialog;
import org.compiere.process.ProcessInfo;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Div;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Html;
/**
*
* Modal Dialog to Start process.
* Displays information about the process
* and lets the user decide to start it
* and displays results (optionally print them).
* Calls ProcessCtl to execute.
* @author Low Heng Sin
* @author arboleda - globalqss
* - Implement ShowHelp option on processes and reports
*/
public class ProcessModalDialog extends Window implements EventListener
{
private boolean m_autoStart;
/**
* Dialog to start a process/report
* @param ctx
* @param parent
* @param title
* @param aProcess
* @param WindowNo
* @param AD_Process_ID
* @param tableId
* @param recordId
* @param autoStart
*/
public ProcessModalDialog (Window parent, String title,
ASyncProcess aProcess, int WindowNo, int AD_Process_ID,
int tableId, int recordId, boolean autoStart)
{
log.info("Process=" + AD_Process_ID );
m_ctx = Env.getCtx();;
m_ASyncProcess = aProcess;
m_WindowNo = WindowNo;
m_AD_Process_ID = AD_Process_ID;
m_tableId = tableId;
m_recordId = recordId;
m_autoStart = autoStart;
try
{
initComponents();
init();
}
catch(Exception ex)
{
log.log(Level.SEVERE, "", ex);
}
} // ProcessDialog
private void initComponents() {
VerticalBox vbox = new VerticalBox();
Div div = new Div();
message = new Html();
div.appendChild(message);
vbox.appendChild(message);
centerPanel = new Panel();
vbox.appendChild(centerPanel);
div = new Div();
div.setAlign("right");
Hbox hbox = new Hbox();
Button btn = new Button("Ok");
btn.setName("ok");
btn.addEventListener(Events.ON_CLICK, this);
hbox.appendChild(btn);
btn = new Button("Cancel");
btn.setName("cancel");
btn.addEventListener(Events.ON_CLICK, this);
hbox.appendChild(btn);
div.appendChild(hbox);
vbox.appendChild(div);
this.appendChild(vbox);
}
private ASyncProcess m_ASyncProcess;
private int m_WindowNo;
private Properties m_ctx;
private int m_tableId;
private int m_recordId;
private int m_AD_Process_ID;
private String m_Name = null;
private StringBuffer m_messageText = new StringBuffer();
private String m_ShowHelp = null; // Determine if a Help Process Window is shown
private boolean m_valid = true;
private Panel centerPanel = null;
private Html message = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(ProcessDialog.class);
//
private ProcessParameterPanel parameterPanel = null;
private ProcessInfo m_pi = null;
/**
* Set Visible
* (set focus to OK if visible)
* @param visible true if visible
*/
public boolean setVisible (boolean visible)
{
return super.setVisible(visible);
} // setVisible
/**
* Dispose
*/
public void dispose()
{
parameterPanel.restoreContext();
m_valid = false;
this.detach();
} // dispose
public boolean isValid()
{
return m_valid;
}
/**
* Dynamic Init
* @return true, if there is something to process (start from menu)
*/
public boolean init()
{
log.config("");
//
boolean trl = !Env.isBaseLanguage(m_ctx, "AD_Process");
String sql = "SELECT Name, Description, Help, IsReport, ShowHelp "
+ "FROM AD_Process "
+ "WHERE AD_Process_ID=?";
if (trl)
sql = "SELECT t.Name, t.Description, t.Help, p.IsReport, p.ShowHelp "
+ "FROM AD_Process p, AD_Process_Trl t "
+ "WHERE p.AD_Process_ID=t.AD_Process_ID"
+ " AND p.AD_Process_ID=? AND t.AD_Language=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_AD_Process_ID);
if (trl)
pstmt.setString(2, Env.getAD_Language(m_ctx));
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_Name = rs.getString(1);
m_ShowHelp = rs.getString(5);
//
m_messageText.append("<b>");
String s = rs.getString(2); // Description
if (rs.wasNull())
m_messageText.append(Msg.getMsg(m_ctx, "StartProcess?"));
else
m_messageText.append(s);
m_messageText.append("</b>");
s = rs.getString(3); // Help
if (!rs.wasNull())
m_messageText.append("<p>").append(s).append("</p>");
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
return false;
}
if (m_Name == null)
return false;
//
this.setTitle(m_Name);
message.setContent(m_messageText.toString());
// Move from APanel.actionButton
m_pi = new ProcessInfo(m_Name, m_AD_Process_ID, m_tableId, m_recordId);
m_pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx()));
m_pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx()));
parameterPanel = new ProcessParameterPanel(m_WindowNo, m_pi);
centerPanel.getChildren().clear();
if ( parameterPanel.init() ) {
centerPanel.appendChild(parameterPanel);
} else {
if (m_ShowHelp != null && m_ShowHelp.equals("N")) {
m_autoStart = true;
}
if (m_autoStart) {
startProcess();
dispose();
}
}
// Check if the process is a silent one
if(isValid() && m_ShowHelp != null && m_ShowHelp.equals("S"))
{
startProcess();
dispose();
}
return true;
} // init
public void startProcess()
{
m_pi.setPrintPreview(true);
ProcessCtl.process(m_ASyncProcess, m_WindowNo, parameterPanel, m_pi, null);
dispose();
}
public boolean isAsap() {
return true;
}
public void onEvent(Event event) {
Component component = event.getTarget();
if (component instanceof Button) {
Button element = (Button)component;
if ("ok".equalsIgnoreCase(element.getName())) {
this.startProcess();
this.dispose();
} else if ("cancel".equalsIgnoreCase(element.getName())) {
this.dispose();
}
}
}
} // ProcessDialog

View File

@ -0,0 +1,413 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 Adempiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*****************************************************************************/
package org.adempiere.webui.apps;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import org.adempiere.webui.component.Grid;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.Row;
import org.adempiere.webui.component.Rows;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WebEditorFactory;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.compiere.apps.IProcessParameter;
import org.compiere.model.GridField;
import org.compiere.model.GridFieldVO;
import org.compiere.model.MPInstancePara;
import org.compiere.process.ProcessInfo;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
/**
* Process Parameter Panel, based on existing ProcessParameter dialog.
* - Embedded in ProcessDialog
* - checks, if parameters exist and inquires and saves them
*
* @author Low Heng Sin
* @version 2006-12-01
*/
@SuppressWarnings("serial")
public class ProcessParameterPanel extends Panel
implements ValueChangeListener, IProcessParameter
{
/**
* Dynamic generated Parameter panel.
* @param WindowNo window
* @param pi process info
*/
public ProcessParameterPanel(int WindowNo, ProcessInfo pi)
{
//
m_WindowNo = WindowNo;
m_processInfo = pi;
//
initComponent();
} // ProcessParameterPanel
private void initComponent() {
centerPanel = new Grid();
this.appendChild(centerPanel);
}
private int m_WindowNo;
private ProcessInfo m_processInfo;
/** Logger */
private static CLogger log = CLogger.getCLogger(ProcessParameterPanel.class);
//
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>();
//
private Grid centerPanel = null;
/**
* Dispose
*/
public void dispose()
{
m_wEditors.clear();
m_wEditors2.clear();
m_mFields.clear();
m_mFields2.clear();
} // dispose
/**
* Read Fields to display
* @return true if loaded OK
*/
public boolean init()
{
log.config("");
//
String sql = null;
if (Env.isBaseLanguage(Env.getCtx(), "AD_Process_Para"))
sql = "SELECT p.Name, p.Description, p.Help, "
+ "p.AD_Reference_ID, p.AD_Process_Para_ID, "
+ "p.FieldLength, p.IsMandatory, p.IsRange, p.ColumnName, "
+ "p.DefaultValue, p.DefaultValue2, p.VFormat, p.ValueMin, p.ValueMax, "
+ "p.SeqNo, p.AD_Reference_Value_ID, vr.Code AS ValidationCode "
+ "FROM AD_Process_Para p"
+ " LEFT OUTER JOIN AD_Val_Rule vr ON (p.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) "
+ "WHERE p.AD_Process_ID=?" // 1
+ " AND p.IsActive='Y' "
+ "ORDER BY SeqNo";
else
sql = "SELECT t.Name, t.Description, t.Help, "
+ "p.AD_Reference_ID, p.AD_Process_Para_ID, "
+ "p.FieldLength, p.IsMandatory, p.IsRange, p.ColumnName, "
+ "p.DefaultValue, p.DefaultValue2, p.VFormat, p.ValueMin, p.ValueMax, "
+ "p.SeqNo, p.AD_Reference_Value_ID, vr.Code AS ValidationCode "
+ "FROM AD_Process_Para p"
+ " INNER JOIN AD_Process_Para_Trl t ON (p.AD_Process_Para_ID=t.AD_Process_Para_ID)"
+ " LEFT OUTER JOIN AD_Val_Rule vr ON (p.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) "
+ "WHERE p.AD_Process_ID=?" // 1
+ " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "'"
+ " AND p.IsActive='Y' "
+ "ORDER BY SeqNo";
// Create Fields
boolean hasFields = false;
Rows rows = new Rows();
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_processInfo.getAD_Process_ID());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
hasFields = true;
createField (rs, rows);
}
rs.close();
pstmt.close();
}
catch(SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
// both vectors the same?
if (m_mFields.size() != m_mFields2.size()
|| m_mFields.size() != m_wEditors.size()
|| m_mFields2.size() != m_wEditors2.size())
log.log(Level.SEVERE, "View & Model vector size is different");
// clean up
if (hasFields)
{
centerPanel.appendChild(rows);
}
else
dispose();
return hasFields;
} // initDialog
/**
* Create Field.
* - creates Fields and adds it to m_mFields list
* - creates Editor and adds it to m_vEditors list
* Handeles Ranges by adding additional mField/vEditor.
* <p>
* mFields are used for default value and mandatory checking;
* vEditors are used to retrieve the value (no data binding)
*
* @param rs result set
*/
private void createField (ResultSet rs, Rows rows)
{
// Create Field
GridFieldVO voF = GridFieldVO.createParameter(Env.getCtx(), m_WindowNo, rs);
GridField mField = new GridField (voF);
m_mFields.add(mField); // add to Fields
Row row = new Row();
// The Editor
WEditor wEditor = WebEditorFactory.getEditor(mField, false);
wEditor.addValueChangeListner(this);
// MField => VEditor - New Field value to be updated to editor
mField.addPropertyChangeListener(wEditor);
// Set Default
Object defaultObject = mField.getDefault();
mField.setValue (defaultObject, true);
//
m_wEditors.add (wEditor); // add to Editors
row.appendChild(wEditor.getLabel());
//
if (voF.isRange)
{
Hbox box = new Hbox();
box.appendChild(wEditor.getComponent());
//
GridFieldVO voF2 = GridFieldVO.createParameter(voF);
GridField mField2 = new GridField (voF2);
m_mFields2.add (mField2);
// The Editor
WEditor wEditor2 = WebEditorFactory.getEditor(mField2, false);
// New Field value to be updated to editor
mField2.addPropertyChangeListener(wEditor2);
// Set Default
Object defaultObject2 = mField2.getDefault();
mField2.setValue (defaultObject2, true);
//
m_wEditors2.add (wEditor2);
box.appendChild(new Label(" - "));
box.appendChild(wEditor2.getComponent());
row.appendChild(box);
}
else
{
row.appendChild(wEditor.getComponent());
m_mFields2.add (null);
m_wEditors2.add (null);
}
rows.appendChild(row);
} // createField
/**
* Save Parameter values
* @return true if parameters saved
*/
public boolean saveParameters()
{
log.config("");
/**
* Mandatory fields
* see - MTable.getMandatory
*/
StringBuffer sb = new StringBuffer();
int size = m_mFields.size();
for (int i = 0; i < size; i++)
{
GridField field = (GridField)m_mFields.get(i);
if (field.isMandatory(true)) // check context
{
WEditor wEditor = (WEditor)m_wEditors.get(i);
Object data = wEditor.getValue();
if (data == null || data.toString().length() == 0)
{
field.setInserting (true); // set editable (i.e. updateable) otherwise deadlock
field.setError(true);
if (sb.length() > 0)
sb.append(", ");
sb.append(field.getHeader());
}
else
field.setError(false);
// Check for Range
WEditor wEditor2 = (WEditor)m_wEditors2.get(i);
if (wEditor2 != null)
{
Object data2 = wEditor.getValue();
GridField field2 = (GridField)m_mFields2.get(i);
if (data2 == null || data2.toString().length() == 0)
{
field.setInserting (true); // set editable (i.e. updateable) otherwise deadlock
field2.setError(true);
if (sb.length() > 0)
sb.append(", ");
sb.append(field.getHeader());
}
else
field2.setError(false);
} // range field
} // mandatory
} // field loop
if (sb.length() != 0)
{
//ADialog.error(m_WindowNo, this, "FillMandatory", sb.toString());
return false;
}
/**********************************************************************
* Save Now
*/
for (int i = 0; i < m_mFields.size(); i++)
{
// Get Values
WEditor editor = (WEditor)m_wEditors.get(i);
WEditor editor2 = (WEditor)m_wEditors2.get(i);
Object result = editor.getValue();
Object result2 = null;
if (editor2 != null)
result2 = editor2.getValue();
// Don't save NULL values
if (result == null && result2 == null)
continue;
// Create Parameter
MPInstancePara para = new MPInstancePara (Env.getCtx(), m_processInfo.getAD_PInstance_ID(), i);
GridField mField = (GridField)m_mFields.get(i);
para.setParameterName(mField.getColumnName());
// Date
if (result instanceof Timestamp || result2 instanceof Timestamp)
{
para.setP_Date((Timestamp)result);
if (editor2 != null && result2 != null)
para.setP_Date_To((Timestamp)result2);
}
// Integer
else if (result instanceof Integer || result2 instanceof Integer)
{
if (result != null)
{
Integer ii = (Integer)result;
para.setP_Number(ii.intValue());
}
if (editor2 != null && result2 != null)
{
Integer ii = (Integer)result2;
para.setP_Number_To(ii.intValue());
}
}
// BigDecimal
else if (result instanceof BigDecimal || result2 instanceof BigDecimal)
{
para.setP_Number ((BigDecimal)result);
if (editor2 != null && result2 != null)
para.setP_Number_To ((BigDecimal)result2);
}
// Boolean
else if (result instanceof Boolean)
{
Boolean bb = (Boolean)result;
String value = bb.booleanValue() ? "Y" : "N";
para.setP_String (value);
// to does not make sense
}
// String
else
{
if (result != null)
para.setP_String (result.toString());
if (editor2 != null && result2 != null)
para.setP_String_To (result2.toString());
}
// Info
para.setInfo (editor.getDisplay());
if (editor2 != null)
para.setInfo_To (editor2.getDisplay());
//
para.save();
log.fine(para.toString());
} // for every parameter
return true;
} // saveParameters
/**
* Editor Listener
* @param evt ValueChangeEvent
*/
public void valueChange(ValueChangeEvent evt)
{
String value = evt.getNewValue() == null ? "" : evt.getNewValue().toString();
if (evt.getSource() instanceof WEditor)
{
WEditor comp = (WEditor)(evt.getSource());
comp.setValue(value);
}
Env.setContext(Env.getCtx(), m_WindowNo, evt.getPropertyName(), value);
}
/**
* Restore window context.
* @author teo_sarca [ 1699826 ]
* @see org.compiere.model.GridField#restoreValue()
*/
protected void restoreContext() {
for (GridField f : m_mFields) {
if (f != null)
f.restoreValue();
}
for (GridField f : m_mFields2) {
if (f != null)
f.restoreValue();
}
}
} // ProcessParameterPanel

View File

@ -0,0 +1,251 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2007 Adempiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*
* Copyright (C) 2007 Low Heng Sin hengsin@avantz.com
* _____________________________________________
*****************************************************************************/
package org.adempiere.webui.apps;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.sql.RowSet;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Window;
import org.adempiere.webui.window.FDialog;
import org.compiere.apps.ProcessCtl;
import org.compiere.model.MQuery;
import org.compiere.model.MRole;
import org.compiere.model.MTable;
import org.compiere.model.PrintInfo;
import org.compiere.print.AReport;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportCtl;
import org.compiere.print.ReportEngine;
import org.compiere.process.ProcessInfo;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.ListModelList;
/**
* Base on org.compiere.print.AReport
* @author Low Heng Sin
*
*/
public class WReport implements EventListener {
/**
* Constructor
*
* @param AD_Table_ID table
* @param invoker component to display popup (optional)
* @param query query
*/
public WReport (int AD_Table_ID, MQuery query)
{
new WReport(AD_Table_ID, query, null, 0);
}
/**
* Constructor
*
* @param AD_Table_ID table
* @param invoker component to display popup (optional)
* @param query query
* @param parent The invoking parent window
* @param WindowNo The invoking parent window number
*/
public WReport (int AD_Table_ID, MQuery query, ASyncProcess parent,
int WindowNo)
{
log.config("AD_Table_ID=" + AD_Table_ID + " " + query);
if (!MRole.getDefault().isCanReport(AD_Table_ID))
{
FDialog.error(0, "AccessCannotReport", query.getTableName());
return;
}
m_query = query;
this.parent = parent;
this.WindowNo = WindowNo;
// See What is there
getPrintFormats (AD_Table_ID);
} // AReport
/** The Query */
private MQuery m_query;
/** The Popup */
private Listbox m_listbox;
private Window m_popup;
/** The Option List */
private ArrayList<KeyNamePair> m_list = new ArrayList<KeyNamePair>();
/** Logger */
private static CLogger log = CLogger.getCLogger(AReport.class);
/** The parent window for locking/unlocking during process execution */
ASyncProcess parent;
/** The parent window number */
int WindowNo;
/**
* Get the Print Formats for the table.
* Fill the list and the popup menu
* @param AD_Table_ID table
* @param invoker component to display popup (optional)
*/
private void getPrintFormats (int AD_Table_ID)
{
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
RowSet rowSet = MPrintFormat.getAccessiblePrintFormats(AD_Table_ID, -1, null);
KeyNamePair pp = null;
try
{
while (rowSet.next())
{
pp = new KeyNamePair (rowSet.getInt(1), rowSet.getString(2));
if (rowSet.getInt(3) == AD_Client_ID)
{
m_list.add(pp);
}
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
// No Format exists - create it
if (m_list.size() == 0)
{
if (pp == null)
createNewFormat (AD_Table_ID); // calls launch
else
copyFormat(pp.getKey(), AD_Client_ID);
}
// One Format exists or no invoker - show it
else if (m_list.size() == 1)
launchReport ((KeyNamePair)m_list.get(0));
// Multiple Formats exist - show selection
else
showPopup(); // below button
} // getPrintFormats
private void showPopup() {
m_listbox = new Listbox();
m_listbox.setModel(ListModelList.instance(m_list));
m_listbox.addEventListener(Events.ON_SELECT, this);
m_listbox.setHeight("300px");
m_popup = new Window();
m_popup.setTitle("Select Report");
m_popup.appendChild(m_listbox);
m_popup.setAttribute("mode", "popup");
m_popup.setWidth("200px");
m_popup.setPosition("center");
AEnv.showWindow(m_popup);
}
/**
* Create and Launch new Format for table
* @param AD_Table_ID table
*/
private void createNewFormat (int AD_Table_ID)
{
MPrintFormat pf = MPrintFormat.createFromTable(Env.getCtx(), AD_Table_ID);
launchReport (pf);
} // createNewFormat
/**
* Copy existing Format
* @param AD_PrintFormat_ID print format
* @param To_Client_ID to client
*/
private void copyFormat (int AD_PrintFormat_ID, int To_Client_ID)
{
MPrintFormat pf = MPrintFormat.copyToClient(Env.getCtx(), AD_PrintFormat_ID, To_Client_ID);
launchReport (pf);
} // copyFormatFromClient
/**
* Launch Report
* @param pp Key=AD_PrintFormat_ID
*/
private void launchReport (KeyNamePair pp)
{
MPrintFormat pf = MPrintFormat.get(Env.getCtx(), pp.getKey(), false);
launchReport (pf);
} // launchReport
/**
* Launch Report
* @param pf print format
*/
private void launchReport (MPrintFormat pf)
{
int Record_ID = 0;
if (m_query.getRestrictionCount()==1 && m_query.getCode(0) instanceof Integer)
Record_ID = ((Integer)m_query.getCode(0)).intValue();
PrintInfo info = new PrintInfo(
pf.getName(),
pf.getAD_Table_ID(),
Record_ID);
info.setDescription(m_query.getInfo());
if(pf != null && pf.getJasperProcess_ID() > 0)
{
// It's a report using the JasperReports engine
ProcessInfo pi = new ProcessInfo ("", pf.getJasperProcess_ID());
// Execute Process
ProcessCtl worker = ProcessCtl.process(parent, WindowNo, pi, null);
}
else
{
// It's a default report using the standard printing engine
ReportEngine re = new ReportEngine (Env.getCtx(), pf, m_query, info);
ReportCtl.preview(re);
}
} // launchReport
/**************************************************************************
* Get AD_Table_ID for Table Name
* @param tableName table name
* @return AD_Table_ID or 0
*/
public static int getAD_Table_ID (String tableName)
{
return MTable.getTable_ID(tableName);
} // getAD_Table_ID
public boolean isAsap() {
return true;
}
public void onEvent(Event event) {
if (event.getTarget() == m_listbox) {
int i = m_listbox.getSelectedIndex();
if (i >= 0 ) {
KeyNamePair pp = (KeyNamePair)m_list.get(i);
m_popup.setVisible(false);
m_popup.detach();
launchReport (pp);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,764 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.component.ConfirmPanel;
import org.adempiere.webui.component.Datebox;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Tab;
import org.adempiere.webui.component.Tabbox;
import org.adempiere.webui.component.Tabpanel;
import org.adempiere.webui.component.Tabpanels;
import org.adempiere.webui.component.Tabs;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WTableDirEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.compiere.model.MArchive;
import org.compiere.model.MBPartner;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MRole;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.compiere.util.TimeUtil;
import org.zkoss.util.media.AMedia;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Iframe;
import org.zkoss.zul.Separator;
/**
* Archive Viewer
*
* @author Niraj Sohun
* @date September 28, 2007
*/
public class WArchiveViewer extends ADForm implements EventListener, ValueChangeListener
{
private static final long serialVersionUID = 1L;
/** Window No */
private int m_WindowNo = 0;
/** The Archives */
private MArchive[] m_archives = new MArchive[0];
/** Archive Index */
private int m_index = 0;
/** Table direct */
private int m_AD_Table_ID = 0;
/** Record direct */
private int m_Record_ID = 0;
/** Logger */
private static CLogger log = CLogger.getCLogger(WArchiveViewer.class);
private VerticalBox queryPanel = new VerticalBox();
private Checkbox reportField = new Checkbox();
private Label processLabel = new Label(Msg.translate(Env.getCtx(), "AD_Process_ID"));
private Listbox processField = new Listbox();
private Label tableLabel = new Label(Msg.translate(Env.getCtx(), "AD_Table_ID"));
private Listbox tableField = new Listbox();
private Label bPartnerLabel = new Label(Msg.translate(Env.getCtx(), "C_BPartner_ID"));
private WEditor bPartnerField = null;
private Label nameQLabel = new Label(Msg.translate(Env.getCtx(), "Name"));
private Textbox nameQField = new Textbox();
private Label descriptionQLabel = new Label(Msg.translate(Env.getCtx(), "Description"));
private Textbox descriptionQField = new Textbox();
private Label helpQLabel = new Label(Msg.translate(Env.getCtx(), "Help"));
private Textbox helpQField = new Textbox();
private Label createdByQLabel = new Label(Msg.translate(Env.getCtx(), "CreatedBy"));
private Listbox createdByQField = new Listbox();
private Label createdQLabel = new Label(Msg.translate(Env.getCtx(), "Created"));
private Datebox createdQFrom = new Datebox();
private Datebox createdQTo = new Datebox();
private VerticalBox viewEnterPanel = new VerticalBox();
private Button bBack = new Button();
private Button bNext = new Button();
private Label positionInfo = new Label(".");
private Label createdByLabel = new Label(Msg.translate(Env.getCtx(), "CreatedBy"));
private Textbox createdByField = new Textbox();
private Datebox createdField = new Datebox();
private Label nameLabel = new Label(Msg.translate(Env.getCtx(), "Name"));
private Textbox nameField = new Textbox("Name");
private Label descriptionLabel = new Label(Msg.translate(Env.getCtx(), "Description"));
private Textbox descriptionField = new Textbox("Description");
private Label helpLabel = new Label(Msg.translate(Env.getCtx(), "Help"));
private Textbox helpField = new Textbox("Help");
private ConfirmPanel confirmPanel = new ConfirmPanel(true);
private Button updateArchive = new Button();
private Tabbox tabbox = new Tabbox();
private Tabs tabs = new Tabs();
private Tabpanels tabpanels = new Tabpanels();
private Iframe iframe = new Iframe();
public WArchiveViewer()
{
init(super.m_windowNo);
}
/**
* Initialize Panel
* @param WindowNo window
*/
public void init (int WindowNo)
{
log.info("");
m_WindowNo = WindowNo;
try
{
dynInit();
jbInit();
}
catch(Exception e)
{
log.log(Level.SEVERE, "init", e);
}
}
/**
* Dynamic Init
*/
private void dynInit()
{
int AD_Role_ID = Env.getAD_Role_ID(Env.getCtx());
//Processes
boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Process");
String lang = Env.getAD_Language(Env.getCtx());
String sql = "SELECT DISTINCT p.AD_Process_ID,"
+ (trl ? "trl.Name" : "p.Name ")
+ " FROM AD_Process p INNER JOIN AD_Process_Access pa ON (p.AD_Process_ID=pa.AD_Process_ID) "
+ (trl ? "LEFT JOIN AD_Process_Trl trl on (trl.AD_Process_ID=p.AD_Process_ID and trl.AD_Language=" + DB.TO_STRING(lang) + ")" : "")
+ " WHERE pa.AD_Role_ID=" + AD_Role_ID
+ " AND p.IsReport='Y' AND p.IsActive='Y' AND pa.IsActive='Y' "
+ "ORDER BY 2";
processField = new Listbox();
KeyNamePair[] keyNamePair = DB.getKeyNamePairs(sql, true);
for (int i = 0; i < keyNamePair.length; i++)
{
processField.appendItem(keyNamePair[i].getName(), keyNamePair[i]);
}
// Tables
trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Table");
sql = "SELECT DISTINCT t.AD_Table_ID,"
+ (trl ? "trl.Name" : "t.Name")
+ " FROM AD_Table t INNER JOIN AD_Tab tab ON (tab.AD_Table_ID=t.AD_Table_ID)"
+ " INNER JOIN AD_Window_Access wa ON (tab.AD_Window_ID=wa.AD_Window_ID) "
+ (trl ? "LEFT JOIN AD_Table_Trl trl on (trl.AD_Table_ID=t.AD_Table_ID and trl.AD_Language=" + DB.TO_STRING(lang) + ")" : "")
+ " WHERE wa.AD_Role_ID=" + AD_Role_ID
+ " AND t.IsActive='Y' AND tab.IsActive='Y' "
+ "ORDER BY 2";
tableField = new Listbox();
keyNamePair = DB.getKeyNamePairs(sql, true);
for (int i = 0; i < keyNamePair.length; i++)
{
tableField.appendItem(keyNamePair[i].getName(), keyNamePair[i]);
}
// Internal Users
sql = "SELECT AD_User_ID, Name "
+ "FROM AD_User u WHERE EXISTS "
+"(SELECT * FROM AD_User_Roles ur WHERE u.AD_User_ID=ur.AD_User_ID) "
+ "ORDER BY 2";
createdByQField = new Listbox();
keyNamePair = DB.getKeyNamePairs(sql, true);
for (int i = 0; i < keyNamePair.length; i++)
{
createdByQField.appendItem(keyNamePair[i].getName(), keyNamePair[i]);
}
MLookup lookup = MLookupFactory.get(Env.getCtx(), m_WindowNo,
0, 2762, DisplayType.Search);
bPartnerField = new WTableDirEditor(lookup, Msg.translate(
Env.getCtx(), "C_BPartner_ID"), "", true, false, true);
bPartnerField.addValueChangeListner(this);
} // dynInit
private void reportViewer(byte[] data)
{
AMedia media = new AMedia("Archive Viewer", "pdf", "application/pdf", data);
iframe.setContent(media);
}
/**
* Static Init
* @throws Exception
*/
private void jbInit() throws Exception
{
tabbox.setWidth("100%");
tabbox.appendChild(tabs);
tabbox.appendChild(tabpanels);
processField.setMold("select");
processField.setRows(1);
tableField.setMold("select");
tableField.setRows(1);
createdByQField.setMold("select");
createdByQField.setRows(1);
nameField.addEventListener(Events.ON_CHANGE, this);
descriptionField.addEventListener(Events.ON_SELECT, this);
helpField.addEventListener(Events.ON_SELECT, this);
updateArchive.addEventListener(Events.ON_CLICK, this);
reportField.setLabel(Msg.translate(Env.getCtx(), "IsReport"));
reportField.addEventListener(Events.ON_CLICK, this);
Hbox boxProcess = new Hbox();
boxProcess.setWidth("100%");
boxProcess.setWidth("30%, 70%");
boxProcess.appendChild(processLabel);
boxProcess.appendChild(processField);
Hbox boxBPartner = new Hbox();
boxBPartner.setWidth("100%");
boxBPartner.setWidths("30%, 70%");
boxBPartner.appendChild(bPartnerLabel);
boxBPartner.appendChild(bPartnerField.getComponent());
Hbox boxTable = new Hbox();
boxTable.setWidth("100%");
boxTable.setWidths("30%, 70%");
boxTable.appendChild(tableLabel);
boxTable.appendChild(tableField);
Hbox boxNameQ = new Hbox();
boxNameQ.setWidth("100%");
boxNameQ.setWidths("30%, 70%");
boxNameQ.appendChild(nameQLabel);
boxNameQ.appendChild(nameQField);
Hbox boxDescritionQ = new Hbox();
boxDescritionQ.setWidth("100%");
boxDescritionQ.setWidths("30%, 70%");
boxDescritionQ.appendChild(descriptionQLabel);
boxDescritionQ.appendChild(descriptionQField);
Hbox boxHelpQ = new Hbox();
boxHelpQ.setWidth("100%");
boxHelpQ.setWidths("30%, 70%");
boxHelpQ.appendChild(helpQLabel);
boxHelpQ.appendChild(helpQField);
Hbox boxCreatedBy = new Hbox();
boxCreatedBy.setWidth("100%");
boxCreatedBy.setWidths("30%, 70%");
boxCreatedBy.appendChild(createdByQLabel);
boxCreatedBy.appendChild(createdByQField);
Hbox boxCreatedQ = new Hbox();
boxCreatedQ.setWidth("100%");
boxCreatedQ.setWidths("30%, 35%, 35%");
boxCreatedQ.appendChild(createdQLabel);
boxCreatedQ.appendChild(createdQFrom);
boxCreatedQ.appendChild(createdQTo);
queryPanel.setWidth("50%");
queryPanel.appendChild(reportField);
queryPanel.appendChild(boxProcess);
queryPanel.appendChild(boxBPartner);
queryPanel.appendChild(boxTable);
queryPanel.appendChild(boxNameQ);
queryPanel.appendChild(boxDescritionQ);
queryPanel.appendChild(boxHelpQ);
queryPanel.appendChild(boxCreatedBy);
queryPanel.appendChild(boxCreatedQ);
Tabpanel tabQueryPanel = new Tabpanel();
tabQueryPanel.appendChild(queryPanel);
Tab tabQuery = new Tab("Query");
tabpanels.appendChild(tabQueryPanel);
tabs.appendChild(tabQuery);
bBack.addEventListener(Events.ON_CLICK, this);
bNext.addEventListener(Events.ON_CLICK, this);
Hbox boxViewEnter = new Hbox();
bBack.setImage("/images/Parent24.gif");
bNext.setImage("/images/Detail24.gif");
boxViewEnter.setWidth("100%");
boxViewEnter.setWidths("10%, 80%, 10%");
boxViewEnter.appendChild(bBack);
boxViewEnter.appendChild(positionInfo);
boxViewEnter.appendChild(bNext);
Hbox boxCreatedByV = new Hbox();
boxCreatedByV.setWidth("100%");
boxCreatedByV.setWidths("30%, 50%, 20%");
boxCreatedByV.appendChild(createdByLabel);
boxCreatedByV.appendChild(createdByField);
boxCreatedByV.appendChild(createdField);
Hbox boxName = new Hbox();
boxName.setWidth("100%");
boxName.setWidths("40%, 60%");
boxName.appendChild(nameLabel);
boxName.appendChild(nameField);
Hbox boxDescription = new Hbox();
boxDescription.setWidth("100%");
boxDescription.setWidths("40%, 60%");
boxDescription.appendChild(descriptionLabel);
boxDescription.appendChild(descriptionField);
Hbox boxHelp = new Hbox();
boxHelp.setWidth("100%");
boxHelp.setWidths("40%, 60%");
boxHelp.appendChild(helpLabel);
boxHelp.appendChild(helpField);
updateArchive.setImage("/images/Ok24.gif");
viewEnterPanel.setWidth("100%");
viewEnterPanel.appendChild(boxViewEnter);
viewEnterPanel.appendChild(boxCreatedByV);
viewEnterPanel.appendChild(boxName);
viewEnterPanel.appendChild(boxDescription);
viewEnterPanel.appendChild(boxHelp);
viewEnterPanel.appendChild(updateArchive);
createdByField.setEnabled(false);
createdField.setEnabled(false);
Tab tabView = new Tab("View");
Tabpanel tabViewPanel = new Tabpanel();
Hbox boxViewSeparator = new Hbox();
boxViewSeparator.setWidth("100%");
boxViewSeparator.setWidths("50%, 50%");
boxViewSeparator.appendChild(iframe);
boxViewSeparator.appendChild(viewEnterPanel);
tabViewPanel.appendChild(boxViewSeparator);
tabs.appendChild(tabView);
tabpanels.appendChild(tabViewPanel);
confirmPanel.addActionListener(Events.ON_CLICK, this);
updateQDisplay();
iframe.setId("reportFrame");
iframe.setHeight("100%");
iframe.setWidth("100%");
this.setWidth("900px");
this.appendChild(tabbox);
this.appendChild(new Separator());
this.appendChild(confirmPanel);
}
public void onEvent(Event e) throws Exception
{
log.info(e.getName());
if (e.getTarget() == updateArchive)
cmd_updateArchive();
else if (confirmPanel.getButton("Cancel").equals(e.getTarget()))
SessionManager.getAppDesktop().removeWindow();
else if (confirmPanel.getButton("Ok").equals(e.getTarget()))
{
if (tabbox.getSelectedIndex() == 1)
SessionManager.getAppDesktop().removeWindow();
else
cmd_query();
}
else if (e.getTarget() == reportField)
updateQDisplay();
else if (e.getTarget() == bBack)
updateVDisplay(false);
else if (e.getTarget() == bNext)
updateVDisplay(true);
}
public void valueChange(ValueChangeEvent evt)
{
if (m_archives.length > 0)
updateArchive.setEnabled(true);
}
/**
* Update Query Display
*/
private void updateQDisplay()
{
boolean reports = reportField.isChecked();
log.config("Reports=" + reports);
// Show
processLabel.setVisible(reports);
processField.setVisible(reports);
// Hide
bPartnerLabel.setVisible(!reports);
bPartnerField.setVisible(!reports);
} // updateQDisplay
/**
* Update View Display
* @param next show next Archive
*/
private void updateVDisplay (boolean next)
{
if (m_archives == null)
m_archives = new MArchive[0];
if (next)
m_index++;
else
m_index--;
if (m_index >= m_archives.length-1)
m_index = m_archives.length-1;
if (m_index < 0)
m_index = 0;
bBack.setEnabled(m_index > 0);
bNext.setEnabled(m_index < m_archives.length-1);
updateArchive.setEnabled(false);
log.info("Index=" + m_index + ", Length=" + m_archives.length);
if (m_archives.length == 0)
{
positionInfo.setValue("No Record Found");
createdByField.setText("");
createdField.setValue(null);
nameField.setText("");
descriptionField.setText("");
helpField.setText("");
iframe.getChildren().clear();
return;
}
positionInfo.setValue(m_index+1 + " of " + m_archives.length);
MArchive ar = m_archives[m_index];
createdByField.setText(ar.getCreatedByName());
createdField.setValue(ar.getCreated());
nameField.setText(ar.getName());
descriptionField.setText(ar.getDescription());
helpField.setText(ar.getHelp());
try
{
InputStream in = ar.getInputStream();
//pdfViewer.setScale(reportField.isSelected() ? 50 : 75);
if (in != null)
reportViewer(ar.getBinaryData());//pdfViewer.loadPDF(in);
else
iframe.getChildren().clear();//pdfViewer.clearDocument();
}
catch (Exception e)
{
log.log(Level.SEVERE, "pdf", e);
iframe.getChildren().clear();//pdfViewer.clearDocument();
}
} // updateVDisplay
/**
* Update Archive Info
*/
private void cmd_updateArchive()
{
MArchive ar = m_archives[m_index];
boolean update = false;
if (!isSame(nameField.getText(), ar.getName()))
{
String newText = nameField.getText();
if (newText != null && newText.length() > 0)
{
ar.setName(newText);
update = true;
}
}
if (!isSame(descriptionField.getText(), ar.getDescription()))
{
ar.setDescription(descriptionField.getText());
update = true;
}
if (!isSame(helpField.getText(), ar.getHelp()))
{
ar.setHelp(helpField.getText());
update = true;
}
log.info("Update=" + update);
if (update)
ar.save();
m_index++;
updateVDisplay(false);
} // cmd_updateArchive
/**
* Is it the same
* @param s1 s1
* @param s2 s1
* @return true if the same
*/
private boolean isSame (String s1, String s2)
{
if (s1 == null)
return s2 == null;
else if (s2 == null)
return false;
else
return s1.equals(s2);
} // isSame
/**
* Query Directly
* @param isReport report
* @param AD_Table_ID table
* @param Record_ID tecord
*/
public void query (boolean isReport, int AD_Table_ID, int Record_ID)
{
log.config("Report=" + isReport + ", AD_Table_ID=" + AD_Table_ID + ",Record_ID=" + Record_ID);
reportField.setChecked(isReport);
m_AD_Table_ID = AD_Table_ID;
m_Record_ID = Record_ID;
cmd_query();
} // query
/**************************************************************************
* Create Query
*/
private void cmd_query()
{
StringBuffer sql = new StringBuffer();
boolean reports = reportField.isChecked();
MRole role = MRole.getDefault();
if (!role.isCanReport())
{
log.warning("User/Role cannot Report AD_User_ID=" + Env.getAD_User_ID(Env.getCtx()));
return;
}
sql.append(" AND IsReport=").append(reports ? "'Y'" : "'N'");
// Process
if (reports)
{
ListItem listitem = processField.getSelectedItem();
KeyNamePair nn = null;
if (listitem != null)
nn = (KeyNamePair)listitem.getValue();
if (nn != null && nn.getKey() > 0)
sql.append(" AND AD_Process_ID=").append(nn.getKey());
}
// Table
if (m_AD_Table_ID > 0)
{
sql.append(" AND ((AD_Table_ID=").append(m_AD_Table_ID);
if (m_Record_ID > 0)
sql.append(" AND Record_ID=").append(m_Record_ID);
sql.append(")");
if (m_AD_Table_ID == MBPartner.Table_ID && m_Record_ID > 0)
sql.append(" OR C_BPartner_ID=").append(m_Record_ID);
sql.append(")");
// Reset for query
m_AD_Table_ID = 0;
m_Record_ID = 0;
}
else
{
ListItem listitem = tableField.getSelectedItem();
KeyNamePair nn = null;
if (listitem != null)
nn = (KeyNamePair)listitem.getValue();
if (nn != null && nn.getKey() > 0)
sql.append(" AND AD_Table_ID=").append(nn.getKey());
}
// Business Partner
if (!reports)
{
Integer ii = (Integer)bPartnerField.getValue();
if (ii != null)
sql.append(" AND C_BPartner_ID=").append(ii);
else
sql.append(" AND C_BPartner_ID IS NOT NULL");
}
// Name
String ss = nameQField.getText();
if (ss != null && ss.length() > 0)
{
if (ss.indexOf('%') != -1 || ss.indexOf('_') != -1)
sql.append(" AND Name LIKE ").append(DB.TO_STRING(ss));
else
sql.append(" AND Name=").append(DB.TO_STRING(ss));
}
// Description
ss = descriptionQField.getText();
if (ss != null && ss.length() > 0)
{
if (ss.indexOf('%') != -1 || ss.indexOf('_') != -1)
sql.append(" AND Description LIKE ").append(DB.TO_STRING(ss));
else
sql.append(" AND Description=").append(DB.TO_STRING(ss));
}
// Help
ss = helpQField.getText();
if (ss != null && ss.length() > 0)
{
if (ss.indexOf('%') != -1 || ss.indexOf('_') != -1)
sql.append(" AND Help LIKE ").append(DB.TO_STRING(ss));
else
sql.append(" AND Help=").append(DB.TO_STRING(ss));
}
// CreatedBy
ListItem listitem = createdByQField.getSelectedItem();
KeyNamePair nn = null;
if (listitem != null)
nn = (KeyNamePair)listitem.getValue();
if (nn != null && nn.getKey() > 0)
sql.append(" AND CreatedBy=").append(nn.getKey());
// Created
Date date = null;
Timestamp tt =null;
if (createdQFrom.getValue() != null)
{
date = createdQFrom.getValue();
tt = new Timestamp(date.getTime());
}
if (tt != null)
sql.append(" AND Created>=").append(DB.TO_DATE(tt, true));
if (createdQTo.getValue() != null)
{
date = createdQTo.getValue();
tt = new Timestamp(date.getTime());
}
if (tt != null)
sql.append(" AND Created<").append(DB.TO_DATE(TimeUtil.addDays(tt,1), true));
log.fine(sql.toString());
// Process Access
sql.append(" AND (AD_Process_ID IS NULL OR AD_Process_ID IN "
+ "(SELECT AD_Process_ID FROM AD_Process_Access WHERE AD_Role_ID=")
.append(role.getAD_Role_ID()).append("))");
// Table Access
sql.append(" AND (AD_Table_ID IS NULL "
+ "OR (AD_Table_ID IS NOT NULL AND AD_Process_ID IS NOT NULL) " // Menu Reports
+ "OR AD_Table_ID IN "
+ "(SELECT t.AD_Table_ID FROM AD_Tab t"
+ " INNER JOIN AD_Window_Access wa ON (t.AD_Window_ID=wa.AD_Window_ID) "
+ "WHERE wa.AD_Role_ID=").append(role.getAD_Role_ID()).append("))");
log.finest(sql.toString());
m_archives = MArchive.get(Env.getCtx(), sql.toString());
log.info("Length=" + m_archives.length);
// Display
//this.setSelectedIndex(1);
m_index = 1;
updateVDisplay(false);
} // cmd_query
}

View File

@ -0,0 +1,902 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.component.ConfirmPanel;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.compiere.model.MInvoice;
import org.compiere.model.MInvoiceLine;
import org.compiere.model.MOrder;
import org.compiere.model.MOrderLine;
import org.compiere.model.MProduct;
import org.compiere.model.MProductBOM;
import org.compiere.model.MProject;
import org.compiere.model.MProjectLine;
import org.compiere.model.MRole;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Caption;
import org.zkoss.zul.Groupbox;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Separator;
public class WBOMDrop extends ADForm implements EventListener
{
private static final long serialVersionUID = 1L;
/** Window No */
private int m_WindowNo = 0;
/** Product to create BOMs from */
private MProduct m_product;
/** BOM Qty */
private BigDecimal m_qty = Env.ONE;
/** Line Counter */
private int m_bomLine = 0;
/** Logger */
private static CLogger log = CLogger.getCLogger(WBOMDrop.class);
/** List of all selectors */
private ArrayList m_selectionList = new ArrayList();
/** List of all quantities */
private ArrayList<Textbox> m_qtyList = new ArrayList<Textbox>();
/** List of all products */
private ArrayList<Integer> m_productList = new ArrayList<Integer>();
/** Alternative Group Lists */
private HashMap<String, Radiogroup> m_buttonGroups = new HashMap<String,Radiogroup>();
private static final int WINDOW_WIDTH = 600; // width of the window
private ConfirmPanel confirmPanel = new ConfirmPanel(true);
private VerticalBox selectionPanel = new VerticalBox();
private Listbox productField = new Listbox();
private Textbox productQty = new Textbox();
private Listbox orderField = new Listbox();
private Listbox invoiceField = new Listbox();
private Listbox projectField = new Listbox();
private Groupbox grpSelectionPanel = new Groupbox();
private Groupbox grpSelectProd = new Groupbox();
public WBOMDrop()
{
init(super.m_windowNo);
}
/**
* Initialize Panel
* @param WindowNo window
* @param frame parent frame
*/
public void init (int WindowNo)
{
log.info("");
m_WindowNo = WindowNo;
try
{
confirmPanel = new ConfirmPanel(true);
// Top Selection Panel
createSelectionPanel(true, true, true);
// Center
createMainPanel();
confirmPanel.addActionListener(Events.ON_CLICK, this);
}
catch(Exception e)
{
log.log(Level.SEVERE, "", e);
}
//sizeIt();
} // init
/**
* Dispose
*/
public void dispose()
{
if (selectionPanel != null)
selectionPanel.getChildren().clear();
selectionPanel = null;
if (m_selectionList != null)
m_selectionList.clear();
m_selectionList = null;
if (m_productList != null)
m_productList.clear();
m_productList = null;
if (m_qtyList != null)
m_qtyList.clear();
m_qtyList = null;
if (m_buttonGroups != null)
m_buttonGroups.clear();
m_buttonGroups = null;
} // dispose
/**************************************************************************
* Create Selection Panel
* @param order
* @param invoice
* @param project
*/
private void createSelectionPanel (boolean order, boolean invoice, boolean project)
{
Caption caption = new Caption(Msg.translate(Env.getCtx(), "Selection"));
grpSelectionPanel.setWidth("100%");
grpSelectionPanel.appendChild(caption);
grpSelectionPanel.appendChild(selectionPanel);
productField.setRows(1);
productField.setMold("select");
KeyNamePair[] keyNamePair = getProducts();
for (int i = 0; i < keyNamePair.length; i++)
{
productField.appendItem(keyNamePair[i].getName(), keyNamePair[i]);
}
Hbox boxProductQty = new Hbox();
Label lblProduct = new Label(Msg.translate(Env.getCtx(), "M_Product_ID"));
Label lblQty = new Label(Msg.translate(Env.getCtx(), "Qty"));
productQty.setValue("1");
productField.addEventListener(Events.ON_SELECT, this);
productQty.addEventListener(Events.ON_CHANGE, this);
boxProductQty.setWidth("100%");
boxProductQty.setWidths("30%, 30%, 10%, 30%");
boxProductQty.appendChild(lblProduct);
boxProductQty.appendChild(productField);
boxProductQty.appendChild(lblQty);
boxProductQty.appendChild(productQty);
selectionPanel.appendChild(boxProductQty);
if (order)
{
keyNamePair = getOrders();
orderField.setRows(1);
orderField.setMold("select");
for (int i = 0; i < keyNamePair.length; i++)
{
orderField.appendItem(keyNamePair[i].getName(), keyNamePair[i]);
}
Label lblOrder = new Label(Msg.translate(Env.getCtx(), "C_Order_ID"));
Hbox boxOrder = new Hbox();
orderField.addEventListener(Events.ON_CLICK, this);
boxOrder.setWidth("100%");
boxOrder.setWidths("30%, 60%");
boxOrder.appendChild(lblOrder);
boxOrder.appendChild(orderField);
selectionPanel.appendChild(boxOrder);
}
if (invoice)
{
invoiceField.setRows(1);
invoiceField.setMold("select");
keyNamePair = getInvoices();
for (int i = 0; i < keyNamePair.length; i++)
{
invoiceField.appendItem(keyNamePair[i].getName(), keyNamePair[i]);
}
Label lblInvoice = new Label(Msg.translate(Env.getCtx(), "C_Invoice_ID"));
Hbox boxInvoices = new Hbox();
invoiceField.addEventListener(Events.ON_SELECT, this);
boxInvoices.setWidth("100%");
boxInvoices.setWidths("30%, 60%");
boxInvoices.appendChild(lblInvoice);
boxInvoices.appendChild(invoiceField);
selectionPanel.appendChild(boxInvoices);
}
if (project)
{
projectField.setRows(1);
projectField.setMold("select");
keyNamePair = getProjects();
for (int i = 0; i < keyNamePair.length; i++)
{
projectField.appendItem(keyNamePair[i].getName(), this);
}
Label lblProject = new Label(Msg.translate(Env.getCtx(), "C_Project_ID"));
Hbox boxProject = new Hbox();
projectField.addEventListener(Events.ON_SELECT, this);
boxProject.setWidth("100%");
boxProject.setWidths("30%, 60%");
boxProject.appendChild(lblProject);
boxProject.appendChild(projectField);
selectionPanel.appendChild(boxProject);
}
// Enabled in ActionPerformed
confirmPanel.setEnabled("Ok", false);
} // createSelectionPanel
/**
* Get Array of BOM Products
* @return products
*/
private KeyNamePair[] getProducts()
{
String sql = "SELECT M_Product_ID, Name "
+ "FROM M_Product "
+ "WHERE IsBOM='Y' AND IsVerified='Y' AND IsActive='Y' "
+ "ORDER BY Name";
return DB.getKeyNamePairs(MRole.getDefault().addAccessSQL(
sql, "M_Product", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
} // getProducts
/**
* Get Array of open Orders
* @return orders
*/
private KeyNamePair[] getOrders()
{
String sql = "SELECT C_Order_ID, DocumentNo || '_' || GrandTotal "
+ "FROM C_Order "
+ "WHERE Processed='N' AND DocStatus='DR' "
+ "ORDER BY DocumentNo";
return DB.getKeyNamePairs(MRole.getDefault().addAccessSQL(
sql, "C_Order", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
} // getOrders
/**
* Get Array of open non service Projects
* @return orders
*/
private KeyNamePair[] getProjects()
{
String sql = "SELECT C_Project_ID, Name "
+ "FROM C_Project "
+ "WHERE Processed='N' AND IsSummary='N' AND IsActive='Y'"
+ " AND ProjectCategory<>'S' "
+ "ORDER BY Name";
return DB.getKeyNamePairs(MRole.getDefault().addAccessSQL(
sql, "C_Project", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
} // getProjects
/**
* Get Array of open Invoices
* @return invoices
*/
private KeyNamePair[] getInvoices()
{
String sql = "SELECT C_Invoice_ID, DocumentNo || '_' || GrandTotal "
+ "FROM C_Invoice "
+ "WHERE Processed='N' AND DocStatus='DR' "
+ "ORDER BY DocumentNo";
return DB.getKeyNamePairs(MRole.getDefault().addAccessSQL(
sql, "C_Invoice", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO), true);
} // getInvoices
/**************************************************************************
* Create Main Panel.
* Called when changing Product
*/
private void createMainPanel ()
{
log.config(": " + m_product);
this.getChildren().clear();
//this.invalidate();
//this.setBorder(null);
m_selectionList.clear();
m_productList.clear();
m_qtyList.clear();
m_buttonGroups.clear();
this.appendChild(new Separator());
this.appendChild(grpSelectionPanel);
this.appendChild(new Separator());
this.appendChild(grpSelectProd);
this.appendChild(new Separator());
this.appendChild(confirmPanel);
this.appendChild(new Separator());
this.setBorder("normal");
Caption title = new Caption(Msg.getMsg(Env.getCtx(), "SelectProduct"));
grpSelectProd.getChildren().clear();
grpSelectProd.appendChild(title);
if (m_product != null && m_product.get_ID() > 0)
{
title.setLabel(m_product.getName());
if (m_product.getDescription() != null && m_product.getDescription().length() > 0)
;//this.setsetToolTipText(m_product.getDescription());
m_bomLine = 0;
addBOMLines(m_product, m_qty);
}
} // createMainPanel
/**
* Add BOM Lines to this.
* Called recursively
* @param product product
* @param qty quantity
*/
private void addBOMLines (MProduct product, BigDecimal qty)
{
MProductBOM[] bomLines = MProductBOM.getBOMLines(product);
for (int i = 0; i < bomLines.length; i++)
{
grpSelectProd.appendChild(new Separator());
addBOMLine (bomLines[i], qty);
grpSelectProd.appendChild(new Separator());
}
log.fine("#" + bomLines.length);
} // addBOMLines
/**
* Add BOM Line to this.
* Calls addBOMLines if added product is a BOM
* @param line BOM Line
* @param qty quantity
*/
private void addBOMLine (MProductBOM line, BigDecimal qty)
{
log.fine(line.toString());
String bomType = line.getBOMType();
if (bomType == null)
bomType = MProductBOM.BOMTYPE_StandardPart;
//
BigDecimal lineQty = line.getBOMQty().multiply(qty);
MProduct product = line.getProduct();
if (product == null)
return;
if (product.isBOM() && product.isVerified())
addBOMLines (product, lineQty); // recursive
else
addDisplay (line.getM_Product_ID(),
product.getM_Product_ID(), bomType, product.getName(), lineQty);
} // addBOMLine
/**
* Add Line to Display
* @param parentM_Product_ID parent product
* @param M_Product_ID product
* @param bomType bom type
* @param name name
* @param lineQty qty
*/
private void addDisplay (int parentM_Product_ID,
int M_Product_ID, String bomType, String name, BigDecimal lineQty)
{
log.fine("M_Product_ID=" + M_Product_ID + ",Type=" + bomType + ",Name=" + name + ",Qty=" + lineQty);
boolean selected = true;
Hbox boxQty = new Hbox();
boxQty.setWidth("100%");
boxQty.setWidths("10%, 40%, 50%");
if (MProductBOM.BOMTYPE_StandardPart.equals(bomType))
{
String title = "";
Checkbox cb = new Checkbox();
cb.setLabel(title);
cb.setChecked(true);
cb.setEnabled(false);
m_selectionList.add(cb);
boxQty.appendChild(cb);
}
else if (MProductBOM.BOMTYPE_OptionalPart.equals(bomType))
{
String title = Msg.getMsg(Env.getCtx(), "Optional");
Checkbox cb = new Checkbox();
cb.setLabel(title);
cb.setChecked(false);
selected = false;
cb.addEventListener(Events.ON_CHECK, this);
m_selectionList.add(cb);
boxQty.appendChild(cb);
}
else // Alternative
{
String title = Msg.getMsg(Env.getCtx(), "Alternative") + " " + bomType;
Radio b = new Radio();
b.setLabel(title);
String groupName = String.valueOf(parentM_Product_ID) + "_" + bomType;
Radiogroup group = (Radiogroup)m_buttonGroups.get(groupName);
if (group == null)
{
log.fine("ButtonGroup=" + groupName);
group = new Radiogroup();
m_buttonGroups.put(groupName, group);
group.appendChild(b);
b.setSelected(true); // select first one
}
else
{
group.appendChild(b);
b.setSelected(false);
selected = false;
}
b.addEventListener(Events.ON_CLICK, this);
m_selectionList.add(b);
boxQty.appendChild(b);
}
// Add to List & display
m_productList.add (new Integer(M_Product_ID));
Textbox qty = new Textbox();
qty.setValue(lineQty.toString());
qty.setEnabled(selected);
m_qtyList.add(qty);
Label label = new Label(name);
boxQty.appendChild(label);
boxQty.appendChild(qty);
grpSelectProd.appendChild(boxQty);
} // addDisplay
/**************************************************************************
* Action Listener
* @param e event
*/
public void onEvent (Event e) throws Exception
{
log.config(e.getName());
Object source = e.getTarget();
// Toggle Qty Enabled
if (source instanceof Checkbox || source instanceof Radio)
{
cmd_selection (source);
// need to de-select the others in group
if (source instanceof Radio)
{
// find Button Group
Iterator it = m_buttonGroups.values().iterator();
while (it.hasNext())
{
Radiogroup group = (Radiogroup)it.next();
Enumeration en = (Enumeration) group.getChildren();
while (en.hasMoreElements())
{
// We found the group
if (source == en.nextElement())
{
Enumeration info = (Enumeration) group.getChildren();
while (info.hasMoreElements())
{
Object infoObj = info.nextElement();
if (source != infoObj)
cmd_selection(infoObj);
}
}
}
}
}
} // JCheckBox or JRadioButton
// Product / Qty
else if (source == productField || source == productQty)
{
m_qty = new BigDecimal(productQty.getValue());
ListItem listitem = productField.getSelectedItem();
KeyNamePair pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
m_product = MProduct.get (Env.getCtx(), pp.getKey());
createMainPanel();
//sizeIt();
}
// Order
else if (source == orderField)
{
ListItem listitem = orderField.getSelectedItem();
KeyNamePair pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
boolean valid = (pp != null && pp.getKey() > 0);
if (invoiceField != null)
invoiceField.setEnabled(!valid);
if (projectField != null)
projectField.setEnabled(!valid);
}
// Invoice
else if (source == invoiceField)
{
ListItem listitem = invoiceField.getSelectedItem();
KeyNamePair pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
boolean valid = (pp != null && pp.getKey() > 0);
if (orderField != null)
orderField.setEnabled(!valid);
if (projectField != null)
projectField.setEnabled(!valid);
}
// Project
else if (source == projectField)
{
ListItem listitem = projectField.getSelectedItem();
KeyNamePair pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
boolean valid = (pp != null && pp.getKey() > 0);
//
if (orderField != null)
orderField.setEnabled(!valid);
if (invoiceField != null)
invoiceField.setEnabled(!valid);
}
// OK
else if (confirmPanel.getButton("Ok").equals(e.getTarget()))
{
if (cmd_save())
SessionManager.getAppDesktop().removeWindow();
}
else if (confirmPanel.getButton("Cancel").equals(e.getTarget()))
SessionManager.getAppDesktop().removeWindow();
// Enable OK
boolean OK = m_product != null;
if (OK)
{
KeyNamePair pp = null;
if (orderField != null)
{
ListItem listitem = orderField.getSelectedItem();
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
}
if ((pp == null || pp.getKey() <= 0) && invoiceField != null)
{
ListItem listitem = invoiceField.getSelectedItem();
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
}
if ((pp == null || pp.getKey() <= 0) && projectField != null)
{
ListItem listitem = projectField.getSelectedItem();
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
}
OK = (pp != null && pp.getKey() > 0);
}
confirmPanel.setEnabled("Ok", OK);
} // actionPerformed
/**
* Enable/disable qty based on selection
* @param source JCheckBox or JRadioButton
*/
private void cmd_selection (Object source)
{
for (int i = 0; i < m_selectionList.size(); i++)
{
if (source == m_selectionList.get(i))
{
boolean selected = isSelectionSelected(source);
Textbox qty = (Textbox)m_qtyList.get(i);
qty.setEnabled(selected);
return;
}
}
log.log(Level.SEVERE, "not found - " + source);
} // cmd_selection
/**
* Is Selection Selected
* @param source CheckBox or RadioButton
* @return true if selected
*/
private boolean isSelectionSelected (Object source)
{
boolean retValue = false;
if (source instanceof Checkbox)
retValue = ((Checkbox)source).isChecked();
else if (source instanceof Radio)
retValue = ((Radio)source).isChecked();
else
log.log(Level.SEVERE, "Not valid - " + source);
return retValue;
} // isSelected
/**************************************************************************
* Save Selection
* @return true if saved
*/
private boolean cmd_save()
{
ListItem listitem = orderField.getSelectedItem();
KeyNamePair pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
if (pp != null && pp.getKey() > 0)
return cmd_saveOrder (pp.getKey());
listitem = invoiceField.getSelectedItem();
pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
if (pp != null && pp.getKey() > 0)
return cmd_saveInvoice (pp.getKey());
listitem = projectField.getSelectedItem();
pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
if (pp != null && pp.getKey() > 0)
return cmd_saveProject (pp.getKey());
log.log(Level.SEVERE, "Nothing selected");
return false;
} // cmd_save
/**
* Save to Order
* @param C_Order_ID id
* @return true if saved
*/
private boolean cmd_saveOrder (int C_Order_ID)
{
log.config("C_Order_ID=" + C_Order_ID);
MOrder order = new MOrder (Env.getCtx(), C_Order_ID, null);
if (order.get_ID() == 0)
{
log.log(Level.SEVERE, "Not found - C_Order_ID=" + C_Order_ID);
return false;
}
int lineCount = 0;
// for all bom lines
for (int i = 0; i < m_selectionList.size(); i++)
{
if (isSelectionSelected(m_selectionList.get(i)))
{
BigDecimal qty = new BigDecimal(((Textbox)m_qtyList.get(i)).getValue());
int M_Product_ID = ((Integer)m_productList.get(i)).intValue();
// Create Line
MOrderLine ol = new MOrderLine (order);
ol.setM_Product_ID(M_Product_ID, true);
ol.setQty(qty);
ol.setPrice();
ol.setTax();
if (ol.save())
lineCount++;
else
log.log(Level.SEVERE, "Line not saved");
} // line selected
} // for all bom lines
log.config("#" + lineCount);
return true;
} // cmd_saveOrder
/**
* Save to Invoice
* @param C_Invoice_ID id
* @return true if saved
*/
private boolean cmd_saveInvoice (int C_Invoice_ID)
{
log.config("C_Invoice_ID=" + C_Invoice_ID);
MInvoice invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null);
if (invoice.get_ID() == 0)
{
log.log(Level.SEVERE, "Not found - C_Invoice_ID=" + C_Invoice_ID);
return false;
}
int lineCount = 0;
// for all bom lines
for (int i = 0; i < m_selectionList.size(); i++)
{
if (isSelectionSelected(m_selectionList.get(i)))
{
BigDecimal qty = new BigDecimal(((Textbox)m_qtyList.get(i)).getValue());
int M_Product_ID = ((Integer)m_productList.get(i)).intValue();
// Create Line
MInvoiceLine il = new MInvoiceLine (invoice);
il.setM_Product_ID(M_Product_ID, true);
il.setQty(qty);
il.setPrice();
il.setTax();
if (il.save())
lineCount++;
else
log.log(Level.SEVERE, "Line not saved");
} // line selected
} // for all bom lines
log.config("#" + lineCount);
return true;
} // cmd_saveInvoice
/**
* Save to Project
* @param C_Project_ID id
* @return true if saved
*/
private boolean cmd_saveProject (int C_Project_ID)
{
log.config("C_Project_ID=" + C_Project_ID);
MProject project = new MProject (Env.getCtx(), C_Project_ID, null);
if (project.get_ID() == 0)
{
log.log(Level.SEVERE, "Not found - C_Project_ID=" + C_Project_ID);
return false;
}
int lineCount = 0;
// for all bom lines
for (int i = 0; i < m_selectionList.size(); i++)
{
if (isSelectionSelected(m_selectionList.get(i)))
{
BigDecimal qty = new BigDecimal(((Textbox)m_qtyList.get(i)).getValue());
int M_Product_ID = ((Integer)m_productList.get(i)).intValue();
// Create Line
MProjectLine pl = new MProjectLine (project);
pl.setM_Product_ID(M_Product_ID);
pl.setPlannedQty(qty);
if (pl.save())
lineCount++;
else
log.log(Level.SEVERE, "Line not saved");
} // line selected
} // for all bom lines
log.config("#" + lineCount);
return true;
} // cmd_saveProject
}

View File

@ -0,0 +1,905 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.component.Column;
import org.adempiere.webui.component.Columns;
import org.adempiere.webui.component.Grid;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.Row;
import org.adempiere.webui.component.Rows;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.component.WConfirmPanel;
import org.adempiere.webui.component.WListbox;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.adempiere.webui.window.FDialog;
import org.compiere.model.MAccount;
import org.compiere.model.MAcctSchema;
import org.compiere.model.MCharge;
import org.compiere.model.MElementValue;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* This class represents the Custom Form for generating charges
* from natural accounts.
*
* The form is comprised of two parts.
* The upper portion can be used to create new charges using the general charge accounts.
* The lower portion can be used to create charges based on the natural account.
*
* @author Andrew Kimball
*
*/
public class WCharge extends ADForm implements EventListener
{
/** Unique identifier. */
private static final long serialVersionUID = 1L;
/** AD_Message for "Create". */
private static final String AD_MESSAGE_CREATE = "Create";
/** Logger. */
private static CLogger log = CLogger.getCLogger(WCharge.class);
/** Account Element identifier. */
private int m_elementId = 0;
/** Account Schema identifier. */
private int m_accountSchemaId = 0;
/** Default Charge Tax Category. */
private int m_taxCategoryId = 0;
/** Identifier for the client. */
private int m_clientId = 0;
/** Identifier for the organisation. */
private int m_organisationId = 0;
/** Accounting schema model. */
private MAcctSchema m_acctSchema = null;
/** Panel for holding other panels. */
private Panel m_pnlMain = new Panel();
// new panel
/** Grid for components for creating a new charge account. */
private Grid m_grdNew = new Grid();
/** Title of new charge account grid. */
private Column m_clmNewTitle = new Column();
/** Value (key) field label. */
private Label m_lblValue = new Label();
/** Field for specifying value (key) of new account. */
private Textbox m_txbValueField = new Textbox();
/** Checkbox for specifying whether or not the new account is an expense account. */
private Checkbox m_chbIsExpense = new Checkbox();
/** Name field label. */
private Label m_lblName = new Label();
/** Field for specifying name of new account. */
private Textbox m_txbNameField = new Textbox();
/** Button to create new account. */
private Button m_btnNew = new Button();
// account panel
/** Grid for components for creating a charge form a selected account. **/
private Grid m_grdAccount = new Grid();
/** Title of account grid. */
private Column m_clmAccountTitle = new Column();
/** Button to create charge from selected account. */
private Button m_btnAccount = new Button();
/** Table to hold data of accounts. */
private WListbox m_tblData = new WListbox();
/** confirmation panel. */
private WConfirmPanel m_pnlConfirm = new WConfirmPanel();
/** Confirmation Grid. */
private Grid m_grdConfirm = new Grid();
/** Enumeration of column names and indices. */
private enum EColumn
{
/** Select column to record whether the account is selected. */
SELECT(0, "Select"),
/** Value column to hold the account key. */
VALUE(1, "Value"),
/** Name column to hold the account name. */
NAME(2, "Name"),
/** Expense column to indicate whether or not the account is an expense account. */
EXPENSE(3, "Expense");
/** The column's index. */
private final int m_index;
/** The column's name. */
private final String m_title;
/**
* Constructor.
*
* @param index index of the column
* @param title name of the column
*/
EColumn(int index, String title)
{
m_index = index;
m_title = title;
}
/**
* Gets the index of the column.
*
* @return the column index.
*/
public int index()
{
return m_index;
}
/**
* Gets the name of the column.
*
* @return the column's name
*/
public String title()
{
return m_title;
}
/**
* Gets the number of columns.
*
* @return the number of columns.
*/
public static int count()
{
return values().length;
}
}
/**
* Default constructor.
*/
public WCharge()
{
super();
}
/**
* Initialises the panel.
*
* @param adFormId The Adempiere identifier for the form
* @param name The name of the form
*/
public void init(int adFormId, String name)
{
super.init(adFormId, name);
log.info("");
try
{
staticInitialise();
dynamicInitialise();
this.appendChild(m_pnlMain);
//this.appendChild(confirmPanel);
}
catch(Exception e)
{
log.log(Level.SEVERE, "", e);
}
return;
}
/**
* Initialises the static components of the form.
*/
private void staticInitialise()
{
createNewChargePanel();
createAccountPanel();
createConfirmPanel();
// TODO
m_pnlMain.appendChild(m_grdNew);
m_pnlMain.appendChild(m_grdAccount);
m_pnlMain.appendChild(m_grdConfirm);
return;
}
/**
* Creates the account panel.
*
* The account panel contains:
* <li>a table detailing all accounts
* <li>a button for creating charges for selected accounts
*/
private void createAccountPanel()
{
Row topRow = new Row();
Row bottomRow = new Row();
Rows rows = new Rows();
Columns header = new Columns();
// header
m_clmAccountTitle.setLabel(Msg.getMsg(Env.getCtx(), "ChargeFromAccount"));
header.appendChild(m_clmAccountTitle);
// top row
m_tblData.setRows(20);
topRow.appendChild(m_tblData);
rows.appendChild(topRow);
// bottom row
bottomRow.setAlign("right");
m_btnAccount.setLabel(Msg.getMsg(Env.getCtx(), AD_MESSAGE_CREATE));
m_btnAccount.addEventListener(Events.ON_CLICK, this);
bottomRow.appendChild(m_btnAccount);
rows.appendChild(bottomRow);
// put it all together
m_grdAccount.appendChild(header);
m_grdAccount.appendChild(rows);
return;
}
/**
* Creates the New Charge panel.
*
* The New Charge panel is used to specify the name and key of an account
* and whether or not the account is a charge account.
*/
private void createNewChargePanel()
{
final int nameFieldColumns = 20;
final int valueFieldColumns = 10;
Row topRow = new Row();
Row bottomRow = new Row();
Rows rows = new Rows();
Columns header = new Columns();
// header
m_clmNewTitle.setLabel(Msg.getMsg(Env.getCtx(), "ChargeNewAccount"));
header.appendChild(m_clmNewTitle);
// top row
m_lblValue.setValue(Msg.translate(Env.getCtx(), EColumn.VALUE.title()));
m_txbValueField.setCols(valueFieldColumns);
m_chbIsExpense.setChecked(true);
m_chbIsExpense.setLabel(Msg.getMsg(Env.getCtx(), EColumn.EXPENSE.title()));
topRow.appendChild(m_lblValue);
topRow.appendChild(m_txbValueField);
topRow.appendChild(m_chbIsExpense);
rows.appendChild(topRow);
// bottom row
m_lblName.setValue(Msg.translate(Env.getCtx(), EColumn.NAME.title()));
m_txbNameField.setCols(nameFieldColumns);
m_btnNew.setLabel(Msg.getMsg(Env.getCtx(), AD_MESSAGE_CREATE));
m_btnNew.addEventListener(Events.ON_CLICK, this);
bottomRow.appendChild(m_lblName);
bottomRow.appendChild(m_txbNameField);
bottomRow.appendChild(m_btnNew);
rows.appendChild(bottomRow);
// put it all together
m_grdNew.appendChild(header);
m_grdNew.appendChild(rows);
return;
}
/**
* Initialises the dynamic components of the form.
* <li>Gets defaults for primary AcctSchema
* <li>Creates Table with Accounts
*/
private void dynamicInitialise()
{
String sql;
findChargeElementID();
if (m_elementId == 0)
{
return;
}
// Table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
sql = "SELECT C_ElementValue_ID,Value, Name, AccountType "
+ "FROM C_ElementValue "
+ "WHERE AccountType IN ('R','E')"
+ " AND IsSummary='N'"
+ " AND C_Element_ID=? "
+ "ORDER BY 2";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_elementId);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
Vector<Object> line = createDataLine(rs);
data.add(line);
}
rs.close();
pstmt.close();
}
catch (SQLException exception)
{
log.log(Level.SEVERE, sql, exception);
}
// Header Info
Vector<String> columnNames = getColumnNames();
// Set Model
ListModelTable model = new ListModelTable(data);
m_tblData.setData(model, columnNames);
//
m_tblData.setColumnClass(EColumn.SELECT.index(), Boolean.class, false); // 0-Selection
m_tblData.setColumnClass(EColumn.VALUE.index(), String.class, true); // 1-Value
m_tblData.setColumnClass(EColumn.NAME.index(), String.class, true); // 2-Name
m_tblData.setColumnClass(EColumn.EXPENSE.index(), Boolean.class, true); // 3-Expense
// Table UI
//m_tblData.autoSize();
// Other Defaults
m_clientId = Env.getAD_Client_ID(Env.getCtx());
m_organisationId = Env.getAD_Org_ID(Env.getCtx());
// TaxCategory
findTaxCategoryID();
return;
} // dynInit
/**
* Finds the identifier for the tax category for the client.
*/
private void findTaxCategoryID()
{
final String sql = "SELECT C_TaxCategory_ID FROM C_TaxCategory "
+ "WHERE IsDefault='Y' AND AD_Client_ID=?";
m_taxCategoryId = 0;
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_clientId);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_taxCategoryId = rs.getInt(1);
}
rs.close();
pstmt.close();
}
catch (SQLException exception)
{
log.log(Level.SEVERE, sql, exception);
}
return;
}
/**
* Gets a vector of column names.
* The column names are used as column headings int he table.
* @return a vector of column names.
*/
private Vector<String> getColumnNames()
{
Vector<String> columnNames = new Vector<String>(EColumn.count());
columnNames.add(Msg.getMsg(Env.getCtx(), EColumn.SELECT.title()));
columnNames.add(Msg.translate(Env.getCtx(), EColumn.VALUE.title()));
columnNames.add(Msg.translate(Env.getCtx(), EColumn.NAME.title()));
columnNames.add(Msg.getMsg(Env.getCtx(), EColumn.EXPENSE.title()));
return columnNames;
}
/**
* Creates a data line from the given <code>ResultSet</code>.
*
* @param rs result set containing details of an account.
* @return a vector containing details of an account.
* @throws SQLException if a database access error occurred
*/
private Vector<Object> createDataLine(ResultSet rs) throws SQLException
{
final int noFields = EColumn.count();
final int valueIdIndex = 1;
final int valueIndex = 2;
final int nameIndex = 3;
final int expenseIndex = 4;
final String expenseType = "E";
boolean isExpenseType;
Vector<Object> line = new Vector<Object>(noFields);
// 0-Selection
line.add(new Boolean(false));
// 1-Value
KeyNamePair pp = new KeyNamePair(rs.getInt(valueIdIndex),
rs.getString(valueIndex));
line.add(pp);
// 2-Name
line.add(rs.getString(nameIndex));
// 3-Expense
isExpenseType = rs.getString(expenseIndex).equals(expenseType);
line.add(new Boolean(isExpenseType));
return line;
}
/**
* Finds the Element Identifier for the current charge.
*
*/
private void findChargeElementID()
{
m_accountSchemaId = Env.getContextAsInt(Env.getCtx(), "$C_AcctSchema_ID");
// get Element
String sql = "SELECT C_Element_ID "
+ "FROM C_AcctSchema_Element "
+ "WHERE ElementType='AC' AND C_AcctSchema_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_accountSchemaId);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_elementId = rs.getInt(1);
}
rs.close();
pstmt.close();
}
catch (SQLException exception)
{
log.log(Level.SEVERE, sql, exception);
}
}
/**
* Event Listener.
*
* @param event event that has been fired.
*/
public void onEvent(Event event)
{
log.info(event.getName());
//
if (event.getName().equals(WConfirmPanel.A_OK) || m_elementId == 0)
{
close();
}
// new Account
else if (event.getTarget().equals(m_btnNew))
{
createNew();
}
else if (event.getTarget().equals(m_btnAccount))
{
createAccount();
}
return;
}
/**
* Create new Chargeable Account.
*/
private void createNew()
{
final String backgroundColorStyle = "background-color:";
String value;
String name;
log.config("");
// Get Input
value = m_txbValueField.getValue();
if (value.length() == 0)
{
/* m_txbValueField.setStyle(backgroundColorStyle
+ ZkCssHelper.createHexColorString(AdempierePLAF.getFieldBackground_Error()));*/
return;
}
name = m_txbNameField.getText();
if (name.length() == 0)
{
/* m_txbNameField.setStyle(backgroundColorStyle
+ ZkCssHelper.createHexColorString(AdempierePLAF.getFieldBackground_Error()));*/
return;
}
// Create Element
int elementValueId = createElementValue (value, name, m_chbIsExpense.isChecked());
if (elementValueId == 0)
{
FDialog.error(m_windowNo, this, "ChargeNotCreated", name);
return;
}
// Create Charge
int chargeId = createCharge(name, elementValueId);
if (chargeId == 0)
{
FDialog.error(m_windowNo, this, "ChargeNotCreated", name);
return;
}
FDialog.info(m_windowNo, this, "ChargeCreated", name);
} // createNew
/**
* Create Element Value for primary Account Schema.
* @param value account key
* @param name account name
* @param isExpenseType is expense account
* @return element value identifier
*/
private int createElementValue (String value, String name, boolean isExpenseType)
{
MElementValue elementValue;
log.config(name);
//
elementValue = new MElementValue(Env.getCtx(),
value,
name,
null,
isExpenseType ? MElementValue.ACCOUNTTYPE_Expense
: MElementValue.ACCOUNTTYPE_Revenue,
MElementValue.ACCOUNTSIGN_Natural,
false,
false,
null);
elementValue.setAD_Org_ID(m_organisationId);
if (!elementValue.save())
{
log.log(Level.WARNING, "C_ElementValue_ID not created");
}
return elementValue.getC_ElementValue_ID();
} // create_ElementValue
/**
* Create Charge and account entries for primary Account Schema.
*
* @param name charge name
* @param elementValueId element value identifier
* @return charge identifier, or 0 if no charge created.
*/
private int createCharge(String name, int elementValueId)
{
MCharge charge;
MAccount account;
log.config(name + " - ");
// Charge
charge = new MCharge(Env.getCtx(), 0, null);
charge.setName(name);
charge.setC_TaxCategory_ID(m_taxCategoryId);
if (!charge.save())
{
log.log(Level.SEVERE, name + " not created");
return 0;
}
refreshAccountSchema();
if (!isAccountSchemaValid())
{
return 0;
}
// Target Account
account = getAccount(elementValueId, charge);
if (account == null)
{
return 0;
}
updateAccount(charge, account);
return charge.getC_Charge_ID();
} // createCharge
/**
* Updates the charge account details.
* @param charge the charge
* @param account the account
*/
private void updateAccount(MCharge charge, MAccount account)
{
StringBuffer sql = createUpdateAccountSql(charge, account);
//
int noAffectedRows = DB.executeUpdate(sql.toString(), null);
if (noAffectedRows != 1)
{
log.log(Level.SEVERE, "Update #" + noAffectedRows + "\n" + sql.toString());
}
return;
}
/**
* Queries whether the current account scheme is valid.
* @return false if the current account is <code>null</code> or
* its identifier is 0 (zero).
*/
private boolean isAccountSchemaValid()
{
if (m_acctSchema == null)
{
return false;
}
else if (m_acctSchema.getC_AcctSchema_ID() == 0)
{
return false;
}
return true;
}
/**
* Creates the SQL statement for updating the account and charge.
*
* @param charge charge
* @param account account
* @return the SQL DML statement for updating the specified account and charge.
*/
private StringBuffer createUpdateAccountSql(MCharge charge, MAccount account)
{
StringBuffer sql = new StringBuffer("UPDATE C_Charge_Acct ");
sql.append("SET CH_Expense_Acct=").append(account.getC_ValidCombination_ID());
sql.append(", CH_Revenue_Acct=").append(account.getC_ValidCombination_ID());
sql.append(" WHERE C_Charge_ID=").append(charge.getC_Charge_ID());
sql.append(" AND C_AcctSchema_ID=").append(m_accountSchemaId);
return sql;
}
/**
* Refreshes the current account schema.
*
*/
private void refreshAccountSchema()
{
// Get AcctSchama
if (m_acctSchema == null)
{
m_acctSchema = new MAcctSchema(Env.getCtx(), m_accountSchemaId, null);
}
return;
}
/**
* Gets the account for the specified charge and element value.
* The account is created if it doesn't already exist.
* @param elementValueId identifier for the element value
* @param charge charge
* @return the account
*/
private MAccount getAccount(int elementValueId, MCharge charge)
{
MAccount defaultAccount = MAccount.getDefault(m_acctSchema, true); // optional null
MAccount account = MAccount.get(Env.getCtx(),
charge.getAD_Client_ID(),
charge.getAD_Org_ID(),
m_acctSchema.getC_AcctSchema_ID(),
elementValueId,
defaultAccount.getC_SubAcct_ID(),
defaultAccount.getM_Product_ID(),
defaultAccount.getC_BPartner_ID(),
defaultAccount.getAD_OrgTrx_ID(),
defaultAccount.getC_LocFrom_ID(),
defaultAccount.getC_LocTo_ID(),
defaultAccount.getC_SalesRegion_ID(),
defaultAccount.getC_Project_ID(),
defaultAccount.getC_Campaign_ID(),
defaultAccount.getC_Activity_ID(),
defaultAccount.getUser1_ID(),
defaultAccount.getUser2_ID(),
defaultAccount.getUserElement1_ID(),
defaultAccount.getUserElement2_ID());
return account;
}
/**
* Creates Charges from Accounts.
* Charges are created for the selected accounts.
* The selection is cleared upon completion.
*/
private void createAccount()
{
StringBuffer listCreated = new StringBuffer();
StringBuffer listRejected = new StringBuffer();
log.config("");
int noCharges = getNoCharges();
for (int chargeIndex = 0; chargeIndex < noCharges; chargeIndex++)
{
if (isRowSelected(chargeIndex))
{
String name = getChargeName(chargeIndex);
int chargeId = createCharge(chargeIndex);
if (chargeId == 0)
{
appendName(listRejected, name);
}
else
{
appendName(listCreated, name);
}
setRowUnselected(chargeIndex);
}
}
if (listCreated.length() > 0)
{
FDialog.info(m_windowNo, this, "ChargeCreated", listCreated.toString());
}
if (listRejected.length() > 0)
{
FDialog.error(m_windowNo, this, "ChargeNotCreated", listRejected.toString());
}
return;
} // createAccount
/**
* Gets the number of charges in the table.
* @return the number of charges in the table.
*/
private int getNoCharges()
{
int noCharges = m_tblData.getRowCount();
return noCharges;
}
/**
* Creates a charge for specified table row.
*
* @param rowIndex index of the row for which a charge is to be created.
* @return the charge identifier.
*/
private int createCharge(int rowIndex)
{
KeyNamePair pp = (KeyNamePair)m_tblData.getValueAt(rowIndex, EColumn.VALUE.index());
int elementValueId = pp.getKey();
String name = getChargeName(rowIndex);
int chargeID = createCharge(name, elementValueId);
return chargeID;
}
/**
* Gets the name for a specified table row.
* @param rowIndex the table row for which to get the name.
* @return the charge name.
*/
private String getChargeName(int rowIndex)
{
String name = (String)m_tblData.getValueAt(rowIndex, EColumn.NAME.index());
return name;
}
/**
* Appends the <code>name</code> to the <code>nameList</code>.
* @param nameList a list of names
* @param name the name to append
*/
private void appendName(StringBuffer nameList, String name)
{
if (nameList.length() > 0)
{
nameList.append(", ");
}
nameList.append(name);
return;
}
/**
* Sets a row at <code>rowIndex</code> as unselected.
* @param rowIndex index of the row to deselect.
*/
private void setRowUnselected(int rowIndex)
{
ListModelTable model = m_tblData.getModel();
model.setDataAt(Boolean.valueOf(false), rowIndex, EColumn.SELECT.index());
return;
}
/**
* Queries whether a row is selected.
* @param rowIndex index of the row to query.
* @return true if the row is selected, false otherwise.
*/
private boolean isRowSelected(int rowIndex)
{
ListModelTable model = m_tblData.getModel();
Boolean isSelected = (Boolean)model.getDataAt(rowIndex, EColumn.SELECT.index());
return isSelected.booleanValue();
}
/**
* Create Confirmation Panel with OK Button.
*/
public void createConfirmPanel()
{
Rows rows = new Rows();
Row row = new Row();
m_pnlConfirm.addEventListener(this);
row.appendChild(m_pnlConfirm);
rows.appendChild(row);
m_grdConfirm.appendChild(rows);
return;
} // ConfirmPanel
public void close()
{
SessionManager.getAppDesktop().removeWindow();
}
}

View File

@ -0,0 +1,600 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.WListbox;
import org.adempiere.webui.component.Window;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.event.WTableModelEvent;
import org.adempiere.webui.event.WTableModelListener;
import org.compiere.model.GridTab;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MOrder;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Separator;
import org.zkoss.zul.Vbox;
/**
* Create From (Base Class) : Based on VCreateFrom
*
* @author Niraj Sohun
* @date Jul 16, 2007
*/
public abstract class WCreateFrom extends Window implements EventListener, WTableModelListener, ValueChangeListener
{
private static CLogger s_log = CLogger.getCLogger (WCreateFrom.class);
protected CLogger log = CLogger.getCLogger(getClass());
protected Hbox hboxCommon = new Hbox();
protected Vbox parameterShipmentPanel = new Vbox();
protected Hbox parameterBankPanel = new Hbox();
protected Vbox parameterInvoicePanel = new Vbox();
private Vbox bottomPanel = new Vbox();
protected Listbox shipmentField = new Listbox();
protected Listbox orderField = new Listbox();
protected Listbox invoiceField = new Listbox();
protected WEditor bankAccountField;
protected WEditor bPartnerField;
protected WEditor locatorField;
protected Button btnCancel = new Button();
protected Button btnOk = new Button();
protected Button btnSelectAll = new Button();
private Label bankAccountLabel = new Label();
private Label bPartnerLabel = new Label();
private Label shipmentLabel = new Label();
private Label orderLabel = new Label();
private Label invoiceLabel = new Label();
private Label locatorLabel = new Label();
protected Label lblStatus = new Label();
protected WListbox dataTable = new WListbox();
protected int p_WindowNo;
protected GridTab p_mTab;
private boolean p_initOK;
protected MOrder p_order = null;
private void init()
{
// Common - BP and Purchase Order
bPartnerLabel.setValue(Msg.getElement(Env.getCtx(), "C_BPartner_ID"));
orderLabel.setValue(Msg.getElement(Env.getCtx(), "C_Order_ID", false));
orderField.setRows(0);
orderField.setMold("select");
orderField.addEventListener(Events.ON_SELECT, this);
hboxCommon.setWidth("700px");
hboxCommon.setWidths("13%, 30%, 12%, 25%");
hboxCommon.appendChild(bPartnerLabel);
if (bPartnerField != null)
hboxCommon.appendChild(bPartnerField.getComponent());
hboxCommon.appendChild(orderLabel);
hboxCommon.appendChild(orderField);
//End Common
// WCreateFromShipment
invoiceLabel.setValue(Msg.getElement(Env.getCtx(), "C_Invoice_ID", false));
locatorLabel.setValue(Msg.translate(Env.getCtx(), "M_Locator_ID"));
invoiceField.setRows(0);
invoiceField.setMold("select");
invoiceField.addEventListener(Events.ON_SELECT, this);
Hbox boxShipment = new Hbox();
boxShipment.setWidth("100%");
boxShipment.setWidths("13%, 30%, 12%, 25%");
boxShipment.appendChild(locatorLabel);
if (locatorField != null)
boxShipment.appendChild(locatorField.getComponent());
boxShipment.appendChild(invoiceLabel);
boxShipment.appendChild(invoiceField);
parameterShipmentPanel.setWidth("700px");
parameterShipmentPanel.appendChild(boxShipment);
// WCreateFromInvoice
shipmentLabel.setValue(Msg.getElement(Env.getCtx(), "M_InOut_ID", false));
shipmentField.setRows(0);
shipmentField.setMold("select");
shipmentField.addEventListener(Events.ON_SELECT, this);
Hbox boxInvoice = new Hbox();
boxInvoice.setWidth("100%");
boxInvoice.setWidths("13%, 30%, 12%, 25%");
boxInvoice.appendChild(new Label());
boxInvoice.appendChild(new Label());
boxInvoice.appendChild(shipmentLabel);
boxInvoice.appendChild(shipmentField);
//boxInvoice.setStyle("text-align:right");
parameterInvoicePanel.setWidth("700px");
parameterInvoicePanel.appendChild(boxInvoice);
// End WCreateFromInvoice
// WCreateFromStatement
bankAccountLabel.setValue(Msg.translate(Env.getCtx(), "C_BankAccount_ID"));
Hbox boxStatement = new Hbox();
boxStatement.appendChild(bankAccountLabel);
if (bankAccountField != null)
boxStatement.appendChild(bankAccountField.getComponent());
boxStatement.setStyle("text-align:center");
parameterBankPanel.setWidth("700px");
parameterBankPanel.appendChild(boxStatement);
// End WCreateFromStatement
// Listbox
dataTable.setCheckmark(true);
dataTable.setMultiSelection(true);
// Buttons & Status
Hbox boxButtons = new Hbox();
boxButtons.setWidth("100%");
boxButtons.setWidths("90%, 5%, 5%" );
boxButtons.setStyle("text-align:left");
btnCancel.addEventListener(Events.ON_CLICK, this);
btnCancel.setImage("/images/Cancel24.gif");
btnOk.addEventListener(Events.ON_CLICK, this);
btnOk.setImage("/images/Ok24.gif");
btnSelectAll.addEventListener(Events.ON_CLICK, this);
btnSelectAll.setLabel("Select All");
boxButtons.appendChild(btnSelectAll);
boxButtons.appendChild(btnCancel);
boxButtons.appendChild(btnOk);
bottomPanel.setWidth("700px");
bottomPanel.appendChild(boxButtons);
bottomPanel.appendChild(lblStatus);
// End Buttons & Status
// Window
this.setWidth("700px");
this.setClosable(true);
this.setBorder("normal");
this.appendChild(hboxCommon);
this.appendChild(new Separator());
this.appendChild(parameterInvoicePanel);
this.appendChild(parameterBankPanel);
this.appendChild(parameterShipmentPanel);
this.appendChild(new Separator());
this.appendChild(dataTable);
this.appendChild(new Separator());
this.appendChild(bottomPanel);
}
public static WCreateFrom create(GridTab mTab)
{
// Dynamic init preparation
int AD_Table_ID = Env.getContextAsInt(Env.getCtx(), mTab.getWindowNo(), "BaseTable_ID");
WCreateFrom retValue = null;
if (AD_Table_ID == 392) // C_BankStatement
retValue = new WCreateFromStatement(mTab);
else if (AD_Table_ID == 318) // C_Invoice
retValue = new WCreateFromInvoice(mTab);
else if (AD_Table_ID == 319) // M_InOut
retValue = new WCreateFromShipment(mTab);
else if (AD_Table_ID == 426) // C_PaySelection
return null; // Ignore - will call process C_PaySelection_CreateFrom
else // Not supported CreateFrom
{
s_log.info("Unsupported AD_Table_ID=" + AD_Table_ID);
return null;
}
return retValue;
}
public WCreateFrom (GridTab mTab)
{
super();
log.info(mTab.toString());
p_WindowNo = mTab.getWindowNo();
p_mTab = mTab;
try
{
if (!dynInit())
return;
init();
//confirmPanel.addActionListener(this);
// Set status
//statusBar.setStatusDB("");
tableChanged(null);
p_initOK = true;
}
catch(Exception e)
{
log.log(Level.SEVERE, "", e);
p_initOK = false;
}
AEnv.showWindow(this);
}
/**
* Init OK to be able to make changes?
* @return on if initialized
*/
public boolean isInitOK()
{
return p_initOK;
}
/**
* Dynamic Init
* @throws Exception if Lookups cannot be initialized
* @return true if initialized
*/
abstract boolean dynInit() throws Exception;
/**
* Init Business Partner Details
* @param C_BPartner_ID BPartner
*/
abstract void initBPDetails(int C_BPartner_ID);
/**
* Add Info
*/
abstract void info();
/**
* Save & Insert Data
* @return true if saved
*/
abstract boolean save();
public void onEvent(Event e) throws Exception
{
//log.config("Action=" + e.getActionCommand());
// OK - Save
if (e.getTarget() == btnOk)
{
if (save())
this.detach();
}
// Cancel
else if (e.getTarget() == btnCancel)
{
this.detach();
}
// Select All
// Trifon
else if (e.getTarget() == btnSelectAll)
{
ListModelTable model = dataTable.getModel();
int rows = model.size();
for (int i = 0; i < rows; i++)
{
//model.setDataAt(new Boolean(true), i, 0);
dataTable.addItemToSelection(dataTable.getItemAtIndex(i));
//dataTable.setSelectedIndex(i);
}
info();
}
// m_action = false;
}
public void tableChanged (WTableModelEvent e)
{
int type = -1;
info();
if (e != null)
{
type = e.getType();
if (type != WTableModelEvent.CONTENTS_CHANGED)
return;
}
log.config("Type=" + type);
info();
}
protected void initBPartner (boolean forInvoice) throws Exception
{
// Load BPartner
int AD_Column_ID = 3499; // C_Invoice.C_BPartner_ID
MLookup lookup = MLookupFactory.get (Env.getCtx(), p_WindowNo, 0, AD_Column_ID, DisplayType.Search);
bPartnerField = new WSearchEditor(lookup, Msg.translate(Env.getCtx(), "C_BPartner_ID"), "", true, false, true);
bPartnerField.addValueChangeListner(this);
int C_BPartner_ID = Env.getContextAsInt(Env.getCtx(), p_WindowNo, "C_BPartner_ID");
bPartnerField.setValue(new Integer(C_BPartner_ID));
// Initial loading
initBPartnerOIS(C_BPartner_ID, forInvoice);
}
/**
* Load PBartner dependent Order/Invoice/Shipment Field.
* @param C_BPartner_ID BPartner
* @param forInvoice for invoice
*/
protected void initBPartnerOIS (int C_BPartner_ID, boolean forInvoice)
{
log.config("C_BPartner_ID=" + C_BPartner_ID);
KeyNamePair pp = new KeyNamePair(0,"");
// Load PO Orders - Closed, Completed
orderField.removeEventListener(Events.ON_SELECT, this);
orderField.getChildren().clear();
orderField.appendItem(pp.getName(), pp);
// Display
StringBuffer display = new StringBuffer("o.DocumentNo||' - ' ||")
.append(DB.TO_CHAR("o.DateOrdered", DisplayType.Date, Env.getAD_Language(Env.getCtx())))
.append("||' - '||")
.append(DB.TO_CHAR("o.GrandTotal", DisplayType.Amount, Env.getAD_Language(Env.getCtx())));
String column = "m.M_InOutLine_ID";
if (forInvoice)
column = "m.C_InvoiceLine_ID";
StringBuffer sql = new StringBuffer("SELECT o.C_Order_ID,").append(display)
.append(" FROM C_Order o "
+ "WHERE o.C_BPartner_ID=? AND o.IsSOTrx='N' AND o.DocStatus IN ('CL','CO')"
+ " AND o.C_Order_ID IN "
+ "(SELECT ol.C_Order_ID FROM C_OrderLine ol"
+ " LEFT OUTER JOIN M_MatchPO m ON (ol.C_OrderLine_ID=m.C_OrderLine_ID) "
+ "GROUP BY ol.C_Order_ID,ol.C_OrderLine_ID, ol.QtyOrdered,").append(column)
.append(" HAVING (ol.QtyOrdered <> SUM(m.Qty) AND ").append(column)
.append(" IS NOT NULL) OR ").append(column).append(" IS NULL) "
+ "ORDER BY o.DateOrdered");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, C_BPartner_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
orderField.appendItem(pp.getName(), pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
orderField.setSelectedIndex(0);
orderField.addEventListener(Events.ON_SELECT, this);
initBPDetails(C_BPartner_ID);
}
protected void loadOrder (int C_Order_ID, boolean forInvoice)
{
/**
* Selected - -
* Qty - 0
* C_UOM_ID - 1
* M_Product_ID - 2
* VendorProductNo - 3
* OrderLine - 4
* ShipmentLine - 5
* InvoiceLine - 6
*/
log.config("C_Order_ID=" + C_Order_ID);
p_order = new MOrder (Env.getCtx(), C_Order_ID, null); // save
Vector<Vector> data = new Vector<Vector>();
StringBuffer sql = new StringBuffer("SELECT "
+ "l.QtyOrdered-SUM(COALESCE(m.Qty,0))," // 1
+ "CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END," // 2
+ " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name)," // 3..4
+ " COALESCE(l.M_Product_ID,0),COALESCE(p.Name,c.Name),po.VendorProductNo," // 5..7
+ " l.C_OrderLine_ID,l.Line " // 8..9
+ "FROM C_OrderLine l"
+ " LEFT OUTER JOIN M_Product_PO po ON (l.M_Product_ID = po.M_Product_ID AND l.C_BPartner_ID = po.C_BPartner_ID) "
+ " LEFT OUTER JOIN M_MatchPO m ON (l.C_OrderLine_ID=m.C_OrderLine_ID AND ");
sql.append(forInvoice ? "m.C_InvoiceLine_ID" : "m.M_InOutLine_ID");
sql.append(" IS NOT NULL)")
.append(" LEFT OUTER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID)"
+ " LEFT OUTER JOIN C_Charge c ON (l.C_Charge_ID=c.C_Charge_ID)");
if (Env.isBaseLanguage(Env.getCtx(), "C_UOM"))
sql.append(" LEFT OUTER JOIN C_UOM uom ON (l.C_UOM_ID=uom.C_UOM_ID)");
else
sql.append(" LEFT OUTER JOIN C_UOM_Trl uom ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
.append(Env.getAD_Language(Env.getCtx())).append("')");
sql.append(" WHERE l.C_Order_ID=? " // #1
+ "GROUP BY l.QtyOrdered,CASE WHEN l.QtyOrdered=0 THEN 0 ELSE l.QtyEntered/l.QtyOrdered END, "
+ "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),po.VendorProductNo, "
+ "l.M_Product_ID,COALESCE(p.Name,c.Name), l.Line,l.C_OrderLine_ID "
+ "ORDER BY l.Line");
log.finer(sql.toString());
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, C_Order_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
Vector<Object> line = new Vector<Object>();
//line.add(new Boolean(false)); // 0-Selection
BigDecimal qtyOrdered = rs.getBigDecimal(1);
BigDecimal multiplier = rs.getBigDecimal(2);
BigDecimal qtyEntered = qtyOrdered.multiply(multiplier);
line.add(new Double(qtyEntered.doubleValue())); // 1-Qty
KeyNamePair pp = new KeyNamePair(rs.getInt(3), rs.getString(4).trim());
line.add(pp); // 2-UOM
pp = new KeyNamePair(rs.getInt(5), rs.getString(6));
line.add(pp); // 3-Product
line.add(rs.getString(7)); // 4-VendorProductNo
pp = new KeyNamePair(rs.getInt(8), rs.getString(9));
line.add(pp); // 5-OrderLine
line.add(null); // 6-Ship
line.add(null); // 7-Invoice
data.add(line);
}
rs.close();
pstmt.close();
}
catch (Exception e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
loadTableOIS (data);
}
/**
* Load Order/Invoice/Shipment data into Table
* @param data data
*/
protected void loadTableOIS (Vector data)
{
// Header Info
Vector<String> columnNames = new Vector<String>(6);
//columnNames.add(Msg.getMsg(Env.getCtx(), "Select"));
columnNames.add(Msg.translate(Env.getCtx(), "Quantity"));
columnNames.add(Msg.translate(Env.getCtx(), "C_UOM_ID"));
columnNames.add(Msg.translate(Env.getCtx(), "M_Product_ID"));
columnNames.add(Msg.getElement(Env.getCtx(), "VendorProductNo", false));
columnNames.add(Msg.getElement(Env.getCtx(), "C_Order_ID", false));
columnNames.add(Msg.getElement(Env.getCtx(), "M_InOut_ID", false));
columnNames.add(Msg.getElement(Env.getCtx(), "C_Invoice_ID", false));
// Remove previous listeners
//dataTable.getModel().removeTableModelListener(this);
// Set Model
ListModelTable model = new ListModelTable(data);
//DefaultTableModel model = new DefaultTableModel(data, columnNames);
model.addTableModelListener(this);
dataTable.setData(model, columnNames);
//dataTable.setColumnClass(0, Boolean.class, false); // 0-Selection
dataTable.setColumnClass(0, Double.class, true); // 1-Qty
dataTable.setColumnClass(1, String.class, true); // 2-UOM
dataTable.setColumnClass(2, String.class, true); // 3-Product
dataTable.setColumnClass(3, String.class, true); // 4-VendorProductNo
dataTable.setColumnClass(4, String.class, true); // 5-Order
dataTable.setColumnClass(5, String.class, true); // 6-Ship
dataTable.setColumnClass(6, String.class, true); // 7-Invoice
// Table UI
//dataTable.autoSize();
}
}

View File

@ -0,0 +1,487 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.event.WTableModelListener;
import org.compiere.model.GridTab;
import org.compiere.model.MInOut;
import org.compiere.model.MInOutLine;
import org.compiere.model.MInvoice;
import org.compiere.model.MInvoiceLine;
import org.compiere.model.MOrder;
import org.compiere.model.MOrderLine;
import org.compiere.model.MProduct;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* Create From Invoice : Based on VCreateFromInvoice
*
* @author Niraj Sohun
* @date Jul 16, 2007
*/
public class WCreateFromInvoice extends WCreateFrom implements EventListener, ValueChangeListener, WTableModelListener
{
private static final long serialVersionUID = 1L;
private MInOut m_inout = null;
private boolean m_actionActive;
/**
* Protected Constructor
* @param mTab MTab
*/
public WCreateFromInvoice(GridTab mTab)
{
super (mTab);
log.info(mTab.toString());
}
@Override
protected boolean dynInit() throws Exception
{
log.config("");
setTitle(Msg.getElement(Env.getCtx(), "C_Invoice_ID", false) + " .. " + Msg.translate(Env.getCtx(), "CreateFrom"));
parameterBankPanel.setVisible(false);
parameterShipmentPanel.setVisible(false);
initBPartner(true);
bPartnerField.addValueChangeListner(this);
return true;
}
protected void initBPDetails(int C_BPartner_ID)
{
log.config("C_BPartner_ID" + C_BPartner_ID);
// Load Shipments (Receipts) - Completed, Closed
shipmentField.removeEventListener(Events.ON_SELECT, this);
shipmentField.getChildren().clear();
// None
KeyNamePair pp = new KeyNamePair(0,"");
shipmentField.appendItem(pp.getName(), pp);
// Display
StringBuffer display = new StringBuffer("s.DocumentNo||' - '||")
.append(DB.TO_CHAR("s.MovementDate", DisplayType.Date, Env.getAD_Language(Env.getCtx())));
StringBuffer sql = new StringBuffer("SELECT s.M_InOut_ID,").append(display)
.append(" FROM M_InOut s "
+ "WHERE s.C_BPartner_ID=? AND s.IsSOTrx='N' AND s.DocStatus IN ('CL','CO')"
+ " AND s.M_InOut_ID IN "
+ "(SELECT sl.M_InOut_ID FROM M_InOutLine sl"
+ " LEFT OUTER JOIN M_MatchInv mi ON (sl.M_InOutLine_ID=mi.M_InOutLine_ID) "
+ "GROUP BY sl.M_InOut_ID,mi.M_InOutLine_ID,sl.MovementQty "
+ "HAVING (sl.MovementQty<>SUM(mi.Qty) AND mi.M_InOutLine_ID IS NOT NULL)"
+ " OR mi.M_InOutLine_ID IS NULL) "
+ "ORDER BY s.MovementDate");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, C_BPartner_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
shipmentField.appendItem(pp.getName(), pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
shipmentField.setSelectedIndex(0);
shipmentField.addEventListener(Events.ON_SELECT, this);
}
public void onEvent(Event e) throws Exception
{
super.onEvent(e);
if (m_actionActive)
return;
m_actionActive = true;
log.config("Action=" + e.getTarget());
// Order
if (e.getTarget() == orderField)
{
ListItem listitem = orderField.getSelectedItem();
KeyNamePair pp = (KeyNamePair)listitem.getValue();
int C_Order_ID = 0;
if (pp != null)
C_Order_ID = pp.getKey();
// Set Invoice and Shipment to Null
invoiceField.setSelectedIndex(-1);
shipmentField.setSelectedIndex(-1);
loadOrder(C_Order_ID, true);
}
// Shipment
else if (e.getTarget() == shipmentField)
{
ListItem listitem = shipmentField.getSelectedItem();
KeyNamePair pp = (KeyNamePair)listitem.getValue();
int M_InOut_ID = 0;
if (pp != null)
M_InOut_ID = pp.getKey();
// Set Order and Invoice to Null
orderField.setSelectedIndex(-1);
invoiceField.setSelectedIndex(-1);
loadShipment(M_InOut_ID);
}
m_actionActive = false;
}
public void valueChange(ValueChangeEvent evt)
{
log.config(evt.getPropertyName() + "=" + evt.getNewValue());
if (evt == null)
return;
if (evt.getSource() instanceof WEditor)
{
if (evt.getPropertyName().equals("C_BPartner_ID"))
{
int C_BPartner_ID = ((Integer)evt.getNewValue()).intValue();
initBPartnerOIS (C_BPartner_ID, true);
}
tableChanged(null);
}
}
private void loadShipment(int M_InOut_ID)
{
log.config("M_InOut_ID=" + M_InOut_ID);
m_inout = new MInOut(Env.getCtx(), M_InOut_ID, null);
p_order = null;
if (m_inout.getC_Order_ID() != 0)
p_order = new MOrder (Env.getCtx(), m_inout.getC_Order_ID(), null);
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
StringBuffer sql = new StringBuffer("SELECT " // QtyEntered
+ "l.MovementQty-SUM(NVL(mi.Qty, 0)), l.QtyEntered/l.MovementQty,"
+ " l.C_UOM_ID, COALESCE(uom.UOMSymbol, uom.Name)," // 3..4
+ " l.M_Product_ID, p.Name, po.VendorProductNo, l.M_InOutLine_ID, l.Line," // 5..9
+ " l.C_OrderLine_ID " // 10
+ " FROM M_InOutLine l "
);
if (Env.isBaseLanguage(Env.getCtx(), "C_UOM"))
sql.append(" LEFT OUTER JOIN C_UOM uom ON (l.C_UOM_ID=uom.C_UOM_ID)");
else
sql.append(" LEFT OUTER JOIN C_UOM_Trl uom ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
.append(Env.getAD_Language(Env.getCtx())).append("')");
sql.append(" LEFT OUTER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID)")
.append(" INNER JOIN M_InOut io ON (l.M_InOut_ID=io.M_InOut_ID)")
.append(" LEFT OUTER JOIN M_Product_PO po ON (l.M_Product_ID = po.M_Product_ID AND io.C_BPartner_ID = po.C_BPartner_ID)")
.append(" LEFT OUTER JOIN M_MatchInv mi ON (l.M_InOutLine_ID=mi.M_InOutLine_ID)")
.append(" WHERE l.M_InOut_ID=? ")
.append("GROUP BY l.MovementQty, l.QtyEntered/l.MovementQty, "
+ "l.C_UOM_ID, COALESCE(uom.UOMSymbol, uom.Name), "
+ "l.M_Product_ID, p.Name, po.VendorProductNo, l.M_InOutLine_ID, l.Line, l.C_OrderLine_ID ")
.append("ORDER BY l.Line");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, M_InOut_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
Vector<Object> line = new Vector<Object>(7);
//line.add(new Boolean(false)); // 0-Selection
BigDecimal qtyMovement = rs.getBigDecimal(1);
BigDecimal multiplier = rs.getBigDecimal(2);
BigDecimal qtyEntered = qtyMovement.multiply(multiplier);
line.add(new Double(qtyEntered.doubleValue())); // 1-Qty
KeyNamePair pp = new KeyNamePair(rs.getInt(3), rs.getString(4).trim());
line.add(pp); // 2-UOM
pp = new KeyNamePair(rs.getInt(5), rs.getString(6));
line.add(pp); // 3-Product
line.add(rs.getString(7)); // 4-VendorProductNo
int C_OrderLine_ID = rs.getInt(10);
if (rs.wasNull())
line.add(null); // 5-Order
else
line.add(new KeyNamePair(C_OrderLine_ID,"."));
pp = new KeyNamePair(rs.getInt(8), rs.getString(9));
line.add(pp); // 6-Ship
line.add(null); // 7-Invoice
data.add(line);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
loadTableOIS(data);
}
@Override
/**
* List number of rows selected
*/
protected void info()
{
ListModelTable model = dataTable.getModel();
int rows = model.size();
int count = 0;
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())//(((Boolean)model.getDataAt(i, 0)).booleanValue())
count++;
}
}
/**
* Save - Create Invoice Lines
* @return true if saved
*/
protected boolean save()
{
log.config("");
ListModelTable model = dataTable.getModel();
int rows = model.size();
if (rows == 0)
return false;
// Invoice
Object obj = p_mTab.getValue("C_Invoice_ID");
if (obj == null)
throw new IllegalStateException("Company Agent or Business Partner has not been selected");
int C_Invoice_ID = ((Integer)p_mTab.getValue("C_Invoice_ID")).intValue();
MInvoice invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null);
log.config(invoice.toString());
if (p_order != null)
{
invoice.setOrder(p_order); // Overwrite header values
invoice.save();
}
// Only first time
if (m_inout != null && m_inout.getM_InOut_ID() != 0 && m_inout.getC_Invoice_ID() == 0)
{
m_inout.setC_Invoice_ID(C_Invoice_ID);
m_inout.save();
}
// Lines
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())//(((Boolean)model.getDataAt(i, 0)).booleanValue())
{
// Variable values
Double d = (Double)model.getDataAt(i, 0); // 1-Qty
BigDecimal QtyEntered = new BigDecimal(d.doubleValue());
KeyNamePair pp = (KeyNamePair)model.getDataAt(i, 1); // 2-UOM
int C_UOM_ID = pp.getKey();
pp = (KeyNamePair)model.getDataAt(i, 2); // 3-Product
int M_Product_ID = 0;
if (pp != null)
M_Product_ID = pp.getKey();
int C_Charge_ID = 0;
int C_OrderLine_ID = 0;
pp = (KeyNamePair)model.getDataAt(i, 4); // 5-OrderLine
if (pp != null)
C_OrderLine_ID = pp.getKey();
int M_InOutLine_ID = 0;
pp = (KeyNamePair)model.getDataAt(i, 5); // 6-Shipment
if (pp != null)
M_InOutLine_ID = pp.getKey();
// Precision of Qty UOM
int precision = 2;
if (M_Product_ID != 0)
{
MProduct product = MProduct.get(Env.getCtx(), M_Product_ID);
precision = product.getUOMPrecision();
}
QtyEntered = QtyEntered.setScale(precision, BigDecimal.ROUND_HALF_DOWN);
log.fine("Line QtyEntered=" + QtyEntered
+ ", Product_ID=" + M_Product_ID
+ ", OrderLine_ID=" + C_OrderLine_ID + ", InOutLine_ID=" + M_InOutLine_ID);
// Create new Invoice Line
MInvoiceLine invoiceLine = new MInvoiceLine (invoice);
invoiceLine.setM_Product_ID(M_Product_ID, C_UOM_ID); // Line UOM
invoiceLine.setQty(QtyEntered); // Invoiced/Entered
// Info
MOrderLine orderLine = null;
if (C_OrderLine_ID != 0)
orderLine = new MOrderLine (Env.getCtx(), C_OrderLine_ID, null);
MInOutLine inoutLine = null;
if (M_InOutLine_ID != 0)
{
inoutLine = new MInOutLine (Env.getCtx(), M_InOutLine_ID, null);
if (orderLine == null && inoutLine.getC_OrderLine_ID() != 0)
{
C_OrderLine_ID = inoutLine.getC_OrderLine_ID();
orderLine = new MOrderLine (Env.getCtx(), C_OrderLine_ID, null);
}
}
else
{
MInOutLine[] lines = MInOutLine.getOfOrderLine(Env.getCtx(),
C_OrderLine_ID, null, null);
log.fine ("Receipt Lines with OrderLine = #" + lines.length);
if (lines.length > 0)
{
for (int j = 0; j < lines.length; j++)
{
MInOutLine line = lines[j];
if (line.getQtyEntered().compareTo(QtyEntered) == 0)
{
inoutLine = line;
M_InOutLine_ID = inoutLine.getM_InOutLine_ID();
break;
}
}
if (inoutLine == null)
{
inoutLine = lines[0]; // First as default
M_InOutLine_ID = inoutLine.getM_InOutLine_ID();
}
}
} // Get Ship info
// Shipment Info
if (inoutLine != null)
{
invoiceLine.setShipLine(inoutLine); // Overwrites
if (inoutLine.getQtyEntered().compareTo(inoutLine.getMovementQty()) != 0)
invoiceLine.setQtyInvoiced(QtyEntered
.multiply(inoutLine.getMovementQty())
.divide(inoutLine.getQtyEntered(), 12, BigDecimal.ROUND_HALF_UP));
}
else
log.fine("No Receipt Line");
// Order Info
if (orderLine != null)
{
invoiceLine.setOrderLine(orderLine); // Overwrites
if (orderLine.getQtyEntered().compareTo(orderLine.getQtyOrdered()) != 0)
invoiceLine.setQtyInvoiced(QtyEntered
.multiply(orderLine.getQtyOrdered())
.divide(orderLine.getQtyEntered(), 12, BigDecimal.ROUND_HALF_UP));
}
else
{
log.fine("No Order Line");
invoiceLine.setPrice();
invoiceLine.setTax();
}
if (!invoiceLine.save())
log.log(Level.SEVERE, "Line NOT created #" + i);
} // if selected
} // for all rows
return true;
}
}

View File

@ -0,0 +1,519 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WLocatorEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.event.WTableModelListener;
import org.compiere.model.GridTab;
import org.compiere.model.MInOut;
import org.compiere.model.MInOutLine;
import org.compiere.model.MInvoice;
import org.compiere.model.MInvoiceLine;
import org.compiere.model.MLocator;
import org.compiere.model.MLocatorLookup;
import org.compiere.model.MOrderLine;
import org.compiere.model.MProduct;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* Create From Shipment : Based on VCreateFromShipment
*
* @author Niraj Sohun
* @date Jul 18, 2007
*/
public class WCreateFromShipment extends WCreateFrom implements EventListener, ValueChangeListener, WTableModelListener
{
private static final long serialVersionUID = 1L;
/** Loaded Invoice */
private MInvoice m_invoice = null;
/**
* Protected Constructor
* @param mTab MTab
*/
WCreateFromShipment(GridTab mTab)
{
super (mTab);
}
protected boolean dynInit() throws Exception
{
log.config("");
setTitle(Msg.getElement(Env.getCtx(), "M_InOut_ID", false) + " .. " + Msg.translate(Env.getCtx(), "CreateFrom"));
parameterBankPanel.setVisible(false);
parameterInvoicePanel.setVisible(false);
//shipmentLabel.setVisible(false);
//shipmentField.setVisible(false);
// Load Locator
int AD_Column_ID = 3537; // M_InOut.M_Locator_ID
MLocatorLookup locator = new MLocatorLookup(Env.getCtx(), p_WindowNo);
locatorField = new WLocatorEditor ("M_Locator_ID", true, false, true, locator);
locatorField.addValueChangeListner(this);
initBPartner(false);
bPartnerField.addValueChangeListner(this);
return true;
}
protected void initBPDetails(int C_BPartner_ID)
{
log.config("C_BPartner_ID=" + C_BPartner_ID);
// Load AP Invoice closed or complete
invoiceField.removeEventListener(Events.ON_SELECT, this);
invoiceField.getChildren().clear();
// None
KeyNamePair pp = new KeyNamePair(0,"");
invoiceField.appendItem(pp.getName(), pp);
StringBuffer display = new StringBuffer("i.DocumentNo||' - '||")
.append(DB.TO_CHAR("DateInvoiced", DisplayType.Date, Env.getAD_Language(Env.getCtx())))
.append("|| ' - ' ||")
.append(DB.TO_CHAR("GrandTotal", DisplayType.Amount, Env.getAD_Language(Env.getCtx())));
StringBuffer sql = new StringBuffer("SELECT i.C_Invoice_ID,").append(display)
.append(" FROM C_Invoice i "
+ "WHERE i.C_BPartner_ID=? AND i.IsSOTrx='N' AND i.DocStatus IN ('CL','CO')"
+ " AND i.C_Invoice_ID IN "
+ "(SELECT il.C_Invoice_ID FROM C_InvoiceLine il"
+ " LEFT OUTER JOIN M_MatchInv mi ON (il.C_InvoiceLine_ID=mi.C_InvoiceLine_ID) "
+ "GROUP BY il.C_Invoice_ID,mi.C_InvoiceLine_ID,il.QtyInvoiced "
+ "HAVING (il.QtyInvoiced<>SUM(mi.Qty) AND mi.C_InvoiceLine_ID IS NOT NULL)"
+ " OR mi.C_InvoiceLine_ID IS NULL) "
+ "ORDER BY i.DateInvoiced");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, C_BPartner_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
invoiceField.appendItem(pp.getName(), pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
invoiceField.setSelectedIndex(0);
invoiceField.addEventListener(Events.ON_SELECT, this);
}
public void onEvent(Event e) throws Exception
{
super.onEvent(e);
log.config("Action=" + e.getTarget());
// Order
if (e.getTarget() == orderField)
{
ListItem listitem = orderField.getSelectedItem();
KeyNamePair pp = (KeyNamePair)listitem.getValue();
if (pp == null || pp.getKey() == 0)
;
else
{
int C_Order_ID = pp.getKey();
// Set Invoice and Shipment to Null
invoiceField.setSelectedIndex(0);
if (shipmentField.getItemCount() > 0)
shipmentField.setSelectedIndex(0);
loadOrder(C_Order_ID, false);
m_invoice = null;
}
}
// Invoice
else if (e.getTarget() == invoiceField)
{
ListItem listitem = invoiceField.getSelectedItem();
KeyNamePair pp = (KeyNamePair)listitem.getValue();
if (pp == null || pp.getKey() == 0)
;
else
{
int C_Invoice_ID = pp.getKey();
// set Order and Shipment to Null
orderField.setSelectedIndex(0);
if (shipmentField.getItemCount() > 0)
shipmentField.setSelectedIndex(0);
loadInvoice(C_Invoice_ID);
}
}
}
public void valueChange(ValueChangeEvent evt)
{
log.config(evt.getPropertyName() + "=" + evt.getNewValue());
if (evt == null)
return;
if (evt.getSource() instanceof WEditor)
{
// BPartner - load Order/Invoice/Shipment
if (evt.getPropertyName().equals("C_BPartner_ID"))
{
int C_BPartner_ID = ((Integer)evt.getNewValue()).intValue();
initBPartnerOIS (C_BPartner_ID, false);
}
tableChanged(null);
}
}
/**
* Load Data - Invoice
* @param C_Invoice_ID Invoice
*/
private void loadInvoice(int C_Invoice_ID)
{
log.config("C_Invoice_ID=" + C_Invoice_ID);
m_invoice = new MInvoice(Env.getCtx(), C_Invoice_ID, null); // save
p_order = null;
Vector<Vector> data = new Vector<Vector>();
StringBuffer sql = new StringBuffer("SELECT " // Entered UOM
+ "l.QtyInvoiced-SUM(NVL(mi.Qty,0)),l.QtyEntered/l.QtyInvoiced,"
+ " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name)," // 3..4
+ " l.M_Product_ID,p.Name, po.VendorProductNo, l.C_InvoiceLine_ID,l.Line," // 5..9
+ " l.C_OrderLine_ID "
+ " FROM C_InvoiceLine l "); // 10
if (Env.isBaseLanguage(Env.getCtx(), "C_UOM"))
sql.append(" LEFT OUTER JOIN C_UOM uom ON (l.C_UOM_ID=uom.C_UOM_ID)");
else
sql.append(" LEFT OUTER JOIN C_UOM_Trl uom ON (l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='")
.append(Env.getAD_Language(Env.getCtx())).append("')");
sql.append(" LEFT OUTER JOIN M_Product p ON (l.M_Product_ID=p.M_Product_ID)")
.append(" INNER JOIN C_Invoice inv ON (l.C_Invoice_ID=inv.C_Invoice_ID)")
.append(" LEFT OUTER JOIN M_Product_PO po ON (l.M_Product_ID = po.M_Product_ID AND inv.C_BPartner_ID = po.C_BPartner_ID)")
.append(" LEFT OUTER JOIN M_MatchInv mi ON (l.C_InvoiceLine_ID=mi.C_InvoiceLine_ID)")
.append(" WHERE l.C_Invoice_ID=? ")
.append("GROUP BY l.QtyInvoiced,l.QtyEntered/l.QtyInvoiced,"
+ "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"
+ "l.M_Product_ID,p.Name, po.VendorProductNo, l.C_InvoiceLine_ID,l.Line,l.C_OrderLine_ID ")
.append("ORDER BY l.Line");
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, C_Invoice_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
Vector<Object> line = new Vector<Object>(7);
//line.add(new Boolean(false)); // 0-Selection
BigDecimal qtyInvoiced = rs.getBigDecimal(1);
BigDecimal multiplier = rs.getBigDecimal(2);
BigDecimal qtyEntered = qtyInvoiced.multiply(multiplier);
line.add(new Double(qtyEntered.doubleValue())); // 1-Qty
KeyNamePair pp = new KeyNamePair(rs.getInt(3), rs.getString(4).trim());
line.add(pp); // 2-UOM
pp = new KeyNamePair(rs.getInt(5), rs.getString(6));
line.add(pp); // 3-Product
line.add(rs.getString(7)); // 4-VendorProductNo
int C_OrderLine_ID = rs.getInt(10);
if (rs.wasNull())
line.add(null); // 5-Order
else
line.add(new KeyNamePair(C_OrderLine_ID, "."));
line.add(null); // 6-Ship
pp = new KeyNamePair(rs.getInt(8), rs.getString(9));
line.add(pp); // 7-Invoice
data.add(line);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
loadTableOIS(data);
} // loadInvoice
/**
* List number of rows selected
*/
protected void info()
{
ListModelTable model = dataTable.getModel();
int rows = model.size();
int count = 0;
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())//(((Boolean) model.getDataAt(i, 0)).booleanValue())
count++;
}
lblStatus.setValue(String.valueOf(count));
} // info
/**
* Save - create Shipments
*
* @return true if saved
*/
protected boolean save()
{
log.config("");
ListModelTable model = dataTable.getModel();
int rows = model.size();
if (rows == 0)
return false;
MLocator mlocator = (MLocator)locatorField.getValue();
//Integer loc = (Integer) locatorField.getValue();
if (mlocator == null || mlocator.getM_Locator_ID()/*.intValue()*/ == 0)
{
/* locatorField.setBackground(AdempierePLAF.getFieldBackground_Error());*/
return false;
}
int M_Locator_ID = mlocator.getM_Locator_ID();
// Get Shipment
int M_InOut_ID = ((Integer) p_mTab.getValue("M_InOut_ID")).intValue();
MInOut inout = new MInOut(Env.getCtx(), M_InOut_ID, null);
log.config(inout + ", C_Locator_ID=" + M_Locator_ID);
// Lines
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())//(((Boolean) model.getDataAt(i, 0)).booleanValue())
{
// Variable values
Double d = (Double) model.getDataAt(i, 0); // 1-Qty
BigDecimal QtyEntered = new BigDecimal(d.doubleValue());
KeyNamePair pp = (KeyNamePair) model.getDataAt(i, 1); // 2-Product
int C_UOM_ID = pp.getKey();
pp = (KeyNamePair) model.getDataAt(i, 2); // 3-Product
int M_Product_ID = pp.getKey();
int C_OrderLine_ID = 0;
pp = (KeyNamePair) model.getDataAt(i, 4); // 5-OrderLine
if (pp != null)
C_OrderLine_ID = pp.getKey();
int C_InvoiceLine_ID = 0;
MInvoiceLine il = null;
pp = (KeyNamePair) model.getDataAt(i, 6); // 7-InvoiceLine
if (pp != null)
C_InvoiceLine_ID = pp.getKey();
if (C_InvoiceLine_ID != 0)
il = new MInvoiceLine (Env.getCtx(), C_InvoiceLine_ID, null);
boolean isInvoiced = (C_InvoiceLine_ID != 0);
// Precision of Qty UOM
int precision = 2;
if (M_Product_ID != 0)
{
MProduct product = MProduct.get(Env.getCtx(), M_Product_ID);
precision = product.getUOMPrecision();
}
QtyEntered = QtyEntered.setScale(precision, BigDecimal.ROUND_HALF_DOWN);
log.fine("Line QtyEntered=" + QtyEntered
+ ", Product=" + M_Product_ID
+ ", OrderLine=" + C_OrderLine_ID + ", InvoiceLine=" + C_InvoiceLine_ID);
// Credit Memo - negative Qty
if (m_invoice != null && m_invoice.isCreditMemo())
QtyEntered = QtyEntered.negate();
// Create new InOut Line
MInOutLine iol = new MInOutLine (inout);
iol.setM_Product_ID(M_Product_ID, C_UOM_ID); // Line UOM
iol.setQty(QtyEntered); // Movement/Entered
MOrderLine ol = null;
if (C_OrderLine_ID != 0)
{
iol.setC_OrderLine_ID(C_OrderLine_ID);
ol = new MOrderLine (Env.getCtx(), C_OrderLine_ID, null);
if (ol.getQtyEntered().compareTo(ol.getQtyOrdered()) != 0)
{
iol.setMovementQty(QtyEntered
.multiply(ol.getQtyOrdered())
.divide(ol.getQtyEntered(), 12, BigDecimal.ROUND_HALF_UP));
iol.setC_UOM_ID(ol.getC_UOM_ID());
}
iol.setM_AttributeSetInstance_ID(ol.getM_AttributeSetInstance_ID());
iol.setDescription(ol.getDescription());
iol.setC_Project_ID(ol.getC_Project_ID());
iol.setC_ProjectPhase_ID(ol.getC_ProjectPhase_ID());
iol.setC_ProjectTask_ID(ol.getC_ProjectTask_ID());
iol.setC_Activity_ID(ol.getC_Activity_ID());
iol.setC_Campaign_ID(ol.getC_Campaign_ID());
iol.setAD_OrgTrx_ID(ol.getAD_OrgTrx_ID());
iol.setUser1_ID(ol.getUser1_ID());
iol.setUser2_ID(ol.getUser2_ID());
}
else if (il != null)
{
if (il.getQtyEntered().compareTo(il.getQtyInvoiced()) != 0)
{
iol.setQtyEntered(QtyEntered
.multiply(il.getQtyInvoiced())
.divide(il.getQtyEntered(), 12, BigDecimal.ROUND_HALF_UP));
iol.setC_UOM_ID(il.getC_UOM_ID());
}
iol.setDescription(il.getDescription());
iol.setC_Project_ID(il.getC_Project_ID());
iol.setC_ProjectPhase_ID(il.getC_ProjectPhase_ID());
iol.setC_ProjectTask_ID(il.getC_ProjectTask_ID());
iol.setC_Activity_ID(il.getC_Activity_ID());
iol.setC_Campaign_ID(il.getC_Campaign_ID());
iol.setAD_OrgTrx_ID(il.getAD_OrgTrx_ID());
iol.setUser1_ID(il.getUser1_ID());
iol.setUser2_ID(il.getUser2_ID());
}
// Charge
if (M_Product_ID == 0)
{
if (ol != null && ol.getC_Charge_ID() != 0) // from order
iol.setC_Charge_ID(ol.getC_Charge_ID());
else if (il != null && il.getC_Charge_ID() != 0) // from invoice
iol.setC_Charge_ID(il.getC_Charge_ID());
}
iol.setM_Locator_ID(M_Locator_ID);
if (!iol.save())
log.log(Level.SEVERE, "Line NOT created #" + i);
// Create Invoice Line Link
else if (il != null)
{
il.setM_InOutLine_ID(iol.getM_InOutLine_ID());
il.save();
}
} // if selected
} // for all rows
/**
* Update Header
* - if linked to another order/invoice - remove link
* - if no link set it
*/
if (p_order != null && p_order.getC_Order_ID() != 0)
{
inout.setC_Order_ID (p_order.getC_Order_ID());
inout.setAD_OrgTrx_ID(p_order.getAD_OrgTrx_ID());
inout.setC_Project_ID(p_order.getC_Project_ID());
inout.setC_Campaign_ID(p_order.getC_Campaign_ID());
inout.setC_Activity_ID(p_order.getC_Activity_ID());
inout.setUser1_ID(p_order.getUser1_ID());
inout.setUser2_ID(p_order.getUser2_ID());
}
if (m_invoice != null && m_invoice.getC_Invoice_ID() != 0)
{
if (inout.getC_Order_ID() == 0)
inout.setC_Order_ID (m_invoice.getC_Order_ID());
inout.setC_Invoice_ID (m_invoice.getC_Invoice_ID());
inout.setAD_OrgTrx_ID(m_invoice.getAD_OrgTrx_ID());
inout.setC_Project_ID(m_invoice.getC_Project_ID());
inout.setC_Campaign_ID(m_invoice.getC_Campaign_ID());
inout.setC_Activity_ID(m_invoice.getC_Activity_ID());
inout.setUser1_ID(m_invoice.getUser1_ID());
inout.setUser2_ID(m_invoice.getUser2_ID());
}
inout.save();
return true;
} // save
}

View File

@ -0,0 +1,314 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Vector;
import java.util.logging.Level;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.event.WTableModelListener;
import org.adempiere.webui.window.FDialog;
import org.compiere.model.GridTab;
import org.compiere.model.MBankStatement;
import org.compiere.model.MBankStatementLine;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MPayment;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.EventListener;
/**
* Create From Statement : Based on VCreateFromStatement
*
* @author Niraj Sohun
* @date Jul 20, 2007
*/
public class WCreateFromStatement extends WCreateFrom implements EventListener, ValueChangeListener, WTableModelListener
{
private static final long serialVersionUID = 1L;
/**
* Protected Constructor
* @param mTab MTab
*/
WCreateFromStatement(GridTab mTab)
{
super(mTab);
//log.info("");
}
/**
* Dynamic Init
* @throws Exception if Lookups cannot be initialized
* @return true if initialized
*/
protected boolean dynInit() throws Exception
{
if (p_mTab.getValue("C_BankStatement_ID") == null)
{
FDialog.error(0, this, "SaveErrorRowNotFound");
return false;
}
setTitle(Msg.translate(Env.getCtx(), "C_BankStatement_ID") + " .. " + Msg.translate(Env.getCtx(), "CreateFrom"));
parameterShipmentPanel.setVisible(false);
parameterInvoicePanel.setVisible(false);
hboxCommon.setVisible(false);
int AD_Column_ID = 4917; // C_BankStatement.C_BankAccount_ID
MLookup lookup = MLookupFactory.get (Env.getCtx(), p_WindowNo, 0, AD_Column_ID, DisplayType.TableDir);
bankAccountField = new WSearchEditor(lookup, "label","desc", true, false, true);
bankAccountField.addValueChangeListner(this);
// Set Default
int C_BankAccount_ID = Env.getContextAsInt(Env.getCtx(), p_WindowNo, "C_BankAccount_ID");
bankAccountField.setValue(new Integer(C_BankAccount_ID));
// Initial Loading
loadBankAccount(C_BankAccount_ID);
return true;
}
/**
* Init Details (never called)
* @param C_BPartner_ID BPartner
*/
protected void initBPDetails(int C_BPartner_ID)
{
}
public void valueChange(ValueChangeEvent evt)
{
log.config(evt.getPropertyName() + "=" + evt.getNewValue());
if (evt == null)
return;
if (evt.getSource() instanceof WEditor)
{
// BankAccount
if (evt.getPropertyName().equals("C_BankAccount_ID"))
{
int C_BankAccount_ID = ((Integer)evt.getNewValue()).intValue();
loadBankAccount(C_BankAccount_ID);
}
tableChanged(null);
}
}
/**
* Load Data - Bank Account
* @param C_BankAccount_ID Bank Account
*/
private void loadBankAccount (int C_BankAccount_ID)
{
log.config ("C_BankAccount_ID=" + C_BankAccount_ID);
/**
* Selected - -
* Date - 1
* C_Payment_ID - 2
* C_Currenncy - 3
* Amt - 4
*/
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
String sql = "SELECT p.DateTrx,p.C_Payment_ID,p.DocumentNo, p.C_Currency_ID,c.ISO_Code, p.PayAmt,"
+ "currencyConvert(p.PayAmt,p.C_Currency_ID,ba.C_Currency_ID,?,null,p.AD_Client_ID,p.AD_Org_ID)," // #1
+ " bp.Name "
+ "FROM C_BankAccount ba"
+ " INNER JOIN C_Payment_v p ON (p.C_BankAccount_ID=ba.C_BankAccount_ID)"
+ " INNER JOIN C_Currency c ON (p.C_Currency_ID=c.C_Currency_ID)"
+ " LEFT OUTER JOIN C_BPartner bp ON (p.C_BPartner_ID=bp.C_BPartner_ID) "
+ "WHERE p.Processed='Y' AND p.IsReconciled='N'"
+ " AND p.DocStatus IN ('CO','CL','RE','VO') AND p.PayAmt<>0" // Bug 1564453 Added Voided payment to bank statement payement selection
+ " AND p.C_BankAccount_ID=?" // #2
+ " AND NOT EXISTS (SELECT * FROM C_BankStatementLine l "
// Voided Bank Statements have 0 StmtAmt
+ "WHERE p.C_Payment_ID=l.C_Payment_ID AND l.StmtAmt <> 0)";
// Get StatementDate
Timestamp ts = (Timestamp)p_mTab.getValue("StatementDate");
if (ts == null)
ts = new Timestamp(System.currentTimeMillis());
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setTimestamp(1, ts);
pstmt.setInt(2, C_BankAccount_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
Vector<Object> line = new Vector<Object>(6);
//line.add(new Boolean(false)); // 0-Selection
line.add(rs.getTimestamp(1)); // 1-DateTrx
KeyNamePair pp = new KeyNamePair(rs.getInt(2), rs.getString(3));
line.add(pp); // 2-C_Payment_ID
pp = new KeyNamePair(rs.getInt(4), rs.getString(5));
line.add(pp); // 3-Currency
line.add(rs.getBigDecimal(6)); // 4-PayAmt
line.add(rs.getBigDecimal(7)); // 5-Conv Amt
line.add(rs.getString(8)); // 6-BParner
data.add(line);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
if (data.size() == 0)
return;
// Header Info
Vector<String> columnNames = new Vector<String>(6);
//columnNames.add(Msg.getMsg(Env.getCtx(), "Select"));
columnNames.add(Msg.translate(Env.getCtx(), "Date"));
columnNames.add(Msg.getElement(Env.getCtx(), "C_Payment_ID"));
columnNames.add(Msg.translate(Env.getCtx(), "C_Currency_ID"));
columnNames.add(Msg.translate(Env.getCtx(), "Amount"));
columnNames.add(Msg.translate(Env.getCtx(), "ConvertedAmount"));
columnNames.add(Msg.translate(Env.getCtx(), "C_BPartner_ID"));
// Remove previous listeners
//dataTable.getModel().removeListDataListener(this);
// Set Model
ListModelTable model = new ListModelTable(data);
model.addTableModelListener(this);
dataTable.setData(model, columnNames);
//dataTable.setColumnClass(0, Boolean.class, false); // 0-Selection
dataTable.setColumnClass(0, Timestamp.class, true); // 1-TrxDate
dataTable.setColumnClass(1, String.class, true); // 2-Payment
dataTable.setColumnClass(2, String.class, true); // 3-Currency
dataTable.setColumnClass(3, BigDecimal.class, true); // 4-Amount
dataTable.setColumnClass(4, BigDecimal.class, true); // 5-ConvAmount
dataTable.setColumnClass(5, String.class, true); // 6-BPartner
// Table UI
//dataTable.autoSize();
} // loadBankAccount
/**
* List total amount
*/
protected void info()
{
DecimalFormat format = DisplayType.getNumberFormat(DisplayType.Amount);
ListModelTable model = dataTable.getModel();
BigDecimal total = new BigDecimal(0.0);
int rows = model.size();
int count = 0;
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())//(((Boolean)model.getDataAt(i, 0)).booleanValue())
{
total = total.add((BigDecimal)model.getDataAt(i, 4));
count++;
}
}
lblStatus.setValue(String.valueOf(count) + " - " + Msg.getMsg(Env.getCtx(), "Sum") + " " + format.format(total));
} // infoStatement
/**
* Save Statement - Insert Data
* @return true if saved
*/
protected boolean save()
{
log.config("");
ListModelTable model = dataTable.getModel();
int rows = model.size();
if (rows == 0)
return false;
// Fixed values
int C_BankStatement_ID = ((Integer)p_mTab.getValue("C_BankStatement_ID")).intValue();
MBankStatement bs = new MBankStatement (Env.getCtx(), C_BankStatement_ID, null);
log.config(bs.toString());
// Lines
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())//(((Boolean)model.getDataAt(i, 0)).booleanValue())
{
Timestamp trxDate = (Timestamp)model.getDataAt(i, 0); // 1-DateTrx
KeyNamePair pp = (KeyNamePair)model.getDataAt(i, 1); // 2-C_Payment_ID
int C_Payment_ID = pp.getKey();
pp = (KeyNamePair)model.getDataAt(i, 2); // 3-Currency
int C_Currency_ID = pp.getKey();
BigDecimal TrxAmt = (BigDecimal)model.getDataAt(i, 3); // 4-PayAmt
// BigDecimal StmtAmt = (BigDecimal)model.getValueAt(i, 5);// 5-Conv Amt
log.fine("Line Date=" + trxDate
+ ", Payment=" + C_Payment_ID + ", Currency=" + C_Currency_ID + ", Amt=" + TrxAmt);
MBankStatementLine bsl = new MBankStatementLine (bs);
bsl.setStatementLineDate(trxDate);
bsl.setPayment(new MPayment(Env.getCtx(), C_Payment_ID, null));
if (!bsl.save())
log.log(Level.SEVERE, "Line not created #" + i);
} // if selected
} // for all rows
return true;
} // save
}

View File

@ -0,0 +1,573 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;
import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.ConfirmPanel;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.adempiere.webui.window.FDialog;
import org.compiere.impexp.ImpFormat;
import org.compiere.impexp.ImpFormatRow;
import org.compiere.model.MRole;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Ini;
import org.compiere.util.Msg;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Separator;
/**
* Fixed length file import
*
* @author Niraj Sohun
* Aug 16, 2007
*
*/
public class WFileImport extends ADForm implements EventListener
{
private static final long serialVersionUID = 1L;
/** Logger */
private static CLogger log = CLogger.getCLogger(WFileImport.class);
/** Window No */
private int m_WindowNo = 0;
private int m_record = -1;
private Listbox pickFormat = new Listbox();
private Listbox fCharset = new Listbox();
private ArrayList<String> m_data = new ArrayList<String>();
private static final String s_none = "----"; // no format indicator
private ImpFormat m_format;
private ConfirmPanel confirmPanel = new ConfirmPanel(true);
private Button bFile = new Button();
private Button bNext = new Button();
private Button bPrevious = new Button();
private InputStream m_file_istream;
private Textbox rawData = new Textbox();
private Textbox[] m_fields;
private Label info = new Label();
private Label[] m_labels;
private Label record = new Label();
private Label labelFormat = new Label();
private VerticalBox previewPanel = new VerticalBox();
private Hbox northPanel = new Hbox();
private Panel rawDataPane = new Panel();
private VerticalBox centerPanel = new VerticalBox();
public WFileImport()
{
init(super.m_windowNo);
}
/**
* Initialize Panel
* @param WindowNo window
*/
public void init (int WindowNo)
{
log.info("");
m_WindowNo = WindowNo;
try
{
jbInit();
dynInit();
this.setWidth("100%");
this.setClosable(true);
this.setTitle("Import File Loader");
this.setBorder("normal");
this.appendChild(northPanel);
this.appendChild(new Separator());
this.appendChild(centerPanel);
this.appendChild(new Separator());
this.appendChild(confirmPanel);
}
catch(Exception e)
{
log.log(Level.SEVERE, "init", e);
}
} // init
/**
* Static Init
* @throws Exception
*/
private void jbInit() throws Exception
{
Charset[] charsets = Ini.getAvailableCharsets();
for (int i = 0; i < charsets.length; i++)
fCharset.appendItem(charsets[i].displayName(), charsets[i]);
bFile.setLabel(Msg.getMsg(Env.getCtx(), "FileImportFile"));
bFile.setTooltiptext(Msg.getMsg(Env.getCtx(), "FileImportFileInfo"));
bFile.addEventListener(Events.ON_CLICK, this);
fCharset.setMold("select");
fCharset.setRows(0);
fCharset.setTooltiptext(Msg.getMsg(Env.getCtx(), "Charset", false));
info.setValue(" ");
labelFormat.setValue(Msg.translate(Env.getCtx(), "AD_ImpFormat_ID"));
pickFormat.setMold("select");
pickFormat.setRows(0);
bNext.setTooltiptext(Msg.getMsg(Env.getCtx(), "Next"));
//bNext.setMargin(new Insets(2, 2, 2, 2));
bNext.setLabel(">");
bNext.addEventListener(Events.ON_CLICK, this);
record.setValue("-");
bPrevious.setTooltiptext(Msg.getMsg(Env.getCtx(), "Previous"));
//bPrevious.setMargin(new Insets(2, 2, 2, 2));
bPrevious.setLabel("<");
bPrevious.addEventListener(Events.ON_CLICK, this);
northPanel.appendChild(bFile);
northPanel.appendChild(fCharset);
northPanel.appendChild(info);
northPanel.appendChild(labelFormat);
northPanel.appendChild(pickFormat);
northPanel.appendChild(bPrevious);
northPanel.appendChild(record);
northPanel.appendChild(bNext);
//rawData.setFont(new java.awt.Font("Monospaced", 0, 10));
//rawData.setColumns(80);
rawData.setWidth("100%");
rawData.setCols(80);
rawData.setRows(5);
previewPanel.setWidth("100%");
//rawDataPane.appendChild(rawData);
centerPanel.appendChild(rawData);
centerPanel.appendChild(new Separator());
centerPanel.appendChild(previewPanel);
//previewPanel.setLayout(previewLayout);
//previewPane.getViewport().add(previewPanel, null);
//previewPane.setPreferredSize(new Dimension(700,80));
//confirmPanel.getButton("Ok").addEventListener(Events.ON_CLICK, this);
//confirmPanel.getButton("Cancel").addEventListener(Events.ON_CLICK, this);
confirmPanel.addActionListener(Events.ON_CLICK, this);
}
/**
* Dynamic Init
*/
private void dynInit()
{
// Load Formats
pickFormat.appendItem(s_none, s_none);
String sql = MRole.getDefault().addAccessSQL("SELECT Name FROM AD_ImpFormat", "AD_ImpFormat",
MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
pickFormat.appendItem(rs.getString(1), rs.getString(1));
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
pickFormat.setSelectedIndex(0);
pickFormat.addEventListener(Events.ON_SELECT, this);
Charset charset = Ini.getCharset();
for (int i = 0; i < fCharset.getItemCount(); i++)
{
ListItem listitem = fCharset.getItemAtIndex(i);
Charset compare = (Charset)listitem.getValue();
if (charset == compare)
{
fCharset.setSelectedIndex(i);
break;
}
}
fCharset.addEventListener(Events.ON_SELECT, this);
confirmPanel.setEnabled("Ok", false);
} // dynInit
public void onEvent(Event e) throws Exception
{
if (e.getTarget() == bFile)
{
cmd_loadFile();
invalidate();
}
else if (e.getTarget() == fCharset)
{
int record = m_record;
cmd_reloadFile();
m_record = record - 1;
cmd_applyFormat(true);
}
else if (e.getTarget() == pickFormat)
{
cmd_loadFormat();
invalidate();
}
else if (e.getTarget() == bNext )
cmd_applyFormat(true);
else if (e.getTarget() == bPrevious )
cmd_applyFormat(false);
else if (e.getTarget() == confirmPanel.getButton("Ok"))
{
confirmPanel.setEnabled("Ok", false);
cmd_process();
/*org.compiere.apps.SwingWorker worker = new org.compiere.apps.SwingWorker()
{
public Object construct()
{
cmd_process();
return Boolean.TRUE;
}
};*/
//worker.start();
// when you need the result:
// x = worker.get(); // this blocks the UI !!
}
else if (e.getTarget() == confirmPanel.getButton("Cancel"))
{
SessionManager.getAppDesktop().removeWindow();
return;
}
if (m_data != null && m_data.size() > 0 // file loaded
&& m_format != null && m_format.getRowCount() > 0) // format loaded
confirmPanel.getButton("Ok").setEnabled(true);
else
confirmPanel.getButton("Ok").setEnabled(false);
}
/**************************************************************************
* Load File
*/
private void cmd_loadFile()
{
String directory = org.compiere.Adempiere.getAdempiereHome()
+ File.separator + "data"
+ File.separator + "import";
log.config(directory);
Media media = null;
try
{
media = Fileupload.get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//JFileChooser chooser = new JFileChooser(directory);
//chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
//chooser.setMultiSelectionEnabled(false);
//chooser.setDialogTitle(Msg.getMsg(Env.getCtx(), "FileImportFileInfo"));
//if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
// return;
if (media == null)
return;
if (Env.isWindows())
m_file_istream = new ByteArrayInputStream(media.getByteData());
else
m_file_istream = new StringBufferInputStream(media.getStringData());
log.config(media.getName());
bFile.setLabel(media.getName());
cmd_reloadFile();
}
/**
* Reload/Load file
*/
private void cmd_reloadFile()
{
if (m_file_istream == null)
return;
m_data.clear();
rawData .setText("");
try
{
// see NaturalAccountMap
ListItem listitem = fCharset.getSelectedItem();
Charset charset = null;
if (listitem == null)
return;
charset = (Charset)listitem.getValue();
BufferedReader in = new BufferedReader(new InputStreamReader(m_file_istream, charset), 10240);
// not safe see p108 Network pgm
String s = null;
String concat = "";
while ((s = in.readLine()) != null)
{
m_data.add(s);
concat += s;
concat += "\n";
if (m_data.size() < 100)
{
rawData.setValue(concat);
//rawData.append("\n");
}
}
in.close();
//rawData.setCaretPosition(0);
}
catch (Exception e)
{
log.log(Level.SEVERE, "", e);
bFile.setLabel(Msg.getMsg(Env.getCtx(), "FileImportFile"));
}
int index = 1; // second line as first may be heading
if (m_data.size() == 1)
index = 0;
int length = 0;
if (m_data.size() > 0)
length = m_data.get(index).toString().length();
info.setValue(Msg.getMsg(Env.getCtx(), "Records") + "=" + m_data.size()
+ ", " + Msg.getMsg(Env.getCtx(), "Length") + "=" + length + " ");
//setCursor (Cursor.getDefaultCursor());
log.config("Records=" + m_data.size() + ", Length=" + length);
} // cmd_loadFile
/**
* Load Format
*/
private void cmd_loadFormat()
{
// clear panel
previewPanel.getChildren().clear();
ListItem listitem = pickFormat.getSelectedItem();
String formatName = (String)listitem.getValue();
if (formatName.equals(s_none))
return;
m_format = ImpFormat.load (formatName);
if (m_format == null)
{
FDialog.error(m_WindowNo, this, formatName);
return;
}
// pointers
int size = m_format.getRowCount();
m_labels = new Label[size];
m_fields = new Textbox[size];
for (int i = 0; i < size; i++)
{
ImpFormatRow row = m_format.getRow(i);
m_labels[i] = new Label(row.getColumnName());
Hbox hbox = new Hbox();
hbox.setWidth("100%");
hbox.setWidths("30%, 70%");
//previewPanel.add(m_labels[i], new GridBagConstraints(i, 0, 1, 1, 1.0, 1.0,
// GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
hbox.appendChild(m_labels[i]);
int length = row.getEndNo() - row.getStartNo();
if (length <= 5)
length = 5;
else if (length > 20)
length = 20;
m_fields[i] = new Textbox();
hbox.appendChild(m_fields[i]);
//previewPanel.add(m_fields[i], new GridBagConstraints(i, 1, 1, 1, 1.0, 1.0,
// GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
previewPanel.appendChild(hbox);
}
m_record = -1;
record.setValue("-");
previewPanel.invalidate();
} // cmd_format
/**
* Apply Current Pattern
* @param next next
*/
private void cmd_applyFormat (boolean next)
{
if (m_format == null)
return;
// set position
if (next)
m_record++;
else
m_record--;
if (m_record < 0)
m_record = 0;
else if (m_record >= m_data.size())
m_record = m_data.size() - 1;
record.setValue(" " + String.valueOf(m_record+1) + " ");
// Line Info
String[] lInfo = m_format.parseLine(m_data.get(m_record).toString(), false, true, false); // no label, trace, no ignore
int size = m_format.getRowCount();
if (lInfo.length != size)
log.log(Level.SEVERE, "FormatElements=" + size + " != Fields=" + lInfo.length);
for (int i = 0; i < size; i++)
{
m_fields[i].setText(lInfo[i]);
//m_fields[i].setCaretPosition(0);
}
} // cmd_applyFormat
/**************************************************************************
* Process File
*/
private void cmd_process()
{
if (m_format == null)
{
FDialog.error(m_WindowNo, this, "FileImportNoFormat");
return;
}
log.config(m_format.getName());
// For all rows - update/insert DB table
int row = 0;
int imported = 0;
for (row = 0; row < m_data.size(); row++)
if (m_format.updateDB(Env.getCtx(), m_data.get(row).toString(), null))
imported++;
FDialog.info(m_WindowNo, this, "FileImportR/I", row + " / " + imported + "#");
SessionManager.getAppDesktop().removeWindow();
} // cmd_process
}

View File

@ -0,0 +1,692 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListHead;
import org.adempiere.webui.component.ListHeader;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.Tab;
import org.adempiere.webui.component.Tabbox;
import org.adempiere.webui.component.Tabpanel;
import org.adempiere.webui.component.Tabpanels;
import org.adempiere.webui.component.Tabs;
import org.adempiere.webui.component.WListbox;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.editor.WTableDirEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.event.WTableModelEvent;
import org.adempiere.webui.event.WTableModelListener;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.compiere.apps.ProcessCtl;
import org.compiere.minigrid.IDColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MOrder;
import org.compiere.model.MPInstance;
import org.compiere.model.MPInstancePara;
import org.compiere.model.MPrivateAccess;
import org.compiere.process.ProcessInfo;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Separator;
/**
* Generate Shipments Manual : Based on VInOutGen
*
* @author Niraj Sohun
* @date Jul 9, 2007
*/
public class WInOutGen extends ADForm implements EventListener, ValueChangeListener, WTableModelListener
{
private static final long serialVersionUID = 1L;
private Separator separator;
private Tabbox tabbox;
private Tabs tabs;
private Tab tabSelect;
private Tab tabGenerate;
private Tabpanels tabpanels;
private Tabpanel pnlSelect;
private Tabpanel pnlGenerate;
// Panel Select
private WEditor warehouseSearch;
private WEditor bPartnerSearch;
private WListbox lstSelect;
// Panel Generate
private Label lblGenerate;
private Label lblNote;
private Listbox lstGenerate;
private Button btnOk;
private Button btnCancel;
private Label lblStatus;
private Label lblNumSelected;
private boolean m_selectionActive = true;
private ArrayList<Integer> selections = null;
@SuppressWarnings("unused")
private Object m_C_BPartner_ID;
private Object m_M_Warehouse_ID;
private static CLogger log = CLogger.getCLogger(WInvoiceGen.class);
public WInOutGen()
{
init();
initComponents();
}
private void init()
{
separator = new Separator();
separator.setHeight("5px");
tabbox = new Tabbox();
tabbox.setWidth("700px");
tabs = new Tabs();
tabSelect = new Tab();
tabSelect.setLabel("Select");
tabSelect.addEventListener(Events.ON_SELECT, this);
tabGenerate = new Tab();
tabGenerate.setLabel("Generate");
tabGenerate.addEventListener(Events.ON_SELECT, this);
tabpanels = new Tabpanels();
pnlSelect = new Tabpanel();
pnlGenerate = new Tabpanel();
lstSelect = new WListbox();
lstSelect.setWidth("690px");
lstSelect.setHeight("250px");
lstSelect.addEventListener(Events.ON_CLICK, this);
lstSelect.getModel().addTableModelListener(this);
btnCancel = new Button();
btnCancel.setImage("/images/Cancel24.gif");
btnCancel.addEventListener(Events.ON_CLICK, this);
btnOk = new Button();
btnOk.setImage("/images/Ok24.gif");
btnOk.addEventListener(Events.ON_CLICK, this);
lblGenerate = new Label();
lblGenerate.setWidth("690px");
lblGenerate.setMultiline(true);
lblNote = new Label();
lblNote.setWidth("690px");
lblNote.setMultiline(true);
lblStatus = new Label(" ");
lblNumSelected = new Label("Number of Records Selected : 0");
lstGenerate = new Listbox();
lstGenerate.setWidth("300px");
populateWarehouse();
showBusinessPartner();
}
private void initComponents()
{
this.setWidth("710px");
tabs.appendChild(tabSelect);
tabs.appendChild(tabGenerate);
tabpanels.appendChild(pnlSelect);
tabpanels.appendChild(pnlGenerate);
tabbox.appendChild(tabs);
tabbox.appendChild(tabpanels);
Hbox mainBox = new Hbox();
mainBox.setWidth("100%");
mainBox.setStyle("text-align:center");
Hbox hOrg = new Hbox();
hOrg.setWidth("100%");
Hbox hBP = new Hbox();
hBP.setWidth("100%");
mainBox.appendChild(hOrg);
mainBox.appendChild(hBP);
Panel pnl1 = new Panel();
pnl1.appendChild(warehouseSearch.getLabel());
pnl1.setStyle("text-align:right");
Panel pnl2 = new Panel();
pnl2.appendChild(warehouseSearch.getComponent());
pnl2.setStyle("text-align:left");
Panel pnl3 = new Panel();
pnl3.appendChild(bPartnerSearch.getLabel());
pnl3.setStyle("text-align:right");
Panel pnl4 = new Panel();
pnl4.appendChild(bPartnerSearch.getComponent());
pnl4.setStyle("text-align:left");
hOrg.appendChild(pnl1);
hOrg.appendChild(pnl2);
hBP.appendChild(pnl3);
hBP.appendChild(pnl4);
pnlSelect.setStyle("text-align:center");
pnlSelect.appendChild(mainBox);
pnlSelect.appendChild(new Separator());
pnlSelect.appendChild(lstSelect);
pnlSelect.appendChild(new Separator());
pnlSelect.addEventListener(Events.ON_SELECT, this);
pnlGenerate.appendChild(lblGenerate);
pnlGenerate.appendChild(lblNote);
pnlGenerate.appendChild(new Separator());
pnlGenerate.appendChild(lstGenerate);
this.appendChild(tabbox);
this.appendChild(new Separator());
Hbox hbox = new Hbox();
hbox.setWidth("80px");
hbox.appendChild(btnCancel);
hbox.appendChild(btnOk);
this.appendChild(hbox);
this.appendChild(new Separator());
hbox = new Hbox();
hbox.setWidth("700px");
Panel p = new Panel();
p.setStyle("text-align:left");
p.appendChild(lblStatus);
hbox.appendChild(p);
p = new Panel();
p.setStyle("text-align:right");
p.appendChild(lblNumSelected);
hbox.appendChild(p);
this.appendChild(hbox);
prepareTable();
}
private void prepareTable()
{
// Create Columns
ListHead listhead = new ListHead();
listhead.setSizable(true);
listhead.appendChild(new ListHeader(""));
listhead.appendChild(new ListHeader("Organization"));
listhead.appendChild(new ListHeader("Document Type"));
listhead.appendChild(new ListHeader("Document No"));
listhead.appendChild(new ListHeader("Business Partner"));
listhead.appendChild(new ListHeader("Date Ordered"));
listhead.appendChild(new ListHeader("Total Lines"));
lstSelect.appendChild(listhead);
lstSelect.addColumn("C_Order_ID");
lstSelect.addColumn("AD_Org_ID");
lstSelect.addColumn("C_DocType_ID");
lstSelect.addColumn("DocumentNo");
lstSelect.addColumn("C_BPartner_ID");
lstSelect.addColumn("DateOrdered");
lstSelect.addColumn("TotalLines");
lstSelect.setMultiSelection(true);
// Set Details
lstSelect.setColumnClass(0, IDColumn.class, false, " ");
lstSelect.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
lstSelect.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "C_DocType_ID"));
lstSelect.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "DocumentNo"));
lstSelect.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "C_BPartner_ID"));
lstSelect.setColumnClass(5, Timestamp.class, true, Msg.translate(Env.getCtx(), "DateOrdered"));
lstSelect.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
// Set Status
lblStatus.setValue(Msg.getMsg(Env.getCtx(), "InvGenerateSel"));
//statusBar.setStatusDB(" ");
}
private void populateWarehouse()
{
final int AD_Column_ID = 2223;
MLookup lookupBP = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, AD_Column_ID, DisplayType.TableDir);
warehouseSearch = new WTableDirEditor(lookupBP, Msg.translate(
Env.getCtx(), "M_Warehouse_ID"), "", true, false, true);
warehouseSearch.addValueChangeListner(this);
}
private void showBusinessPartner()
{
final int AD_BPartner_ID = 3499;
MLookup lookupBP = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, AD_BPartner_ID, DisplayType.Search);
bPartnerSearch = new WSearchEditor(lookupBP, Msg.translate(
Env.getCtx(), "C_BPartner_ID"), "", true, false, true);
bPartnerSearch.addValueChangeListner(this);
}
private void executeQuery()
{
log.info("");
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
// Create SQL
StringBuffer sql = new StringBuffer(
"SELECT C_Order_ID, o.Name, dt.Name, DocumentNo, bp.Name, DateOrdered, TotalLines "
+ "FROM M_InOut_Candidate_v ic, AD_Org o, C_BPartner bp, C_DocType dt "
+ "WHERE ic.AD_Org_ID=o.AD_Org_ID"
+ " AND ic.C_BPartner_ID=bp.C_BPartner_ID"
+ " AND ic.C_DocType_ID=dt.C_DocType_ID"
+ " AND ic.AD_Client_ID=?");
if (m_M_Warehouse_ID != null)
sql.append(" AND ic.M_Warehouse_ID=").append(m_M_Warehouse_ID);
if (m_C_BPartner_ID != null)
sql.append(" AND ic.C_BPartner_ID=").append(m_C_BPartner_ID);
// bug - [ 1713317 ] Generate Shipments (manual) show locked records
/* begin - Exclude locked records; @Trifon */
int AD_User_ID = Env.getContextAsInt(Env.getCtx(), "#AD_User_ID");
String lockedIDs = MPrivateAccess.getLockedRecordWhere(MOrder.Table_ID, AD_User_ID);
if (lockedIDs != null)
{
if (sql.length() > 0)
sql.append(" AND ");
sql.append("C_Order_ID").append(lockedIDs);
}
/* end - Exclude locked records; @Trifon */
sql.append(" ORDER BY o.Name,bp.Name,DateOrdered");
log.fine(sql.toString());
// Reset table
int row = 0;
if (lstSelect != null)
lstSelect.clearTable();
// Execute
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
// Extend table
lstSelect.setRowCount(row+1);
// Set values
lstSelect.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // C_Order_ID
lstSelect.setValueAt(rs.getString(2), row, 1); // Org
lstSelect.setValueAt(rs.getString(3), row, 2); // DocType
lstSelect.setValueAt(rs.getString(4), row, 3); // Doc No
lstSelect.setValueAt(rs.getString(5), row, 4); // BPartner
lstSelect.setValueAt(rs.getTimestamp(6), row, 5); // DateOrdered
lstSelect.setValueAt(rs.getBigDecimal(7), row, 6); // TotalLines
// Prepare next
row++;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
}
private void saveSelection()
{
log.info("");
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
if (selections != null)
selections.clear();
// Get Selected Entries
int rows = lstSelect.getItemCount();
for (int i = 0; i < rows; i++)
{
// ID in Column 0
IDColumn id = (IDColumn)lstSelect.getValueAt(i, 0);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return;
selections = results;
}
private void generateShipments()
{
log.info("M_Warehouse_ID=" + m_M_Warehouse_ID);
// Trx needs to be committed too
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true);
// Prevents from being called twice
m_selectionActive = false;
//lblStatus.setValue(Msg.getMsg(Env.getCtx(), "InOutGenerateGen"));
//statusBar.setStatusDB(String.valueOf(selection.size()));
// Prepare Process
// M_InOutCreate
int AD_Process_ID = 199;
MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
if (!instance.save())
{
//info.setText(Msg.getMsg(Env.getCtx(), "ProcessNoInstance"));
return;
}
// Insert selection
StringBuffer insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
int counter = 0;
for(Integer selectedId : selections)
{
counter++;
if (counter > 1)
insert.append(" UNION ");
insert.append("SELECT ");
insert.append(instance.getAD_PInstance_ID());
insert.append(", ");
insert.append(selectedId);
insert.append(" FROM DUAL ");
if (counter == 1000)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
//info.setText(msg);
trx.rollback();
return;
}
insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
counter = 0;
}
}
if (counter > 0)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
//info.setText(msg);
trx.rollback();
return;
}
}
// Call process
ProcessInfo pi = new ProcessInfo ("WInOutGen", AD_Process_ID);
pi.setAD_PInstance_ID (instance.getAD_PInstance_ID());
// Add Parameter - Selection = Y
MPInstancePara ip = new MPInstancePara(instance, 10);
ip.setParameter("Selection","Y");
if (!ip.save())
{
String msg = "No Parameter added"; // not translated
//info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
// Add Parameter - M_Warehouse_ID = x
ip = new MPInstancePara(instance, 20);
ip.setParameter("M_Warehouse_ID", Integer.parseInt(m_M_Warehouse_ID.toString()));
if (!ip.save())
{
String msg = "No Parameter added"; // not translated
//info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
// Execute Process
ProcessCtl worker = new ProcessCtl(null, super.m_windowNo, pi, trx);
worker.start(); // complete tasks in unlockUI / generateShipments_complete
lstSelect.clearTable();
displayInfo();
}
private void displayInfo()
{
lblGenerate.setValue("Created = " + selections.size());
lblNote.setValue("(Shipments are generated depending on the 'Delivery Rule' selection in the Order)");
lstGenerate.getChildren().clear();
for (int i = 0; i < selections.size(); i++)
{
ListItem listitem = new ListItem();
Timestamp time = new Timestamp(System.currentTimeMillis());
listitem.appendChild(new Listcell(time.toString()));
listitem.appendChild(new Listcell(selections.get(i).toString()));
lstGenerate.appendChild(listitem);
}
tabbox.setSelectedPanel(pnlGenerate);
}
private void generateInvoiceComplete (ProcessInfo pi)
{
}
public void onEvent(Event evt)
{
if (evt != null)
{
if (evt.getTarget() == tabSelect)
{
m_selectionActive = true;
executeQuery();
}
if ((evt.getTarget() == warehouseSearch) || (evt.getTarget() == bPartnerSearch))
{
if (evt.getTarget() == warehouseSearch)
{
m_M_Warehouse_ID = warehouseSearch.getValue();
}
if (evt.getTarget() == bPartnerSearch)
{
m_C_BPartner_ID = bPartnerSearch.getValue();
}
executeQuery();
}
if ((evt.getTarget() == btnOk) || (evt.getTarget() == btnCancel))
{
if (evt.getTarget() == btnCancel)
{
SessionManager.getAppDesktop().removeWindow();
}
saveSelection();
if (selections != null && selections.size() > 0 && m_selectionActive)
generateShipments();
else
SessionManager.getAppDesktop().removeWindow();
}
}
}
public void valueChange(ValueChangeEvent evt)
{
if (evt == null)
return;
if (evt.getSource() instanceof WEditor)
{
String name = evt.getPropertyName();
Object value = evt.getNewValue() == null ? "" : evt.getNewValue();
if (name.equals("C_BPartner_ID"))
{
bPartnerSearch.setValue(value);
m_C_BPartner_ID = ((Integer) value).intValue();
executeQuery();
}
if (name.equals("M_Warehouse_ID"))
{
warehouseSearch.setValue(value);
m_M_Warehouse_ID = ((Integer) value).intValue();
executeQuery();
}
}
}
public void tableChanged(WTableModelEvent event)
{
int rowsSelected = 0;
int rows = lstSelect.getItemCount();
for (int i = 0; i < rows; i++)
{
// ID in column 0
IDColumn id = (IDColumn)lstSelect.getValueAt(i, 0);
if (id != null && id.isSelected())
rowsSelected++;
}
// Set Status
Integer size = rowsSelected;
lblNumSelected.setValue("Number of Records Selected : " + size.toString());
}
}

View File

@ -0,0 +1,724 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListHead;
import org.adempiere.webui.component.ListHeader;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.Tab;
import org.adempiere.webui.component.Tabbox;
import org.adempiere.webui.component.Tabpanel;
import org.adempiere.webui.component.Tabpanels;
import org.adempiere.webui.component.Tabs;
import org.adempiere.webui.component.WListbox;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.editor.WTableDirEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.event.WTableModelEvent;
import org.adempiere.webui.event.WTableModelListener;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.compiere.apps.ProcessCtl;
import org.compiere.minigrid.IDColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MOrder;
import org.compiere.model.MPInstance;
import org.compiere.model.MPInstancePara;
import org.compiere.model.MPrivateAccess;
import org.compiere.process.ProcessInfo;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Separator;
/**
* Generate Invoices Manual : Based on VInvoiceGen
*
* @author Niraj Sohun
* @date Jul 5, 2007
*/
public class WInvoiceGen extends ADForm implements EventListener, ValueChangeListener, WTableModelListener
{
private static final long serialVersionUID = 1L;
private Separator separator;
private Tabbox tabbox;
private Tabs tabs;
private Tab tabSelect;
private Tab tabGenerate;
private Tabpanels tabpanels;
private Tabpanel pnlSelect;
private Tabpanel pnlGenerate;
// Panel Select
private WEditor organizationSearch;
private WEditor bPartnerSearch;
private WListbox lstSelect;
// Panel Generate
private Label lblGenerate;
private Label lblNote;
private Listbox lstGenerate;
private Button btnOk;
private Button btnCancel;
private Label lblStatus;
private Label lblNumSelected;
private boolean m_selectionActive = true;
private ArrayList<Integer> selections = null;
@SuppressWarnings("unused")
private Object m_AD_Org_ID;
@SuppressWarnings("unused")
private Object m_C_BPartner_ID;
private static CLogger log = CLogger.getCLogger(WInvoiceGen.class);
public WInvoiceGen()
{
init();
initComponents();
}
private void init()
{
separator = new Separator();
separator.setHeight("5px");
tabbox = new Tabbox();
tabbox.setWidth("700px");
tabs = new Tabs();
tabSelect = new Tab();
tabSelect.setLabel("Select");
tabSelect.addEventListener(Events.ON_SELECT, this);
tabGenerate = new Tab();
tabGenerate.setLabel("Generate");
tabGenerate.addEventListener(Events.ON_SELECT, this);
tabpanels = new Tabpanels();
pnlSelect = new Tabpanel();
pnlGenerate = new Tabpanel();
lstSelect = new WListbox();
lstSelect.setWidth("690px");
lstSelect.setHeight("250px");
lstSelect.addEventListener(Events.ON_SELECT, this);
lstSelect.getModel().addTableModelListener(this);
btnCancel = new Button();
btnCancel.setImage("/images/Cancel24.gif");
btnCancel.addEventListener(Events.ON_CLICK, this);
btnOk = new Button();
btnOk.setImage("/images/Ok24.gif");
btnOk.addEventListener(Events.ON_CLICK, this);
lblGenerate = new Label();
lblGenerate.setWidth("450px");
lblGenerate.setMultiline(true);
lblNote = new Label();
lblNote.setWidth("450px");
lblNote.setMultiline(true);
lblStatus = new Label(" ");
lblNumSelected = new Label("Number of Records Selected : 0");
lstGenerate = new Listbox();
lstGenerate.setWidth("300px");
populateOrganisation();
showBusinessPartner();
}
private void initComponents()
{
this.setWidth("710px");
tabs.appendChild(tabSelect);
tabs.appendChild(tabGenerate);
tabpanels.appendChild(pnlSelect);
tabpanels.appendChild(pnlGenerate);
tabbox.appendChild(tabs);
tabbox.appendChild(tabpanels);
Hbox mainBox = new Hbox();
mainBox.setWidth("100%");
mainBox.setStyle("text-align:center");
Hbox hOrg = new Hbox();
hOrg.setWidth("100%");
Hbox hBP = new Hbox();
hBP.setWidth("100%");
mainBox.appendChild(hOrg);
mainBox.appendChild(hBP);
Panel pnl1 = new Panel();
pnl1.appendChild(organizationSearch.getLabel());
pnl1.setStyle("text-align:right");
Panel pnl2 = new Panel();
pnl2.appendChild(organizationSearch.getComponent());
pnl2.setStyle("text-align:left");
Panel pnl3 = new Panel();
pnl3.appendChild(bPartnerSearch.getLabel());
pnl3.setStyle("text-align:right");
Panel pnl4 = new Panel();
pnl4.appendChild(bPartnerSearch.getComponent());
pnl4.setStyle("text-align:left");
hOrg.appendChild(pnl1);
hOrg.appendChild(pnl2);
hBP.appendChild(pnl3);
hBP.appendChild(pnl4);
pnlSelect.setStyle("text-align:center");
pnlSelect.appendChild(mainBox);
pnlSelect.appendChild(new Separator());
pnlSelect.appendChild(lstSelect);
pnlSelect.appendChild(new Separator());
pnlSelect.addEventListener(Events.ON_SELECT, this);
pnlGenerate.appendChild(lblGenerate);
pnlGenerate.appendChild(lblNote);
pnlGenerate.appendChild(new Separator());
pnlGenerate.appendChild(lstGenerate);
this.appendChild(tabbox);
this.appendChild(new Separator());
Hbox hbox = new Hbox();
hbox.setWidth("80px");
hbox.appendChild(btnCancel);
hbox.appendChild(btnOk);
//pnlSelect.appendChild(hbox);
//pnlSelect.appendChild(new Separator());
this.appendChild(hbox);
this.appendChild(new Separator());
hbox = new Hbox();
hbox.setWidth("700px");
Panel p = new Panel();
p.setStyle("text-align:left");
p.appendChild(lblStatus);
hbox.appendChild(p);
p = new Panel();
p.setStyle("text-align:right");
p.appendChild(lblNumSelected);
hbox.appendChild(p);
//pnlSelect.appendChild(hbox);
this.appendChild(hbox);
prepareTable();
populateOrganisation();
}
private void prepareTable()
{
// Create Columns
ListHead listhead = new ListHead();
listhead.setSizable(true);
listhead.appendChild(new ListHeader(""));
listhead.appendChild(new ListHeader("Organization"));
listhead.appendChild(new ListHeader("Document Type"));
listhead.appendChild(new ListHeader("Document No"));
listhead.appendChild(new ListHeader("Business Partner"));
listhead.appendChild(new ListHeader("Date Ordered"));
listhead.appendChild(new ListHeader("Total Lines"));
lstSelect.appendChild(listhead);
lstSelect.addColumn("C_Order_ID");
lstSelect.addColumn("AD_Org_ID");
lstSelect.addColumn("C_DocType_ID");
lstSelect.addColumn("DocumentNo");
lstSelect.addColumn("C_BPartner_ID");
lstSelect.addColumn("DateOrdered");
lstSelect.addColumn("TotalLines");
lstSelect.setMultiSelection(true);
// Set Details
lstSelect.setColumnClass(0, IDColumn.class, false, " ");
lstSelect.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
lstSelect.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "C_DocType_ID"));
lstSelect.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "DocumentNo"));
lstSelect.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "C_BPartner_ID"));
lstSelect.setColumnClass(5, Timestamp.class, true, Msg.translate(Env.getCtx(), "DateOrdered"));
lstSelect.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
// Set Status
lblStatus.setValue(Msg.getMsg(Env.getCtx(), "InvGenerateSel"));
//statusBar.setStatusDB(" ");
}
private void populateOrganisation()
{
final int AD_Column_ID = 2163;
MLookup lookupBP = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, AD_Column_ID, DisplayType.TableDir);
organizationSearch = new WTableDirEditor(lookupBP, Msg.translate(
Env.getCtx(), "AD_Org_ID"), "", true, false, true);
organizationSearch.addValueChangeListner(this);
}
private void showBusinessPartner()
{
final int AD_Column_ID = 3499;
MLookup lookupBP = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, AD_Column_ID, DisplayType.Search);
bPartnerSearch = new WSearchEditor(lookupBP, Msg.translate(
Env.getCtx(), "C_BPartner_ID"), "", true, false, true);
bPartnerSearch.addValueChangeListner(this);
}
private void executeQuery()
{
log.info("");
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
// Create SQL
StringBuffer sql = new StringBuffer(
"SELECT C_Order_ID, o.Name, dt.Name, DocumentNo, bp.Name, DateOrdered, TotalLines "
+ "FROM C_Invoice_Candidate_v ic, AD_Org o, C_BPartner bp, C_DocType dt "
+ "WHERE ic.AD_Org_ID=o.AD_Org_ID"
+ " AND ic.C_BPartner_ID=bp.C_BPartner_ID"
+ " AND ic.C_DocType_ID=dt.C_DocType_ID"
+ " AND ic.AD_Client_ID=?");
if (organizationSearch.getValue() != null)
{
sql.append(" AND ic.AD_Org_ID=").append(organizationSearch.getValue().toString());
}
if (bPartnerSearch.getDisplay() != "")
{
sql.append(" AND ic.C_BPartner_ID=").append(bPartnerSearch.getValue().toString());
}
// bug - [ 1713337 ] "Generate Invoices (manual)" show locked records.
/* begin - Exclude locked records; @Trifon */
int AD_User_ID = Env.getContextAsInt(Env.getCtx(), "#AD_User_ID");
String lockedIDs = MPrivateAccess.getLockedRecordWhere(MOrder.Table_ID, AD_User_ID);
if (lockedIDs != null)
{
if (sql.length() > 0)
sql.append(" AND ");
sql.append("C_Order_ID").append(lockedIDs);
}
/* end - Exclude locked records; @Trifon */
sql.append(" ORDER BY o.Name,bp.Name,DateOrdered");
// Reset Table
int row = 0;
lstSelect.clearTable();
// Execute
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
// Extend table
lstSelect.setRowCount(row+1);
// Set values
lstSelect.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // C_Order_ID
lstSelect.setValueAt(rs.getString(2), row, 1); // Org
lstSelect.setValueAt(rs.getString(3), row, 2); // DocType
lstSelect.setValueAt(rs.getString(4), row, 3); // Doc No
lstSelect.setValueAt(rs.getString(5), row, 4); // BPartner
lstSelect.setValueAt(rs.getTimestamp(6), row, 5); // DateOrdered
lstSelect.setValueAt(rs.getBigDecimal(7), row, 6); // TotalLines
// Prepare next
row++;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
// Set Status
//statusBar.setStatusDB(String.valueOf(miniTable.getRowCount()));
}
private void saveSelection()
{
log.info("");
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
if (selections != null)
selections.clear();
// Get Selected Entries
int rows = lstSelect.getItemCount();
for (int i = 0; i < rows; i++)
{
// ID in Column 0
IDColumn id = (IDColumn)lstSelect.getValueAt(i, 0);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return;
selections = results;
}
private void generateInvoices()
{
String trxName = Trx.createTrxName("IVG");
Trx trx = Trx.get(trxName, true); // Trx needs to be committed too
m_selectionActive = false; // Prevents from being called twice
// Set Status
//lblStatus.setValue(Msg.getMsg(Env.getCtx(), "InvGenerateGen"));
//statusBar.setStatusDB(String.valueOf(selections.size()));
// Prepare Process
int AD_Process_ID = 134; // C_InvoiceCreate
MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
if (!instance.save())
{
return;
}
// Insert selection
StringBuffer insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
int counter = 0;
for(Integer selectedId : selections)
{
counter++;
if (counter > 1)
insert.append(" UNION ");
insert.append("SELECT ");
insert.append(instance.getAD_PInstance_ID());
insert.append(", ");
insert.append(selectedId);
insert.append(" FROM DUAL ");
if (counter == 1000)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // Not translated!
log.config(msg);
trx.rollback();
return;
}
insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
counter = 0;
}
}
if (counter > 0)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // Not translated!
log.config(msg);
trx.rollback();
return;
}
}
ProcessInfo pi = new ProcessInfo ("", AD_Process_ID);
pi.setAD_PInstance_ID (instance.getAD_PInstance_ID());
// Add Parameters
MPInstancePara para = new MPInstancePara(instance, 10);
para.setParameter("Selection", "Y");
if (!para.save())
{
String msg = "No Selection Parameter added"; // Not translated
log.log(Level.SEVERE, msg);
return;
}
para = new MPInstancePara(instance, 20);
para.setParameter("DocAction", "CO");
if (!para.save())
{
String msg = "No DocAction Parameter added"; // Not translated
log.log(Level.SEVERE, msg);
return;
}
// Execute Process
ProcessCtl worker = new ProcessCtl(null, super.m_windowNo, pi, trx);
worker.start();
lstSelect.clearTable();
displayInfo();
}
private void displayInfo()
{
lblGenerate.setValue("Created = " + selections.size());
lblNote.setValue("(Invoices are generated depending on the 'Invoice Rule' selection in the Order)");
lstGenerate.getChildren().clear();
for (int i = 0; i < selections.size(); i++)
{
ListItem listitem = new ListItem();
Timestamp time = new Timestamp(System.currentTimeMillis());
listitem.appendChild(new Listcell(time.toString()));
listitem.appendChild(new Listcell(selections.get(i).toString()));
lstGenerate.appendChild(listitem);
}
tabbox.setSelectedPanel(pnlGenerate);
}
private void generateInvoiceComplete (ProcessInfo pi)
{
// Print invoices
int AD_Process_ID = 134;
/* for (int i = 0; i < selections.size(); i++)
{
ProcessModalDialog dialog = new ProcessModalDialog(
null, this.getTitle(), null, 0, AD_Process_ID,
table_ID, selections.get(i), true);
if (dialog.isValid())
{
dialog.setPosition("center");
try
{
dialog.doModal();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}*/
}
public void onEvent(Event evt)
{
if (evt != null)
{
if (evt.getTarget() == tabSelect)
{
m_selectionActive = true;
executeQuery();
}
if ((evt.getTarget() == organizationSearch) || (evt.getTarget() == bPartnerSearch))
{
if (evt.getTarget() == organizationSearch)
{
m_AD_Org_ID = organizationSearch.getValue();
}
if (evt.getTarget() == bPartnerSearch)
{
m_C_BPartner_ID = bPartnerSearch.getValue();
}
executeQuery();
}
if ((evt.getTarget() == btnOk) || (evt.getTarget() == btnCancel))
{
if (evt.getTarget() == btnCancel)
{
SessionManager.getAppDesktop().removeWindow();
}
saveSelection();
if (selections != null && selections.size() > 0 && m_selectionActive)
generateInvoices();
else
SessionManager.getAppDesktop().removeWindow();
}
}
}
public void valueChange(ValueChangeEvent evt)
{
if (evt == null)
return;
if (evt.getSource() instanceof WEditor)
{
String name = evt.getPropertyName();
Object value = evt.getNewValue() == null ? "" : evt.getNewValue();
if (name.equals("C_BPartner_ID"))
{
bPartnerSearch.setValue(value);
m_C_BPartner_ID = ((Integer) value).intValue();
executeQuery();
}
if (name.equals("AD_Org_ID"))
{
organizationSearch.setValue(value);
m_AD_Org_ID = ((Integer) value).intValue();
executeQuery();
}
}
}
public void tableChanged(WTableModelEvent event)
{
int rowsSelected = 0;
int rows = lstSelect.getItemCount();
for (int i = 0; i < rows; i++)
{
// ID in column 0
IDColumn id = (IDColumn)lstSelect.getValueAt(i, 0);
if (id != null && id.isSelected())
rowsSelected++;
}
// Set Status
Integer size = rowsSelected;
lblNumSelected.setValue("Number of Records Selected : " + size.toString());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,572 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.adempiere.webui.component.Grid;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.Row;
import org.adempiere.webui.component.Rows;
import org.adempiere.webui.component.WConfirmPanel;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.editor.WTableDirEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.adempiere.webui.window.FDialog;
import org.compiere.model.MBPartner;
import org.compiere.model.MInvoice;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MPayment;
import org.compiere.model.X_M_Cost;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
/**
* Merge Entities : Based on VMerge
*
* @author Niraj Sohun
* @date Jul 28, 2007
*/
public class WMerge extends ADForm implements EventListener, ValueChangeListener
{
private static final long serialVersionUID = 1L;
private static CLogger log = CLogger.getCLogger(WInvoiceGen.class);
private Grid grdAll;
private Rows rows;
private Row row;
/** Confirmation panel containing Ok and Cancel button. */
private WConfirmPanel m_pnlConfirm;
private WEditor[] from = new WEditor[4];
private WEditor[] to = new WEditor[4];
private int[] fromIDs = new int[4];
private int[] toIDs = new int[4];
private int[] AD_Column_ID = new int[] {2163, 2762, 971, 2221};
private String[] text = new String[] {"AD_Org_ID", "C_BPartner_ID", "AD_User_ID", "M_Product_ID"};
private int m_totalCount;
private StringBuffer m_errorLog;
private Trx m_trx;
static private String AD_ORG_ID = "AD_Org_ID";
static private String C_BPARTNER_ID = "C_BPartner_ID";
static private String AD_USER_ID = "AD_User_ID";
static private String M_PRODUCT_ID = "M_Product_ID";
/** Tables to delete (not update) for AD_Org */
static private String[] s_delete_Org = new String[] {"AD_OrgInfo"};
/** Tables to delete (not update) for AD_User */
static private String[] s_delete_User = new String[] {"AD_User_Roles"};
/** Tables to delete (not update) for C_BPartner */
static private String[] s_delete_BPartner = new String[] {"C_BP_Employee_Acct",
"C_BP_Vendor_Acct", "C_BP_Customer_Acct", "T_Aging"};
/** Tables to delete (not update) for M_Product */
static private String[] s_delete_Product = new String[] {"M_Product_PO", "M_Replenish", "T_Replenish",
"M_ProductPrice", "M_Product_Costing",
"M_Cost", // teo_sarca [ 1704554 ]
"M_Product_Trl", "M_Product_Acct"}; // M_Storage
private String[] m_columnName = new String[]{"AD_Org_ID", "C_BPartner_ID", "AD_User_ID", "M_Product_ID"};
private String[] m_deleteTables = null;
public WMerge()
{
init();
initComponents();
}
public void init()
{
grdAll = new Grid();
grdAll.setWidth("700px");
/*btnCancel = new Button();
btnCancel.setImage("/images/Cancel24.gif");
btnCancel.addEventListener(Events.ON_CLICK, this);
btnOk = new Button();
btnOk.setImage("/images/Ok24.gif");
btnOk.addEventListener(Events.ON_CLICK, this);*/
m_pnlConfirm = new WConfirmPanel(true);
m_pnlConfirm.addEventListener(this);
}
public void initComponents()
{
this.setWidth("710px");
this.setBorder("normal");
components();
rows = new Rows();
// Row 1
row = new Row();
row.appendChild(new Label(""));
row.appendChild(new Label("Merge From (Deleted)"));
row.appendChild(new Label("Merge To (Surviving)"));
rows.appendChild(row);
for (int i = 0; i < 4; i++)
{
row = new Row();
row.appendChild(from[i].getLabel());
row.appendChild(from[i].getComponent());
row.appendChild(to[i].getComponent());
rows.appendChild(row);
}
grdAll.appendChild(rows);
this.appendChild(grdAll);
// Row 6
this.appendChild(m_pnlConfirm);
}
private void components()
{
MLookup lookup = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, AD_Column_ID[0], DisplayType.TableDir);
from[0] = new WTableDirEditor(lookup, Msg.translate(
Env.getCtx(), text[0]), "from", true, false, true);
from[0].addValueChangeListner(this);
to[0] = new WTableDirEditor(lookup, Msg.translate(
Env.getCtx(), text[0]), "to", true, false, true);
to[0].addValueChangeListner(this);
// Search Editors
for (int i = 1; i < AD_Column_ID.length; i++)
{
lookup = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, AD_Column_ID[i], DisplayType.Search);
from[i] = new WSearchEditor(lookup, Msg.translate(
Env.getCtx(), text[i]), "from", true, false, true);
from[i].addValueChangeListner(this);
to[i] = new WSearchEditor(lookup, Msg.translate(
Env.getCtx(), text[i]), "to", true, false, true);
to[i].addValueChangeListner(this);
}
}
public void valueChange(ValueChangeEvent evt)
{
if (evt == null)
{
return;
}
WEditor edit = (WEditor)evt.getSource();
String des = edit.getDescription();
String name = evt.getPropertyName();
Object value = evt.getNewValue();
if (name.equals("AD_Org_ID"))
{
if (des == "from")
{
from[0].setValue(value);
fromIDs[0] = ((Integer)value).intValue();
}
else
{
to[0].setValue(value);
toIDs[0] = ((Integer)value).intValue();
}
}
else if (name.equals("C_BPartner_ID"))
{
if (des == "from")
{
from[1].setValue(value);
fromIDs[1] = ((Integer)value).intValue();
}
else
{
to[1].setValue(value);
toIDs[1] = ((Integer)value).intValue();
}
}
else if (name.equals("M_Product_ID"))
{
if (des == "from")
{
from[3].setValue(value);
fromIDs[3] = ((Integer)value).intValue();
}
else
{
to[3].setValue(value);
toIDs[3] = ((Integer)value).intValue();
}
}
else if (name.equals("AD_User_ID"))
{
if (des == "from")
{
from[2].setValue(value);
fromIDs[2] = ((Integer)value).intValue();
}
else
{
to[2].setValue(value);
toIDs[2] = ((Integer)value).intValue();
}
}
}
private boolean merge (String ColumnName, int from_ID, int to_ID)
{
String TableName = ColumnName.substring(0, ColumnName.length()-3);
//log.config(ColumnName + " - From=" + from_ID + ",To=" + to_ID);
boolean success = true;
m_totalCount = 0;
m_errorLog = new StringBuffer();
String sql = "SELECT t.TableName, c.ColumnName "
+ "FROM AD_Table t"
+ " INNER JOIN AD_Column c ON (t.AD_Table_ID=c.AD_Table_ID) "
+ "WHERE t.IsView='N'"
+ " AND t.TableName NOT IN ('C_TaxDeclarationAcct')"
+ " AND ("
+ "(c.ColumnName=? AND c.IsKey='N')" // #1 - direct
+ " OR "
+ "c.AD_Reference_Value_ID IN " // Table Reference
+ "(SELECT rt.AD_Reference_ID FROM AD_Ref_Table rt"
+ " INNER JOIN AD_Column cc ON (rt.AD_Table_ID=cc.AD_Table_ID AND rt.AD_Key=cc.AD_Column_ID) "
+ "WHERE cc.IsKey='Y' AND cc.ColumnName=?)" // #2
+ ") "
+ "ORDER BY t.LoadSeq DESC";
PreparedStatement pstmt = null;
try
{
m_trx = Trx.get(Trx.createTrxName("merge"), true);
pstmt = DB.prepareStatement(sql, Trx.createTrxName());
pstmt.setString(1, ColumnName);
pstmt.setString(2, ColumnName);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
String tName = rs.getString(1);
String cName = rs.getString(2);
if (!TableName.equals(tName)) // to be sure - sql should prevent it
{
int count = mergeTable (tName, cName, from_ID, to_ID);
if (count < 0)
success = false;
else
m_totalCount += count;
}
}
rs.close();
pstmt.close();
pstmt = null;
//log.config("Success=" + success + " - " + ColumnName + " - From=" + from_ID + ",To=" + to_ID);
if (success)
{
sql = "DELETE " + TableName + " WHERE " + ColumnName + "=" + from_ID;
if ( DB.executeUpdate(sql, m_trx.getTrxName()) < 0 )
{
m_errorLog.append(Env.NL).append("DELETE ").append(TableName).append(" - ");
success = false;
//log.config(m_errorLog.toString());
m_trx.rollback();
return false;
}
}
if (success)
m_trx.commit();
else
m_trx.rollback();
m_trx.close();
}
catch (Exception ex)
{
// log.log(Level.SEVERE, ColumnName, ex);
}
// Cleanup
try
{
if (pstmt != null)
pstmt.close();
}
catch (Exception ex)
{
}
pstmt = null;
return success;
}
/**
* Merge Table
* @param TableName table
* @param ColumnName column
* @param from_ID from
* @param to_ID to
* @return -1 for error or number of changes
*/
private int mergeTable (String TableName, String ColumnName, int from_ID, int to_ID)
{
// log.fine(TableName + "." + ColumnName + " - From=" + from_ID + ",To=" + to_ID);
String sql = "UPDATE " + TableName
+ " SET " + ColumnName + "=" + to_ID
+ " WHERE " + ColumnName + "=" + from_ID;
boolean delete = false;
for (int i = 0; i < m_deleteTables.length; i++)
{
if (m_deleteTables[i].equals(TableName))
{
delete = true;
sql = "DELETE " + TableName + " WHERE " + ColumnName + "=" + from_ID;
}
}
// Delete newly created MCost records - teo_sarca [ 1704554 ]
if (delete && X_M_Cost.Table_Name.equals(TableName) && M_PRODUCT_ID.equals(ColumnName))
{
sql += " AND " + X_M_Cost.COLUMNNAME_CurrentCostPrice + "=0"
+ " AND " + X_M_Cost.COLUMNNAME_CurrentQty + "=0"
+ " AND " + X_M_Cost.COLUMNNAME_CumulatedAmt + "=0"
+ " AND " + X_M_Cost.COLUMNNAME_CumulatedQty + "=0";
}
int count = DB.executeUpdate(sql, m_trx.getTrxName());
if ( count < 0 )
{
count = -1;
m_errorLog.append(Env.NL).append(delete ? "DELETE " : "UPDATE ").append(TableName).append(" - ").append(" - ").append(sql);
//log.config(m_errorLog.toString());
m_trx.rollback();
}
//log.fine(count + (delete ? " -Delete- " : " -Update- ") + TableName);
return count;
}
/**
* Post Merge
* @param ColumnName column name
* @param to_ID ID
*/
private void postMerge (String ColumnName, int to_ID)
{
if (ColumnName.equals(AD_ORG_ID))
{
}
else if (ColumnName.equals(AD_USER_ID))
{
}
else if (ColumnName.equals(C_BPARTNER_ID))
{
MBPartner bp = new MBPartner (Env.getCtx(), to_ID, null);
if (bp.get_ID() != 0)
{
MPayment[] payments = MPayment.getOfBPartner(Env.getCtx(), bp.getC_BPartner_ID(), null);
for (int i = 0; i < payments.length; i++)
{
MPayment payment = payments[i];
if (payment.testAllocation())
payment.save();
}
MInvoice[] invoices = MInvoice.getOfBPartner(Env.getCtx(), bp.getC_BPartner_ID(), null);
for (int i = 0; i < invoices.length; i++)
{
MInvoice invoice = invoices[i];
if (invoice.testAllocation())
invoice.save();
}
bp.setTotalOpenBalance();
bp.setActualLifeTimeValue();
bp.save();
}
}
else if (ColumnName.equals(M_PRODUCT_ID))
{
}
}
private void process()
{
String columnName = null;
String from_Info = null;
String to_Info = null;
int from_ID = 0;
int to_ID = 0;
for (int i = 0; (i < m_columnName.length && from_ID == 0 && to_ID == 0); i++)
{
Object value;
value = from[i].getValue();
if (value != null)
{
if (value instanceof Integer)
from_ID = ((Integer)value).intValue();
else
continue;
value = to[i].getValue();
if (value != null && value instanceof Integer)
to_ID = ((Integer)value).intValue();
else
from_ID = 0;
if (from_ID != 0)
{
columnName = m_columnName[i];
from_Info = from[i].getDisplay ();
to_Info = to[i].getDisplay ();
}
}
} // get first merge pair
if (from_ID == 0 || from_ID == to_ID)
return;
String msg = Msg.getMsg(Env.getCtx(), "MergeFrom") + " = " + from_Info
+ "\n" + Msg.getMsg(Env.getCtx(), "MergeTo") + " = " + to_Info;
//if (!FDialog.ask(super.m_windowNo, this, msg))
// return;
// ** Update **
if (columnName.equals(AD_ORG_ID))
m_deleteTables = s_delete_Org;
else if (columnName.equals(AD_USER_ID))
m_deleteTables = s_delete_User;
else if (columnName.equals(C_BPARTNER_ID))
m_deleteTables = s_delete_BPartner;
else if (columnName.equals(M_PRODUCT_ID))
m_deleteTables = s_delete_Product;
//setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//confirmPanel.getOKButton().setEnabled(false);
boolean success = merge (columnName, from_ID, to_ID);
postMerge(columnName, to_ID);
//confirmPanel.getOKButton().setEnabled(true);
//setCursor(Cursor.getDefaultCursor());
//
if (success)
{
FDialog.info (super.m_windowNo, this, msg);
}
else
{
FDialog.error(super.m_windowNo, this, "MergeError", m_errorLog.toString());
return;
}
}
/**
* React to Ok and Cancel buttons being triggered.
*
* @param event the event to which to respond
* @throws Exception if an exception occurred
*/
public void onEvent(Event event) throws Exception
{
if (event != null)
{
if (event.getName().equals(WConfirmPanel.A_CANCEL))
{
SessionManager.getAppDesktop().removeWindow();
return;
}
else if (event.getName().equals(WConfirmPanel.A_OK))
{
process();
}
}
}
}

View File

@ -0,0 +1,706 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.session.SessionManager;
import org.adempiere.webui.window.FDialog;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MLookupInfo;
import org.compiere.model.MPaySelectionCheck;
import org.compiere.model.MPaymentBatch;
import org.compiere.print.ReportCtl;
import org.compiere.print.ReportEngine;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Ini;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.compiere.util.ValueNamePair;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Hbox;
public class WPayPrint extends ADForm implements EventListener
{
/** Window No */
private int m_WindowNo = 0;
/** Used Bank Account */
private int m_C_BankAccount_ID = -1;
/** Payment Information */
private MPaySelectionCheck[] m_checks = null;
/** Payment Batch */
private MPaymentBatch m_batch = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(WPayPrint.class);
// Static Variables
private Hbox centerPanel = new Hbox();
private Hbox southPanel = new Hbox();
private Button bPrint = new Button();
private Button bExport = new Button();
private Button bCancel = new Button();
private Button bProcess = new Button();//(Msg.getMsg(Env.getCtx(), "VPayPrintProcess"));
private Label lPaySelect = new Label();
private Listbox fPaySelect = new Listbox();
private Label lBank = new Label();
private Label fBank = new Label();
private Label lPaymentRule = new Label();
private Listbox fPaymentRule = new Listbox();
private Label lDocumentNo = new Label();
private Textbox fDocumentNo = new Textbox();
private Label lNoPayments = new Label();
private Label fNoPayments = new Label();
private Label lBalance = new Label();
private Textbox fBalance = new Textbox();
private Label lCurrency = new Label();
private Label fCurrency = new Label();
public WPayPrint()
{
init(super.m_windowNo);
}
public void init (int WindowNo)
{
log.info("");
m_WindowNo = WindowNo;
try
{
jbInit();
dynInit();
this.appendChild(centerPanel);
this.appendChild(southPanel);
fPaySelect.setSelectedIndex(0);
loadPaySelectInfo();
}
catch(Exception e)
{
log.log(Level.SEVERE, "", e);
}
} // init
/**
* Static Init
* @throws Exception
*/
private void jbInit() throws Exception
{
fPaySelect.setRows(1);
fPaySelect.setMold("select");
fPaymentRule.setRows(1);
fPaymentRule.setMold("select");
bCancel.setImage("/images/Cancel24.gif");
bPrint.setImage("/images/Print24.gif");
bExport.setImage("/images/ExportX24.gif");
bPrint.addEventListener(Events.ON_CLICK, this);
bExport.addEventListener(Events.ON_CLICK, this);
bCancel.addEventListener(Events.ON_CLICK, this);
bProcess.setLabel(Msg.getMsg(Env.getCtx(), "EFT"));
bProcess.setEnabled(false);
bProcess.addEventListener(Events.ON_CLICK, this);
lPaySelect.setValue(Msg.translate(Env.getCtx(), "C_PaySelection_ID"));
fPaySelect.addEventListener(Events.ON_SELECT, this);
lBank.setValue(Msg.translate(Env.getCtx(), "C_BankAccount_ID"));
lPaymentRule.setValue(Msg.translate(Env.getCtx(), "PaymentRule"));
fPaymentRule.addEventListener(Events.ON_SELECT, this);
lDocumentNo.setValue(Msg.translate(Env.getCtx(), "DocumentNo"));
lNoPayments.setValue(Msg.getMsg(Env.getCtx(), "NoOfPayments"));
fNoPayments.setValue("0");
lBalance.setValue(Msg.translate(Env.getCtx(), "CurrentBalance"));
fBalance.setEnabled(false);
lCurrency.setValue(Msg.translate(Env.getCtx(), "C_Currency_ID"));
Hbox boxPaySelect = new Hbox();
fPaySelect.setWidth("100%");
boxPaySelect.setWidth("100%");
boxPaySelect.setWidths("40%, 60%");
boxPaySelect.appendChild(lPaySelect);
boxPaySelect.appendChild(fPaySelect);
Hbox boxBank = new Hbox();
boxBank.setWidth("100%");
boxBank.setWidths("40%, 60%");
boxBank.appendChild(lBank);
boxBank.appendChild(fBank);
Hbox boxPaymentRule = new Hbox();
boxPaymentRule.setWidth("100%");
boxPaymentRule.setWidths("40%, 60%");
boxPaymentRule.appendChild(lPaymentRule);
boxPaymentRule.appendChild(fPaymentRule);
Hbox boxDocNo = new Hbox();
boxDocNo.setWidth("100%");
boxDocNo.setWidths("40%, 60%");
boxDocNo.appendChild(lDocumentNo);
boxDocNo.appendChild(fDocumentNo);
Hbox boxNoPayments = new Hbox();
boxNoPayments.setWidth("100%");
boxNoPayments.setWidths("50%, 50%");
boxNoPayments.appendChild(lNoPayments);
boxNoPayments.appendChild(fNoPayments);
Hbox boxBalance = new Hbox();
boxBalance.setWidth("100%");
boxBalance.setWidths("50%, 50%");
boxBalance.appendChild(lBalance);
boxBalance.appendChild(fBalance);
Hbox boxCurrency = new Hbox();
boxCurrency.setWidth("100%");
boxCurrency.setWidths("50%, 50%");
boxCurrency.appendChild(lCurrency);
boxCurrency.appendChild(fCurrency);
centerPanel.setWidth("100%");
centerPanel.setWidths("65%, 35%");
VerticalBox vBox1 = new VerticalBox();
vBox1.setWidth("100%");
vBox1.appendChild(boxPaySelect);
vBox1.appendChild(boxBank);
vBox1.appendChild(boxPaymentRule);
vBox1.appendChild(boxDocNo);
VerticalBox vBox2 = new VerticalBox();
vBox2.setWidth("100%");
vBox2.appendChild(new Label(""));
vBox2.appendChild(boxBalance);
vBox2.appendChild(boxCurrency);
vBox2.appendChild(boxNoPayments);
centerPanel.appendChild(vBox1);
centerPanel.appendChild(vBox2);
southPanel.appendChild(bCancel);
southPanel.appendChild(bExport);
southPanel.appendChild(bPrint);
southPanel.appendChild(bProcess);
} // WPayPrint
/**
* Dynamic Init
*/
private void dynInit()
{
log.config("");
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
// Load PaySelect
String sql = "SELECT C_PaySelection_ID, Name || ' - ' || TotalAmt FROM C_PaySelection "
+ "WHERE AD_Client_ID=? AND Processed='Y' AND IsActive='Y'"
+ "ORDER BY PayDate DESC";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
KeyNamePair pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
fPaySelect.appendItem(pp.getName(), pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
if (fPaySelect.getItemCount() == 0)
FDialog.info(m_WindowNo, this, "VPayPrintNoRecords");
} // dynInit
/**
* Set Payment Selection
* @param C_PaySelection_ID id
*/
public void setPaySelection (int C_PaySelection_ID)
{
if (C_PaySelection_ID == 0)
return;
//
for (int i = 0; i < fPaySelect.getItemCount(); i++)
{
ListItem listitem = fPaySelect.getItemAtIndex(i);
KeyNamePair pp = null;
if (listitem != null)
pp = (KeyNamePair)listitem.getValue();
if (pp.getKey() == C_PaySelection_ID)
{
fPaySelect.setSelectedIndex(i);
return;
}
}
} // setsetPaySelection
/**************************************************************************
* Action Listener
* @param e event
*/
public void onEvent(Event e)
{
if (e.getTarget() == fPaySelect)
loadPaySelectInfo();
else if (e.getTarget() == fPaymentRule)
loadPaymentRuleInfo();
else if (e.getTarget() == bCancel)
SessionManager.getAppDesktop().removeWindow();
else if (e.getTarget() == bExport)
cmd_export();
else if (e.getTarget() == bProcess)
cmd_EFT();
else if (e.getTarget() == bPrint)
cmd_print();
} // actionPerformed
/**
* PaySelect changed - load Bank
*/
private void loadPaySelectInfo()
{
log.info( "VPayPrint.loadPaySelectInfo");
if (fPaySelect.getSelectedIndex() == -1)
return;
// load Banks from PaySelectLine
ListItem listitem = fPaySelect.getSelectedItem();
KeyNamePair key = null;
if (listitem != null)
key = (KeyNamePair)listitem.getValue();
int C_PaySelection_ID = key.getKey();
m_C_BankAccount_ID = -1;
String sql = "SELECT ps.C_BankAccount_ID, b.Name || ' ' || ba.AccountNo," // 1..2
+ " c.ISO_Code, CurrentBalance " // 3..4
+ "FROM C_PaySelection ps"
+ " INNER JOIN C_BankAccount ba ON (ps.C_BankAccount_ID=ba.C_BankAccount_ID)"
+ " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID)"
+ " INNER JOIN C_Currency c ON (ba.C_Currency_ID=c.C_Currency_ID) "
+ "WHERE ps.C_PaySelection_ID=? AND ps.Processed='Y' AND ba.IsActive='Y'";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_PaySelection_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_C_BankAccount_ID = rs.getInt(1);
fBank.setValue(rs.getString(2));
fCurrency.setValue(rs.getString(3));
fBalance.setValue(rs.getBigDecimal(4).toString());
}
else
{
m_C_BankAccount_ID = -1;
fBank.setValue("");
fCurrency.setValue("");
fBalance.setValue("0");
log.log(Level.SEVERE, "No active BankAccount for C_PaySelection_ID=" + C_PaySelection_ID);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
loadPaymentRule();
} // loadPaySelectInfo
/**
* Bank changed - load PaymentRule
*/
private void loadPaymentRule()
{
log.info("");
if (m_C_BankAccount_ID == -1)
return;
// load PaymentRule for Bank
ListItem listitem = fPaySelect.getSelectedItem();
KeyNamePair kp = null;
if (listitem != null)
kp = (KeyNamePair)listitem.getValue();
else
return;
int C_PaySelection_ID = kp.getKey();
fPaymentRule.getChildren().clear();
int AD_Reference_ID = 195; // MLookupInfo.getAD_Reference_ID("All_Payment Rule");
Language language = Language.getLanguage(Env.getAD_Language(Env.getCtx()));
MLookupInfo info = MLookupFactory.getLookup_List(language, AD_Reference_ID);
String sql = info.Query.substring(0, info.Query.indexOf(" ORDER BY"))
+ " AND " + info.KeyColumn
+ " IN (SELECT PaymentRule FROM C_PaySelectionCheck WHERE C_PaySelection_ID=?) "
+ info.Query.substring(info.Query.indexOf(" ORDER BY"));
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_PaySelection_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
ValueNamePair pp = new ValueNamePair(rs.getString(2), rs.getString(3));
fPaymentRule.appendItem(pp.getName(), pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
if (fPaymentRule.getItemCount() == 0)
log.config("PaySel=" + C_PaySelection_ID + ", BAcct=" + m_C_BankAccount_ID + " - " + sql);
fPaymentRule.setSelectedIndex(0);
loadPaymentRuleInfo();
} // loadPaymentRule
/**
* PaymentRule changed - load DocumentNo, NoPayments,
* enable/disable EFT, Print
*/
private void loadPaymentRuleInfo()
{
ListItem listitem = fPaymentRule.getSelectedItem();
ValueNamePair pp = null;
if (listitem != null)
pp = (ValueNamePair)listitem.getValue();
if (pp == null)
return;
String PaymentRule = pp.getValue();
log.info("PaymentRule=" + PaymentRule);
fNoPayments.setValue(" ");
listitem = fPaySelect.getSelectedItem();
KeyNamePair kp = null;
if (listitem != null)
kp = (KeyNamePair)listitem.getValue();
int C_PaySelection_ID = kp.getKey();
String sql = "SELECT COUNT(*) "
+ "FROM C_PaySelectionCheck "
+ "WHERE C_PaySelection_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_PaySelection_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
fNoPayments.setValue(String.valueOf(rs.getInt(1)));
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
bProcess.setEnabled(PaymentRule.equals("T"));
// DocumentNo
sql = "SELECT CurrentNext "
+ "FROM C_BankAccountDoc "
+ "WHERE C_BankAccount_ID=? AND PaymentRule=? AND IsActive='Y'";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, m_C_BankAccount_ID);
pstmt.setString(2, PaymentRule);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
fDocumentNo.setValue(new Integer(rs.getInt(1)).toString());
else
{
log.log(Level.SEVERE, "VPayPrint.loadPaymentRuleInfo - No active BankAccountDoc for C_BankAccount_ID="
+ m_C_BankAccount_ID + " AND PaymentRule=" + PaymentRule);
FDialog.error(m_WindowNo, this, "VPayPrintNoDoc");
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
} // loadPaymentRuleInfo
/**************************************************************************
* Export payments to file
*/
private void cmd_export()
{
ListItem listitem = fPaymentRule.getSelectedItem();
ValueNamePair vp = null;
if (listitem != null)
vp = (ValueNamePair)listitem.getValue();
String PaymentRule = null;
if (vp != null)
PaymentRule = vp.getValue();
log.info(PaymentRule);
if (!getChecks(PaymentRule))
return;
File file = null;
FileInputStream fstream = null;
int no = -1;
try
{
file = File.createTempFile("temp", "txt");
no = MPaySelectionCheck.exportToFile(m_checks, file);
fstream = new FileInputStream(file);
}
catch (IOException e1)
{
e1.printStackTrace();
}
Filedownload.save(fstream, "", file.getAbsolutePath());
// Create File
FDialog.info(m_WindowNo, this, "Saved",
file.getAbsolutePath() + "\n"
+ Msg.getMsg(Env.getCtx(), "NoOfLines") + "=" + no);
if (FDialog.ask(m_WindowNo, this, "VPayPrintSuccess?"))
{
// int lastDocumentNo =
MPaySelectionCheck.confirmPrint (m_checks, m_batch);
// document No not updated
}
SessionManager.getAppDesktop().removeWindow();
} // cmd_export
/**
* Create EFT payment
*/
private void cmd_EFT()
{
ListItem listitem = fPaymentRule.getSelectedItem();
ValueNamePair vp = null;
if (listitem != null)
vp = (ValueNamePair)listitem.getValue();
String PaymentRule = vp.getValue();
log.info(PaymentRule);
if (!getChecks(PaymentRule))
return;
SessionManager.getAppDesktop().removeWindow();
} // cmd_EFT
/**
* Print Checks and/or Remittance
*/
private void cmd_print()
{
ListItem listitem = fPaymentRule.getSelectedItem();
ValueNamePair vp = null;
if (listitem != null)
vp = (ValueNamePair)listitem.getValue();
String PaymentRule = vp.getValue();
log.info(PaymentRule);
if (!getChecks(PaymentRule))
return;
boolean somethingPrinted = false;
boolean directPrint = !Ini.isPropertyBool(Ini.P_PRINTPREVIEW);
// for all checks
for (int i = 0; i < m_checks.length; i++)
{
MPaySelectionCheck check = m_checks[i];
// ReportCtrl will check BankAccountDoc for PrintFormat
boolean ok = ReportCtl.startDocumentPrint(ReportEngine.CHECK, check.get_ID(), null, super.m_windowNo, directPrint);
if (!somethingPrinted && ok)
somethingPrinted = true;
}
// Confirm Print and Update BankAccountDoc
if (somethingPrinted && FDialog.ask(m_WindowNo, this, "VPayPrintSuccess?"))
{
int lastDocumentNo = MPaySelectionCheck.confirmPrint (m_checks, m_batch);
if (lastDocumentNo != 0)
{
StringBuffer sb = new StringBuffer();
sb.append("UPDATE C_BankAccountDoc SET CurrentNext=").append(++lastDocumentNo)
.append(" WHERE C_BankAccount_ID=").append(m_C_BankAccount_ID)
.append(" AND PaymentRule='").append(PaymentRule).append("'");
DB.executeUpdate(sb.toString(), null);
}
} // confirm
if (FDialog.ask(m_WindowNo, this, "VPayPrintPrintRemittance"))
{
for (int i = 0; i < m_checks.length; i++)
{
MPaySelectionCheck check = m_checks[i];
ReportCtl.startDocumentPrint(ReportEngine.REMITTANCE, check.get_ID(), null, super.m_windowNo, directPrint);
}
} // remittance
SessionManager.getAppDesktop().removeWindow();
} // cmd_print
/**************************************************************************
* Get Checks
* @param PaymentRule Payment Rule
* @return true if payments were created
*/
private boolean getChecks(String PaymentRule)
{
// do we have values
if (fPaySelect.getSelectedIndex() == -1 || m_C_BankAccount_ID == -1
|| fPaymentRule.getSelectedIndex() == -1 || fDocumentNo.getValue() == null)
{
FDialog.error(m_WindowNo, this, "VPayPrintNoRecords",
"(" + Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID") + "=0)");
return false;
}
// get data
ListItem listitem = fPaySelect.getSelectedItem();
KeyNamePair kp = null;
if (listitem != null)
kp = (KeyNamePair)listitem.getValue();
int C_PaySelection_ID = kp.getKey();
int startDocumentNo = new Integer(fDocumentNo.getValue());
log.config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo);
// get Selections
m_checks = MPaySelectionCheck.get(C_PaySelection_ID, PaymentRule, startDocumentNo, null);
if (m_checks == null || m_checks.length == 0)
{
FDialog.error(m_WindowNo, this, "VPayPrintNoRecords",
"(" + Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID") + " #0");
return false;
}
m_batch = MPaymentBatch.getForPaySelection (Env.getCtx(), C_PaySelection_ID, null);
return true;
} // getChecks
}

View File

@ -0,0 +1,840 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import org.adempiere.webui.apps.ProcessModalDialog;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.component.Datebox;
import org.adempiere.webui.component.Grid;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Row;
import org.adempiere.webui.component.Rows;
import org.adempiere.webui.component.WListbox;
import org.adempiere.webui.event.WTableModelEvent;
import org.adempiere.webui.event.WTableModelListener;
import org.adempiere.webui.panel.ADForm;
import org.adempiere.webui.window.FDialog;
import org.compiere.minigrid.ColumnInfo;
import org.compiere.minigrid.IDColumn;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MLookupInfo;
import org.compiere.model.MPaySelection;
import org.compiere.model.MPaySelectionLine;
import org.compiere.model.MRole;
import org.compiere.model.X_C_Order;
import org.compiere.model.X_C_PaySelection;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.compiere.util.ValueNamePair;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Separator;
/**
* Pay Selection Manual Custom Form : Based on VPaySelect
*
* @author Niraj Sohun
* @date Jun 25, 2007
*/
public class WPaySelect extends ADForm implements EventListener, WTableModelListener
{
private static final long serialVersionUID = 1L;
/** Logger */
private static CLogger log = CLogger.getCLogger(WPaySelect.class);
// Input Part of Form
private Grid parameters;
private Rows rows;
private Row row1;
private Row row2;
private Row row3;
// Labels
private Label lblBalanceAmt;
private Label lblBottom;
// Components
private Listbox lstBankAccount;
private Listbox lstBusinessPartner;
private Checkbox dueInvoices;
private Datebox date;
private Listbox lstPaymentRule;
private Button refresh;
private Button btnProcess;
// Data Grid
private WListbox dataTable;
private int m_AD_Client_ID = 0;
private String m_sql = "";
private DecimalFormat m_format = DisplayType.getNumberFormat(DisplayType.Amount);
private Float currentBalance;
/**
*
*
*/
public WPaySelect()
{
init();
}
/**
*
*
*/
private void init()
{
dataTable = new WListbox();
dataTable.setWidth("700px");
dataTable.setMultiple(true);
// Input Part of Form
parameters = new Grid();
parameters.setWidth("700px");
parameters.setAlign("center");
rows = new Rows();
row1 = new Row();
row2 = new Row();
row3 = new Row();
// Components
lblBalanceAmt = new Label();
lblBottom = new Label();
lstBankAccount = new Listbox();
lstBankAccount.setWidth("150px");
lstBankAccount.setRows(1);
lstBankAccount.setMold("select");
lstBankAccount.addEventListener(Events.ON_SELECT, this);
lstBusinessPartner = new Listbox();
lstBusinessPartner.setWidth("150px");
lstBusinessPartner.setRows(1);
lstBusinessPartner.setMold("select");
lstBusinessPartner.addEventListener(Events.ON_SELECT, this);
dueInvoices = new Checkbox();
dueInvoices.setLabel(Msg.getMsg(Env.getCtx(), "OnlyDue"));
dueInvoices.addEventListener(Events.ON_SELECT, this);
date = new Datebox();
date.setWidth("150px");
date.setValue(new Timestamp(System.currentTimeMillis()));
date.addEventListener(Events.ON_SELECT, this);
lstPaymentRule = new Listbox();
lstPaymentRule.setWidth("150px");
lstPaymentRule.setWidth("150px");
lstPaymentRule.setRows(1);
lstPaymentRule.setMold("select");
lstPaymentRule.addEventListener(Events.ON_SELECT, this);
refresh = new Button();
refresh.setImage("/images/Refresh24.gif");
refresh.addEventListener(Events.ON_CLICK, this);
btnProcess = new Button();
btnProcess.setImage("/images/Process24.gif");
btnProcess.setEnabled(false);
btnProcess.addEventListener(Events.ON_CLICK, this);
display();
}
/**
*
*
*/
private void display()
{
row1.appendChild(new Label("Bank Account"));
row1.appendChild(lstBankAccount);
row1.appendChild(new Label("Current Balance"));
row1.appendChild(lblBalanceAmt);
row2.setSpans(",2,");
row2.appendChild(new Label("Business Partner"));
row2.appendChild(lstBusinessPartner);
row2.appendChild(dueInvoices);
row3.appendChild(new Label("Payment Date"));
row3.appendChild(date);
row3.appendChild(new Label("Payment Rule"));
row3.appendChild(lstPaymentRule);
rows.appendChild(row1);
rows.appendChild(row2);
rows.appendChild(row3);
parameters.appendChild(rows);
Hbox mainBox = new Hbox();
mainBox.setWidth("700px");
Hbox hboxButtons = new Hbox();
hboxButtons.setWidth("80px");
hboxButtons.appendChild(btnProcess);
hboxButtons.appendChild(refresh);
Hbox hLbl = new Hbox();
hLbl.appendChild(lblBottom);
mainBox.appendChild(hboxButtons);
mainBox.appendChild(hLbl);
this.setHeight("710px");
this.setWidth("100%");
this.setBorder("normal");
this.appendChild(parameters);
this.appendChild(new Separator());
this.appendChild(dataTable);
this.appendChild(new Separator());
this.appendChild(mainBox);
populateBankAccount();
populateBusinessPartner();
populateGrid();
}
/**
*
*
*/
private void process()
{
int adProcessId = 155;
String trxName = null;
calculateSelection();
MPaySelection m_ps = new MPaySelection(Env.getCtx(), 0, trxName);
ListItem payRule = lstPaymentRule.getSelectedItem();
Timestamp payDate = (Timestamp)date.getValue();
m_ps.setName (Msg.getMsg(Env.getCtx(), "WPaySelect")
+ " - " + ((ValueNamePair)payRule.getValue()).getName()
+ " - " + payDate);
m_ps.setPayDate (payDate);
BankInfo bi = getSelectedBankAccount();
m_ps.setC_BankAccount_ID(bi.C_BankAccount_ID);
m_ps.setIsApproved(true);
if (!m_ps.save())
{
FDialog.error(super.m_windowNo, this, "SaveError", Msg.translate(Env.getCtx(), "C_PaySelection_ID"));
m_ps = null;
return;
}
// Create Lines
int rows = dataTable.getItemCount();
int line = 0;
ListItem pyRule = lstPaymentRule.getSelectedItem();
String strPayRule = ((ValueNamePair)pyRule.getValue()).getValue();
for (int i = 0; i < rows; i++)
{
if (dataTable.getItemAtIndex(i).isSelected())
{
line += 10;
MPaySelectionLine psl = new MPaySelectionLine (m_ps, line, strPayRule);
// List<ListCell> celllist = (List<ListCell>)(dataTable.getItemAtIndex(i).getChildren());
// ListCell invID = celllist.get(0);
// ListCell openAmt = celllist.get(8);
// ListCell payAmt = celllist.get(9);
IDColumn id = (IDColumn)dataTable.getValueAt(i, 0);
Integer C_Invoice_ID = id.getRecord_ID();
BigDecimal OpenAmt = new BigDecimal(dataTable.getValueAt(i, 8).toString());
BigDecimal PayAmt = new BigDecimal(dataTable.getValueAt(i, 9).toString());
boolean isSOTrx = false;
psl.setInvoice(C_Invoice_ID, isSOTrx, OpenAmt, PayAmt, OpenAmt.subtract(PayAmt));
if (!psl.save(trxName))
{
FDialog.error(this.m_windowNo, this, "SaveError", Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID"));
return;
}
log.fine("C_Invoice_ID=" + C_Invoice_ID
+ ", PayAmt=" + PayAmt);
}
}
// Ask to Post it
if (!FDialog.ask(this.m_windowNo, this, "(" + m_ps.getName() + ")"))
{
return;
}
ProcessModalDialog msg = new ProcessModalDialog(
this, "Payment Selection Manual", null, this.m_windowNo, adProcessId,
X_C_PaySelection.Table_ID, m_ps.getC_PaySelection_ID(), true);
if (msg.isValid())
{
msg.setTitle("Payment Selection (Manual)");
msg.setPage(this.getPage());
msg.setClosable(true);
msg.setWidth("500px");
try
{
msg.doModal();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void calculateSelection()
{
int noSelected = 0;
BigDecimal invoiceAmt = new BigDecimal(0.0);
int rows = dataTable.getRowCount();
for (int rowIndex = 0; rowIndex < rows; rowIndex++)
{
// TODO remove this magic number
IDColumn id = (IDColumn)dataTable.getValueAt(rowIndex, 0);
if (id.isSelected())
{
// TODO remove this magic number
BigDecimal amt = (BigDecimal)dataTable.getValueAt(rowIndex, 9);
invoiceAmt = invoiceAmt.add(amt);
noSelected++;
}
}
// Information
BankInfo bi = getSelectedBankAccount();
BigDecimal remaining = bi.Balance.subtract(invoiceAmt);
StringBuffer info = new StringBuffer();
info.append(noSelected).append(" ").append(Msg.getMsg(Env.getCtx(), "Selected")).append(" - ");
info.append(m_format.format(invoiceAmt)).append(", ");
info.append(Msg.getMsg(Env.getCtx(), "Remaining")).append(" ").append(m_format.format(remaining));
lblBottom.setValue(info.toString());
if (noSelected == 0)
{
btnProcess.setEnabled(false);
}
else
{
btnProcess.setEnabled(true);
}
return;
}
/**
* Obtain details of the selected bank account
*
* @return the BankInfo of the selected account
*/
private BankInfo getSelectedBankAccount()
{
ListItem bankAccountItem = lstBankAccount.getSelectedItem();
BankInfo bi = (BankInfo)bankAccountItem.getValue();
return bi;
}
private void populateBankAccount()
{
String sql = MRole.getDefault().addAccessSQL(
"SELECT ba.C_BankAccount_ID," // 1
+ "b.Name || ' ' || ba.AccountNo AS Name," // 2
+ "ba.C_Currency_ID, c.ISO_Code," // 3..4
+ "ba.CurrentBalance " // 5
+ "FROM C_Bank b, C_BankAccount ba, C_Currency c "
+ "WHERE b.C_Bank_ID=ba.C_Bank_ID"
+ " AND ba.C_Currency_ID=c.C_Currency_ID "
+ " AND EXISTS (SELECT * FROM C_BankAccountDoc d WHERE d.C_BankAccount_ID=ba.C_BankAccount_ID) "
+ "ORDER BY 2",
"b", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RW);
BankInfo bi = null;
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
boolean Transfers = false;
bi = new BankInfo (rs.getInt(1), rs.getInt(3), rs.getString(2), rs.getString(4), rs.getBigDecimal(5), Transfers);
lstBankAccount.appendItem(bi.Name, bi);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
if (lstBankAccount.getItemCount() == 0)
{
throw new IllegalStateException("No Bank Account has been found");
}
else
{
// Selecting the first item
lstBankAccount.setSelectedIndex(0);
populatePaymentRule();
updateCurrentBalance();
}
}
private void updateCurrentBalance()
{
BankInfo bnkInf = getSelectedBankAccount();
currentBalance = bnkInf.Balance.floatValue();
lblBalanceAmt.setValue(currentBalance.toString() + " " + bnkInf.Currency);
lblBottom.setValue("");
}
/**
* Query the database for Business Partners and populate the Business
* Partner combobox with the returned resultset
*/
private void populateBusinessPartner()
{
KeyNamePair pp = new KeyNamePair(0, "");
lstBusinessPartner.appendItem(pp.getName(), pp);
String sql = MRole.getDefault().addAccessSQL(
"SELECT bp.C_BPartner_ID, bp.Name FROM C_BPartner bp", "bp",
MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
+ " AND EXISTS (SELECT * FROM C_Invoice i WHERE bp.C_BPartner_ID=i.C_BPartner_ID"
+ " AND (i.IsSOTrx='N' OR (i.IsSOTrx='Y' AND i.PaymentRule='D'))"
+ " AND i.IsPaid<>'Y') "
+ "ORDER BY 2";
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
lstBusinessPartner.appendItem(pp.getName(), pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
// TODO need to do something with this exception
log.log(Level.SEVERE, sql, e);
}
lstBusinessPartner.setSelectedIndex(0);
}
/**
* Query the database for Payment Rules and populate the Payment
* Rules combobox with the returned resultset
*/
private void populatePaymentRule()
{
ListItem temp = lstBankAccount.getSelectedItem();
BankInfo bankInfo = (BankInfo)temp.getValue();
if (bankInfo == null)
{
return;
}
// PaymentRule
lstPaymentRule.getChildren().clear();
int AD_Reference_ID = 195; //TODO: Find this reference in the models
Language language = Env.getLanguage(Env.getCtx());
MLookupInfo info = MLookupFactory.getLookup_List(language, AD_Reference_ID);
String sql = info.Query.substring(0, info.Query.indexOf(" ORDER BY"))
+ " AND " + info.KeyColumn
+ " IN (SELECT PaymentRule FROM C_BankAccountDoc WHERE C_BankAccount_ID=?) "
+ info.Query.substring(info.Query.indexOf(" ORDER BY"));
try
{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, bankInfo.C_BankAccount_ID);
ResultSet rs = pstmt.executeQuery();
ValueNamePair vp = null;
while (rs.next())
{
vp = new ValueNamePair(rs.getString(2), rs.getString(3)); // returns also not active
lstPaymentRule.appendItem(vp.getName(), vp);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
lstPaymentRule.setSelectedIndex(0);
}
/**
* Prepare the data table
*
*/
private void prepareGrid()
{
// FROM VPaySelect.dynInit
// MiniTable Parameters
Properties ctx = Env.getCtx();
ColumnInfo[] columnInfo = new ColumnInfo[10];
columnInfo[0] = new ColumnInfo(" ", "i.C_Invoice_ID", IDColumn.class, false, false, null);
columnInfo[1] = new ColumnInfo(Msg.translate(ctx, "DueDate"), "paymentTermDueDate(i.C_PaymentTerm_ID, i.DateInvoiced) AS DateDue", Timestamp.class, true, true, null);
columnInfo[2] = new ColumnInfo(Msg.translate(ctx, "C_BPartner_ID"), "bp.Name", KeyNamePair.class, true, false, "i.C_BPartner_ID");
columnInfo[3] = new ColumnInfo(Msg.translate(ctx, "DocumentNo"), "i.DocumentNo", String.class);
columnInfo[4] = new ColumnInfo(Msg.translate(ctx, "C_Currency_ID"), "c.ISO_Code", KeyNamePair.class, true, false, "i.C_Currency_ID");
columnInfo[5] = new ColumnInfo(Msg.translate(ctx, "GrandTotal"), "i.GrandTotal", BigDecimal.class);
columnInfo[6] = new ColumnInfo(Msg.translate(ctx, "DiscountAmt"), "paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?)", BigDecimal.class);
columnInfo[7] = new ColumnInfo(Msg.getMsg(ctx, "DiscountDate"), "SysDate-paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced,SysDate)", Timestamp.class);
columnInfo[8] = new ColumnInfo(Msg.getMsg(ctx, "AmountDue"), "currencyConvert(invoiceOpen(i.C_Invoice_ID,i.C_InvoicePaySchedule_ID),i.C_Currency_ID, ?,?,i.C_ConversionType_ID, i.AD_Client_ID,i.AD_Org_ID)", BigDecimal.class);
columnInfo[9] = new ColumnInfo(Msg.getMsg(ctx, "AmountPay"), "currencyConvert(invoiceOpen(i.C_Invoice_ID,i.C_InvoicePaySchedule_ID)-paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?),i.C_Currency_ID, ?,?,i.C_ConversionType_ID, i.AD_Client_ID,i.AD_Org_ID)", BigDecimal.class);
String fromClause = "C_Invoice_v i"
+ " INNER JOIN C_BPartner bp ON (i.C_BPartner_ID=bp.C_BPartner_ID)"
+ " INNER JOIN C_Currency c ON (i.C_Currency_ID=c.C_Currency_ID)"
+ " INNER JOIN C_PaymentTerm p ON (i.C_PaymentTerm_ID=p.C_PaymentTerm_ID)";
String whereClause = "i.IsSOTrx=? AND IsPaid='N'"
+ " AND NOT EXISTS (SELECT * FROM C_PaySelectionLine psl"
+ " WHERE i.C_Invoice_ID=psl.C_Invoice_ID AND psl.C_PaySelectionCheck_ID IS NOT NULL)"
+ " AND i.DocStatus IN ('CO','CL')"
+ " AND i.AD_Client_ID=?";
boolean multiSelect = true;
String tableName = "i";
// Create MiniTable
m_sql = dataTable.prepareTable(columnInfo, fromClause, whereClause, multiSelect,tableName);
dataTable.getModel().addTableModelListener(this);
//TODO
//fieldPayDate.setMandatory(true);
m_AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
}
private void populateGrid()
{
prepareGrid();
// FROM VPaySelect.loadTableInfo
if (m_sql == null)
{
return;
}
String sql = m_sql;
// Parameters
Timestamp payDate = (Timestamp)date.getValue();
dataTable.setColorCompare(payDate);
log.config("PayDate=" + payDate);
// Bank Account
BankInfo bi = getSelectedBankAccount();
String isSOTrx = "N";
// Payment Rule
ListItem selectedRule = lstPaymentRule.getSelectedItem();
ValueNamePair vp = (ValueNamePair)selectedRule.getValue();
if (vp != null && X_C_Order.PAYMENTRULE_DirectDebit.equals(vp.getValue()))
{
isSOTrx = "Y";
sql += " AND i.PaymentRule='" + X_C_Order.PAYMENTRULE_DirectDebit + "'";
}
if (dueInvoices.isChecked())
{
sql += " AND paymentTermDueDate(i.C_PaymentTerm_ID, i.DateInvoiced) <= ?";
}
// Business Partner
ListItem selectedBPartner = lstBusinessPartner.getSelectedItem();
KeyNamePair pp = (KeyNamePair)selectedBPartner.getValue();
int C_BPartner_ID = pp.getKey();
if (C_BPartner_ID != 0)
sql += " AND i.C_BPartner_ID=?";
sql += " ORDER BY 2,3";
log.finest(sql + " - C_Currecny_ID=" + bi.C_Currency_ID + ", C_BPartner_ID=" + C_BPartner_ID);
//int m_AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
// Get Open Invoices
try
{
int columnIndex = 1;
PreparedStatement pstmt = DB.prepareStatement(sql, null);
pstmt.setTimestamp(columnIndex++, payDate); // DiscountAmt
pstmt.setInt(columnIndex++, bi.C_Currency_ID); // DueAmt
pstmt.setTimestamp(columnIndex++, payDate);
pstmt.setTimestamp(columnIndex++, payDate); // PayAmt
pstmt.setInt(columnIndex++, bi.C_Currency_ID);
pstmt.setTimestamp(columnIndex++, payDate);
pstmt.setString(columnIndex++, isSOTrx); // IsSOTrx
pstmt.setInt(columnIndex++, m_AD_Client_ID); // Client
if (dueInvoices.isChecked())
{
pstmt.setTimestamp(columnIndex++, payDate);
}
if (C_BPartner_ID != 0)
{
pstmt.setInt(columnIndex++, C_BPartner_ID);
}
ResultSet rs = pstmt.executeQuery();
dataTable.loadTable(rs);
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql, e);
}
}
public void onEvent(Event evt) throws Exception
{
if (evt != null)
{
if (evt.getTarget() == lstBankAccount)
{
populatePaymentRule();
updateCurrentBalance();
dataTable.getItems().clear();
populateGrid();
}
if (evt.getTarget() == lstBusinessPartner)
{
dataTable.getItems().clear();
populateGrid();
}
if (evt.getTarget() == lstPaymentRule)
{
dataTable.getItems().clear();
populateGrid();
}
if (evt.getTarget() == dueInvoices)
{
dataTable.getItems().clear();
populateGrid();
}
if (evt.getTarget() == date)
{
dataTable.getItems().clear();
populateGrid();
}
if (evt.getTarget() == refresh)
{
dataTable.clear();
populateGrid();
}
if (evt.getTarget() == btnProcess)
{
if (dataTable.getSelectedCount() <= 0)
{
btnProcess.setEnabled(false);
throw new IllegalArgumentException("No records selected");
}
process();
}
if (evt.getTarget() instanceof ListItem)
{
btnProcess.setEnabled(true);
ListItem lstitem = (ListItem)(evt.getTarget());
if (lstitem.isSelected())
{
dataTable.addItemToSelection(lstitem);
}
Integer size = dataTable.getSelectedCount();
Float amt = calculateTotalAmount();
Float remaining = currentBalance - amt;
lblBottom.setValue(size.toString() + " Selected :: " + amt.toString() + ", Remaining " + remaining.toString());
}
}
}
private Float calculateTotalAmount()
{
Float amount = new Float(0);
for (int i = 0; i < dataTable.getItemCount(); i++)
{
if (dataTable.getItemAtIndex(i).isSelected())
{
List<Listcell> celllist = (List<Listcell>)(dataTable.getItemAtIndex(i).getChildren());
Listcell payAmt = celllist.get(9);
amount += new Float(payAmt.getLabel());
}
}
return amount;
}
/* (non-Javadoc)
* @see org.adempiere.webui.event.WTableModelListener#tableChanged(org.adempiere.webui.event.WTableModelEvent)
*/
public void tableChanged(WTableModelEvent event)
{
if (event.getColumn() == 0)
{
calculateSelection();
}
}
public class BankInfo
{
/**
* BankInfo
* @param newC_BankAccount_ID
* @param newC_Currency_ID
* @param newName
* @param newCurrency
* @param newBalance
* @param newTransfers
*/
public BankInfo (int newC_BankAccount_ID, int newC_Currency_ID, String newName, String newCurrency, BigDecimal newBalance, boolean newTransfers)
{
C_BankAccount_ID = newC_BankAccount_ID;
C_Currency_ID = newC_Currency_ID;
Name = newName;
Currency = newCurrency;
Balance = newBalance;
}
int C_BankAccount_ID;
int C_Currency_ID;
String Name;
String Currency;
BigDecimal Balance;
boolean Transfers;
/**
* to String
* @return info
*/
public String toString()
{
return Name;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,175 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Grid;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.Row;
import org.adempiere.webui.component.Rows;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.panel.ADForm;
import org.compiere.apps.form.VSQLProcess;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* A Custom Form to specify and process SQL statements.
*
* The range of statement types that can be performed can be restricted
* by allowing or disallowing DML statements.
*
* @author Andrew Kimball
*
*/
public class WSQLProcess extends ADForm implements EventListener
{
/** Serial Version Unique Identifier. */
private static final long serialVersionUID = 1L;
/** Log. */
private static CLogger log = CLogger.getCLogger(VSQLProcess.class);
/** Grid used to layout components. */
private Grid m_grdMain = new Grid();
/** SQL label. */
private Label m_lblSql = new Label("SQL");
/** SQL statement field. */
private Textbox m_txbSqlField = new Textbox();
/** Process button. */
private Button m_btnSql = createProcessButton();
/** Field to hold result of SQL statement execution. */
private Textbox m_txbResultField = new Textbox();
/**
* Default constructor.
*/
public WSQLProcess()
{
super();
}
/*
* (non-Javadoc)
* @see org.adempiere.webui.panel.ADForm#init(int, java.lang.String)
*/
public void init(int adFormId, String name)
{
Row rwTop = new Row();
Row rwBottom = new Row();
Rows rows = new Rows();
final int noColumns = 60;
final int maxStatementLength = 9000;
final int noStatementRows = 3;
final int noResultRows = 20;
super.init(adFormId, name);
m_grdMain.setWidth("80%");
// create the top row of components
m_txbSqlField.setMultiline(true);
m_txbSqlField.setMaxlength(maxStatementLength);
m_txbSqlField.setRows(noStatementRows);
m_txbSqlField.setCols(noColumns);
m_txbSqlField.setReadonly(false);
m_btnSql.addEventListener(Events.ON_CLICK, this);
rwTop.appendChild(m_lblSql);
rwTop.appendChild(m_txbSqlField);
rwTop.appendChild(m_btnSql);
rows.appendChild(rwTop);
// create the bottom row of components
m_txbResultField.setCols(noColumns);
m_txbResultField.setRows(noResultRows);
m_txbResultField.setReadonly(true);
rwBottom.appendChild(m_txbResultField);
rwBottom.setSpans("3");
rwBottom.setAlign("center");
rows.appendChild(rwBottom);
// put it all together
m_grdMain.appendChild(rows);
this.appendChild(m_grdMain);
return;
}
/**
* Create Process Button.
* @return button
*/
public static final Button createProcessButton()
{
Button btnProcess = new Button();
btnProcess.setImage("/images/Process24.gif");
btnProcess.setName(Msg.getMsg(Env.getCtx(), "Process"));
return btnProcess;
} // createProcessButton
/**
* Process a semicolon delimitted list of SQL Statements.
*
* @param sqlStatements one or more statements separated by a semicolon (';')
* @param allowDML whether to allow DML statements
* @return a string summarising the results
*/
public static String processStatements (String sqlStatements, boolean allowDML)
{
return VSQLProcess.processStatements(sqlStatements, allowDML);
}
/**
* Process SQL Statements.
*
* @param sqlStatement a single SQL statement
* @param allowDML whether to allow DML statements
* @return a string summarising the results
*/
public static String processStatement (String sqlStatement, boolean allowDML)
{
return VSQLProcess.processStatement(sqlStatement, allowDML);
}
/*
* (non-Javadoc)
* @see org.adempiere.webui.panel.ADForm#onEvent(org.zkoss.zk.ui.event.Event)
*/
public void onEvent(Event event) throws Exception
{
m_txbResultField.setText(processStatements (m_txbSqlField.getText(), false));
}
}

View File

@ -0,0 +1,628 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/**
* 2007, Modified by Posterita Ltd.
*/
package org.adempiere.webui.apps.form;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.table.AbstractTableModel;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.ConfirmPanel;
import org.adempiere.webui.component.Datebox;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.Panel;
import org.adempiere.webui.component.VerticalBox;
import org.adempiere.webui.component.WStatusBar;
import org.adempiere.webui.editor.WEditor;
import org.adempiere.webui.editor.WLocatorEditor;
import org.adempiere.webui.editor.WSearchEditor;
import org.adempiere.webui.editor.WTableDirEditor;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.panel.ADForm;
import org.compiere.model.GridField;
import org.compiere.model.GridTab;
import org.compiere.model.GridTable;
import org.compiere.model.GridWindow;
import org.compiere.model.GridWindowVO;
import org.compiere.model.MLocatorLookup;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MQuery;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.NamePair;
import org.zkforge.yuiext.grid.Column;
import org.zkforge.yuiext.grid.Columns;
import org.zkforge.yuiext.grid.Grid;
import org.zkforge.yuiext.grid.Row;
import org.zkforge.yuiext.grid.Rows;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Separator;
public class WTrxMaterial extends ADForm implements EventListener, ValueChangeListener
{
private static final long serialVersionUID = 1L;
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
//private FormFrame m_frame;
/** GridController */
private Grid m_gridController = new Grid();
private Columns columns = new Columns();
private Rows rows = new Rows();
/** MWindow */
private GridWindow m_mWindow = null;
/** MTab pointer */
private GridTab m_mTab = null;
private MQuery m_staticQuery = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(WTrxMaterial.class);
private VerticalBox mainPanel = new VerticalBox();
private Hbox parameterPanel = new Hbox();
private Label orgLabel = new Label();
private WEditor orgField;
private Label locatorLabel = new Label();
private WLocatorEditor locatorField;
private Label productLabel = new Label();
private WEditor productField;
private Label dateFLabel = new Label();
private Datebox dateFField;
private Label dateTLabel = new Label();
private Datebox dateTField;
private Label mtypeLabel = new Label();
private WEditor mtypeField;
private Panel southPanel = new Panel();
private ConfirmPanel confirmPanel = new ConfirmPanel(true, true, false, false, false, true);
private WStatusBar statusBar = new WStatusBar();
public WTrxMaterial()
{
init(super.m_windowNo);
}
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo)
{
log.info("");
m_WindowNo = WindowNo;
try
{
dynParameter();
jbInit();
dynInit();
this.appendChild(mainPanel);
this.appendChild(statusBar);
}
catch(Exception ex)
{
log.log(Level.SEVERE, "", ex);
}
} // init
/**
* Static Init
* @throws Exception
*/
void jbInit() throws Exception
{
orgLabel.setValue(Msg.translate(Env.getCtx(), "AD_Org_ID"));
locatorLabel.setValue(Msg.translate(Env.getCtx(), "M_Locator_ID"));
productLabel.setValue(Msg.translate(Env.getCtx(), "Product"));
dateFLabel.setValue(Msg.translate(Env.getCtx(), "DateFrom"));
dateTLabel.setValue(Msg.translate(Env.getCtx(), "DateTo"));
mtypeLabel.setValue(Msg.translate(Env.getCtx(), "MovementType"));
m_gridController.setWidth("900px");
m_gridController.setHeight("550px");
mainPanel.setWidth("100%");
mainPanel.appendChild(new Separator());
mainPanel.appendChild(parameterPanel);
mainPanel.appendChild(new Separator());
mainPanel.appendChild(m_gridController);
mainPanel.appendChild(new Separator());
Hbox boxOrg = new Hbox();
boxOrg.setWidth("100%");
boxOrg.setWidth("35%, 75%");
boxOrg.appendChild(orgLabel);
boxOrg.appendChild(orgField.getComponent());
Hbox boxMType = new Hbox();
boxMType.setWidth("100%");
boxMType.setWidth("35%, 75%");
boxMType.appendChild(mtypeLabel);
boxMType.appendChild(mtypeField.getComponent());
Hbox boxDateF = new Hbox();
boxDateF.setWidth("100%");
boxDateF.setWidth("35%, 75%");
boxDateF.appendChild(dateFLabel);
boxDateF.appendChild(dateFField);
Hbox boxLocator = new Hbox();
boxLocator.setWidth("100%");
boxLocator.setWidth("35%, 75%");
boxLocator.appendChild(locatorLabel);
boxLocator.appendChild(locatorField.getComponent());
Hbox boxProduct = new Hbox();
boxProduct.setWidth("100%");
boxProduct.setWidth("35%, 75%");
boxProduct.appendChild(productLabel);
boxProduct.appendChild(productField.getComponent());
Hbox boxDateT = new Hbox();
boxDateT.setWidth("100%");
boxDateT.setWidth("35%, 75%");
boxDateT.appendChild(dateTLabel);
boxDateT.appendChild(dateTField);
VerticalBox boxCol1 = new VerticalBox();
boxCol1.setWidth("100%");
boxCol1.appendChild(boxOrg);
boxCol1.appendChild(boxLocator);
VerticalBox boxCol2 = new VerticalBox();
boxCol2.setWidth("100%");
boxCol2.appendChild(boxMType);
boxCol2.appendChild(boxProduct);
VerticalBox boxCol3 = new VerticalBox();
boxCol3.setWidth("100%");
boxCol3.appendChild(boxDateF);
boxCol3.appendChild(boxDateT);
parameterPanel.setWidth("100%");
parameterPanel.setStyle("text-align:right");
parameterPanel.appendChild(boxCol1);
parameterPanel.appendChild(new Separator());
parameterPanel.appendChild(boxCol2);
parameterPanel.appendChild(new Separator());
parameterPanel.appendChild(boxCol3);
southPanel.appendChild(confirmPanel);
southPanel.appendChild(new Separator());
southPanel.appendChild(statusBar);
mainPanel.appendChild(southPanel);
this.setWidth("100%");
this.appendChild(mainPanel);
}
/**
* Initialize Parameter fields
* @throws Exception if Lookups cannot be initialized
*/
private void dynParameter() throws Exception
{
Properties ctx = Env.getCtx();
// Organization
MLookup orgLookup = MLookupFactory.get (ctx, m_WindowNo, 0, 3660, DisplayType.TableDir);
orgField = new WTableDirEditor(orgLookup, "AD_Org_ID", "", false, false, true);
orgField.addValueChangeListner(this);
// Locator
MLocatorLookup locatorLookup = new MLocatorLookup(ctx, m_WindowNo);
locatorField = new WLocatorEditor ("M_Locator_ID", false, false, true, locatorLookup);
locatorField.addValueChangeListner(this);
// Product
MLookup productLookup = MLookupFactory.get (ctx, m_WindowNo, 0, 3668, DisplayType.Search);
productField = new WSearchEditor(productLookup, "M_Product_ID", "", false, false, true);
productField.addValueChangeListner(this);
// Movement Type
MLookup mtypeLookup = MLookupFactory.get (ctx, m_WindowNo, 0, 3666, DisplayType.List);
mtypeField = new WTableDirEditor(mtypeLookup, "MovementType", "", false, false, true);
mtypeField.addValueChangeListner(this);
// Dates
dateFField = new Datebox();//"DateFrom", false, false, true, DisplayType.Date, Msg.getMsg(Env.getCtx(), "DateFrom"));
dateTField = new Datebox();//"DateTo", false, false, true, DisplayType.Date, Msg.getMsg(Env.getCtx(), "DateTo"));
confirmPanel.addActionListener(Events.ON_CLICK, this);
statusBar.setStatusLine("");
} // dynParameter
/**
* Dynamic Layout (Grid).
* Based on AD_Window: Material Transactions
*/
private void dynInit()
{
m_staticQuery = new MQuery();
m_staticQuery.addRestriction("AD_Client_ID", MQuery.EQUAL, Env.getAD_Client_ID(Env.getCtx()));
int AD_Window_ID = 223; // Hardcoded
GridWindowVO wVO = AEnv.getMWindowVO (m_WindowNo, AD_Window_ID, 0);
if (wVO == null)
return;
m_mWindow = new GridWindow (wVO);
m_mTab = m_mWindow.getTab(0);
m_mWindow.initTab(0);
populateGrid();
//m_gridController.initGrid(m_mTab, true, m_WindowNo, null, null);
//mainPanel.add(m_gridController, BorderLayout.CENTER);
m_mTab.setQuery(MQuery.getEqualQuery("1", "2"));
m_mTab.query(false);
statusBar.setStatusLine(" ", false);
statusBar.setStatusDB(" ");
} // dynInit
private void populateGrid()
{
m_gridController.getChildren().clear();
m_gridController.appendChild(columns);
m_gridController.appendChild(rows);
columns.getChildren().clear();
Column column = new Column();
AbstractTableModel tableModel = m_mTab.getTableModel();
GridField[] gridfields = ((GridTable)tableModel).getFields();
for (int i = 0; i < gridfields.length; i++)
{
if (gridfields[i].isDisplayed())
{
column = new Column(gridfields[i].getHeader());
columns.appendChild(column);
}
}
rows.getChildren().clear();
for (int i = 0; i < tableModel.getRowCount(); i++)
{
Row row = new Row();
for (int j = 0; j < tableModel.getColumnCount(); j++)
{
org.zkforge.yuiext.grid.Label lab = new org.zkforge.yuiext.grid.Label();
Label label = new Label("");
if (!gridfields[j].isDisplayed())
break;
Object obj = tableModel.getValueAt(i, j);
if (obj != null)
{
if (tableModel.getColumnClass(j).equals(String.class))
{
label.setValue(obj.toString());
}
else if (tableModel.getColumnClass(j).equals(BigDecimal.class))
{
label.setValue(obj.toString());
}
else if (tableModel.getColumnClass(j).equals(Integer.class))
{
if (gridfields[j].isLookup())
{
MLookup lookup = MLookupFactory.get(Env.getCtx(), super.m_windowNo,
0, gridfields[j].getAD_Column_ID(), gridfields[j].getDisplayType());
NamePair namepair = lookup.get(obj);
if (namepair != null)
label.setValue(namepair.getName());
else
label.setValue("");
}
}
else if (tableModel.getColumnClass(j).equals(Timestamp.class))
{
SimpleDateFormat dateFormat = DisplayType.getDateFormat(DisplayType.Date);
label.setValue(dateFormat.format((Timestamp)obj));
}
else
label.setValue("Missing Class");
}
lab = new org.zkforge.yuiext.grid.Label(label.getValue());
row.appendChild(lab);
}
rows.appendChild(row);
}
}
/**
* Dispose
*/
public void dispose()
{
/*if (m_gridController != null)
m_gridController.dispose();
*/
m_gridController = null;
m_mTab = null;
if (m_mWindow != null)
m_mWindow.dispose();
m_mWindow = null;
orgField = null;
locatorField = null;
productField = null;
mtypeField = null;
dateFField = null;
dateTField = null;
} // dispose
/**************************************************************************
* Action Listener
* @param e event
*/
public void onEvent(Event event) throws Exception
{
if (confirmPanel.getButton("Cancel").equals(event.getTarget()))
dispose();
else if (confirmPanel.getButton("Refresh").equals(event.getTarget())
|| confirmPanel.getButton("Ok").equals(event.getTarget()))
refresh();
else if (confirmPanel.getButton("Zoom").equals(event.getTarget()))
zoom();
}
/**************************************************************************
* Property Listener
* @param e event
*/
public void valueChange(ValueChangeEvent evt)
{
if (evt.getPropertyName().equals("M_Product_ID"))
productField.setValue(evt.getNewValue());
}
/**************************************************************************
* Refresh - Create Query and refresh grid
*/
private void refresh()
{
/**
* Create Where Clause
*/
MQuery query = m_staticQuery.deepCopy();
// Organization
Object value = null;
if (orgField.getDisplay() != "")
value = orgField.getValue();
if (value != null && value.toString().length() > 0)
query.addRestriction("AD_Org_ID", MQuery.EQUAL, value);
// Locator
value = null;
if (locatorField.getDisplay() != "")
value = locatorField.getValue();
if (value != null && value.toString().length() > 0)
query.addRestriction("M_Locator_ID", MQuery.EQUAL, value);
// Product
value = null;
if (productField.getDisplay() != "")
value = productField.getValue();
if (value != null && value.toString().length() > 0)
query.addRestriction("M_Product_ID", MQuery.EQUAL, value);
// MovementType
value = null;
if (mtypeField.getDisplay() != "")
value = mtypeField.getValue();
if (value != null && value.toString().length() > 0)
query.addRestriction("MovementType", MQuery.EQUAL, value);
// DateFrom
Date f = null;
Timestamp ts =null;
if (dateFField.getValue() != null)
{
f = dateFField.getValue();
ts = new Timestamp(f.getTime());
}
if (ts != null)
query.addRestriction("TRUNC(MovementDate)", MQuery.GREATER_EQUAL, ts);
// DateTO
Date t = null;
ts = null;
if (dateTField.getValue() != null)
{
t = dateTField.getValue();
ts = new Timestamp(t.getTime());
}
if (ts != null)
query.addRestriction("TRUNC(MovementDate)", MQuery.LESS_EQUAL, ts);
log.info( "VTrxMaterial.refresh query=" + query.toString());
/**
* Refresh/Requery
*/
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "StartSearch"), false);
m_mTab.setQuery(query);
m_mTab.query(false);
int no = m_mTab.getRowCount();
statusBar.setStatusLine(" ", false);
statusBar.setStatusDB(Integer.toString(no));
populateGrid();
} // refresh
/**
* Zoom
*/
private void zoom()
{
log.info("");
int AD_Window_ID = 0;
String ColumnName = null;
String SQL = null;
int lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_InOutLine_ID");
if (lineID != 0)
{
log.fine("M_InOutLine_ID=" + lineID);
if (Env.getContext(Env.getCtx(), m_WindowNo, "MovementType").startsWith("C"))
AD_Window_ID = 169; // Customer
else
AD_Window_ID = 184; // Vendor
ColumnName = "M_InOut_ID";
SQL = "SELECT M_InOut_ID FROM M_InOutLine WHERE M_InOutLine_ID=?";
}
else
{
lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_InventoryLine_ID");
if (lineID != 0)
{
log.fine("M_InventoryLine_ID=" + lineID);
AD_Window_ID = 168;
ColumnName = "M_Inventory_ID";
SQL = "SELECT M_Inventory_ID FROM M_InventoryLine WHERE M_InventoryLine_ID=?";
}
else
{
lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_MovementLine_ID");
if (lineID != 0)
{
log.fine("M_MovementLine_ID=" + lineID);
AD_Window_ID = 170;
ColumnName = "M_Movement_ID";
SQL = "SELECT M_Movement_ID FROM M_MovementLine WHERE M_MovementLine_ID=?";
}
else
{
lineID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "M_ProductionLine_ID");
if (lineID != 0)
{
log.fine("M_ProductionLine_ID=" + lineID);
AD_Window_ID = 191;
ColumnName = "M_Production_ID";
SQL = "SELECT M_Production_ID FROM M_ProductionLine WHERE M_ProductionLine_ID=?";
}
else
log.fine("Not found WindowNo=" + m_WindowNo);
}
}
}
if (AD_Window_ID == 0)
return;
// Get Parent ID
int parentID = 0;
try
{
PreparedStatement pstmt = DB.prepareStatement(SQL, null);
pstmt.setInt(1, lineID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
parentID = rs.getInt(1);
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, SQL, e);
}
MQuery query = MQuery.getEqualQuery(ColumnName, parentID);
log.config("AD_Window_ID=" + AD_Window_ID + " - " + query);
if (parentID == 0)
log.log(Level.SEVERE, "No ParentValue - " + SQL + " - " + lineID);
// Zoom
AEnv.zoom(AD_Window_ID, query);
/* ADWindow frame = new ADWindow(Env.getCtx(), AD_Window_ID);
if (frame == null)
return;
SessionManager.getAppDesktop().showWindow(frame);
frame = null;
*/ } // zoom
}

View File

@ -0,0 +1,166 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.util.Arrays;
import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zul.Comboitem;
/**
* Auto-complete with combobox.
* Based on ZK's Auto-complete
*
* @author Niraj Sohun
* Aug 20, 2007
*/
public class AutoComplete extends Combobox
{
private static final long serialVersionUID = 1L;
/** comboItems All menu labels */
private static String[] comboItems;
/** strDescription Description of menu items */
private static String[] strDescription;
/**
* Set menu labels
*
* @param vals Menu labels
*/
public void setDict(String[] vals)
{
comboItems = vals;
if (comboItems != null)
{
Arrays.sort(comboItems);
}
}
/**
* Set description of menu items
*
* @param vals Description of menu items
*/
public void setDescription(String[] vals)
{
strDescription = vals;
}
/**
* Constructor
*/
public AutoComplete()
{
if (comboItems != null)
refresh("");
}
public AutoComplete(String value)
{
super.setValue(value);
}
public void setValue(String value)
{
super.setValue(value);
refresh(value);
}
/**
* Event handler responsible to reducing number of items
* Method is invoked each time something is typed in the combobox
*
* @param evt The event
*/
public void onChanging(InputEvent evt)
{
if (!evt.isChangingBySelectBack())
refresh(evt.getValue());
}
/**
* Refresh comboitem based on the specified value.
*/
private void refresh(String val)
{
val = val.toLowerCase();
/* int j = Arrays.binarySearch(comboItemsL, val);
if (j < 0)
j = -j-1;
Iterator it = getItems().iterator();
for (; j < comboItems.length; ++j)
{
if (!comboItemsL[j].contains(val))
break;
if (it != null && it.hasNext())
{
((Comboitem)it.next()).setLabel(comboItems[j]);
//if (strDescription[j] != null)
// comboitem.setDescription(strDescription[j]);
}
else
{
it = null;
Comboitem comboitem = new Comboitem(comboItems[j]);
if (strDescription[j] != null)
comboitem.setDescription(strDescription[j]);
comboitem.setParent(this);
}
}
while (it != null && it.hasNext())
{
it.next();
it.remove();
}*/
super.getChildren().clear();
if ((val == null) || (val.trim() == null))
return;
for (int i = 0; i < comboItems.length; i++)
{
if (comboItems[i].toLowerCase().contains(val))
{
Comboitem comboitem = new Comboitem();
comboitem.setLabel(comboItems[i]);
comboitem.setDescription(strDescription[i]);
super.appendChild(comboitem);
}
}
}
}

View File

@ -0,0 +1,27 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
public final class BackgroundColours
{
public final static String MANDATORY = "background-color:#fbb5b5";
public final static String ERROR = "background-color:#ffffff";
public final static String CORRECT = "background-color:#d18ae3";
}

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 11, 2007
* @version $Revision: 0.10 $
*/
public class Bandbox extends org.zkoss.zul.Bandbox
{
private static final long serialVersionUID = 1L;
public void setEnabled(boolean enabled)
{
this.setDisabled(!enabled);
}
}

View File

@ -0,0 +1,61 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 12, 2007
* @version $Revision: 0.10 $
*/
public class Button extends org.zkoss.zul.Button
{
private static final long serialVersionUID = 1L;
private String name;
public Button()
{
super();
}
public Button(String label)
{
super(label);
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setEnabled(boolean enabled)
{
super.setDisabled(!enabled);
}
public boolean isEnabled()
{
return !super.isDisabled();
}
}

View File

@ -0,0 +1,427 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import org.adempiere.webui.constants.EventConstants;
import org.adempiere.webui.event.ToolbarListener;
import org.compiere.util.CLogger;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Label;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class CWindowToolbar extends FToolbar implements EventListener
{
private static final long serialVersionUID = 1L;
private static final String BUTTON_WIDTH = "32px";
private static CLogger log = CLogger.getCLogger(CWindowToolbar.class);
private Button btnIgnore;
private Button btnHelp, btnNew, btnDelete, btnSave;
private Button btnRefresh, btnFind, btnAttachment;
private Button btnGridToggle;
private Button btnHistoryRecords, btnMenu, btnParentRecord, btnDetailRecord;
private Button btnFirst, btnPrevious, btnNext, btnLast;
private Button btnReport, btnArchive, btnPrint;
private Button btnZoomAcross, btnActiveWorkflows, btnRequests, btnProductInfo;
private Button btnExit;
private ArrayList<ToolbarListener> listeners = new ArrayList<ToolbarListener>();
public CWindowToolbar()
{
init();
}
private void init()
{
btnIgnore = new Button("");
btnIgnore.setName("btnIgnore");
btnIgnore.setImage("/images/Ignore16.gif");
btnIgnore.setTooltiptext("Ignore Changes");
// --
btnHelp = new Button("");
btnHelp.setName("btnHelp");
btnHelp.setImage("/images/Help24.gif");
btnHelp.setTooltiptext("Help");
btnNew = new Button("");
btnNew.setName("btnNew");
btnNew.setImage("/images/New24.gif");
btnNew.setTooltiptext("New Record");
btnDelete = new Button("");
btnDelete.setName("btnDelete");
btnDelete.setImage("/images/Delete24.gif");
btnDelete.setTooltiptext("Delete current record");
btnSave = new Button("");
btnSave.setName("btnSave");
btnSave.setImage("/images/Save24.gif");
btnSave.setTooltiptext("Save changes");
// --
btnRefresh = new Button("");
btnRefresh.setName("btnRefresh");
btnRefresh.setImage("/images/Refresh24.gif");
btnRefresh.setTooltiptext("Refresh Data");
btnFind = new Button("");
btnFind.setName("btnFind");
btnFind.setImage("/images/Find24.gif");
btnFind.setTooltiptext("Find Records");
btnAttachment = new Button("");
btnAttachment.setName("btnAttachment");
btnAttachment.setImage("/images/Attachment24.gif");
btnAttachment.setTooltiptext("Attachments");
// --
btnGridToggle = new Button("");
btnGridToggle.setName("btnGridToggle");
btnGridToggle.setImage("/images/ZoomAcross24.gif");
btnGridToggle.setTooltiptext("Grid Toggle");
btnHistoryRecords = new Button("");
btnHistoryRecords.setName("btnHistoryRecords");
btnHistoryRecords.setImage("/images/HistoryX24.gif");
btnHistoryRecords.setTooltiptext("History Records");
btnMenu = new Button("");
btnMenu.setName("btnHome");
btnMenu.setImage("/images/Home24.gif");
btnMenu.setTooltiptext("Home");
btnParentRecord = new Button("");
btnParentRecord.setName("btnParentRecord");
btnParentRecord.setImage("/images/Parent24.gif");
btnDetailRecord = new Button("");
btnDetailRecord.setName("btnDetailRecord");
btnDetailRecord.setImage("/images/Detail24.gif");
// --
btnFirst = new Button("");
btnFirst.setName("btnFirst");
btnFirst.setImage("/images/First24.gif");
btnPrevious = new Button("");
btnPrevious.setName("btnPrevious");
btnPrevious.setImage("/images/Previous24.gif");
btnNext = new Button("");
btnNext.setName("btnNext");
btnNext.setImage("/images/Next24.gif");
btnLast = new Button("");
btnLast.setName("btnLast");
btnLast.setImage("/images/Last24.gif");
// --
btnReport = new Button("");
btnReport.setName("btnReport");
btnReport.setImage("/images/Report24.gif");
btnArchive = new Button("");
btnArchive.setName("btnArchive");
btnArchive.setImage("/images/Archive24.gif");
btnPrint = new Button("");
btnPrint.setName("btnPrint");
btnPrint.setImage("/images/Print24.gif");
// --
btnZoomAcross = new Button("");
btnZoomAcross.setName("btnZoomAcross");
btnZoomAcross.setImage("/images/ZoomAcross24.gif");
btnActiveWorkflows = new Button("");
btnActiveWorkflows.setName("btnActiveWorkflows");
btnActiveWorkflows.setImage("/images/WorkFlow24.gif");
btnRequests = new Button("");
btnRequests.setName("btnRequests");
btnRequests.setImage("/images/Request24.gif");
btnProductInfo = new Button("");
btnProductInfo.setName("btnProductInfo");
btnProductInfo.setImage("/images/Product24.gif");
btnExit = new Button("");
btnExit.setName("btnExit");
btnExit.setImage("/images/End24.gif");
this.appendChild(btnIgnore);
addSeparator();
this.appendChild(btnHelp);
this.appendChild(btnNew);
// this.appendChild(btnEdit);
this.appendChild(btnDelete);
this.appendChild(btnSave);
addSeparator();
this.appendChild(btnRefresh);
this.appendChild(btnFind);
this.appendChild(btnAttachment);
this.appendChild(btnGridToggle);
addSeparator();
this.appendChild(btnHistoryRecords);
this.appendChild(btnMenu);
this.appendChild(btnParentRecord);
this.appendChild(btnDetailRecord);
addSeparator();
this.appendChild(btnFirst);
this.appendChild(btnPrevious);
this.appendChild(btnNext);
this.appendChild(btnLast);
addSeparator();
this.appendChild(btnReport);
this.appendChild(btnArchive);
this.appendChild(btnPrint);
addSeparator();
//this.appendChild(btnZoomAcross);
this.appendChild(btnActiveWorkflows);
this.appendChild(btnRequests);
this.appendChild(btnProductInfo);
addSeparator();
this.appendChild(btnExit);
for (Object obj : this.getChildren())
{
if (obj instanceof Button)
{
((Button)obj).setWidth(BUTTON_WIDTH);
((Button)obj).addEventListener(Events.ON_CLICK, this);
((Button)obj).setEnabled(false);
}
}
// Help and Exit should always be enabled
btnHelp.setEnabled(true);
btnExit.setEnabled(true);
// Testing Purposes
btnGridToggle.setEnabled(true);
}
protected void addSeparator()
{
Label lblSeparator = new Label();
lblSeparator.setWidth("3px");
lblSeparator.setHeight("16px");
lblSeparator.setValue(" ");
this.appendChild(lblSeparator);
}
public void addListener(ToolbarListener toolbarListener)
{
listeners.add(toolbarListener);
}
public void removeListener(ToolbarListener toolbarListener)
{
listeners.remove(toolbarListener);
}
public void onEvent(Event event)
{
String eventName = event.getName();
Component eventComp = event.getTarget();
Iterator<ToolbarListener> listenerIter = listeners.iterator();
if(eventName.equals(EventConstants.ONCLICK))
{
if(eventComp instanceof Button)
{
Button cComponent = (Button) eventComp;
String compName = cComponent.getName();
String methodName = "on" + compName.substring(3);
while(listenerIter.hasNext())
{
try
{
ToolbarListener tListener = listenerIter.next();
Method method = tListener.getClass().getMethod(methodName, (Class[]) null);
method.invoke(tListener, (Object[]) null);
}
catch(SecurityException e)
{
log.log(Level.SEVERE, "Could not invoke Toolbar listener method: " + methodName + "()", e);
}
catch(NoSuchMethodException e)
{
log.log(Level.SEVERE, "Could not invoke Toolbar listener method: " + methodName + "()", e);
}
catch(IllegalArgumentException e)
{
log.log(Level.SEVERE, "Could not invoke Toolbar listener method: " + methodName + "()", e);
}
catch(IllegalAccessException e)
{
log.log(Level.SEVERE, "Could not invoke Toolbar listener method: " + methodName + "()", e);
}
catch(InvocationTargetException e)
{
log.log(Level.SEVERE, "Could not invoke Toolbar listener method: " + methodName + "()", e);
}
}
}
}
}
public void enableHistoryRecords(boolean enabled)
{
this.btnHistoryRecords.setEnabled(enabled);
}
public void enableNavigation(boolean enabledd)
{
this.btnFirst.setEnabled(enabledd);
this.btnPrevious.setEnabled(enabledd);
this.btnNext.setEnabled(enabledd);
this.btnLast.setEnabled(enabledd);
}
public void enableTabNavigation(boolean enabled)
{
enableTabNavigation(enabled, enabled);
}
public void enableTabNavigation(boolean enableParent, boolean enableDetail)
{
this.btnParentRecord.setEnabled(enableParent);
this.btnDetailRecord.setEnabled(enableDetail);
}
public void enableFirstNavigation(boolean enabled)
{
this.btnFirst.setEnabled(enabled);
this.btnPrevious.setEnabled(enabled);
}
public void enableLastNavigation(boolean enabled)
{
this.btnLast.setEnabled(enabled);
this.btnNext.setEnabled(enabled);
}
public void enabledNew(boolean enabled)
{
this.btnNew.setEnabled(enabled);
}
/* public void enableEdit(boolean enabled)
{
this.btnEdit.setEnabled(enabled);
}*/
public void enableRefresh(boolean enabled)
{
this.btnRefresh.setEnabled(enabled);
}
public void enableSave(boolean enabled)
{
this.btnSave.setEnabled(enabled);
}
public void enableExit(boolean enabled)
{
this.btnExit.setEnabled(enabled);
}
public void enableDelete(boolean enabled)
{
this.btnDelete.setEnabled(enabled);
}
public void enableDeleteSelection(boolean enabled)
{
// TODO add delete selection button
}
public void enableChanges(boolean enabled)
{
this.btnNew.setEnabled(enabled);
this.btnIgnore.setEnabled(enabled);
}
public void enableIgnore(boolean enabled)
{
this.btnIgnore.setEnabled(enabled);
}
public void enableNew(boolean enabled)
{
this.btnNew.setEnabled(enabled);
}
public void enableAttachment(boolean enabled)
{
this.btnAttachment.setEnabled(enabled);
}
public void enablePrint(boolean enabled)
{
this.btnPrint.setEnabled(enabled);
}
public void enableReport(boolean enabled)
{
this.btnReport.setEnabled(enabled);
}
public void enableCopy(boolean enabled)
{
}
public void enableFind(boolean enabled)
{
this.btnFind.setEnabled(enabled);
}
public void enableGridToggle(boolean enabled)
{
btnGridToggle.setEnabled(enabled);
}
public boolean isAsap()
{
return true;
}
}

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Checkbox extends org.zkoss.zul.Checkbox
{
private static final long serialVersionUID = 1L;
public void setEnabled(boolean enabled)
{
this.setDisabled(!enabled);
}
}

View File

@ -0,0 +1,35 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
public class Column extends org.zkoss.zul.Column
{
private static final long serialVersionUID = 1L;
public Column()
{
this(null);
}
public Column(String str)
{
this.setLabel(str);
}
}

View File

@ -0,0 +1,24 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
public class Columns extends org.zkoss.zul.Columns
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,47 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
* Bad stuff, cannot overide method equals in AbstractComponent.
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 10, 2007
* @version $Revision: 0.10 $
*/
public class ComboItem extends org.zkoss.zul.Comboitem
{
private static final long serialVersionUID = 1L;
private Object obj;
public ComboItem(String label)
{
super(label);
}
public ComboItem(String label, String object)
{
super(label);
this.obj = object;
}
public Object getObject()
{
return obj;
}
}

View File

@ -0,0 +1,43 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.zkoss.zul.Comboitem;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Combobox extends org.zkoss.zul.Combobox
{
private static final long serialVersionUID = 1L;
public void setEnabled(boolean enabled)
{
this.setDisabled(!enabled);
}
public Comboitem appendItem(String label)
{
ComboItem item = new ComboItem(label);
item.setParent(this);
return item;
}
}

View File

@ -0,0 +1,350 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.util.Iterator;
import java.util.List;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Messagebox;
/**
* Application Confirm Panel
* Web UI port of the rich client's ConfirmPanel by Jorg Janke
* @author Sendy Yagambrum
* @date July 25, 2007
**/
public final class ConfirmPanel extends Hbox
{
private static final long serialVersionUID = 1L;
/**
* Creates a button of the specified id
*
* @param id button id
* @return button
*
* <p>The string can be any of the following and the corresponding button will be created: </p>
* <dl>
* <dt>Ok</dt> <dd>Ok button</dd>
* <dt>Cancel</dt> <dd>Cancel button</dd>
* <dt>Refresh</dt> <dd>Refresh button</dd>
* <dt>Reset</dt> <dd>Reset button</dd>
* <dt>History</dt> <dd>History button</dd>
* <dt>Process</dt> <dd>Process button</dd>
* <dt>New</dt> <dd>New button</dd>
* <dt>Customize</dt> <dd>Customize button</dd>
* <dt>Delete</dt> <dd>Delete button</dd>
* <dt>Save</dt> <dd>Save button</dd>
* <dt>Zoom</dt> <dd>Zoom button</dd>
* <dt>Help</dt> <dd>Help button</dd>
* </dl>
*
*/
public Button createButton(String name)
{
Button button = new Button();
button.setName("btn"+name);
button.setId(name);
button.setSrc("images/"+name+"24.gif");
return button;
}
/**
* create confirm panel with multiple options
* @param withCancelButton with cancel
* @param withRefreshButton with refresh
* @param withResetButton with reset
* @param withCustomizeButton with customize
* @param withHistoryButton with history
* @param withZoomButton with zoom
*/
public ConfirmPanel(boolean withCancelButton,
boolean withRefreshButton,
boolean withResetButton,
boolean withCustomizeButton,
boolean withHistoryButton,
boolean withZoomButton)
{
init();
setVisible("Cancel", withCancelButton);
addComponentsRight(createButton("Ok"));
addComponentsRight(createButton("Cancel"));
if (withRefreshButton)
{
addComponentsLeft(createButton("Refresh"));
}
if (withResetButton)
{
addComponentsLeft(createButton("Reset"));
}
if (withCustomizeButton)
{
addComponentsLeft(createButton("Customize"));
}
if (withHistoryButton)
{
addComponentsLeft(createButton("History"));
}
if (withZoomButton)
{
addComponentsLeft(createButton("Zoom"));
}
}
/**
* Create confirm panel with Ok button only
*/
public ConfirmPanel()
{
this(false,false,false,false,false,false);
}
/**
* Create confirm panel with Ok and Cancel button
* @param withCancel with cancel
*
*/
public ConfirmPanel(boolean withCancel)
{
this(true,false,false,false,false,false);
}
//
private Hbox hboxBtnLeft;
private Hbox hboxBtnRight;
//
private Panel pnlBtnRight;
private Panel pnlBtnLeft;
/**
* initialise components
*/
private void init()
{
pnlBtnLeft = new Panel();
pnlBtnLeft.setAlign("left");
pnlBtnRight = new Panel();
pnlBtnRight.setAlign("right");
hboxBtnRight = new Hbox();
hboxBtnRight.appendChild(pnlBtnRight);
hboxBtnRight.setWidth("100%");
hboxBtnRight.setStyle("text-align:right");
hboxBtnLeft = new Hbox();
hboxBtnLeft.appendChild(pnlBtnLeft);
hboxBtnLeft.setWidth("100%");
hboxBtnLeft.setStyle("text-align:left");
this.appendChild(hboxBtnLeft);
this.appendChild(hboxBtnRight);
this.setWidth("100%");
}
/**
* add button to the left side of the confirm panel
* @param button button
*/
public void addComponentsLeft(Button button)
{
pnlBtnLeft.appendChild(button);
}
/**
* add button to the right side of the confirm panel
* @param button button
*/
public void addComponentsRight(Button button)
{
pnlBtnRight.appendChild(button);
}
/**
* return button of the specified id
* @param id button id
* @return button or null if no button is found
* <p> The button id can be any of the following
* <dl>
* <dt>Ok</dt> <dd>Ok button</dd>
* <dt>Cancel</dt> <dd>Cancel button</dd>
* <dt>Refresh</dt> <dd>Refresh button</dd>
* <dt>Reset</dt> <dd>Reset button</dd>
* <dt>History</dt> <dd>History button</dd>
* <dt>Process</dt> <dd>Process button</dd>
* <dt>New</dt> <dd>New button</dd>
* <dt>Customize</dt> <dd>Customize button</dd>
* <dt>Delete</dt> <dd>Delete button</dd>
* <dt>Save</dt> <dd>Save button</dd>
* <dt>Zoom</dt> <dd>Zoom button</dd>
* <dt>Help</dt> <dd>Help button</dd>
* </dl>
*/
public Button getButton(String id)
{
return (Button)this.getFellowIfAny(id);
}
/**
* sets the visibility of the specified button
* @param btnName button name
* @param visible visibility
* <p> The button name can be any of the following
* <dl>
* <dt>Ok</dt> <dd>Ok button</dd>
* <dt>Cancel</dt> <dd>Cancel button</dd>
* <dt>Refresh</dt> <dd>Refresh button</dd>
* <dt>Reset</dt> <dd>Reset button</dd>
* <dt>History</dt> <dd>History button</dd>
* <dt>Process</dt> <dd>Process button</dd>
* <dt>New</dt> <dd>New button</dd>
* <dt>Customize</dt> <dd>Customize button</dd>
* <dt>Delete</dt> <dd>Delete button</dd>
* <dt>Save</dt> <dd>Save button</dd>
* <dt>Zoom</dt> <dd>Zoom button</dd>
* <dt>Help</dt> <dd>Help button</dd>
* </dl>
*/
public void setVisible(String id, boolean visible)
{
Button btn = getButton(id);
if (btn != null)
{
btn.setVisible(visible);
}
}
/**
* returns whether the specified button is visible or not
* @param btnName
* @return visibility of the button
* <p> The button name can be any of the following
* <dl>
* <dt>Ok</dt> <dd>Ok button</dd>
* <dt>Cancel</dt> <dd>Cancel button</dd>
* <dt>Refresh</dt> <dd>Refresh button</dd>
* <dt>Reset</dt> <dd>Reset button</dd>
* <dt>History</dt> <dd>History button</dd>
* <dt>Process</dt> <dd>Process button</dd>
* <dt>New</dt> <dd>New button</dd>
* <dt>Customize</dt> <dd>Customize button</dd>
* <dt>Delete</dt> <dd>Delete button</dd>
* <dt>Save</dt> <dd>Save button</dd>
* <dt>Zoom</dt> <dd>Zoom button</dd>
* <dt>Help</dt> <dd>Help button</dd>
* </dl>
*/
public boolean isVisible(String btnName)
{
Button btn = getButton(btnName);
if (btn != null)
{
return btn.isVisible();
}
else
{
try
{
Messagebox.show("No "+btnName+" button available");
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
}
/**
* enable specific button
* @param id button id
* @param enabled enabled
*
* <p> The button id can be any of the following
* <dl>
* <dt>Ok</dt> <dd>Ok button</dd>
* <dt>Cancel</dt> <dd>Cancel button</dd>
* <dt>Refresh</dt> <dd>Refresh button</dd>
* <dt>Reset</dt> <dd>Reset button</dd>
* <dt>History</dt> <dd>History button</dd>
* <dt>Process</dt> <dd>Process button</dd>
* <dt>New</dt> <dd>New button</dd>
* <dt>Customize</dt> <dd>Customize button</dd>
* <dt>Delete</dt> <dd>Delete button</dd>
* <dt>Save</dt> <dd>Save button</dd>
* <dt>Zoom</dt> <dd>Zoom button</dd>
* <dt>Help</dt> <dd>Help button</dd>
* </dl>
*/
public void setEnabled(String id, boolean enabled)
{
Button button = getButton(id);
if (button != null)
{
button.setEnabled(enabled);
}
}
/**
* enable all components
* @param enabled enabled
*/
public void setEnabledAll(boolean enabled)
{
List list1 = pnlBtnLeft.getChildren();
List list2 = pnlBtnRight.getChildren();
Iterator iter1 = list1.iterator();
Iterator iter2 = list2.iterator();
while (iter1.hasNext())
{
Button button = (Button)iter1.next();
button.setEnabled(enabled);
}
while (iter2.hasNext())
{
Button button = (Button)iter2.next();
button.setEnabled(enabled);
}
}
/**
* add action listener on the existing buttons
* @param event event
* @param listener listener
*/
public void addActionListener(String event, EventListener listener)
{
List list1 = pnlBtnLeft.getChildren();
List list2 = pnlBtnRight.getChildren();
Iterator iter1 = list1.iterator();
Iterator iter2 = list2.iterator();
while (iter1.hasNext())
{
Button button = (Button)iter1.next();
button.addEventListener(event, listener);
}
while (iter2.hasNext())
{
Button button = (Button)iter2.next();
button.addEventListener(event, listener);
}
}
} // ConfirmPanel

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Datebox extends org.zkoss.zul.Datebox
{
private static final long serialVersionUID = 1L;
public void setEnabled(boolean enabled)
{
this.setDisabled(!enabled);
}
}

View File

@ -0,0 +1,102 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.zkoss.zk.ui.event.EventListener;
/**
* Editor Box consists of a text box and a button.
* May be used instaed of SearchBox, LocationBox....
*
* @author Niraj Sohun
* @date Jul 24, 2007
*/
public class EditorBox extends Panel
{
private static final long serialVersionUID = 1L;
private PropertyChangeSupport m_propertyChangeListeners = new PropertyChangeSupport(this);
private Textbox txt;
private Button btn;
public EditorBox()
{
initComponents();
}
public EditorBox(String text)
{
initComponents();
setText(text);
}
public void setButtonImage(String imageSrc)
{
btn.setImage(imageSrc);
}
private void initComponents()
{
txt = new Textbox();
btn = new Button();
this.appendChild(txt);
this.appendChild(btn);
}
public Textbox getTextBox()
{
return txt;
}
public void setText(String value)
{
txt.setText(value);
}
public String getText()
{
return txt.getText();
}
public void setEnabled(boolean enabled)
{
txt.setReadonly(enabled);
btn.setEnabled(enabled);
}
public boolean isEnabled()
{
return txt.isReadonly();
}
public boolean addEventListener(String evtnm, EventListener listener)
{
return btn.addEventListener(evtnm, listener);
}
public synchronized void addPropertyChangeListener(PropertyChangeListener l)
{
m_propertyChangeListeners.addPropertyChangeListener(l);
}
}

View File

@ -0,0 +1,257 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.util.ArrayList;
import org.adempiere.webui.panel.ADTabpanel;
import org.compiere.grid.VTabbedPane;
import org.compiere.model.DataStatusEvent;
import org.compiere.model.GridTab;
import org.compiere.util.CLogger;
import org.compiere.util.Evaluator;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Tabpanels;
import org.zkoss.zul.Tabs;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class FTabbox extends Tabbox
{
private static final long serialVersionUID = 1L;
/** Logger */
private static CLogger log = CLogger.getCLogger (VTabbedPane.class);
/** List of dependent Variables */
private ArrayList<String> m_dependents = new ArrayList<String>();
/** Tab Panels for this tab box */
private FTabpanels tabpanels;
/** Tabs associated to this tab box */
private Tabs tabs;
public FTabbox()
{
super();
init();
}
private void init()
{
tabpanels = new FTabpanels();
tabs = new Tabs();
//this.setSclass("lite");
this.appendChild(tabs);
this.appendChild(tabpanels);
this.setOrient("vertical");
}// init
/**
* Add Tab
* @param tabName name
* @param gTab grid tab model
* @param tabElement GridController or VSortTab
*/
public void addTab(GridTab gTab, Tabpanel tabPanel)
{
Tab tab = new Tab(gTab.getName());
tabPanel.setEnabled(gTab.isDisplayed());
tabs.appendChild(tab);
tabpanels.appendChild(tabPanel);
ArrayList<String> dependents = gTab.getDependentOn();
for (int i = 0; i < dependents.size(); i++)
{
String name = dependents.get(i);
if (!m_dependents.contains(name))
{
m_dependents.add(name);
}
}
}// addTab
/**
* @param index of tab panel
* @return
*/
public boolean isEnabledAt(int index)
{
Tabpanel tabpanel = tabpanels.getTabpanel(index);
if (tabpanel == null)
{
return false;
}
return tabpanel.isEnabled();
}// isEnabledAt
private boolean isDisplay(ADTabpanel tabpanel)
{
String logic = tabpanel.getDisplayLogic();
if (logic != null && logic.length() > 0)
{
boolean display = Evaluator.evaluateLogic(tabpanel, logic);
if (!display)
{
log.info("Not displayed - " + logic);
return false;
}
}
return true;
}
/**
*
* @param oldIndex
* @param newIndex
* @return
*/
public boolean updateSelectedIndex(int oldIndex, int newIndex)
{
Tabpanel tabpanel = tabpanels.getTabpanel(newIndex);
ADTabpanel newTab = (ADTabpanel)tabpanel;
if (tabpanel == null || !isDisplay(newTab))
{
super.setSelectedIndex(oldIndex);
return false;
}
boolean canJump = true;
if (newIndex != oldIndex)
{
ADTabpanel oldTabpanel = tabpanels.getTabpanel(oldIndex);
if (oldTabpanel != null)
{
ADTabpanel oldTab = oldTabpanel;
if (newTab.getTabLevel() > oldTab.getTabLevel())
{
int currentLevel = newTab.getTabLevel();
for (int i = newIndex - 1; i >= 0; i--)
{
ADTabpanel tabPanel = tabpanels.getTabpanel(i);
if (tabPanel.getTabLevel() < currentLevel)
{
if (!tabPanel.isCurrent())
{
canJump = false;
break;
}
currentLevel = tabPanel.getTabLevel();
}
}
}
}
else
{
canJump = false;
}
}
if (canJump)
{
super.setSelectedIndex(newIndex);
}
else
{
super.setSelectedIndex (oldIndex);
}
return canJump;
}
/**
* Evaluate Tab Logic
* @param e event
*/
public void evaluate (DataStatusEvent e)
{
boolean process = e == null;
String columnName = null;
if (!process)
{
columnName = e.getColumnName();
if (columnName != null)
process = m_dependents.contains(columnName);
else
process = true;
}
if (process)
{
log.config(columnName == null ? "" : columnName);
for (int i = 0; i < this.getTabCount(); i++)
{
ADTabpanel tabPanel = tabpanels.getTabpanel(i);
String logic = tabPanel.getDisplayLogic();
boolean display = true;
if (logic != null && logic.length() > 0)
{
display = Evaluator.evaluateLogic(tabPanel, logic);
}
tabPanel.setEnabled(display);
}
}
} // evaluate
/**
* @return the number of tab panels present
*/
public int getTabCount()
{
return tabpanels.getChildren().size();
}
public ADTabpanel getTabpanel(int index)
{
try
{
Tabpanels tabpanels = this.getTabpanels();
ADTabpanel tabPanel = (ADTabpanel)tabpanels.getChildren().get(index);
return tabPanel;
}
catch (Exception ex)
{
throw new IndexOutOfBoundsException(ex.getMessage());
}
}
/**
* Return the selected Tab Panel
*/
public ADTabpanel getSelectedTabpanel()
{
return getTabpanel(this.getSelectedIndex());
}
/**
* @return whether all events should be reported as they occur.
*/
public boolean isAsap()
{
return true;
}
public boolean containsTab(Tab tab)
{
return tabs.getChildren().contains(tab);
}
}

View File

@ -0,0 +1,49 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.adempiere.webui.panel.ADTabpanel;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class FTabpanels extends Tabpanels
{
private static final long serialVersionUID = 1L;
public boolean appendChild(Tabpanel tabPanel)
{
return super.appendChild(tabPanel);
}
public ADTabpanel getTabpanel(int index)
{
try
{
ADTabpanel tabPanel = (ADTabpanel)this.getChildren().get(index);
return tabPanel;
}
catch (Exception ex)
{
return null;
}
}
}

View File

@ -0,0 +1,36 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.zkoss.zul.Toolbar;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class FToolbar extends Toolbar
{
private static final long serialVersionUID = 1L;
public String getName()
{
return getId();
}
}

View File

@ -0,0 +1,35 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class FWindow extends Window
{
private static final long serialVersionUID = 1L;
public FWindow()
{
super();
}
}

View File

@ -0,0 +1,29 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Grid extends org.zkoss.zul.Grid
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,271 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.swing.table.AbstractTableModel;
import org.adempiere.webui.panel.ADWindowPanel;
import org.compiere.model.GridField;
import org.compiere.model.GridTab;
import org.compiere.model.GridTable;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.NamePair;
import org.zkforge.yuiext.grid.Column;
import org.zkforge.yuiext.grid.Columns;
import org.zkforge.yuiext.grid.Grid;
import org.zkforge.yuiext.grid.Label;
import org.zkforge.yuiext.grid.Row;
import org.zkforge.yuiext.grid.Rows;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Separator;
public class GridPanel extends Panel implements EventListener
{
private static final long serialVersionUID = 1L;
private Grid grid = new Grid();
private Rows rows = new Rows();
private Row row = new Row();
private Columns columns = new Columns();
private Column column = new Column();
private Label label = new Label();
private int pageSize = 10;
private long numPages;
private GridField[] gridField;
private AbstractTableModel tableModel;
private int numColumns = 5;
private int numRows;
private Button[] buttons;
private Hbox boxButtons = new Hbox();
private ADWindowPanel windowPanel;
private int windowNo;
private GridTab gridTab;
private int pageId = 0;
public GridPanel()
{
super();
}
public GridPanel(int windowNo, ADWindowPanel windowPanel)
{
this.windowNo = windowNo;
this.windowPanel = windowPanel;
}
public void init(GridTab gridTab)
{
this.gridTab = gridTab;
tableModel = gridTab.getTableModel();
numColumns = tableModel.getColumnCount();
numRows = tableModel.getRowCount();
gridField = ((GridTable)tableModel).getFields();
loadButtons();
loadGridHeader();
loadRecords(0, pageSize);
loadDisplay();
}
public void setPageSize(int pageSize)
{
this.pageSize = pageSize;
}
public void clear()
{
this.getChildren().clear();
}
public void showGrid(boolean bool)
{
if (bool)
this.setVisible(true);
else
this.setVisible(false);
}
private void loadGridHeader()
{
if (grid.getColumns() != null)
return;
columns = new Columns();
for (int i = 0; i < numColumns; i++)
{
if (gridField[i].isDisplayed())
{
column = new Column(gridField[i].getHeader());
columns.appendChild(column);
}
}
grid.appendChild(columns);
}
private void loadButtons()
{
double pages = (double)numRows / (double)pageSize;
pages = Math.ceil(pages);
numPages = Math.round(pages);
if (numPages == 1)
return;
buttons = new Button[(int)numPages];
if (boxButtons.getChildren() != null)
boxButtons.getChildren().clear();
for (int i = 0; i < buttons.length; i++)
{
Integer count = i;
buttons[i] = new Button();
buttons[i].setId(count.toString());
buttons[i].addEventListener(Events.ON_CLICK, this);
buttons[i].setLabel(count.toString());
boxButtons.appendChild(buttons[i]);
}
}
private String getCell(Object obj, int columnIndex)
{
if (obj == null)
return "";
if (tableModel.getColumnClass(columnIndex).equals(Integer.class))
{
if (gridField[columnIndex].isLookup())
{
MLookup lookup = MLookupFactory.get(
Env.getCtx(), windowNo, 0, gridField[columnIndex].getAD_Column_ID(),
gridField[columnIndex].getDisplayType());
NamePair namepair = lookup.get(obj);
if (namepair != null)
return namepair.getName();
else
return "";
}
else
return "Lookup";
}
else if (tableModel.getColumnClass(columnIndex).equals(Timestamp.class))
{
SimpleDateFormat dateFormat = DisplayType.getDateFormat(DisplayType.Date);
return dateFormat.format((Timestamp)obj);
}
else
return obj.toString();
}
private void loadRecords(int start, int end)
{
if (grid.getRows() != null)
grid.getRows().getChildren().clear();
if (rows.getChildren() != null)
rows.getChildren().clear();
if (end > numRows)
end = numRows;
for (int i = start; i < end; i++)
{
row = new Row();
for (int j = 0; j < numColumns; j++)
{
if (!gridField[j].isDisplayed())
break;
label = new Label(getCell(tableModel.getValueAt(i, j), j));
row.appendChild(label);
}
rows.appendChild(row);
}
if (grid.getRows() == null)
grid.appendChild(rows);
}
private void loadDisplay()
{
this.setWidth("800px");
//this.setHeight("1000px");
grid.setWidth("100%");
grid.setHeight("800px");
grid.addEventListener(Events.ON_SELECT, this);
boxButtons.setWidth("60%");
this.appendChild(grid);
this.appendChild(new Separator());
this.appendChild(boxButtons);
}
public void onEvent(Event event) throws Exception
{
if (event == null)
return;
if (event.getTarget() instanceof Button)
{
Button btn = (Button)event.getTarget();
pageId = new Integer(btn.getId());
int start = pageId * pageSize;
int end = start + pageSize;
loadRecords(start, end);
}
else if (event.getTarget() == grid)
{
int keyRecordId = grid.getSelectedIndex() + (pageId * pageSize);
gridTab.navigate(keyRecordId);
this.setVisible(false);
windowPanel.showTabbox(true);
}
}
}

View File

@ -0,0 +1,39 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Label extends org.zkoss.zul.Label
{
private static final long serialVersionUID = 1L;
public Label()
{
super();
}
public Label(String value)
{
super(value);
}
}

View File

@ -0,0 +1,32 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
public class ListCell extends org.zkoss.zul.Listcell
{
private static final long serialVersionUID = 1L;
public ListCell(String str)
{
super(str);
}
public ListCell()
{
super();
}
}

View File

@ -0,0 +1,23 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
public class ListHead extends org.zkoss.zul.Listhead
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,33 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
public class ListHeader extends org.zkoss.zul.Listheader
{
private static final long serialVersionUID = 1L;
public ListHeader(String str)
{
super(str);
}
public ListHeader()
{
}
}

View File

@ -0,0 +1,47 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 25, 2007
* @version $Revision: 0.10 $
*/
public class ListItem extends org.zkoss.zul.Listitem
{
private static final long serialVersionUID = 1L;
private PropertyChangeSupport m_propertyChangeListeners = new PropertyChangeSupport(this);
public ListItem(String label, Object value)
{
super(label, value);
}
public ListItem()
{
super();
}
public synchronized void addPropertyChangeListener(PropertyChangeListener l)
{
m_propertyChangeListeners.addPropertyChangeListener(l);
}
}

View File

@ -0,0 +1,306 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Vector;
import org.adempiere.webui.event.WTableModelEvent;
import org.adempiere.webui.event.WTableModelListener;
import org.zkoss.zul.ListModelExt;
import org.zkoss.zul.ListModelList;
/**
* This is a ListModel to be used with Listbox.
* The model allows for a table structure to be created, with columns
* in addition to the rows provided by {@link org.zkoss.zul.ListModelList}.
*
* @author Andrew Kimball
*
*/
public class ListModelTable extends ListModelList implements ListModelExt
{
/**
* The Uniqe Identifier of the class
*/
private static final long serialVersionUID = 1L;
/** Array of listeners to changes in the table model. */
protected ArrayList<WTableModelListener> m_listeners = new ArrayList<WTableModelListener>();
/** The number of columns in the table. */
private int m_noColumns;
/**
* Default constructor.
*
*/
public ListModelTable()
{
super();
}
/**
* Construct the ListModel with a collection of objects.
* A copy is made of the collection.
* The objects should be vectors of objects
*
* @param collection The collection of objects with which to initialise the list
*/
public ListModelTable(Collection collection)
{
super(collection);
m_noColumns = 0;
for (Object row : getInnerList())
{
if (row instanceof Vector)
{
m_noColumns = Math.max(m_noColumns, ((Vector)row).size());
}
else
{
throw new IllegalArgumentException("The collection must contain vectors of objects");
}
}
}
/**
* Query thenumber of columns in the table.
*
* @return the number of columns in the table. 0 if uninitialised.
*/
public int getNoColumns()
{
return m_noColumns;
}
/**
* Add a column to the model.
*
*/
public void addColumn()
{
m_noColumns++;
ensureRowSize();
return;
}
/**
* Ensure that each of the rows contains the correct number of elements.
* Please note that the table cannot be shrunk.
*/
private void ensureRowSize()
{
Iterator<Vector<Object>> rowIterator = this.getInnerList().iterator();
while (rowIterator.hasNext())
{
rowIterator.next().setSize(m_noColumns);
}
return;
}
/**
* Set the number of columns that the table is to contain.
* @param columns The number of columns.
*/
public void setNoColumns(int columns)
{
m_noColumns = columns;
ensureRowSize();
}
/**
* Query the number of rows in the table.
* @return the number of rows in the table
*/
public int getNoRows()
{
return this.getSize();
}
/**
* Returns the cell value at <code>rowIndex</code> and <code>columnIndex</code>.
*
* @param rowIndex the index of the row whose value is to be queried
* @param columnIndex the index of the column whose value is to be queried
* @return The object stored at the specified position
*/
public Object getDataAt(int rowIndex, int columnIndex)
{
Vector modelRow;
Object dataObject;
try
{
modelRow = (Vector)getElementAt(rowIndex);
dataObject = modelRow.get(columnIndex);
}
catch (Exception exception)
{
throw new IllegalArgumentException("Attempted to access "
+ "nonexistent ListModelTable field at "
+ rowIndex + ", " + columnIndex);
}
return dataObject;
}
/**
* Set the cell value at <code>row</code> and <code>column</code>.
*
* @param aValue The value to set
* @param row the index of the row whose value is to be set
* @param col the index of the column whose value is to be set
*/
public void setDataAt(Object aValue, int row, int col)
{
Vector<Object> vector;
WTableModelEvent tcEvent;
try
{
if (getElementAt(row) instanceof Vector)
{
vector = (Vector<Object>)getElementAt(row);
try
{
vector.set(col, aValue);
// create a new event and fire the event
tcEvent = new WTableModelEvent(this, row, col);
fireTableChange(tcEvent);
}
catch (ArrayIndexOutOfBoundsException exception)
{
throw new IllegalArgumentException("Attempted to access "
+ "nonexistent ListModelTable column at index "
+ col);
}
}
else
{
throw new IllegalArgumentException("The ListModelTable cannot contain "
+ "anything other than object vectors as its row elements");
}
}
catch (IndexOutOfBoundsException exception)
{
throw new IllegalArgumentException("Attempted to access "
+ "nonexistent ListModelTable row at index " + row);
}
return;
}
/**
* Set the number of rows in the table and initialise new rows.
* For each new row, an empty collection of the size specified by
* {@link #setNoColumns(int)} is created.
* Please note that the number of rows in a table cannot be decreased.
* @param rowCount The number of rows to be contained in the table
*/
public void setNoRows(int rowCount)
{
Vector newRow = null;
if (rowCount >= getSize())
{
while (getSize() < rowCount)
{
newRow = new Vector<Object>(getNoColumns());
newRow.setSize(getNoColumns());
add(newRow);
}
}
else
{
throw new IllegalArgumentException("The ListModelTable cannot be shrunk");
}
}
/**
* Add a listener for events from the data model.
*
* The listener will only be added if it doesn't already exist.
*
* @param listener A listener for changes in the table mode
*/
public void addTableModelListener(WTableModelListener listener)
{
if (listener == null)
{
return;
}
if (!m_listeners.contains(listener))
{
m_listeners.add(listener);
}
return;
}
public void removeTableModelListener(WTableModelListener listener)
{
m_listeners.remove(listener);
}
/**
* Send the specified <code>event</code> to all listeners.
*
* @param event The event tofire
*/
private void fireTableChange(WTableModelEvent event)
{
for (WTableModelListener listener : m_listeners)
{
listener.tableChanged(event);
}
return;
}
/*
* (non-Javadoc)
* @see org.zkoss.zul.ListModelList#sort(java.util.Comparator, boolean)
*/
public void sort(Comparator cmpr, boolean ascending)
{
Collections.sort(this.getInnerList(), cmpr);
WTableModelEvent event = new WTableModelEvent(this,
WTableModelEvent.ALL_ROWS,
WTableModelEvent.ALL_COLUMNS);
fireTableChange(event);
return;
}
}

View File

@ -0,0 +1,111 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.List;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Listbox extends org.zkoss.zul.Listbox
{
private static final long serialVersionUID = 1L;
private PropertyChangeSupport m_propertyChangeListeners = new PropertyChangeSupport(this);
public void setEnabled(boolean enabled)
{
this.setDisabled(!enabled);
}
public boolean isEnabled()
{
return !this.isDisabled();
}
public ListItem appendItem(String label, Object value)
{
ListItem item = new ListItem(label, value);
super.appendChild(item);
return item;
}
public ListItem appendItem(String label, String value)
{
ListItem item = new ListItem(label, value);
super.appendChild(item);
return item;
}
public ListItem getItemAtIndex(int index)
{
return (ListItem)super.getItemAtIndex(index);
}
public ListItem getSelectedItem()
{
return (ListItem)super.getSelectedItem();
}
@SuppressWarnings("unchecked")
public List<ListItem> getItems()
{
return (List<ListItem>)super.getItems();
}
public synchronized void addPropertyChangeListener(PropertyChangeListener l)
{
m_propertyChangeListeners.addPropertyChangeListener(l);
}
/**
* Set selected item for the list box based on the value of list item
* set selected to none if no item found matching the value given or
* value is null
* @param value Value of ListItem to set as selected
*/
public void setValue(Object value)
{
setSelectedItem(null);
if (value == null)
{
return ;
}
List<ListItem> items = getItems();
for (ListItem item : items)
{
if (value.equals(item.getValue()))
{
setSelectedItem(item);
break;
}
}
}
public ListHead getListHead()
{
return (ListHead)super.getListhead();
}
}

View File

@ -0,0 +1,95 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.zkoss.zk.ui.event.EventListener;
/** Location Editor component
* @author <a href="mailto:sendy.yagambrum@posterita.org">Sendy Yagambrum</a>
* @date July 16, 2007
**/
public class Locationbox extends Panel
{
private static final long serialVersionUID = 1L;
private PropertyChangeSupport m_propertyChangeListeners = new PropertyChangeSupport(this);
private Textbox txt;
private Button btn;
public Locationbox()
{
initComponents();
}
public Locationbox(String text)
{
initComponents();
setText(text);
}
public void setButtonImage(String imageSrc)
{
btn.setImage(imageSrc);
}
private void initComponents()
{
txt = new Textbox();
btn = new Button();
this.appendChild(txt);
this.appendChild(btn);
}
public Textbox getTextBox()
{
return txt;
}
public void setText(String value)
{
txt.setText(value);
}
public String getText()
{
return txt.getText();
}
public void setEnabled(boolean enabled)
{
txt.setReadonly(enabled);
btn.setEnabled(enabled);
}
public boolean isEnabled()
{
return !txt.isReadonly();
}
public boolean addEventListener(String evtnm, EventListener listener)
{
return btn.addEventListener(evtnm, listener);
}
public synchronized void addPropertyChangeListener(PropertyChangeListener l)
{
m_propertyChangeListeners.addPropertyChangeListener(l);
}
}

View File

@ -0,0 +1,272 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.adempiere.webui.apps.AEnv;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Image;
import org.zkoss.zul.Separator;
/**
* Messagebox : Replaces ZK's Messagebox
*
* @author Niraj Sohun
* @date Jul 31, 2007
*/
public class Messagebox extends Window implements EventListener
{
private static final long serialVersionUID = 1L;
private String msg = new String("");
private String imgSrc = new String("");
private Label lblMsg = new Label();
private Button btnOk = new Button();
private Button btnCancel = new Button();
private Button btnYes = new Button();
private Button btnNo = new Button();
private Button btnAbort = new Button();
private Button btnRetry = new Button();
private Button btnIgnore = new Button();
private Image img = new Image();
private int returnValue;
/** A OK button. */
public static final int OK = 0x0001;
/** A Cancel button. */
public static final int CANCEL = 0x0002;
/** A Yes button. */
public static final int YES = 0x0010;
/** A No button. */
public static final int NO = 0x0020;
/** A Abort button. */
public static final int ABORT = 0x0100;
/** A Retry button. */
public static final int RETRY = 0x0200;
/** A IGNORE button. */
public static final int IGNORE = 0x0400;
/** A symbol consisting of a question mark in a circle. */
public static final String QUESTION = "~./zul/img/question.gif";
/** A symbol consisting of an exclamation point in a triangle with a yellow background. */
public static final String EXCLAMATION = "~./zul/img/exclamation.gif";
/** A symbol of a lowercase letter i in a circle. */
public static final String INFORMATION = "~./zul/img/information.gif";
/** A symbol consisting of a white X in a circle with a red background. */
public static final String ERROR = "~./zul/img/error.gif";
/** Contains no symbols. */
public static final String NONE = null;
public Messagebox()
{
super();
}
private void init()
{
lblMsg.setValue(msg);
btnOk.setLabel("OK");
btnOk.setImage("/images/Ok24.gif");
btnOk.addEventListener(Events.ON_CLICK, this);
btnCancel.setLabel("Cancel");
btnCancel.setImage("/images/Cancel24.gif");
btnCancel.addEventListener(Events.ON_CLICK, this);
btnYes.setLabel("Yes");
btnYes.setImage("/images/Ok24.gif");
btnYes.addEventListener(Events.ON_CLICK, this);
btnNo.setLabel("No");
btnNo.setImage("/images/Cancel24.gif");
btnNo.addEventListener(Events.ON_CLICK, this);
btnAbort.setLabel("Abort");
//btnAbort.setImage("/images/");
btnAbort.addEventListener(Events.ON_CLICK, this);
btnRetry.setLabel("Retry");
//btnRetry.setImage("/images/");
btnRetry.addEventListener(Events.ON_CLICK, this);
btnIgnore.setLabel("Ignore");
btnIgnore.setImage("/images/Ignore24.gif");
btnIgnore.addEventListener(Events.ON_CLICK, this);
Panel pnlMessage = new Panel();
pnlMessage.setWidth("100%");
pnlMessage.setStyle("text-align:left");
pnlMessage.appendChild(lblMsg);
Panel pnlImage = new Panel();
img.setSrc(imgSrc);
pnlImage.setWidth("100%");
pnlImage.setStyle("text-align:center");
pnlImage.appendChild(img);
Hbox hbox = new Hbox();
hbox.setWidth("100%");
hbox.setWidths("10%, 90%");
hbox.appendChild(pnlImage);
hbox.appendChild(pnlMessage);
Hbox pnlButtons = new Hbox();
pnlButtons.setWidth("100%");
pnlButtons.setStyle("text-align:center");
pnlButtons.appendChild(btnOk);
pnlButtons.appendChild(btnCancel);
pnlButtons.appendChild(btnYes);
pnlButtons.appendChild(btnNo);
pnlButtons.appendChild(btnAbort);
pnlButtons.appendChild(btnRetry);
pnlButtons.appendChild(btnIgnore);
this.setWidth("100%");
this.setBorder("normal");
this.setContentStyle("background-color:#c0d1d2");
this.setPosition("left, top");
Separator blank = new Separator();
blank.setOrient("vertical");
blank.setHeight("5px");
hbox.appendChild(blank);
hbox.appendChild(pnlButtons);
this.appendChild(hbox);
}
public int show(String message, String title, int buttons, String icon)
throws InterruptedException
{
this.msg = message;
this.imgSrc = icon;
btnOk.setVisible(false);
btnCancel.setVisible(false);
btnYes.setVisible(false);
btnNo.setVisible(false);
btnRetry.setVisible(false);
btnAbort.setVisible(false);
btnIgnore.setVisible(false);
if ((buttons & OK) != 0)
btnOk.setVisible(true);
if ((buttons & CANCEL) != 0)
btnCancel.setVisible(true);
if ((buttons & YES) != 0)
btnYes.setVisible(true);
if ((buttons & NO) != 0)
btnNo.setVisible(true);
if ((buttons & RETRY) != 0)
btnRetry.setVisible(true);
if ((buttons & ABORT) != 0)
btnAbort.setVisible(true);
if ((buttons & IGNORE) != 0)
btnIgnore.setVisible(true);
init();
if (icon == QUESTION)
{
this.setTitle(title);
this.setWidth("500px");
this.setPosition("center");
this.setClosable(true);
this.setAttribute("mode", "modal");
}
else
this.setAttribute("mode", "overlapped");
this.setVisible(true);
AEnv.showWindow(this);
return returnValue;
}
public static int showDialog(String message, String title, int buttons, String icon) throws InterruptedException
{
Messagebox msg = new Messagebox();
return msg.show(message, title, buttons, icon);
}
public void onEvent(Event event) throws Exception
{
if (event == null)
return;
if (event.getTarget() == btnOk)
{
returnValue = OK;
}
else if (event.getTarget() == btnCancel)
{
returnValue = CANCEL;
}
else if (event.getTarget() == btnYes)
{
returnValue = YES;
}
else if (event.getTarget() == btnNo)
{
returnValue = NO;
}
else if (event.getTarget() == btnAbort)
{
returnValue = ABORT;
}
else if (event.getTarget() == btnRetry)
{
returnValue = RETRY;
}
else if (event.getTarget() == btnIgnore)
{
returnValue = IGNORE;
}
this.detach();
}
}

View File

@ -0,0 +1,276 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.text.NumberFormat;
import java.text.ParseException;
import org.zkoss.zul.Bandpopup;
import org.zkoss.zul.Button;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Vbox;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 11, 2007
* @version $Revision: 0.10 $
*/
public class NumberBox extends Bandbox
{
private static final long serialVersionUID = 1L;
private Textbox txtCalc = new Textbox();
boolean integral = false;
NumberFormat format = null;
public NumberBox(boolean integral)
{
super();
this.integral = integral;
init();
}
private void init()
{
this.setImage("/images/Calculator16.gif");
this.setAction("onKeyPress : return calc.validate('" +
this.getId() + "'," + integral + ", event);");
this.appendChild(getBandPopup());
}
public void setFormat(NumberFormat format)
{
this.format = format;
}
public void setValue(Number value)
{
if (format != null)
{
super.setValue(format.format(value));
}
else
{
super.setValue(value.toString());
}
}
public void setRawValue(Object value)
{
super.setRawValue(value);
}
public String getText()
{
return super.getText();
}
public void setValue(String value)
{
String formattedValue = "";
Number numberValue = null;
if (format != null)
{
try
{
numberValue = format.parse(value);
formattedValue = format.format(numberValue);
}
catch (ParseException e)
{
formattedValue = value;
}
}
else
{
formattedValue = value;
}
super.setValue(formattedValue);
}
public void setReadonly(boolean readonly)
{
// Due to bug in bandbox - once set readonly, setting to not readonly
// does not work
super.setDisabled(readonly);
}
private Bandpopup getBandPopup()
{
Bandpopup bandPopup = new Bandpopup();
Vbox vbox = new Vbox();
txtCalc = new Textbox();
txtCalc.setAction("onKeyPress : return calc.validate('" +
this.getId() + "!real','" + txtCalc.getId()
+ "'," + integral + ", event);");
txtCalc.setMaxlength(250);
txtCalc.setCols(30);
String txtCalcId = txtCalc.getId();
vbox.appendChild(txtCalc);
Hbox row1 = new Hbox();
Button btnAC = new Button();
btnAC.setWidth("40px");
btnAC.setLabel("AC");
btnAC.setAction("onClick : calc.clearAll('" + txtCalcId + "')");
Button btn7 = new Button();
btn7.setWidth("30px");
btn7.setLabel("7");
btn7.setAction("onClick : calc.append('" + txtCalcId + "', '7')");
Button btn8 = new Button();
btn8.setWidth("30px");
btn8.setLabel("8");
btn8.setAction("onClick : calc.append('" + txtCalcId + "', '8')");
Button btn9 = new Button();
btn9.setWidth("30px");
btn9.setLabel("9");
btn9.setAction("onClick : calc.append('" + txtCalcId + "', '9')");
Button btnMultiply = new Button();
btnMultiply.setWidth("30px");
btnMultiply.setLabel("*");
btnMultiply.setAction("onClick : calc.append('" + txtCalcId + "', ' * ')");
row1.appendChild(btnAC);
row1.appendChild(btn7);
row1.appendChild(btn8);
row1.appendChild(btn9);
row1.appendChild(btnMultiply);
Hbox row2 = new Hbox();
Button btnC = new Button();
btnC.setWidth("40px");
btnC.setLabel("C");
btnC.setAction("onClick : calc.clear('" + txtCalcId + "')");
Button btn4 = new Button();
btn4.setWidth("30px");
btn4.setLabel("4");
btn4.setAction("onClick : calc.append('" + txtCalcId + "', '4')");
Button btn5 = new Button();
btn5.setWidth("30px");
btn5.setLabel("5");
btn5.setAction("onClick : calc.append('" + txtCalcId + "', '5')");
Button btn6 = new Button();
btn6.setWidth("30px");
btn6.setLabel("6");
btn6.setAction("onClick : calc.append('" + txtCalcId + "', '6')");
Button btnDivide = new Button();
btnDivide.setWidth("30px");
btnDivide.setLabel("/");
btnDivide.setAction("onClick : calc.append('" + txtCalcId + "', ' / ')");
row2.appendChild(btnC);
row2.appendChild(btn4);
row2.appendChild(btn5);
row2.appendChild(btn6);
row2.appendChild(btnDivide);
Hbox row3 = new Hbox();
Button btnModulo = new Button();
btnModulo.setWidth("40px");
btnModulo.setLabel("%");
btnModulo.setAction("onClick : calc.append('" + txtCalcId + "', ' % ')");
Button btn1 = new Button();
btn1.setWidth("30px");
btn1.setLabel("1");
btn1.setAction("onClick : calc.append('" + txtCalcId + "', '1')");
Button btn2 = new Button();
btn2.setWidth("30px");
btn2.setLabel("2");
btn2.setAction("onClick : calc.append('" + txtCalcId + "', '2')");
Button btn3 = new Button();
btn3.setWidth("30px");
btn3.setLabel("3");
btn3.setAction("onClick : calc.append('" + txtCalcId + "', '3')");
Button btnSubstract = new Button();
btnSubstract.setWidth("30px");
btnSubstract.setLabel("-");
btnSubstract.setAction("onClick : calc.append('" + txtCalcId + "', ' - ')");
row3.appendChild(btnModulo);
row3.appendChild(btn1);
row3.appendChild(btn2);
row3.appendChild(btn3);
row3.appendChild(btnSubstract);
Hbox row4 = new Hbox();
Button btnCurrency = new Button();
btnCurrency.setWidth("40px");
btnCurrency.setLabel("$");
btnCurrency.setDisabled(true);
Button btn0 = new Button();
btn0.setWidth("30px");
btn0.setLabel("0");
btn0.setAction("onClick : calc.append('" + txtCalcId + "', '0')");
Button btnDot = new Button();
btnDot.setWidth("30px");
btnDot.setLabel(".");
btnDot.setDisabled(integral);
btnDot.setAction("onClick : calc.append('" + txtCalcId + "', '.')");
Button btnEqual = new Button();
btnEqual.setWidth("30px");
btnEqual.setLabel("=");
btnEqual.setAction("onClick : calc.evaluate('" + this.getId() + "!real','"
+ txtCalcId + "')");
Button btnAdd = new Button();
btnAdd.setWidth("30px");
btnAdd.setLabel("+");
btnAdd.setAction("onClick : calc.append('" + txtCalcId + "', ' + ')");
row4.appendChild(btnCurrency);
row4.appendChild(btnDot);
row4.appendChild(btn0);
row4.appendChild(btnEqual);
row4.appendChild(btnAdd);
vbox.appendChild(row1);
vbox.appendChild(row2);
vbox.appendChild(row3);
vbox.appendChild(row4);
bandPopup.appendChild(vbox);
return bandPopup;
}
}

View File

@ -0,0 +1,40 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.zkoss.zul.Div;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Panel extends Div
{
private static final long serialVersionUID = 1L;
public static final String HORIZONTAL = "horizontal";
public static final String VERTICAL = "vertical";
public Panel()
{
super();
}
}

View File

@ -0,0 +1,30 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Row extends org.zkoss.zul.Row
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,30 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Rows extends org.zkoss.zul.Rows
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,107 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.zkoss.zk.ui.event.EventListener;
public class Searchbox extends Panel
{
private static final long serialVersionUID = 1L;
private PropertyChangeSupport m_propertyChangeListeners = new PropertyChangeSupport(this);
private Textbox txt;
private Button btn;
public Searchbox()
{
initComponents();
}
public Searchbox(String text)
{
initComponents();
setText(text);
}
public void setButtonImage(String imageSrc)
{
btn.setImage(imageSrc);
}
private void initComponents()
{
txt = new Textbox();
btn = new Button();
appendChild(txt);
appendChild(btn);
}
public Textbox getTextBox()
{
return txt;
}
public void setText(String value)
{
txt.setText(value);
}
public String getText()
{
return txt.getText();
}
public void setEnabled(boolean enabled)
{
txt.setEnabled(enabled);
btn.setEnabled(enabled);
}
public boolean isEnabled()
{
return txt.isReadonly();
}
public boolean addEventListener(String evtnm, EventListener listener)
{
if("onClick".equals(evtnm))
{
return btn.addEventListener(evtnm, listener);
}
else
{
return txt.addEventListener(evtnm, listener);
}
}
public synchronized void addPropertyChangeListener(PropertyChangeListener l)
{
m_propertyChangeListeners.addPropertyChangeListener(l);
}
/**
* Set whether the SearchBox represents a mandatory field.
*
* @param mandatory whether the search box must be filled
*/
public void setMandatory(boolean mandatory)
{
txt.setMandatory(mandatory);
}
}

View File

@ -0,0 +1,40 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Tab extends org.zkoss.zul.Tab
{
private static final long serialVersionUID = 1L;
public Tab(String str)
{
this.setLabel(str);
}
public Tab()
{
}
}

View File

@ -0,0 +1,50 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.zkoss.zul.Tabpanels;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Tabbox extends org.zkoss.zul.Tabbox
{
private static final long serialVersionUID = 1L;
public Tabpanel getTabpanel(int index)
{
try
{
Tabpanels tabpanels = this.getTabpanels();
Tabpanel tabPanel = (Tabpanel)tabpanels.getChildren().get(index);
return tabPanel;
}
catch (Exception ex)
{
throw new IndexOutOfBoundsException(ex.getMessage());
}
}
public Tabpanel getSelectedTabpanel()
{
return getTabpanel(this.getSelectedIndex());
}
}

View File

@ -0,0 +1,41 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Tabpanel extends org.zkoss.zul.Tabpanel
{
private static final long serialVersionUID = 1L;
private boolean enabled;
public boolean isEnabled()
{
return enabled;
}
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
}

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Tabpanels extends org.zkoss.zul.Tabpanels
{
private static final long serialVersionUID = 1L;
public Tabpanels()
{
super();
}
}

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 2, 2007
* @version $Revision: 0.10 $
*/
public class Tabs extends org.zkoss.zul.Tabs
{
private static final long serialVersionUID = 1L;
public Tabs()
{
super();
}
}

View File

@ -0,0 +1,62 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.zkoss.zk.ui.WrongValueException;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Textbox extends org.zkoss.zul.Textbox
{
private static final long serialVersionUID = 1L;
public Textbox()
{
super();
}
public Textbox(String value) throws WrongValueException
{
super(value);
}
public void setEnabled(boolean enabled)
{
this.setDisabled(!enabled);
}
/**
* Set whether the textbox represents a mandatory field.
*
* @param mandatory whether the texbox must be filled
*/
public void setMandatory(boolean mandatory)
{
/* if (mandatory)
{
ZkCssHelper.setStyleBackgroundColor(this, AdempierePLAF.getFieldBackground_Mandatory());
}
*/
this.setStyle("background-color:#e1d6d6");
}
}

View File

@ -0,0 +1,29 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
* @author Sendy Yagambrum
* @date July, 10 2007
*/
public class ToolBar extends org.zkoss.zul.Toolbar
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,29 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
* @author Sendy Yagambrum
* @date July, 10 2007
*/
public class ToolBarButton extends org.zkoss.zul.Toolbarbutton
{
private static final long serialVersionUID = 0L;
}

View File

@ -0,0 +1,86 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import org.zkoss.zk.ui.event.EventListener;
/**
* URL Box
*/
public class Urlbox extends Panel
{
private static final long serialVersionUID = 1L;
private Textbox txtUrl;
private Button btnUrl;
public Urlbox()
{
initComponents();
}
public Urlbox(String url)
{
initComponents();
setText(url);
}
public void setButtonImage(String imageSrc)
{
btnUrl.setImage(imageSrc);
}
private void initComponents()
{
txtUrl = new Textbox();
btnUrl = new Button();
appendChild(txtUrl);
appendChild(btnUrl);
}
public void setText(String value)
{
txtUrl.setText(value);
}
public String getText()
{
return txtUrl.getText();
}
public void setEnabled(boolean enabled)
{
txtUrl.setEnabled(enabled);
btnUrl.setEnabled(enabled);
}
public void setButtonEnabled(boolean enabled)
{
btnUrl.setEnabled(enabled);
}
public boolean addEventListener(String evtnm, EventListener listener)
{
if ("onClick".equals(evtnm))
return btnUrl.addEventListener(evtnm, listener);
else
return txtUrl.addEventListener(evtnm, listener);
}
}

View File

@ -0,0 +1,30 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class VerticalBox extends org.zkoss.zul.Vbox
{
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,211 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.awt.Dimension;
import java.io.IOException;
import java.net.URI;
import org.adempiere.webui.apps.AEnv;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* Application Action.
* Creates Action with MenuItem and Button, delegate execution of action to an attached ActionListener instance
* The ActionCommand is translated for display
* If translated text contains &, the next character is the Mnemonic
*
* @author Andrew Kimball
*/
public class WAppsAction implements EventListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Application Action
*
* @param action base action command - used as AD_Message for Text and Icon name
* @param accelerator optional keystroke for accelerator
* @param toggle is toggle action (maintains state)
*/
public WAppsAction (String action, String accelerator) throws IOException
{
this (action, accelerator, null);
}
/**
* Application Action.
*
* @param action base action command - used as AD_Message for Text and Icon name
* @param accelerator optional keystroke for accelerator
* @param toolTipText text, if null defered from action
* @param toggle is toggle action (maintains state)
*/
public WAppsAction (String action, String accelerator, String toolTipText) throws IOException
{
super();
String newToolTipText = toolTipText;
m_action = action;
if (m_accelerator == null)
{
m_accelerator = "";
}
else
{
m_accelerator = accelerator;
}
// Data
if (newToolTipText == null)
{
newToolTipText = Msg.getMsg(Env.getCtx(), action);
}
int pos = newToolTipText.indexOf('&');
if (pos != -1 && newToolTipText.length() > pos) // We have a nemonic - creates ALT-_
{
// TODO create mnemonic
Character ch = new Character(newToolTipText.toLowerCase().charAt(pos + 1));
if (ch != ' ')
{
// remove ampersand
newToolTipText = newToolTipText.substring(0, pos)
+ newToolTipText.substring(pos + 1);
// append ALT-mnemonic to accelerator
m_accelerator += "@" + ch;
}
}
//
//Image small = getImage(action, true);
URI large = getImage(action, false);
//Image largePressed = null;
// Attributes
m_button = new Button();
m_button.setTooltiptext(newToolTipText); // Display
// Create Button
m_button.setName(action);
// Correcting Action items
if (large != null)
{
m_button.setImage(large.getPath());
//m_button.setImage("/images/Cancel16.gif");
m_button.setLabel(null);
}
m_button.setWidth(Integer.toString(Double.valueOf(BUTTON_SIZE.getWidth()).intValue()));
m_button.setHeight(Integer.toString(Double.valueOf(BUTTON_SIZE.getHeight()).intValue()));
} // Action
/** Button Size */
public static final Dimension BUTTON_SIZE = new Dimension(28,28);
/** CButton or CToggelButton */
private Button m_button;
private String m_action = null;
private String m_accelerator = null;
private EventListener m_delegate = null;
/**
* Get Icon with name action
* @param name name
* @param small small
* @return Icon
*/
private URI getImage(String name, boolean small) throws IOException
{
String fullName = name + (small ? "16" : "24");
URI uri = AEnv.getImage2(fullName);
return uri;
} // getIcon
/**
* Get Name/ActionCommand
* @return ActionName
*/
public String getName()
{
return m_action;
} // getName
/**
* Return Button
* @return Button
*/
public Button getButton()
{
return m_button;
} // getButton
/**
* Set Delegate to receive the actionPerformed calls
* @param listener listener
* @throws IllegalArgumentException if the listener is not a window. This
* exception can be ignored as events will still be fired for button presses.
*/
public void setDelegate(EventListener listener) throws IllegalArgumentException
{
m_button.addEventListener(Events.ON_CLICK, this);
m_delegate = listener;
if (listener instanceof Window)
{
((Window) listener).setCtrlKeys(this.m_accelerator);
((Window) listener).addEventListener(Events.ON_CTRL_KEY, this);
}
else
{
throw new IllegalArgumentException("Functionality has been restricted. "
+ " as a result of the listener not being a Window. "
+ "Consequently, it is unable to respond to keystrokes");
}
return;
} // setDelegate
/* (non-Javadoc)
* @see org.zkoss.zk.ui.event.EventListener#onEvent(org.zkoss.zk.ui.event.Event)
*/
public void onEvent(Event event) throws Exception
{
// TODO Auto-generated method stub
Event newEvent = new Event(this.m_action, event.getTarget());
m_delegate.onEvent(newEvent);
return;
}
public String getCtrlKeys()
{
return this.m_accelerator;
}
}

View File

@ -0,0 +1,652 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.io.IOException;
import java.util.logging.Level;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* @author Andrew Kimball
*
*/
public class WConfirmPanel extends Panel implements EventListener
{
/** Action String OK. */
public static final String A_OK = "Ok";
/** Action String Cancel. */
public static final String A_CANCEL = "Cancel";
/** Action String Refresh. */
public static final String A_REFRESH = "Refresh";
/** Action String Reset. */
public static final String A_RESET = "Reset";
/** Action String Customize. */
public static final String A_CUSTOMIZE = "Customize";
/** Action String History. */
public static final String A_HISTORY = "History";
/** Action String Zoom. */
public static final String A_ZOOM = "Zoom";
/** Action String Process. */
public static final String A_PROCESS = "Process";
/** Action String Print. */
public static final String A_PRINT = "Print";
/** Action String Export. */
public static final String A_EXPORT = "Export";
/** Action String Help. */
public static final String A_HELP = "Help";
/** Action String Delete. */
public static final String A_DELETE = "Delete";
/** Action String PAttribute. */
public static final String A_PATTRIBUTE = "PAttribute";
/** Action String New. */
public static final String A_NEW = "New";
/** Logger. */
private static CLogger log = CLogger.getCLogger(WConfirmPanel.class);
/** Cancel action. */
private WAppsAction m_actionCancel;
private WAppsAction m_actionOk;
private WAppsAction m_actionRefresh;
private WAppsAction m_actionReset;
private WAppsAction m_actionCustomize;
private WAppsAction m_actionHistory;
private WAppsAction m_actionZoom;
/**
* Create Confirmation Panel with OK Button.
*/
public WConfirmPanel()
{
this (false, false, false, false, false, false, true);
} // ConfirmPanel
/**
* Create Confirmation Panel with OK and Cancel Button.
* @param withCancelButton with cancel
*/
public WConfirmPanel(boolean withCancelButton)
{
this(withCancelButton, false, false, false, false, false, true);
}
/**
* Create Confirmation Panel with different buttons.
* @param withCancelButton with cancel
* @param withRefreshButton with refresh
* @param withResetButton with reset
* @param withCustomizeButton with customize
* @param withHistoryButton with history
* @param withZoomButton with zoom
* @param withText with tool tip text
*/
public WConfirmPanel(boolean withCancelButton,
boolean withRefreshButton,
boolean withResetButton,
boolean withCustomizeButton,
boolean withHistoryButton,
boolean withZoomButton,
boolean withText)
{
Panel pnlOkCancel = new Panel();
Button button;
try
{
this.setAlign("right");
// Cancel
m_actionCancel = createCancelButton(withText);
Button btnCancel = m_actionCancel.getButton();
setCancelVisible(btnCancel, withCancelButton);
pnlOkCancel.appendChild(btnCancel);
// OK
m_actionOk = createOKButton(withText);
Button btnOk = m_actionOk.getButton();
pnlOkCancel.appendChild(btnOk);
this.appendChild(pnlOkCancel);
//
if (withRefreshButton)
{
m_actionRefresh = createRefreshButton(withText);
Button btnRefresh = m_actionRefresh.getButton();
this.appendChild(btnRefresh);
}
if (withResetButton)
{
m_actionReset = createResetButton(withText);
Button btnReset = m_actionReset.getButton();
this.appendChild(btnReset);
}
if (withCustomizeButton)
{
m_actionCustomize = createCustomizeButton(withText);
Button btnCustomize = m_actionCustomize.getButton();
this.appendChild(btnCustomize);
}
if (withHistoryButton)
{
m_actionHistory = createHistoryButton(withText);
Button btnHistory = m_actionHistory.getButton();
this.appendChild(btnHistory);
}
if (withZoomButton)
{
m_actionZoom = createZoomButton(withText);
Button btnZoom = m_actionZoom.getButton();
this.appendChild(btnZoom);
}
}
catch(Exception exception)
{
log.log(Level.WARNING, "Failed to correctly create Confirmation Panel:"
+ exception.getMessage());
}
} // ConfirmPanel
/**
* Create OK Button with Standard text.
* @param withText with text
* @return OK Button
*/
public static final WAppsAction createOKButton (boolean withText) throws IOException
{
if (withText)
{
return createOKButton(Msg.getMsg(Env.getCtx(), A_OK));
}
return createOKButton("");
} // createOKButton
/**
* Create OK Button with label text and F4 Shortcut.
* @param text text
* @return OK Button
*/
public static final WAppsAction createOKButton (String text) throws IOException
{
final String specialKey = "#f2";
WAppsAction aa = new WAppsAction(A_OK, specialKey, text);
return aa;
} // createOKButton
/**
* Create Cancel Button wlth label text and register ESC as KeyStroke.
* @param text text
* @return Cancel Button
*/
public static final WAppsAction createCancelButton(String text) throws IOException
{
WAppsAction aa = new WAppsAction(A_CANCEL, null, text);
return aa;
} // createCancelButton
/**
* Create Cancel Button wlth Standard text.
* @param withText with text
* @return Button
*/
public static final WAppsAction createCancelButton(boolean withText) throws IOException
{
if (withText)
{
return createCancelButton(Msg.getMsg(Env.getCtx(), A_CANCEL));
}
return createCancelButton("");
} // createCancelButton
/**
* Create Refresh Button wlth label text and F5.
* @param text text
* @return button
*/
public static final WAppsAction createRefreshButton (String text) throws IOException
{
final String specialKey = "#f5";
WAppsAction aa = new WAppsAction(A_REFRESH, specialKey, text);
return aa;
} // createRefreshButton
/**
* Create Refresh Button wlth Standard text.
* @param withText with text
* @return Button
*/
public static final WAppsAction createRefreshButton (boolean withText) throws IOException
{
if (withText)
{
return createRefreshButton(Msg.getMsg(Env.getCtx(), A_REFRESH));
}
return createRefreshButton("");
} // createRefreshButton
/**
* Create Reset Button wlth label text.
* @param text text
* @return button
*/
public static final WAppsAction createResetButton (String text) throws IOException
{
WAppsAction aa = new WAppsAction(A_RESET, null, text);
return aa;
} // createResetButton
/**
* Create Reset Button wlth Standard text.
* @param withText with text
* @return Button
*/
public static final WAppsAction createResetButton (boolean withText) throws IOException
{
if (withText)
{
return createResetButton(Msg.getMsg(Env.getCtx(), A_RESET));
}
return createResetButton(null);
} // createRefreshButton
/**
* Create Customize Button wlth label text.
* @param text text
* @return button
*/
public static final WAppsAction createCustomizeButton (String text) throws IOException
{
WAppsAction aa = new WAppsAction(A_CUSTOMIZE, null, text);
return aa;
// Env.getImageIcon("Preference24.gif"));
} // createCustomizeButton
/**
* Create Customize Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createCustomizeButton (boolean withText) throws IOException
{
if (withText)
{
return createCustomizeButton(Msg.getMsg(Env.getCtx(), A_CUSTOMIZE));
}
return createCustomizeButton(null);
} // createCustomizeButton
/**
* Create History Button wlth label text.
* @param text text
* @return aa
*/
public static final WAppsAction createHistoryButton (String text) throws IOException
{
final String specialKey = "#f9";
WAppsAction aa = new WAppsAction(A_HISTORY, specialKey, text);
return aa;
} // createHistoryButton
/**
* Create History Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createHistoryButton (boolean withText) throws IOException
{
if (withText)
{
return createHistoryButton(Msg.getMsg(Env.getCtx(), A_HISTORY));
}
return createHistoryButton(null);
} // createHistoryButton
/**
* Create Zoom Button wlth label text.
* @param text text
* @return aa
*/
public static final WAppsAction createZoomButton (String text) throws IOException
{
WAppsAction aa = new WAppsAction(A_ZOOM, null, text);
return aa;
} // createZoomButton
/**
* Create Zoom Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createZoomButton (boolean withText) throws IOException
{
if (withText)
{
return createZoomButton(Msg.getMsg(Env.getCtx(), A_ZOOM));
}
return createZoomButton(null);
} // createZoomButton
/**
* Create Process Button wlth label text Shift-F4.
* @param text text
* @return aa
*/
public static final WAppsAction createProcessButton (String text) throws IOException
{
// Shift-F4
final String specialKey = "$#f4";
WAppsAction aa = new WAppsAction(A_PROCESS, specialKey, text);
return aa;
} // createProcessButton
/**
* Create Process Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createProcessButton (boolean withText) throws IOException
{
if (withText)
{
return createProcessButton(Msg.getMsg(Env.getCtx(), A_PROCESS));
}
return createProcessButton(null);
} // createProcessButton
/**
* Create Print Button wlth label text.
* @param text text
* @return aa
*/
public static final WAppsAction createPrintButton (String text) throws IOException
{
final String specialKey = "#f12";
WAppsAction aa = new WAppsAction(A_PRINT, specialKey, text);
return aa;
} // createPrintButton
/**
* Create Print Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createPrintButton (boolean withText) throws IOException
{
if (withText)
{
return createPrintButton(Msg.getMsg(Env.getCtx(), A_PRINT));
}
return createPrintButton(null);
} // createPrintButton
/**
* Create Help Button wlth label text.
* @param text text
* @return aa
*/
public static final WAppsAction createHelpButton (String text) throws IOException
{
final String specialKey = "#f1";
WAppsAction aa = new WAppsAction(A_HELP, specialKey, text);
return aa;
} // createHelpButton
/**
* Create Help Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createHelpButton (boolean withText) throws IOException
{
if (withText)
{
return createHelpButton(Msg.getMsg(Env.getCtx(), A_HELP));
}
return createHelpButton(null);
} // createHelpButton
/**
* Create Export Button wlth label text.
* @param text text
* @return aa
*/
public static final WAppsAction createExportButton (String text) throws IOException
{
WAppsAction aa = new WAppsAction(A_EXPORT, null, text);
return aa;
} // createExportButton
/**
* Create Export Button wlth Standard text.
* @param withText with text
* @return aa
*/
public static final WAppsAction createExportButton (boolean withText) throws IOException
{
if (withText)
{
return createExportButton(Msg.getMsg(Env.getCtx(), A_EXPORT));
}
return createExportButton(null);
} // createExportButton
/************************
* Create Delete Button with label text - F3.
* @param text text
* @return Delete Button
*/
public static final WAppsAction createDeleteButton (String text) throws IOException
{
final String specialKey = "#f3";
WAppsAction aa = new WAppsAction(A_DELETE, specialKey, text);
return aa;
} // createDeleteButton
/**
* Create Delete Button with Standard text.
* @param withText with text
* @return Delete Button
*/
public static final WAppsAction createDeleteButton (boolean withText) throws IOException
{
if (withText)
{
return createDeleteButton(Msg.getMsg(Env.getCtx(), A_DELETE));
}
return createDeleteButton(null);
} // createDeleteButton
/************************
* Create Product Attribute Button with Standard text.
* @param withText with text
* @return Product Attribute Button
*/
public static final WAppsAction createPAttributeButton (boolean withText) throws IOException
{
if (withText)
{
return createPAttributeButton(Msg.getMsg(Env.getCtx(), A_PATTRIBUTE));
}
return createPAttributeButton(null);
} // createPAttributeButton
/**
* Create Product Attribute Button with label text.
* @param text text
* @return Product Attribute Button
*/
public static final WAppsAction createPAttributeButton (String text) throws IOException
{
WAppsAction aa = new WAppsAction(A_PATTRIBUTE, null, text);
return aa;
} // createPAttributeButton
/**
* Create New Button with Standard text.
* @param withText with text
* @return New Button
*/
public static final WAppsAction createNewButton (boolean withText) throws IOException
{
if (withText)
{
return createNewButton(Msg.getMsg(Env.getCtx(), A_NEW));
}
return createNewButton(null);
} // createNewButton
/**
* Create New Button with label text - F2.
* @param text text
* @return Product Attribute Button
*/
public static final WAppsAction createNewButton (String text) throws IOException
{
final String specialKey = "#f2";
WAppsAction aa = new WAppsAction(A_NEW, specialKey, text);
return aa;
} // createNewButton
/**
* Show Cancel button.
* @param value trie for visible
*/
public void setCancelVisible (Button button, boolean value)
{
button.setVisible(value);
button.setEnabled(value);
}
/**
* Add Event Listener.
* <code>
* if (e.getActionCommand().equals(ConfirmPanel.A_OK))
* </code>
* In order to respond to keystrokes, the <code>EventListener</code>
* should be a <code>Window</code>. If the listener is not a window
* the panel will only respond to <code>onClick</code> events.
*
* @param listener the event listener
*/
public void addEventListener(EventListener listener)
{
String ctrlKeys = "";
try
{
m_actionOk.setDelegate(listener);
ctrlKeys += m_actionOk.getCtrlKeys();
m_actionCancel.setDelegate(listener);
ctrlKeys += m_actionCancel.getCtrlKeys();
//
if (m_actionRefresh != null)
{
m_actionRefresh.setDelegate(listener);
ctrlKeys += m_actionRefresh.getCtrlKeys();
}
if (m_actionReset != null)
{
m_actionReset.setDelegate(listener);
ctrlKeys += m_actionReset.getCtrlKeys();
}
if (m_actionCustomize != null)
{
m_actionCustomize.setDelegate(listener);
ctrlKeys += m_actionCustomize.getCtrlKeys();
}
if (m_actionHistory != null)
{
m_actionHistory.setDelegate(listener);
ctrlKeys += m_actionHistory.getCtrlKeys();
}
if (m_actionZoom != null)
{
m_actionZoom.setDelegate(listener);
ctrlKeys += m_actionZoom.getCtrlKeys();
}
}
catch (IllegalArgumentException exception)
{
log.warning(exception.getMessage());
}
// Set OK as default Button
// and Cancel as cancel button
if (listener instanceof Window)
{
((Window) listener).addEventListener(Events.ON_CANCEL, m_actionCancel);
((Window) listener).addEventListener(Events.ON_OK, m_actionOk);
// TODO enable Ctrl Keys
//((Window) listener).setCtrlKeys(ctrlKeys);
//((Window) listener).addEventListener(Events.ON_CTRL_KEY, this);
}
else
{
log.warning("Functionality of the Confirmation Panel has been restricted. "
+ " as a result of the specified listener not being a Window. "
+ "Consequently, it is unable to respond to keystrokes");
}
} // addActionListener
/* (non-Javadoc)
* @see org.zkoss.zk.ui.event.EventListener#onEvent(org.zkoss.zk.ui.event.Event)
*/
public void onEvent(Event event) throws Exception
{
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,684 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.awt.Color;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import org.adempiere.webui.event.TableValueChangeEvent;
import org.adempiere.webui.event.TableValueChangeListener;
import org.compiere.minigrid.IDColumn;
import org.compiere.util.DisplayType;
import org.compiere.util.MSort;
import org.compiere.util.Util;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.SelectEvent;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.ListitemRendererExt;
/**
* Renderer for {@link org.adempiere.webui.component.ListItems}
* for the {@link org.adempiere.webui.component.Listbox}.
*
* @author Andrew Kimball
*
*/
public class WListItemRenderer implements ListitemRenderer, EventListener, ListitemRendererExt
{
/** Array of listeners for changes in the table components. */
protected ArrayList<TableValueChangeListener> m_listeners =
new ArrayList<TableValueChangeListener>();
/** A list containing the indices of the currently selected ListItems. */
private Set m_selectedItems = new HashSet<ListItem>();
/** Array of table details. */
private ArrayList<WTableColumn> m_tableColumns = new ArrayList<WTableColumn>();
/** Array of {@link ListHeader}s for the list head. */
private ArrayList<ListHeader> m_headers = new ArrayList<ListHeader>();
/**
* Default constructor.
*
*/
public WListItemRenderer()
{
super();
}
/**
* Constructor specifying the column headers.
*
* @param columnNames vector of column titles.
*/
public WListItemRenderer(Vector< ? extends String> columnNames)
{
super();
WTableColumn tableColumn;
for (String columnName : columnNames)
{
tableColumn = new WTableColumn();
tableColumn.setHeaderValue(Util.cleanAmp(columnName));
m_tableColumns.add(tableColumn);
}
}
/**
* Get the column details of the specified <code>column</code>.
*
* @param columnIndex The index of the column for which details are to be retrieved.
* @return The details of the column at the specified index.
*/
private WTableColumn getColumn(int columnIndex)
{
try
{
return m_tableColumns.get(columnIndex);
}
catch (IndexOutOfBoundsException exception)
{
throw new IllegalArgumentException("There is no WTableColumn at column "
+ columnIndex);
}
}
/* (non-Javadoc)
* @see org.zkoss.zul.ListitemRenderer#render(org.zkoss.zul.Listitem, java.lang.Object)
*/
public void render(Listitem item, Object data) throws Exception
{
render((ListItem)item, data);
}
/**
* Renders the <code>data</code> to the specified <code>Listitem</code>.
*
* @param item the listitem to render the result.
* Note: when this method is called, the listitem has no child
* at all.
* @param data that is returned from {@link ListModel#getElementAt}
* @throws Exception
* @see {@link #render(Listitem, Object)}
*/
private void render(ListItem item, Object data)
{
Listcell listcell = null;
int colIndex = 0;
int rowIndex = item.getIndex();
WListbox table = null;
if (item.getListbox() instanceof WListbox)
{
table = (WListbox)item.getListbox();
}
if (!(data instanceof Vector))
{
throw new IllegalArgumentException("A model element was not a vector");
}
for (Object field : (Vector)data)
{
listcell = getCellComponent(table, field, rowIndex, colIndex);
listcell.setParent(item);
colIndex++;
}
return;
}
/**
* Obtain the foreground colour to be used for the specified field.
*
* @param table The table containing the affected field.
* @param row The row of the field for which the colour is wanted.
* @return The <code>Color</code> to be used.
*/
/* private Color getForegroundColour(WListbox table, int row)
{
Color fg = AdempierePLAF.getTextColor_Normal();
int colourCode = table.getColorCode(row);
//
if (colourCode == 0)
{
// Black
}
else if (colourCode < 0)
{
fg = AdempierePLAF.getTextColor_Issue(); // Red
}
else
{
fg = AdempierePLAF.getTextColor_OK(); // Blue
}
// Highlighted row
if (table.isSelected)
{
//fg = table.getSelectionForeground();
}
return fg;
}
*/
/**
* Obtain the background colour to be used for the specified field.
*
* @param table The table containing the affected field.
* @param row The row of the field for which the colour is wanted.
* @param column The column of the field for which the colour is wanted.
* @return The <code>Color</code> to be used.
*/
/* private Color getBackgroundColour(WListbox table, int row, int column)
{
Color bg = AdempierePLAF.getFieldBackground_Normal();
boolean isCellReadOnly = !table.isCellEditable(row, column);
if (isCellReadOnly)
{
bg = AdempierePLAF.getFieldBackground_Inactive();
if (isSelected && !hasFocus)
{
bg = bg.darker();
}
}
// Highlighted row
if (isSelected)
{
// Windows is white on blue
bg = table.getSelectionBackground();
if (hasFocus)
{
bg = GraphUtil.brighter(bg, .9);
}
}
return bg;
}
*/
/**
* Generate the cell for the given <code>field</code>.
*
* @param table The table into which the cell will be placed.
* @param field The data field for which the cell is to be created.
* @param rowIndex The row in which the cell is to be placed.
* @param columnIndex The column in which the cell is to be placed.
* @return The list cell component.
*/
private Listcell getCellComponent(WListbox table, Object field,
int rowIndex, int columnIndex)
{
ListCell listcell = new ListCell();
boolean isCellEditable = table.isCellEditable(rowIndex, columnIndex);
/* Color fgColor = getForegroundColour(table, rowIndex);
Color bgColor = getBackgroundColour(table, rowIndex, columnIndex);
ZkCssHelper.appendStyle(listcell, "color:#" + ZkCssHelper.createHexColorString(fgColor)
+ "; bgcolor:#" + ZkCssHelper.createHexColorString(bgColor));
*/
// TODO put this in factory method for generating cell renderers, which
// are assigned to Table Columns
if (field != null)
{
if (field instanceof Boolean)
{
listcell.setValue(Boolean.valueOf(field.toString()));
table.setCheckmark(false);
Checkbox checkbox = new Checkbox();
checkbox.setChecked(Boolean.valueOf(field.toString()));
if (isCellEditable)
{
checkbox.setEnabled(true);
checkbox.addEventListener(Events.ON_CHECK, this);
}
else
{
checkbox.setEnabled(false);
}
listcell.appendChild(checkbox);
ZkCssHelper.appendStyle(listcell, "text-align:center");
}
else if (field instanceof BigDecimal)
{
DecimalFormat format = DisplayType.getNumberFormat(DisplayType.Amount);
// set cell value to allow sorting
listcell.setValue(field.toString());
if (isCellEditable)
{
NumberBox numberbox = new NumberBox(false);
numberbox.setFormat(format);
numberbox.setValue((BigDecimal)field);
numberbox.setWidth("100px");
numberbox.setButtonVisible(true);
numberbox.setReadonly(false);
numberbox.setStyle("text-align:right; "
+ listcell.getStyle());
numberbox.addEventListener(Events.ON_CHANGE, this);
listcell.appendChild(numberbox);
}
else
{
listcell.setLabel(format.format(((BigDecimal)field).doubleValue()));
ZkCssHelper.appendStyle(listcell, "text-align:right");
}
}
else if (field instanceof Timestamp)
{
SimpleDateFormat dateFormat = DisplayType.getDateFormat(DisplayType.Date);
listcell.setValue(dateFormat.format((Timestamp)field));
listcell.setLabel(dateFormat.format((Timestamp)field));
}
// if ID column make it invisible
else if (field instanceof IDColumn)
{
//listcell.setLabel(field.toString());
listcell.setValue(((IDColumn) field).getRecord_ID());
//listcell.setVisible(false);
table.setCheckmark(true);
table.addEventListener(Events.ON_SELECT, this);
}
else
{
listcell.setLabel(field.toString());
listcell.setValue(field.toString());
}
}
else
{
listcell.setLabel("");
listcell.setValue("");
}
return listcell;
}
/**
* Update Table Column.
*
* @param index The index of the column to update
* @param header The header text for the column
*/
public void updateColumn(int index, String header)
{
WTableColumn tableColumn;
tableColumn = getColumn(index);
tableColumn.setHeaderValue(Util.cleanAmp(header));
return;
} // updateColumn
/**
* Add Table Column.
* after adding a column, you need to set the column classes again
* (DefaultTableModel fires TableStructureChanged, which calls
* JTable.tableChanged .. createDefaultColumnsFromModel
* @param header The header text for the column
*/
public void addColumn(String header)
{
WTableColumn tableColumn;
tableColumn = new WTableColumn();
tableColumn.setHeaderValue(Util.cleanAmp(header));
m_tableColumns.add(tableColumn);
return;
} // addColumn
/**
* Get the number of columns.
* @return the number of columns
*/
public int getNoColumns()
{
return m_tableColumns.size();
}
/**
* This is unused.
* The readonly proprty of a column should be set in
* the parent table.
*
* @param colIndex
* @param readOnly
* @deprecated
*/
public void setRO(int colIndex, Boolean readOnly)
{
return;
}
/**
* Create a ListHeader using the given <code>headerValue</code> to
* generate the header text.
* The <code>toString</code> method of the <code>headerValue</code>
* is used to set the header text.
*
* @param headerValue The object to use for generating the header text.
* @param headerIndex The column index of the header
* @return The generated ListHeader
* @see #renderListHead(ListHead)
*/
private Component getListHeaderComponent(Object headerValue, int headerIndex)
{
ListHeader header = null;
if (m_headers.size() <= headerIndex)
{
Comparator ascComparator = getColumnComparator(true, headerIndex);
Comparator dscComparator = getColumnComparator(false, headerIndex);
header = new ListHeader(headerValue.toString());
header.setSort("auto");
header.setSortAscending(ascComparator);
header.setSortDescending(dscComparator);
header.setWidth("auto");
m_headers.add(header);
}
else
{
header = m_headers.get(headerIndex);
if (!header.getLabel().equals(headerValue.toString()))
{
header.setLabel(headerValue.toString());
}
}
return header;
}
/**
* Obtain the comparator for a given column.
*
* @param ascending whether the comparator will sort ascending
* @param columnIndex the index of the column for which the comparator is required
* @return comparator for the given column for the given direction
*/
protected Comparator getColumnComparator(boolean ascending, final int columnIndex)
{
Comparator comparator;
final MSort sort = new MSort(0, null);
sort.setSortAsc(ascending);
comparator = new Comparator<Object>()
{
public int compare(Object o1, Object o2)
{
Object item1 = ((Vector)o1).get(columnIndex);
Object item2 = ((Vector)o2).get(columnIndex);
return sort.compare(item1, item2);
}
};
return comparator;
}
/**
* Render the ListHead for the table with headers for the table columns.
*
* @param head The ListHead component to render.
* @see #addColumn(String)
* @see #WListItemRenderer(Vector)
*/
public void renderListHead(ListHead head)
{
Component header;
WTableColumn column;
for (int columnIndex = 0; columnIndex < m_tableColumns.size(); columnIndex++)
{
column = m_tableColumns.get(columnIndex);
header = getListHeaderComponent(column.getHeaderValue(), columnIndex);
head.appendChild(header);
}
head.setSizable(true);
head.setWidth("auto");
return;
}
/* (non-Javadoc)
* @see org.zkoss.zk.ui.event.EventListener#onEvent(org.zkoss.zk.ui.event.Event)
*/
public void onEvent(Event event) throws Exception
{
int col = -1;
int row = -1;
Object value = null;
TableValueChangeEvent vcEvent = null;
Set newlyUnselectedItems = new HashSet<Listitem>();
Set newlySelectedItems = new HashSet<Listitem>();
WTableColumn tableColumn;
Component source = event.getTarget();
if (source instanceof WListbox)
{
if (event instanceof SelectEvent)
{
col = 0;
tableColumn = m_tableColumns.get(col);
newlyUnselectedItems.addAll(m_selectedItems);
newlyUnselectedItems.removeAll(((SelectEvent)event).getSelectedItems());
newlySelectedItems.addAll(((SelectEvent)event).getSelectedItems());
newlySelectedItems.removeAll(m_selectedItems);
m_selectedItems.clear();
m_selectedItems.addAll(((SelectEvent)event).getSelectedItems());
for (Object item : newlySelectedItems)
{
row =((ListItem)item).getIndex();
value = Boolean.TRUE;
vcEvent = new TableValueChangeEvent(source,
tableColumn.getHeaderValue().toString(),
row, col,
value, value);
fireTableValueChange(vcEvent);
}
for (Object item : newlyUnselectedItems)
{
row =((ListItem)item).getIndex();
value = Boolean.FALSE;
vcEvent = new TableValueChangeEvent(source,
tableColumn.getHeaderValue().toString(),
row, col,
value, value);
fireTableValueChange(vcEvent);
}
}
}
else if (source.getParent() instanceof Listcell)
{
row = getRowPosition(source);
col = getColumnPosition(source);
tableColumn = m_tableColumns.get(col);
if (source instanceof Checkbox)
{
value = Boolean.valueOf(((Checkbox)source).isChecked());
}
else if (source instanceof NumberBox)
{
value = new BigDecimal(((NumberBox)source).getValue());
}
if(value != null)
{
vcEvent = new TableValueChangeEvent(source,
tableColumn.getHeaderValue().toString(),
row, col,
value, value);
fireTableValueChange(vcEvent);
}
}
return;
}
/**
* Get the row index of the given <code>source</code> component.
*
* @param source The component for which the row index is to be found.
* @return The row index of the given component.
*/
protected int getRowPosition(Component source)
{
Listcell cell;
ListItem item;
int row = -1;
cell = (Listcell)source.getParent();
item = (ListItem)cell.getParent();
row = item.getIndex();
return row;
}
/**
* Get the column index of the given <code>source</code> component.
*
* @param source The component for which the column index is to be found.
* @return The column index of the given component.
*/
protected int getColumnPosition(Component source)
{
Listcell cell;
int col = -1;
cell = (Listcell)source.getParent();
col = cell.getColumnIndex();
return col;
}
/**
* Reset the renderer.
* This should be called if the table using this renderer is cleared.
*/
public void clearColumns()
{
m_tableColumns.clear();
}
/**
* Clear the renderer.
* This should be called if the table using this renderer is cleared.
*/
public void clearSelection()
{
m_selectedItems.clear();
}
/**
* Add a listener for changes in the table's component values.
*
* @param listener The listener to add.
*/
public void addTableValueChangeListener(TableValueChangeListener listener)
{
if (listener == null)
{
return;
}
m_listeners.add(listener);
return;
}
/**
* Fire the given table value change <code>event</code>.
*
* @param event The event to pass to the listeners
*/
private void fireTableValueChange(TableValueChangeEvent event)
{
for (TableValueChangeListener listener : m_listeners)
{
listener.tableValueChange(event);
}
}
/* (non-Javadoc)
* @see org.zkoss.zul.ListitemRendererExt#getControls()
*/
public int getControls()
{
return DETACH_ON_RENDER;
}
/* (non-Javadoc)
* @see org.zkoss.zul.ListitemRendererExt#newListcell(org.zkoss.zul.Listitem)
*/
public Listcell newListcell(Listitem item)
{
return null;
}
/* (non-Javadoc)
* @see org.zkoss.zul.ListitemRendererExt#newListitem(org.zkoss.zul.Listbox)
*/
public Listitem newListitem(Listbox listbox)
{
return new ListItem();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,241 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.awt.Color;
import org.adempiere.webui.component.Label;
import org.compiere.model.DataStatusEvent;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* Web UI status bar. Based upon the rich client's
* {@link org.compiere.apps.StatusBar}. The basic status bar contains one or
* both of (a) a general status description and (b) a database status
* description. In addition, components can be added to the status bar to extend
* its functionaility
*
* @author Andrew Kimball
*/
public class WStatusBar extends Grid implements EventListener
{
private static final long serialVersionUID = 1L;
/** label */
private Label statusLine = new Label();
private Label statusDB = new Label();
private Row statusBar = new Row();
private String m_text;
private DataStatusEvent m_dse = null;
private boolean mt_error;
private String mt_text;
/**
* Constructor for a Standard Status Bar.
*/
public WStatusBar()
{
super();
Rows rows = new Rows();
try
{
initialise();
// this.setBorder("normal");
rows.appendChild(statusBar);
this.appendChild(rows);
this.setWidth("98%");
}
catch (Exception e)
{
}
// this.setName("statusBar");
} // StatusBar
/**
* Static Initialisation.
*
* @throws Exception
*/
private void initialise() throws Exception
{
statusLine.setValue("statusLine");
statusBar.appendChild(statusLine);
statusDB.setValue("#");
statusDB.setStyle("text-align:right; " + "color:"
+ ZkCssHelper.createHexColorString(Color.blue));
statusDB.addEventListener(Events.ON_CLICK, this);
statusBar.appendChild(statusDB);
} // jbInit
/**
* Get Status Line text.
*
* @return StatusLine text
*/
public final String getStatusLine()
{
return statusLine.getValue().trim();
} // getStatusLine
/**
* Set Status Line
*
* @param text
* text
* @param error
* error
*/
public final void setStatusLine(final String text, final boolean error)
{
mt_error = error;
mt_text = text;
if (mt_error)
{
/* ZkCssHelper.appendStyle(statusLine, ZkCssHelper
.createHexColorString(AdempierePLAF.getTextColor_Issue()));
*/ }
else
{
/* ZkCssHelper.appendStyle(statusLine, ZkCssHelper
.createHexColorString(AdempierePLAF.getTextColor_OK()));
*/ }
statusLine.setValue(mt_text);
//
Thread.yield();
} // setStatusLine
/**
* Set ToolTip of StatusLine
*
* @param tip
* tooltip text
*/
public final void setStatusToolTip(final String tip)
{
statusLine.setTooltiptext(tip);
} // setStatusToolTip
/**
* Set Standard Status Line (non error)
*
* @param text
* text to display on the status line
*/
public final void setStatusLine(final String text)
{
if (text == null)
{
setStatusLine("", false);
}
else
{
setStatusLine(text, false);
}
} // setStatusLine
/**
* Set Status DB Info
*
* @param text
* description of database status
* @param dse
* data status event
*/
public final void setStatusDB(final String text, final DataStatusEvent dse)
{
if (text == null || text.length() == 0)
{
statusDB.setValue("");
statusDB.setVisible(false);
statusDB.detach();
}
else
{
StringBuffer sb = new StringBuffer(" ");
sb.append(text).append(" ");
statusDB.setValue(sb.toString());
if (!statusDB.isVisible())
{
statusDB.setVisible(true);
}
statusDB.setParent(statusBar);
}
// Save
m_text = text;
m_dse = dse;
} // setStatusDB
/**
* Set Status DB Info
*
* @param text
* description of database status
*/
public final void setStatusDB(final String text)
{
setStatusDB(text, null);
} // setStatusDB
/**
* Set Status DB Info
*
* @param no
* Database status identifier
*/
public final void setStatusDB(final int no)
{
setStatusDB(String.valueOf(no), null);
} // setStatusDB
/**
* Add Component to East of StatusBar
*
* @param component
* component
*/
public final void addStatusComponent(final Component component)
{
this.appendChild(component);
} // addStatusComponent
/*
* (non-Javadoc)
*
* @see org.zkoss.zk.ui.event.EventListener#onEvent(org.zkoss.zk.ui.event.Event)
*/
public void onEvent(final Event evt) throws Exception
{
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,255 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
* @author Andrew Kimball
*
*/
public class WTableColumn
{
/** The width of the column. */
protected int width;
/** The minimum width of the column. */
protected int minWidth;
/** The preferred width of the column. */
private int preferredWidth;
/** The maximum width of the column. */
protected int maxWidth;
/** If true, the user is allowed to resize the column; the default is true. */
protected boolean isResizable;
/** The header value of the column. */
protected Object headerValue;
/**
* Cover method, using a default width of 75
* @see #WTableColumn(int)
*/
public WTableColumn() {
this(75);
}
public WTableColumn(int width)
{
this.width = width;
this.preferredWidth = width;
// Set other instance variables to default values.
minWidth = 15;
maxWidth = Integer.MAX_VALUE;
isResizable = true;
headerValue = null;
}
/**
* Sets the <code>Object</code> whose string representation will be
* used as the value for the <code>headerRenderer</code>. When the
* <code>WTableColumn</code> is created, the default <code>headerValue</code>
* is <code>null</code>.
*
* @param headerValue the new headerValue
* @see #getHeaderValue
*/
public void setHeaderValue(Object headerValue)
{
this.headerValue = headerValue;
return;
}
/**
* Returns the <code>Object</code> used as the value for the header
* renderer.
*
* @return the <code>headerValue</code> property
* @see #setHeaderValue
*/
public Object getHeaderValue()
{
return headerValue;
}
/**
* This method should not be used to set the widths of columns in the
* <code>WListbox</code>, use <code>setPreferredWidth</code> instead.
* This method sets this column's width to <code>width</code>.
* If <code>width</code> exceeds the minimum or maximum width,
* it is adjusted to the appropriate limiting value.
* <p>
* @param width the new width
* @see #getWidth
* @see #setMinWidth
* @see #setMaxWidth
* @see #setPreferredWidth
*/
public void setWidth(int width)
{
this.width = Math.min(Math.max(width, minWidth), maxWidth);
return;
}
/**
* Returns the width of the <code>TableColumn</code>. The default width is
* 75.
*
* @return the <code>width</code> property
* @see #setWidth
*/
public int getWidth()
{
return width;
}
/**
* Sets this column's preferred width to <code>preferredWidth</code>.
* If <code>preferredWidth</code> exceeds the minimum or maximum width,
* it is adjusted to the appropriate limiting value.
*
* @param preferredWidth the new preferred width
* @see #getPreferredWidth
*/
public void setPreferredWidth(int preferredWidth)
{
this.preferredWidth = Math.min(Math.max(preferredWidth, minWidth), maxWidth);;
}
/**
* Returns the preferred width of the <code>WTableColumn</code>.
* The default preferred width is 75.
*
* @return the <code>preferredWidth</code> property
* @see #setPreferredWidth
*/
public int getPreferredWidth()
{
return preferredWidth;
}
/**
* Sets the <code>WTableColumn</code>'s minimum width to
* <code>minWidth</code>; also adjusts the current width
* and preferred width if they are less than this value.
*
* @param minWidth the new minimum width
* @see #getMinWidth
* @see #setPreferredWidth
* @see #setMaxWidth
*/
public void setMinWidth(int minWidth)
{
this.minWidth = Math.max(minWidth, 0);
if (width < minWidth)
{
setWidth(minWidth);
}
if (preferredWidth < minWidth)
{
setPreferredWidth(minWidth);
}
return;
}
/**
* Returns the minimum width for the <code>WTableColumn</code>. The
* <code>WTableColumn</code>'s width can't be made less than this either
* by the user or programmatically. The default minWidth is 15.
*
* @return the <code>minWidth</code> property
* @see #setMinWidth
*/
public int getMinWidth()
{
return minWidth;
}
/**
* Sets the <code>WTableColumn</code>'s maximum width to
* <code>maxWidth</code>; also adjusts the width and preferred
* width if they are greater than this value.
*
* @param maxWidth the new maximum width
* @see #getMaxWidth
* @see #setPreferredWidth
* @see #setMinWidth
*/
public void setMaxWidth(int maxWidth)
{
this.maxWidth = Math.max(minWidth, maxWidth);
if (width > maxWidth)
{
setWidth(maxWidth);
}
if (preferredWidth > maxWidth)
{
setPreferredWidth(maxWidth);
}
return;
}
/**
* Returns the maximum width for the <code>WTableColumn</code>. The
* <code>WTableColumn</code>'s width can't be made larger than this
* either by the user or programmatically. The default maxWidth
* is Integer.MAX_VALUE.
*
* @return the <code>maxWidth</code> property
* @see #setMaxWidth
*/
public int getMaxWidth()
{
return maxWidth;
}
/**
* Sets whether this column can be resized.
*
* @param isResizable if true, resizing is allowed; otherwise false
* @see #getResizable
*/
public void setResizable(boolean isResizable)
{
this.isResizable = isResizable;
}
/**
* Returns true if the user is allowed to resize the
* <code>WTableColumn</code>'s
* width, false otherwise. You can change the width programmatically
* regardless of this setting. The default is true.
*
* @return the <code>isResizable</code> property
* @see #setResizable
*/
public boolean getResizable()
{
return isResizable;
}
}

View File

@ -0,0 +1,42 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 25, 2007
* @version $Revision: 0.10 $
*/
public class Window extends org.zkoss.zul.Window
{
private static final long serialVersionUID = 1L;
public static final String MODE_MODAL = "modal";
public static final String MODE_POPUP = "popup";
public static final String MODE_OVERLAPPED = "overlapped";
public static final String MODE_EMBEDDED = "embedded";
public Window()
{
super();
}
}

View File

@ -0,0 +1,177 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component;
import java.awt.Color;
import org.zkoss.zk.ui.HtmlBasedComponent;
/**
* Utility function to support ZK functions.
*
* Provides functionsfor manipulating the CSS style for
* ZK components.
*
* @author Andrew Kimball
*
*/
public final class ZkCssHelper
{
/** Left text alignment CSS style property and value. */
public static final String STYLE_TEXT_ALIGN_LEFT = "text-align:left";
/** Right text alignment CSS style property and value. */
public static final String STYLE_TEXT_ALIGN_RIGHT = "text-align:right";
/** Centre text alignment CSS style property and value. */
public static final String STYLE_TEXT_ALIGN_CENTER = "text-align:center";
/** CSS style property for color. */
public static final String STYLE_COLOR = "color:#";
/** CSS style property for background color. */
public static final String STYLE_BACKGROUND_COLOR = "background-color:#";
/**
* Private default constructor.
* This exists purely for conformance and should not be used.
*/
private ZkCssHelper()
{
}
/**
* Obtains the string description of the RGB components of a <code>color</code>.
* The returned string is suitable for using in CSS styles.
* The red, green and blue components are formatted as hexadecimal characters.
* Each component is in the range 00 to FF.
* The entire string is therefore
* a 6 character string ranging from "000000" to "FFFFFF".
*
* @param color The color for which the string is to be created
* @return The string representation of the colour's RGB components.
*/
public static String createHexColorString(Color color)
{
String colorString = String.format("%02X%02X%02X",
color.getRed(),
color.getGreen(),
color.getBlue());
return colorString;
}
/**
* Adds a new CSS style to <code>component</code>.
* The ";" prefix is not required.
*
* @param component the HTML based ZK component whose CSS style is to be modified
* @param style CSS style string to append to current style
*
* @see #setStyle(String)
*/
public static void appendStyle(HtmlBasedComponent component, String style)
{
String oldStyle = "";
if (component.getStyle() != null)
{
oldStyle = component.getStyle();
}
component.setStyle(oldStyle
+ "; " + style);
return;
}
/**
* Adds a CSS color style to <code>component</code>.
*
* The current style of the component is retained.
*
* @param component the HTML based ZK component whose CSS style is to be modified
* @param color the color to be set
* @see #appendStyleBackgroundColor(HtmlBasedComponent, Color)
* @see #setStyleColor(HtmlBasedComponent, Color)
*/
public static void appendStyleColor(HtmlBasedComponent component, Color color)
{
String colorString = createHexColorString(color);
String colorStyleString = STYLE_COLOR + colorString;
appendStyle(component, colorStyleString);
return;
}
/**
* Sets CSS color style for <code>component</code>.
*
* Previous styles are removed.
*
* @param component the HTML based ZK component whose CSS style is to be modified
* @param color the color to be set
* @see #setStyleBackgroundColor(HtmlBasedComponent, Color)
* @see #appendStyleColor(HtmlBasedComponent, Color)
*/
public static void setStyleColor(HtmlBasedComponent component, Color color)
{
String colorString = createHexColorString(color);
String colorStyleString = STYLE_COLOR + colorString;
component.setStyle(colorStyleString);
return;
}
/**
* Adds a CSS background color style to <code>component</code>.
*
* The current style of the component is retained.
*
* @param component the HTML based ZK component whose CSS style is to be modified
* @param color the color to be set
* @see #appendStyleBackColor(HtmlBasedComponent, Color)
* @see #setStyleBackgroundColor(HtmlBasedComponent, Color)
*/
public static void appendStyleBackgroundColor(HtmlBasedComponent component, Color color)
{
String colorString = createHexColorString(color);
String colorStyleString = STYLE_BACKGROUND_COLOR + colorString;
appendStyle(component, colorStyleString);
return;
}
/**
* Sets CSS background color style for <code>component</code>.
*
* Previous styles are removed.
*
* @param component the HTML based ZK component whose CSS style is to be modified
* @param color the color to be set
* @see #appendStyleBackgroundColor(HtmlBasedComponent, Color)
* @see #setStyleColor(HtmlBasedComponent, Color)
*/
public static void setStyleBackgroundColor(HtmlBasedComponent component, Color color)
{
String colorString = createHexColorString(color);
String colorStyleString = STYLE_BACKGROUND_COLOR + colorString;
component.setStyle(colorStyleString);
return;
}
}

View File

@ -0,0 +1,38 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component.test;
import org.adempiere.webui.component.test.ListModelTableTest;
import org.adempiere.webui.component.test.WListItemRendererTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* Test Suite for running all of the tests in
* {@link org.adempiere.webui.component.test}.
*
* @author Andrew Kimball
*
*/
@RunWith(value=Suite.class)
@SuiteClasses({ListModelTableTest.class, WListItemRendererTest.class})
public class ComponentTests
{
}

View File

@ -0,0 +1,231 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component.test;
import java.util.Vector;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.event.WTableModelEvent;
import org.adempiere.webui.event.WTableModelListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import static org.junit.Assert.*;
/**
* Test class for {@link org.adempiere.webui.component.ListModelTable}.
*
* @author Andrew Kimball
*
*/
public class ListModelTableTest implements WTableModelListener
{
/** First data object. */
private static final Integer ms_number0 = Integer.valueOf(0);
/** Second data object. */
private static final Integer ms_number1 = Integer.valueOf(1);
/** Third data object. */
private static final Integer ms_number2 = Integer.valueOf(2);
/** Third data object. */
private static final Integer ms_number3 = Integer.valueOf(3);
/** Fourth data object. */
private static final Integer ms_number4 = Integer.valueOf(4);
/** Fifth data object. */
private static final Integer ms_number5 = Integer.valueOf(5);
/** Sixth data object. */
private static final Integer ms_number6 = Integer.valueOf(6);
/** The table instance on which tests are to be run. */
private ListModelTable m_table;
/** A flag to indicate whether the listener has been called and has succeeded. */
private boolean m_isListenerCalled = false;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
Vector<Integer> row0 = new Vector<Integer>();
Vector<Integer> row1 = new Vector<Integer>();
Vector<Object> data = new Vector<Object>();
// create two rows of data
row0.add(ms_number0);
row0.add(ms_number1);
row1.add(ms_number2);
row1.add(ms_number3);
// create the data
data.add(row0);
data.add(row1);
// instantiate the model
m_table = new ListModelTable(data);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#ListModelTable()}.
*/
@Test
public final void testListModelTable()
{
ListModelTable table = new ListModelTable();
boolean isException = false;
Object data;
assertEquals(0, table.getNoColumns());
assertEquals(0, table.getSize());
// try to get data from an invalid field
try
{
data = table.getDataAt(0, 0);
// never reach here, but removes warnings
assertNull(data);
}
catch (IllegalArgumentException exception)
{
isException = true;
}
assertTrue(isException);
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#ListModelTable(java.util.Collection)}.
*/
@Test (expected= IllegalArgumentException.class)
public final void testListModelTableCollection()
{
final int invalidRow = 2;
final int noColumns = 2;
Object data;
assertEquals(noColumns, m_table.getNoColumns());
assertEquals(noColumns, m_table.getSize());
assertEquals(Integer.valueOf(0), m_table.getDataAt(0, 0));
//try to get data from an invalid field
data = m_table.getDataAt(invalidRow, 0);
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#addColumn()}.
*/
@Test
public final void testAddColumn()
{
final int noColumns = 3;
m_table.addColumn();
assertEquals(noColumns, m_table.getNoColumns());
assertNull(m_table.getDataAt(0, noColumns - 1));
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#setNoColumns(int)}.
*/
@Test
public final void testSetNoColumns()
{
final int noColumns = 3;
m_table.setNoColumns(noColumns);
assertEquals(noColumns, m_table.getNoColumns());
assertNull(m_table.getDataAt(0, noColumns - 1));
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#getDataAt(int, int)}.
*/
@Test
public final void testGetDataAt()
{
assertEquals(ms_number0, m_table.getDataAt(0, 0));
assertEquals(ms_number3, m_table.getDataAt(1, 1));
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#setDataAt(java.lang.Object, int, int)}.
*/
@Test (expected= IllegalArgumentException.class)
public final void testSetDataAt()
{
final int invalidRow = 2;
m_table.setDataAt(ms_number4, 0, 0);
m_table.setDataAt(ms_number5, 1, 1);
assertEquals(ms_number4, m_table.getDataAt(0, 0));
assertEquals(ms_number5, m_table.getDataAt(1, 1));
// expect this to throw an exception
m_table.setDataAt(ms_number6, invalidRow, 0);
}
/**
* Test method for {@link org.adempiere.webui.component.ListModelTable#setNoRows(int)}.
*/
@Test
public final void testSetNoRows()
{
final int noRows = 3;
m_table.setNoRows(m_table.getSize() + 1);
assertEquals(noRows, m_table.getSize());
assertEquals(ms_number3, m_table.getDataAt(1, 1));
assertNull(m_table.getDataAt(2, 1));
}
/**
* Test method for
* {@link org.adempiere.webui.component.ListModelTable#addTableModelListener(org.adempiere.webui.event.WTableModelListener)}.
*/
@Test
public final void testAddTableModelListener()
{
m_table.addTableModelListener(this);
m_table.setDataAt(ms_number4, 0, 0);
assertTrue(m_isListenerCalled);
}
/* (non-Javadoc)
* @see org.adempiere.webui.event.WTableModelListener#tableChanged(org.adempiere.webui.event.WTableModelEvent)
*/
public void tableChanged(WTableModelEvent event)
{
assertEquals(ms_number4, m_table.getDataAt(0, 0));
m_isListenerCalled = true;
}
}

View File

@ -0,0 +1,222 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.component.test;
import static org.junit.Assert.*;
import java.util.Vector;
import org.adempiere.webui.component.ListHead;
import org.adempiere.webui.component.ListHeader;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.ListModelTable;
import org.adempiere.webui.component.WListItemRenderer;
import org.adempiere.webui.component.WListbox;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.zkoss.zul.Listitem;
/**
* @author Andrew Kimball
*
*/
public class WListItemRendererTest
{
WListItemRenderer m_renderer;
Vector<Object> m_dataValid = new Vector<Object>();
Vector<Object> m_dataInvalid = new Vector<Object>();
Vector<String> m_columnNames = new Vector<String>();
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
Vector<Object> dataRowValid = new Vector<Object>();
Vector<Object> dataRowInvalid = new Vector<Object>();
m_columnNames.add("Name");
m_columnNames.add("Age");
m_renderer = new WListItemRenderer(m_columnNames);
dataRowValid.add("River Phoenix");
dataRowValid.add(Integer.valueOf(23));
m_dataValid.add(dataRowValid);
dataRowInvalid.add("Elvis Presley");
dataRowInvalid.add(Integer.valueOf(42));
dataRowInvalid.add("Graceland");
m_dataInvalid.add(dataRowInvalid);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#WListItemRenderer()}.
*/
@Test
public final void testWListItemRenderer()
{
WListItemRenderer renderer = new WListItemRenderer();
assertEquals(0, renderer.getNoColumns());
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#WListItemRenderer(java.util.Vector)}.
*/
@Test
public final void testWListItemRendererVectorOfQextendsString()
{
assertEquals(2, m_renderer.getNoColumns());
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#render(org.zkoss.zul.Listitem, java.lang.Object)}.
*/
@Ignore("Not running because instantiating a ZX listbox causes a NullPointerException as it" +
" attempts to post events")
@Test
public final void testRender() throws Exception
{
/*ListModelTable model = new ListModelTable(m_dataValid);
WListbox table = new WListbox();
table.setData(model, m_columnNames);
Listitem item = m_renderer.newListitem(table);
m_renderer.render(item, table.getModel().get(0));
*/
fail("Not yet implemented");
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#updateColumn(int, java.lang.String)}.
*/
@Test
public final void testUpdateColumn()
{
ListHead head = new ListHead();
ListHeader header;
m_renderer.updateColumn(1, "Address");
assertEquals(2, m_renderer.getNoColumns());
m_renderer.renderListHead(head);
header = (ListHeader)head.getChildren().get(1);
assertEquals("Address", header.getLabel());
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#addColumn(java.lang.String)}.
*/
@Test
public final void testAddColumn()
{
m_renderer.addColumn("Address");
assertEquals(3, m_renderer.getNoColumns());
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#renderListHead(org.adempiere.webui.component.ListHead)}.
*/
@Test
public final void testRenderListHead()
{
ListHead head = new ListHead();
Object header;
m_renderer.renderListHead(head);
assertEquals(2, head.getChildren().size());
header = head.getChildren().get(1);
assertTrue(header instanceof ListHeader);
assertEquals("Age", ((ListHeader)header).getLabel());
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#getRowPosition(org.zkoss.zk.ui.Component)}.
*/
@Ignore("Not running because the ZX listbox cannot be instantiated in JUnit")
@Test
public final void testGetRowPosition()
{
fail("Not yet implemented");
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#getColumnPosition(org.zkoss.zk.ui.Component)}.
*/
@Ignore("Not running because the ZX listbox cannot be instantiated in JUnit")
@Test
public final void testGetColumnPosition()
{
fail("Not yet implemented");
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#clearColumns()}.
*/
@Test
public final void testClearColumns()
{
ListHead head = new ListHead();
m_renderer.clearColumns();
assertEquals(0, m_renderer.getNoColumns());
m_renderer.renderListHead(head);
assertEquals(0, head.getChildren().size());
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#clearSelection()}.
*/
@Ignore("Not running because the ZX listbox cannot be instantiated in JUnit")
@Test
public final void testClearSelection()
{
fail("Not yet implemented");
}
/**
* Test method for {@link org.adempiere.webui.component.WListItemRenderer#addTableValueChangeListener(org.adempiere.webui.event.TableValueChangeListener)}.
*/
@Ignore("Not running because the ZX listbox cannot be instantiated in JUnit")
@Test
public final void testAddTableValueChangeListener()
{
fail("Not yet implemented");
}
}

View File

@ -0,0 +1,40 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.constants;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.SimpleConstraint;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 18, 2007
* @version $Revision: 0.10 $
*/
public class Constraints
{
public static final Constraint MANDATORY;
public static final Constraint NO_CONSTRAINT;
static
{
MANDATORY = new SimpleConstraint(SimpleConstraint.NO_EMPTY);
NO_CONSTRAINT = (Constraint)null;
}
}

View File

@ -0,0 +1,34 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.constants;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Feb 18, 2007
* @version $Revision: 0.10 $
*/
public class EventConstants
{
public static final String ONCLICK = "onClick";
public static final String ONCHANGE = "onChange";
public static final String ONSELECT = "onSelect";
}

View File

@ -0,0 +1,267 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.event.ActionEvent;
import org.adempiere.webui.event.ActionListener;
import org.compiere.model.GridField;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.compiere.util.NamePair;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
* This class is based on org.compiere.grid.ed.VButton written by Jorg Janke.
* @author Jorg Janke
*
* Modifications - UI Compatibility
* @author ashley
*/
public class WButtonEditor extends WEditor
{
private static final String[] LISTENER_EVENTS = {};
private static final CLogger logger;
static
{
logger = CLogger.getCLogger(WButtonEditor.class);
}
private Button button;
private String m_text;
private boolean m_mandatory;
private Object m_value;
/** List of Key/Name */
private HashMap<String,String> m_values = null;
/** Description as ToolTip */
private MLookup m_lookup;
private int AD_Process_ID;
private GridField gridfield = null;
private ArrayList<ActionListener> actionListeners = new ArrayList<ActionListener>();
public WButtonEditor(GridField gridField)
{
super(new Button(), gridField);
button = (Button)super.component;
m_text = gridField.getHeader();
AD_Process_ID = gridField.getAD_Process_ID();
gridfield = gridField;
init();
}
/**
* Get AD_Process_ID
* @return AD_Process_ID or 0
*/
public int getProcess_ID()
{
return AD_Process_ID;
} // getProcess_ID
public GridField getGridField()
{
return gridfield;
}
private void init()
{
label.setValue(" ");
button.setLabel(gridField.getHeader());
button.setTooltiptext(gridField.getDescription());
button.addEventListener(Events.ON_CLICK, this);
String columnName = super.getColumnName();
if (columnName.equals("PaymentRule"))
{
readReference(195);
// this.setForeground(Color.blue);
button.setImage("/images/Payment16.gif"); // 29*14
}
else if (columnName.equals("DocAction"))
{
readReference(135);
// this.setForeground(Color.blue);
button.setImage("/images/Process16.gif"); // 16*16
}
else if (columnName.equals("CreateFrom"))
{
button.setImage("/images/Copy16.gif"); // 16*16
}
else if (columnName.equals("Record_ID"))
{
button.setImage("/images/Zoom16.gif"); // 16*16
button.setLabel(Msg.getMsg(Env.getCtx(), "ZoomDocument"));
}
else if (columnName.equals("Posted"))
{
readReference(234);
// this.setForeground(Color.magenta);
button.setImage("/images/InfoAccount16.gif"); // 16*16
}
if (gridField.getColumnName().endsWith("_ID") && !gridField.getColumnName().equals("Record_ID"))
{
m_lookup = MLookupFactory.get(Env.getCtx(), gridField.getWindowNo(), 0,
gridField.getAD_Column_ID(), DisplayType.Search);
}
else if (gridField.getAD_Reference_Value_ID() != 0)
{
// Assuming List
m_lookup = MLookupFactory.get(Env.getCtx(), gridField.getWindowNo(), 0,
gridField.getAD_Column_ID(), DisplayType.List);
}
}
@Override
public String getDisplay()
{
return m_value.toString();
}
@Override
public Object getValue()
{
return m_values;
}
@Override
public boolean isMandatory()
{
return m_mandatory;
}
@Override
public void setMandatory(boolean mandatory)
{
m_mandatory = mandatory;
}
@Override
public void setValue(Object value)
{
m_value = value;
String text = m_text;
// Nothing to show or Record_ID
if (value == null || super.getColumnName().equals("Record_ID"))
{
;
}
else if (m_values != null)
{
text = (String)m_values.get(value);
}
else if (m_lookup != null)
{
NamePair pp = m_lookup.get(value);
if (pp != null)
text = pp.getName();
}
button.setLabel(text != null ? text : "");
}
public HashMap getValues()
{
return m_values;
} // getValues
/**
* Fill m_Values with Ref_List values
* @param AD_Reference_ID reference
*/
private void readReference(int AD_Reference_ID)
{
m_values = new HashMap<String,String>();
String SQL;
if (Env.isBaseLanguage(Env.getCtx(), "AD_Ref_List"))
SQL = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=?";
else
SQL = "SELECT l.Value, t.Name FROM AD_Ref_List l, AD_Ref_List_Trl t "
+ "WHERE l.AD_Ref_List_ID=t.AD_Ref_List_ID"
+ " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "'"
+ " AND l.AD_Reference_ID=?";
try
{
PreparedStatement pstmt = DB.prepareStatement(SQL, null);
pstmt.setInt(1, AD_Reference_ID);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
String value = rs.getString(1);
String name = rs.getString(2);
m_values.put(value,name);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
logger.log(Level.SEVERE, SQL, e);
}
} // readReference
public void addActionListener(ActionListener actionListener)
{
actionListeners.add(actionListener);
}
@Override
public String[] getEvents()
{
return LISTENER_EVENTS;
}
public void onEvent(Event event) throws Exception
{
if (Events.ON_CLICK.equals(event.getName()))
{
ActionEvent actionEvent = new ActionEvent(this, getColumnName(), Events.ON_CLICK);
for (ActionListener evtListener : actionListeners)
{
evtListener.actionPerformed(actionEvent);
}
}
}
}

View File

@ -0,0 +1,146 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.sql.Timestamp;
import java.util.Date;
import java.util.logging.Level;
import org.adempiere.webui.component.Datebox;
import org.adempiere.webui.event.ValueChangeEvent;
import org.compiere.model.GridField;
import org.compiere.util.CLogger;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 12, 2007
* @version $Revision: 0.10 $
*/
public class WDateEditor extends WEditor
{
private static final String[] LISTENER_EVENTS = {Events.ON_CHANGE};
private static final CLogger logger;
static
{
logger = CLogger.getCLogger(WDateEditor.class);
}
private Timestamp oldValue = new Timestamp(0);
private Datebox datebox;
public WDateEditor(GridField gridField)
{
super(new Datebox(), gridField);
datebox = (Datebox)super.component;
}
/**
* Constructor for use if a grid field is unavailable
*
* @param label
* column name (not displayed)
* @param description
* description of component
* @param mandatory
* whether a selection must be made
* @param readonly
* whether or not the editor is read only
* @param updateable
* whether the editor contents can be changed
*/
public WDateEditor (String label, String description, boolean mandatory, boolean readonly, boolean updateable)
{
super(new Datebox(), label, description, mandatory, readonly, updateable);
this.datebox = (Datebox)super.component;
setColumnName("Date");
}
public WDateEditor()
{
this("Date", "Date", false, false, true);
} // VDate
public void onEvent(Event event)
{
Date date = datebox.getValue();
Timestamp newValue = null;
if (date != null)
{
newValue = new Timestamp(date.getTime());
}
ValueChangeEvent changeEvent = new ValueChangeEvent(this, this.getColumnName(), oldValue, newValue);
super.fireValueChange(changeEvent);
oldValue = newValue;
}
@Override
public String getDisplay()
{
return null;
}
@Override
public Object getValue()
{
return null;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public void setMandatory(boolean mandatory)
{
}
@Override
public void setValue(Object value)
{
if (value == null)
{
oldValue = null;
}
else if (value instanceof Timestamp)
{
datebox.setValue((Timestamp)value);
oldValue = (Timestamp)value;
}
else
{
logger.log(Level.SEVERE, "New field value is not of type timestamp");
}
}
public String[] getEvents()
{
return LISTENER_EVENTS;
}
}

View File

@ -0,0 +1,393 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import org.adempiere.webui.component.Button;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.component.Datebox;
import org.adempiere.webui.component.EditorBox;
import org.adempiere.webui.component.Label;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.component.Locationbox;
import org.adempiere.webui.component.Searchbox;
import org.adempiere.webui.component.Urlbox;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.compiere.model.GridField;
import org.compiere.model.GridTab;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.HtmlBasedComponent;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.impl.InputElement;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 11, 2007
* @version $Revision: 0.10 $
*/
public abstract class WEditor implements EventListener, PropertyChangeListener
{
private static final String[] lISTENER_EVENTS = {};
public static final int MAX_DISPLAY_LENGTH = 35;
protected GridField gridField;
protected GridTab gridTab;
protected Label label;
protected Component component;
protected boolean mandatory;
protected ArrayList<ValueChangeListener> listeners = new ArrayList<ValueChangeListener>();
private String strLabel;
private String description;
private boolean readOnly;
private boolean updateable;
private String columnName;
public WEditor(Component comp, GridField gridField)
{
if (comp == null)
{
throw new IllegalArgumentException("Component cannot be null");
}
if (gridField == null)
{
throw new IllegalArgumentException("Grid field cannot be null");
}
this.setComponent(comp);
this.gridField = gridField;
this.setMandatory(gridField.isMandatory(false));
this.readOnly = gridField.isReadOnly();
this.description = gridField.getDescription();
this.updateable = gridField.isUpdateable();
this.columnName = gridField.getColumnName();
this.strLabel = gridField.getHeader();
init();
}
/**
* Method is used to distinguish between 2 similar WSearchEditors
*
*/
public String getDescription()
{
return description;
}
/**
* Constructor for use if a grid field is unavailable
*
* @param comp The editor's component
* @param label column name (not displayed)
* @param description description of component
* @param mandatory whether a selection must be made
* @param readonly whether or not the editor is read only
* @param updateable whether the editor contents can be changed
*/
public WEditor(Component comp, String label, String description, boolean mandatory, boolean readonly, boolean updateable)
{
if (comp == null)
{
throw new IllegalArgumentException("Component cannot be null");
}
this.setComponent(comp);
this.setMandatory(mandatory);
this.readOnly = readonly;
this.description = description;
this.updateable = updateable;
this.strLabel = label;
init();
}
/**
* Set the editor component.
* @param comp the editor component
*/
protected void setComponent(Component comp)
{
this.component = comp;
}
private void init()
{
label = new Label("");
label.setValue(strLabel);
label.setTooltiptext(description);
this.setMandatory (mandatory);
if (readOnly || !updateable)
{
this.setReadWrite(false);
}
else
{
this.setReadWrite(true);
}
((HtmlBasedComponent)component).setTooltiptext(description);
label.setTooltiptext(description);
}
public GridField getGridField()
{
return gridField;
}
public String getColumnName()
{
return columnName;
}
/**
* Remove the table qualifier from the supplied column name.
*
* The column name may be prefixed with the table name
* i.e. <code>[table name].[column name]</code>.
* The function returns
*
* @param originalColumnName The column name to clean
* @return the column name with any table qualifier removed
* i.e. <code>[column name]</code>
*/
protected String cleanColumnName(String originalColumnName)
{
String cleanColumnName;
/*
* The regular expression to use to find the table qualifier.
* Matches "<table name>."
*/
final String regexTablePrefix = ".*\\.";
cleanColumnName = originalColumnName.replaceAll(regexTablePrefix, "");
return cleanColumnName;
}
protected void setColumnName(String columnName)
{
String cleanColumnName = cleanColumnName(columnName);
this.columnName = cleanColumnName;
}
public Component getComponent()
{
return component;
}
public void setGridTab(GridTab gridTab)
{
this.gridTab = gridTab;
}
public WEditorPopupMenu getPopupMenu()
{
return null;
}
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
{
setValue((evt.getNewValue()));
}
}
public void addValueChangeListner(ValueChangeListener listener)
{
if (listener == null)
{
return;
}
if (listeners.size() == 0)
{
for (String event : this.getEvents())
{
component.addEventListener(event, this);
}
}
listeners.add(listener);
}
protected void fireValueChange(ValueChangeEvent event)
{
for (ValueChangeListener listener : listeners)
{
listener.valueChange(event);
}
}
public Label getLabel()
{
return label;
}
public void setReadWrite(boolean readWrite)
{
if (component instanceof Checkbox)
{
((Checkbox)component).setEnabled(readWrite);
}
else if (component instanceof Button)
{
((Button)component).setEnabled(readWrite);
}
else if (component instanceof Listbox)
{
((Listbox)component).setEnabled(readWrite);
}
else if (component instanceof Datebox)
{
((Datebox)component).setEnabled(readWrite);
}
else if (component instanceof Urlbox)
{
((Urlbox)component).setEnabled(readWrite);
}
else if (component instanceof Searchbox)
{
((Searchbox)component).setEnabled(readWrite);
}
else if (component instanceof Locationbox)
{
((Locationbox)component).setEnabled(readWrite);
}
else if (component instanceof EditorBox)
{
((EditorBox)component).setEnabled(readWrite);
}
else
{
((InputElement)component).setReadonly(!readWrite);
}
}
public boolean isReadWrite()
{
if (component instanceof Checkbox)
{
return ((Checkbox)component).isDisabled();
}
else if (component instanceof Button)
{
return ((Button)component).isEnabled();
}
else if (component instanceof Listbox)
{
return ((Listbox)component).isEnabled();
}
else if (component instanceof Searchbox)
{
return ((Searchbox)component).isEnabled();
}
else if (component instanceof Locationbox)
{
return ((Locationbox)component).isEnabled();
}
else if (component instanceof EditorBox)
{
return ((EditorBox)component).isEnabled();
}
else
{
return ((InputElement)component).isReadonly();
}
}
public void setVisible(boolean visible)
{
label.setVisible(visible);
component.setVisible(visible);
}
public boolean isVisible()
{
return component.isVisible();
}
public void setBackground(boolean error)
{
}
public void setBackground(Color color)
{
}
public String toString()
{
StringBuffer sb = new StringBuffer(30);
sb.append(this.getClass().getName());
sb.append("[").append(this.getColumnName());
sb.append("=");
sb.append(this.getValue()).append("]");
return sb.toString();
}
abstract public void setValue(Object value);
abstract public Object getValue();
abstract public String getDisplay();
public String[] getEvents()
{
return WEditor.lISTENER_EVENTS;
}
/**
* Set whether the editor represents a mandatory field.
* @param mandatory whether the field is mandatory
*/
public void setMandatory (boolean mandatory)
{
this.mandatory = mandatory;
}
public boolean isMandatory()
{
return this.mandatory;
}
public boolean isAsap()
{
return true;
}
}

View File

@ -0,0 +1,147 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.util.ArrayList;
import org.adempiere.webui.event.ContextMenuEvent;
import org.adempiere.webui.event.ContextMenuListener;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Menuitem;
import org.zkoss.zul.Menupopup;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 25, 2007
* @version $Revision: 0.10 $
*/
public class WEditorPopupMenu extends Menupopup implements EventListener
{
private static final long serialVersionUID = 1L;
private static final String EVENT_ATTRIBUTE = "EVENT";
public static final String ZOOM_EVENT = "ZOOM";
public static final String REQUERY_EVENT = "REQUERY";
public static final String PREFERENCE_EVENT = "VALUE_PREFERENCE";
public static final String NEW_EVENT = "NEW_RECORD";
private boolean newEnabled = true;
private boolean zoomEnabled = true;
private boolean requeryEnabled = true;
private boolean preferencesEnabled = true;
private Menuitem zoomItem;
private Menuitem requeryItem;
private Menuitem prefItem;
private Menuitem newItem;
private ArrayList<ContextMenuListener> menuListeners = new ArrayList<ContextMenuListener>();
public WEditorPopupMenu(boolean zoom, boolean requery, boolean preferences)
{
super();
this.zoomEnabled = zoom;
this.requeryEnabled = requery;
this.preferencesEnabled = preferences;
init();
}
public WEditorPopupMenu(boolean zoom, boolean requery, boolean preferences, boolean newRecord)
{
super();
this.zoomEnabled = zoom;
this.requeryEnabled = requery;
this.preferencesEnabled = preferences;
this.newEnabled = newRecord;
init();
}
private void init()
{
if (zoomEnabled)
{
zoomItem = new Menuitem();
zoomItem.setAttribute(EVENT_ATTRIBUTE, ZOOM_EVENT);
zoomItem.setLabel("Zoom");
zoomItem.setImage("/images/Zoom16.gif");
zoomItem.addEventListener(Events.ON_CLICK, this);
this.appendChild(zoomItem);
}
if (requeryEnabled)
{
requeryItem = new Menuitem();
requeryItem.setAttribute(EVENT_ATTRIBUTE, REQUERY_EVENT);
requeryItem.setLabel("ReQuery");
requeryItem.setImage("/images/Refresh16.gif");
requeryItem.addEventListener(Events.ON_CLICK, this);
this.appendChild(requeryItem);
}
if (preferencesEnabled)
{
prefItem = new Menuitem();
prefItem.setAttribute(EVENT_ATTRIBUTE, PREFERENCE_EVENT);
prefItem.setLabel("Value Preference");
prefItem.setImage("/images/VPreference16.gif");
prefItem.addEventListener(Events.ON_CLICK, this);
this.appendChild(prefItem);
}
if (newEnabled)
{
newItem = new Menuitem();
newItem.setAttribute(EVENT_ATTRIBUTE, NEW_EVENT);
newItem.setLabel("New Record");
newItem.setImage("/images/New16.gif");
newItem.addEventListener(Events.ON_CLICK, this);
this.appendChild(newItem);
}
}
public void addMenuListener(ContextMenuListener listener)
{
menuListeners.add(listener);
}
public boolean isAsap()
{
return true;
}
public void onEvent(Event event)
{
String evt = (String)event.getTarget().getAttribute(EVENT_ATTRIBUTE);
if (evt != null)
{
ContextMenuEvent menuEvent = new ContextMenuEvent(evt);
for (ContextMenuListener listener : menuListeners)
{
listener.onMenu(menuEvent);
}
}
}
}

View File

@ -0,0 +1,163 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.Locationbox;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.window.WLocationDialog;
import org.compiere.model.MLocation;
import org.compiere.model.MLocationLookup;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* @author Sendy Yagambrum
* @date July 16, 2007
*
* This class is based on VLocation written by Jorg Janke
**/
public class WLocationEditor extends WEditor implements EventListener, PropertyChangeListener
{
private static final String[] LISTENER_EVENTS = {Events.ON_CLICK};
private static CLogger log = CLogger.getCLogger(WLocationEditor.class);
private static final long serialVersionUID = 1L;
private Locationbox locationbox;
private String m_columnName;
private MLocationLookup m_Location;
private MLocation m_value;
/**
* Constructor without GridField
* @param columnName column name
* @param mandatory mandatory
* @param isReadOnly read only
* @param isUpdateable updateable
* @param mLocation location model
**/
public WLocationEditor(String columnName, boolean mandatory, boolean isReadOnly, boolean isUpdateable,
MLocationLookup mLocation)
{
super(new Locationbox(), "Address","",mandatory,isReadOnly,isUpdateable);
m_columnName = columnName;
m_Location = mLocation;
locationbox = (Locationbox)super.component;
locationbox.setButtonImage("/images/Location10.gif");
}
@Override
public String getDisplay()
{
return locationbox.getText();
}
@Override
public Object getValue()
{
if (m_value == null)
return null;
return new Integer(m_value.getC_Location_ID());
}
@Override
public void setValue(Object value)
{
if (value == null)
{
m_value = null;
locationbox.setText(null);
}
else
{
m_value = m_Location.getLocation(value, null);
if (m_value == null)
locationbox.setText("<" + value + ">");
else
locationbox.setText(m_value.toString());
}
}
/**
* Return Editor value
* @return value
*/
public int getC_Location_ID()
{
if (m_value == null)
return 0;
return m_value.getC_Location_ID();
}
/**
* Property Change Listener
* @param evt PropertyChangeEvent
*/
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
}
public void onEvent(Event event) throws Exception
{
//
if ("onClick".equals(event.getName()))
{
log.config( "actionPerformed - " + m_value);
WLocationDialog ld = new WLocationDialog(Msg.getMsg(Env.getCtx(), "Location"), m_value);
ld.setVisible(true);
AEnv.showWindow(ld);
m_value = ld.getValue();
//
if (!ld.isChanged())
return;
// Data Binding
int C_Location_ID = 0;
if (m_value != null)
C_Location_ID = m_value.getC_Location_ID();
Integer ii = new Integer(C_Location_ID);
// force Change - user does not realize that embedded object is already saved.
ValueChangeEvent valuechange = new ValueChangeEvent(this,m_columnName,null,null);
fireValueChange(valuechange); // resets m_mLocation
if (C_Location_ID != 0)
{
ValueChangeEvent vc = new ValueChangeEvent(this,m_columnName,null,ii);
fireValueChange(vc);
}
setValue(ii);
}
}
/**
* return listener events to be associated with editor component
*/
public String[] getEvents()
{
return LISTENER_EVENTS;
}
}

View File

@ -0,0 +1,417 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.EditorBox;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.window.WLocatorDialog;
import org.compiere.model.MLocator;
import org.compiere.model.MLocatorLookup;
import org.compiere.model.MRole;
import org.compiere.model.MWarehouse;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
/**
* Locator Editor : Based on VLocator
*
* @author Niraj Sohun
* @date Jul 23, 2007
*/
public class WLocatorEditor extends WEditor implements EventListener, PropertyChangeListener
{
private static final String[] LISTENER_EVENTS = {Events.ON_CLICK};
private String m_columnName;
private MLocatorLookup m_mLocator;
private EditorBox editorbox;
private MLocator m_value;
private int m_WindowNo;
private static CLogger log = CLogger.getCLogger(WLocatorEditor.class);
/**
* IDE Constructor
*/
public WLocatorEditor()
{
this("M_Locator_ID", false, false, true, null);
}
/**
* Constructor
*
* @param columnName ColumnName
* @param mandatory mandatory
* @param isReadOnly read only
* @param isUpdateable updateable
* @param mLocator locator (lookup) model
* @param WindowNo window no
*/
public WLocatorEditor( String columnName, boolean mandatory, boolean isReadOnly,
boolean isUpdateable, MLocatorLookup mLocator)
{
super(new EditorBox(), "Locator", "", mandatory, isReadOnly, isUpdateable);
m_columnName = columnName;
m_mLocator = mLocator;
editorbox = (EditorBox)super.component;
editorbox.setButtonImage("/images/Locator10.gif");
setDefault_Locator_ID(); // set default locator, teo_sarca [ 1661546 ]
}
public void setValue(Object value)
{
setValue (value, false);
}
/**
* Set Value
* @param value value
* @param fire data binding
*/
private void setValue (Object value, boolean fire)
{
if (value != null)
{
m_mLocator.setOnly_Warehouse_ID (getOnly_Warehouse_ID ());
m_mLocator.setOnly_Product_ID(getOnly_Product_ID());
if (!m_mLocator.isValid(value))
value = null;
}
m_value = m_mLocator.getMLocator(value, null);
editorbox.setText(m_mLocator.getDisplay(value)); // loads value
// Data Binding
ValueChangeEvent val = new ValueChangeEvent(this, m_columnName, null, value);
fireValueChange(val);
}
/**
* Return Editor value
* @return value
*/
public Object getValue()
{
if (getM_Locator_ID() == 0)
return null;
return m_value;
} // getValue
/**
* Get M_Locator_ID
* @return id
*/
public int getM_Locator_ID()
{
if (m_value != null/* && m_value instanceof Integer*/)
return m_value.getM_Locator_ID();
return 0;
} // getM_Locator_ID
/**
* Return Display Value
* @return display value
*/
public String getDisplay()
{
return editorbox.getText();
} // getDisplay
public void onEvent(Event event) throws Exception
{
// Warehouse/Product
int only_Warehouse_ID = getOnly_Warehouse_ID();
int only_Product_ID = getOnly_Product_ID();
log.config("Only Warehouse_ID=" + only_Warehouse_ID + ", Product_ID=" + only_Product_ID);
// Text Entry ok
if (event.getTarget() == editorbox && actionText(only_Warehouse_ID, only_Product_ID))
return;
// Button - Start Dialog
int M_Locator_ID = 0;
//if (m_value instanceof Integer)
if (m_value != null)
M_Locator_ID = m_value.getM_Locator_ID();
m_mLocator.setOnly_Warehouse_ID(only_Warehouse_ID);
m_mLocator.setOnly_Product_ID(getOnly_Product_ID());
WLocatorDialog ld = new WLocatorDialog(Msg.translate(Env.getCtx(), m_columnName),
m_mLocator, M_Locator_ID, isMandatory(), only_Warehouse_ID, this.m_WindowNo);
// display
ld.setVisible(true);
AEnv.showWindow(ld);
m_mLocator.setOnly_Warehouse_ID(0);
// redisplay
if (!ld.isChanged())
return;
setValue (ld.getValue(), true);
}
/**
* Hit Enter in Text Field
* @param only_Warehouse_ID if not 0 restrict warehouse
* @param only_Product_ID of not 0 restricted product
* @return true if found
*/
private boolean actionText(int only_Warehouse_ID, int only_Product_ID)
{
String text = editorbox.getText();
log.fine(text);
// Null
if (text == null || text.length() == 0)
{
if (isMandatory())
return false;
else
{
setValue (null, true);
return true;
}
}
if (text.endsWith("%"))
text = text.toUpperCase();
else
text = text.toUpperCase() + "%";
// Look up - see MLocatorLookup.run
StringBuffer sql = new StringBuffer("SELECT M_Locator_ID FROM M_Locator ")
.append(" WHERE IsActive='Y' AND UPPER(Value) LIKE ")
.append(DB.TO_STRING(text));
if (getOnly_Warehouse_ID() != 0)
sql.append(" AND M_Warehouse_ID=?");
if (getOnly_Product_ID() != 0)
sql.append(" AND (IsDefault='Y' ") // Default Locator
.append("OR EXISTS (SELECT * FROM M_Product p ") // Product Locator
.append("WHERE p.M_Locator_ID=M_Locator.M_Locator_ID AND p.M_Product_ID=?)")
.append("OR EXISTS (SELECT * FROM M_Storage s ") // Storage Locator
.append("WHERE s.M_Locator_ID=M_Locator.M_Locator_ID AND s.M_Product_ID=?))");
String finalSql = MRole.getDefault(Env.getCtx(), false).addAccessSQL(
sql.toString(), "M_Locator", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
int M_Locator_ID = 0;
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(finalSql, null);
int index = 1;
if (only_Warehouse_ID != 0)
pstmt.setInt(index++, only_Warehouse_ID);
if (only_Product_ID != 0)
{
pstmt.setInt(index++, only_Product_ID);
pstmt.setInt(index++, only_Product_ID);
}
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
M_Locator_ID = rs.getInt(1);
if (rs.next())
M_Locator_ID = 0; // more than one
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException ex)
{
log.log(Level.SEVERE, finalSql, ex);
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (SQLException ex1)
{
}
pstmt = null;
if (M_Locator_ID == 0)
return false;
setValue (new Integer(M_Locator_ID), true);
return true;
} // actionText
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField Model Field
*/
public void setField (org.compiere.model.GridField mField)
{
} // setField
/**
* Get Warehouse restriction if any.
* @return M_Warehouse_ID or 0
*/
private int getOnly_Warehouse_ID()
{
String only_Warehouse = Env.getContext(Env.getCtx(), m_WindowNo, "M_Warehouse_ID", true);
int only_Warehouse_ID = 0;
try
{
if (only_Warehouse != null && only_Warehouse.length () > 0)
only_Warehouse_ID = Integer.parseInt (only_Warehouse);
}
catch (Exception ex)
{
}
return only_Warehouse_ID;
} // getOnly_Warehouse_ID
/**
* Get Product restriction if any.
* @return M_Product_ID or 0
*/
private int getOnly_Product_ID()
{
if (!Env.isSOTrx(Env.getCtx(), m_WindowNo))
return 0; // No product restrictions for PO
String only_Product = Env.getContext(Env.getCtx(), m_WindowNo, "M_Product_ID", true);
int only_Product_ID = 0;
try
{
if (only_Product != null && only_Product.length () > 0)
only_Product_ID = Integer.parseInt (only_Product);
}
catch (Exception ex)
{
}
return only_Product_ID;
} // getOnly_Product_ID
/**
* Set the default locator if this field is mandatory
* and we have a warehouse restriction.
*
* @since 3.1.4
*/
private void setDefault_Locator_ID()
{
// teo_sarca, FR [ 1661546 ] Mandatory locator fields should use defaults
if (!isMandatory() || m_mLocator == null)
{
return;
}
int M_Warehouse_ID = getOnly_Warehouse_ID();
if (M_Warehouse_ID <= 0)
{
return;
}
MWarehouse wh = MWarehouse.get(Env.getCtx(), M_Warehouse_ID);
if (wh == null || wh.get_ID() <= 0)
{
return;
}
MLocator loc = wh.getDefaultLocator();
if (loc == null || loc.get_ID() <= 0)
{
return;
}
setValue(Integer.valueOf(loc.get_ID()));
}
/**
* Property Change Listener
* @param evt PropertyChangeEvent
*/
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
}
/**
* return listener events to be associated with editor component
*/
public String[] getEvents()
{
return LISTENER_EVENTS;
}
}

View File

@ -0,0 +1,129 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import org.adempiere.webui.component.NumberBox;
import org.adempiere.webui.event.ContextMenuEvent;
import org.adempiere.webui.event.ValueChangeEvent;
import org.compiere.model.GridField;
import org.compiere.util.DisplayType;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 11, 2007
* @version $Revision: 0.10 $
*/
public class WNumberEditor extends WEditor
{
public final String[] LISTENER_EVENTS = {Events.ON_CHANGE};
public static final int MAX_DISPLAY_LENGTH = 20;
private NumberBox comp;
private String oldValue;
private boolean mandatory = false;
public WNumberEditor(GridField gridField)
{
super(new NumberBox(gridField.getDisplayType() == DisplayType.Integer),
gridField);
comp = (NumberBox)super.component;
init();
}
public WNumberEditor(GridField gridField, boolean integral)
{
super(new NumberBox(integral), gridField);
comp = (NumberBox)super.component;
init();
}
private void init()
{
comp.setMaxlength(gridField.getFieldLength());
comp.setCols(MAX_DISPLAY_LENGTH);
comp.setTooltiptext(gridField.getDescription());
}
public void onEvent(Event event)
{
String newValue = comp.getValue();
ValueChangeEvent changeEvent = new ValueChangeEvent(this, this.getColumnName(), oldValue, newValue);
super.fireValueChange(changeEvent);
oldValue = newValue;
}
@Override
public String getDisplay()
{
return comp.getValue();
}
@Override
public Object getValue()
{
return comp.getValue();
}
@Override
public boolean isMandatory()
{
return mandatory;
}
@Override
public void setMandatory(boolean mandatory)
{
this.mandatory = mandatory;
}
@Override
public void setValue(Object value)
{
if (value != null)
{
comp.setValue(value.toString());
}
else
{
comp.setValue("0");
}
}
public String[] getEvents()
{
return LISTENER_EVENTS;
}
public void onMenu(ContextMenuEvent evt)
{
/* Wrong implementation for Value Preference - Swing is being called
if (WEditorPopupMenu.PREFERENCE_EVENT.equals(evt.getContextEvent()))
{
if (MRole.getDefault().isShowPreference())
ValuePreference.start (this.getGridField(), getValue());
return;
}
*/
}
}

View File

@ -0,0 +1,37 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import org.compiere.model.GridField;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 12, 2007
* @version $Revision: 0.10 $
*/
public class WPasswordEditor extends WStringEditor
{
public WPasswordEditor(GridField gridField)
{
super(gridField);
super.setTypePassword(true);
}
}

View File

@ -0,0 +1,846 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.Searchbox;
import org.adempiere.webui.event.ContextMenuEvent;
import org.adempiere.webui.event.ContextMenuListener;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.event.ValueChangeListener;
import org.adempiere.webui.grid.WBPartner;
import org.adempiere.webui.panel.InfoBPartnerPanel;
import org.adempiere.webui.panel.InfoPanel;
import org.adempiere.webui.panel.InfoProductPanel;
import org.compiere.grid.ed.ValuePreference;
import org.compiere.model.GridField;
import org.compiere.model.Lookup;
import org.compiere.model.MLookup;
import org.compiere.model.MRole;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
* Search Editor for web UI.
* Web UI port of search type VLookup
*
* @author Ashley G Ramdass
*
*/
public class WSearchEditor extends WEditor implements ContextMenuListener, PropertyChangeListener, ValueChangeListener
{
private static final String[] LISTENER_EVENTS = {Events.ON_CLICK, Events.ON_CHANGE};
private Searchbox searchbox;
private Lookup lookup;
private String m_tableName = null;
private String m_keyColumnName = null;
private String columnName;
private WEditorPopupMenu popupMenu;
private Object value;
private static CLogger log = CLogger.getCLogger(WSearchEditor.class);
public WSearchEditor (GridField gridField)
{
super(new Searchbox(), gridField);
lookup = gridField.getLookup();
if (lookup != null)
columnName = lookup.getColumnName();
init();
}
/**
* Set the underlying component.
*
* @param comp the component to use
*/
protected void setComponent(Component comp)
{
// TODO remove this duplication of components.
// Only need component from WEditor (superclass)
// and can then override get component and cast it to Searchbox
if (!(comp instanceof Searchbox))
{
throw new IllegalArgumentException("A search editor must contain a Searchbox");
}
super.setComponent(comp);
this.searchbox = (Searchbox)super.component;
}
/**
* Constructor for use if a grid field is unavailable
*
* @param lookup Store of selectable data
* @param label column name (not displayed)
* @param description description of component
* @param mandatory whether a selection must be made
* @param readonly whether or not the editor is read only
* @param updateable whether the editor contents can be changed
*/
public WSearchEditor (Lookup lookup, String label, String description, boolean mandatory, boolean readonly, boolean updateable)
{
super(new Searchbox(), label, description, mandatory, readonly, updateable);
if (lookup == null)
{
throw new IllegalArgumentException("Lookup cannot be null");
}
this.lookup = lookup;
columnName = lookup.getColumnName();
super.setColumnName(columnName);
init();
}
/**
* initialise editor
* @param columnName columnName
*/
private void init()
{
columnName = this.getColumnName();
popupMenu = new WEditorPopupMenu(true, true, true, true);
(searchbox.getTextBox()).setContext(popupMenu.getId());
if (columnName.equals("C_BPartner_ID"))
{
searchbox.setButtonImage("/images/BPartner10.gif");
}
else if (columnName.equals("M_Product_ID"))
{
searchbox.setButtonImage("/images/Product10.gif");
}
else
{
searchbox.setButtonImage("/images/PickOpen10.gif");
}
return;
}
public WEditorPopupMenu getPopupMenu()
{
return popupMenu;
}
@Override
public void setValue(Object value)
{
this.value = value;
if (value != null && !"".equals(String.valueOf(value)))
{
String text = lookup.getDisplay(value);
if (text.startsWith("_"))
{
text = text.substring(1);
}
searchbox.setText(text);
}
else
{
searchbox.setText("");
}
}
/**
* Set whether the editor represents a mandatory field.
*
* @param mandatory whether the editor must be filled
*/
public void setMandatory(boolean mandatory)
{
searchbox.setMandatory(mandatory);
super.setMandatory(mandatory);
}
@Override
public Object getValue()
{
return value;
}
@Override
public String getDisplay()
{
return searchbox.getText();
}
public void onEvent(Event e)
{
if ("onChange".equals(e.getName()))
{
actionText(searchbox.getText());
}
else if ("onClick".equals(e.getName()))
{
actionButton("");
}
}
public void propertyChange(PropertyChangeEvent evt)
{
if ("FieldValue".equals(evt.getPropertyName()))
{
if ( evt.getNewValue()== null)
{
actionRefresh("");
}
else
{
actionRefresh(evt.getNewValue());
}
}
}
private void actionRefresh(Object value)
{
boolean mandatory = isMandatory();
AEnv.actionRefresh(lookup, value, mandatory);
setValue(value);
}
private void actionZoom()
{
AEnv.actionZoom(lookup, getValue());
}
private void actionZoom(Object value)
{
AEnv.actionZoom(lookup, value);
}
public void onMenu(ContextMenuEvent evt)
{
if (WEditorPopupMenu.REQUERY_EVENT.equals(evt.getContextEvent()))
{
actionRefresh(getValue());
}
else if (WEditorPopupMenu.ZOOM_EVENT.equals(evt.getContextEvent()))
{
actionZoom();
}
else if (WEditorPopupMenu.PREFERENCE_EVENT.equals(evt.getContextEvent()))
{
if (MRole.getDefault().isShowPreference())
ValuePreference.start (this.getGridField(), getValue());
return;
}
else if (WEditorPopupMenu.NEW_EVENT.equals(evt.getContextEvent()))
{
actionBPartner(true);
}
}
private void actionText(String text)
{
// Nothing entered
if (text == null || text.length() == 0 || text.equals("%"))
{
actionButton(text);
return;
}
text = text.toUpperCase();
log.config(getColumnName() + " - " + text);
// Exact first
PreparedStatement pstmt = null;
String finalSQL = Msg.parseTranslation(Env.getCtx(), getDirectAccessSQL(text));
int id = -3;
try
{
pstmt = DB.prepareStatement(finalSQL, null);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
id = rs.getInt(1); // first
if (rs.next())
id = -1; // only if unique
}
rs.close();
pstmt.close();
}
catch (Exception e)
{
log.log(Level.SEVERE, finalSQL, e);
id = -2;
}
// Try like
if (id == -3 && !text.endsWith("%"))
{
text += "%";
finalSQL = Msg.parseTranslation(Env.getCtx(), getDirectAccessSQL(text));
try
{
pstmt = DB.prepareStatement(finalSQL, null);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
id = rs.getInt(1); // first
if (rs.next())
id = -1; // only if unique
}
rs.close();
pstmt.close();
}
catch (Exception e)
{
log.log(Level.SEVERE, finalSQL, e);
id = -2;
}
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (Exception e)
{
}
// No (unique) result
if (id <= 0)
{
if (id == -3)
log.fine(getColumnName() + " - Not Found - " + finalSQL);
else
log.fine(getColumnName() + " - Not Unique - " + finalSQL);
//m_value = null; // force re-display
actionButton(searchbox.getText());
return;
}
log.fine(getColumnName() + " - Unique ID=" + id);
actionCombo(new Integer(id)); // data binding
//m_text.requestFocus();
} // actionText
private void actionCombo (Object value)
{
log.fine("Value=" + value);
ValueChangeEvent evt = new ValueChangeEvent(this, this.getColumnName(), value, value);
// -> ADTabpanel - valuechange
fireValueChange(evt);
/*
// is the value updated ?
boolean updated = false;
if (value == null && getValue() == null)
updated = true;
else if (value != null && value.equals(getValue()))
updated = true;
if (!updated)
{
// happens if VLookup is used outside of APanel/GridController (no property listener)
log.fine(getColumnName() + " - Value explicitly set - new=" + value + ", old=" + getValue());
if (getListeners(PropertyChangeListener.class).length <= 0)
setValue(value);
}
*/
} // actionCombo
/**
* Action - Special BPartner Screen
* @param newRecord true if new record should be created
*/
private void actionBPartner (boolean newRecord)
{
WBPartner vbp = new WBPartner (lookup.getWindowNo());
int BPartner_ID = 0;
// if update, get current value
if (!newRecord)
{
if (value instanceof Integer)
BPartner_ID = ((Integer)value).intValue();
else if (value != null)
BPartner_ID = Integer.parseInt(value.toString());
}
vbp.loadBPartner (BPartner_ID);
vbp.setVisible(true);
AEnv.showWindow(vbp);
// get result
int result = vbp.getC_BPartner_ID();
if (result == 0 // 0 = not saved
&& result == BPartner_ID) // the same
return;
// Maybe new BPartner - put in cache
lookup.getDirect(new Integer(result), false, true);
setValue(new Integer(result));
actionCombo (new Integer(result)); // data binding
//setValue(getValue());
} // actionBPartner
private void actionButton(String queryValue)
{
// m_button.setEnabled(false); // disable double click
if (lookup == null)
return; // leave button disabled
//m_text.requestFocus(); // closes other editors
/**
* Three return options:
* - Value Selected & OK pressed => store result => result has value
* - Cancel pressed => store null => result == null && cancelled
* - Window closed -> ignore => result == null && !cancalled
*/
//Object result = null; // Not Being Used
//boolean cancelled = false; // Not Being Used
String col = lookup.getColumnName(); // fully qualified name
if (col.indexOf('.') != -1)
col = col.substring(col.indexOf('.')+1);
// Zoom / Validation
String whereClause = getWhereClause();
log.fine(col + ", Zoom=" + lookup.getZoom() + " (" + whereClause + ")");
// boolean resetValue = false; // Reset value so that is always treated as new entry
if (col.equals("M_Product_ID"))
{
// Reset
Env.setContext(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID", "0");
Env.setContext(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID", "0");
Env.setContext(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_Lookup_ID", "0");
// Replace Value with name if no value exists
if (queryValue.length() == 0 && searchbox.getText().length() > 0)
queryValue = "@" + searchbox.getText() + "@"; // Name indicator - otherwise Value
int M_Warehouse_ID = Env.getContextAsInt(Env.getCtx(), lookup.getWindowNo(), "M_Warehouse_ID");
int M_PriceList_ID = Env.getContextAsInt(Env.getCtx(), lookup.getWindowNo(), "M_PriceList_ID");
// Show Info
InfoProductPanel ip = new InfoProductPanel (lookup.getWindowNo(),
M_Warehouse_ID, M_PriceList_ID, false,queryValue, whereClause);
ip.setVisible(true);
ip.setTitle("Product Info");
ip.setStyle("border: 2px");
ip.setClosable(true);
ip.setAttribute("mode", "modal");
ip.addValueChangeListener(this);
AEnv.showWindow(ip);
}
else if (col.equals("C_BPartner_ID"))
{
// Replace Value with name if no value exists
if (queryValue.length() == 0 && searchbox.getText().length() > 0)
queryValue = searchbox.getText();
boolean isSOTrx = true; // default
if (Env.getContext(Env.getCtx(), lookup.getWindowNo(), "IsSOTrx").equals("N"))
isSOTrx = false;
InfoBPartnerPanel ip = new InfoBPartnerPanel(queryValue, lookup.getWindowNo(), isSOTrx,false, whereClause);
ip.setVisible(true);
ip.setTitle("Business Partner Info");
ip.setStyle("border: 2px");
ip.setClosable(true);
ip.setAttribute("mode", "modal");
ip.addValueChangeListener(this);
AEnv.showWindow(ip);
/*
cancelled = ip.isCancelled();
result = ip.getSelectedKey();
*/
}
else // General Info
{
if (m_tableName == null) // sets table name & key column
getDirectAccessSQL("*");
if (queryValue.length() == 0 && searchbox.getText().length() > 0)
queryValue = searchbox.getText();
boolean isSOTrx = true; // default
if (Env.getContext(Env.getCtx(), lookup.getWindowNo(), "IsSOTrx").equals("N"))
isSOTrx = false;
InfoPanel ig = InfoPanel.create(lookup.getWindowNo(), m_tableName,m_keyColumnName,queryValue, false, whereClause);
ig.setVisible(true);
ig.setStyle("border: 2px");
ig.setClosable(true);
ig.setAttribute("mode", "modal");
ig.addValueChangeListener(this);
AEnv.showWindow(ig);
}
/*
// Result
if (result != null)
{
log.config(m_columnName + " - Result = " + result.toString() + " (" + result.getClass().getName() + ")");
// make sure that value is in cache
m_lookup.getDirect(result, false, true);
if (resetValue)
actionCombo (null);
actionCombo (result); // data binding
}
else if (cancelled)
{
log.config(m_columnName + " - Result = null (cancelled)");
actionCombo(null);
}
else
{
log.config(m_columnName + " - Result = null (not cancelled)");
setValue(m_value); // to re-display value
}
//
m_button.setEnabled(true);
m_text.requestFocus();
*/
}
/**
* Generate Access SQL for Search.
* The SQL returns the ID of the value entered
* Also sets m_tableName and m_keyColumnName
* @param text uppercase text for LIKE comparison
* @return sql or ""
* Example
* SELECT C_Payment_ID FROM C_Payment WHERE UPPER(DocumentNo) LIKE x OR ...
*/
private String getDirectAccessSQL (String text)
{
String m_columnName = getColumnName();
StringBuffer sql = new StringBuffer();
m_tableName = m_columnName.substring(0, m_columnName.length()-3);
m_keyColumnName = m_columnName;
if (m_columnName.equals("M_Product_ID"))
{
// Reset
Env.setContext(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_Product_ID", "0");
Env.setContext(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_AttributeSetInstance_ID", "0");
Env.setContext(Env.getCtx(), Env.WINDOW_INFO, Env.TAB_INFO, "M_Locator_ID", "0");
sql.append("SELECT M_Product_ID FROM M_Product WHERE (UPPER(Value) LIKE ")
.append(DB.TO_STRING(text))
.append(" OR UPPER(Name) LIKE ").append(DB.TO_STRING(text))
.append(" OR UPC LIKE ").append(DB.TO_STRING(text)).append(")");
}
else if (m_columnName.equals("C_BPartner_ID"))
{
sql.append("SELECT C_BPartner_ID FROM C_BPartner WHERE (UPPER(Value) LIKE ")
.append(DB.TO_STRING(text))
.append(" OR UPPER(Name) LIKE ").append(DB.TO_STRING(text)).append(")");
}
else if (m_columnName.equals("C_Order_ID"))
{
sql.append("SELECT C_Order_ID FROM C_Order WHERE UPPER(DocumentNo) LIKE ")
.append(DB.TO_STRING(text));
}
else if (m_columnName.equals("C_Invoice_ID"))
{
sql.append("SELECT C_Invoice_ID FROM C_Invoice WHERE UPPER(DocumentNo) LIKE ")
.append(DB.TO_STRING(text));
}
else if (m_columnName.equals("M_InOut_ID"))
{
sql.append("SELECT M_InOut_ID FROM M_InOut WHERE UPPER(DocumentNo) LIKE ")
.append(DB.TO_STRING(text));
}
else if (m_columnName.equals("C_Payment_ID"))
{
sql.append("SELECT C_Payment_ID FROM C_Payment WHERE UPPER(DocumentNo) LIKE ")
.append(DB.TO_STRING(text));
}
else if (m_columnName.equals("GL_JournalBatch_ID"))
{
sql.append("SELECT GL_JournalBatch_ID FROM GL_JournalBatch WHERE UPPER(DocumentNo) LIKE ")
.append(DB.TO_STRING(text));
}
else if (m_columnName.equals("SalesRep_ID"))
{
sql.append("SELECT AD_User_ID FROM AD_User WHERE UPPER(Name) LIKE ")
.append(DB.TO_STRING(text));
m_tableName = "AD_User";
m_keyColumnName = "AD_User_ID";
}
// Predefined
if (sql.length() > 0)
{
String wc = getWhereClause();
if (wc != null && wc.length() > 0)
sql.append(" AND ").append(wc);
sql.append(" AND IsActive='Y'");
// ***
log.finest(m_columnName + " (predefined) " + sql.toString());
return MRole.getDefault().addAccessSQL(sql.toString(),
m_tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
}
// Check if it is a Table Reference
if (lookup != null && lookup instanceof MLookup)
{
int AD_Reference_ID = ((MLookup)lookup).getAD_Reference_Value_ID();
if (AD_Reference_ID != 0)
{
String query = "SELECT kc.ColumnName, dc.ColumnName, t.TableName "
+ "FROM AD_Ref_Table rt"
+ " INNER JOIN AD_Column kc ON (rt.AD_Key=kc.AD_Column_ID)"
+ " INNER JOIN AD_Column dc ON (rt.AD_Display=dc.AD_Column_ID)"
+ " INNER JOIN AD_Table t ON (rt.AD_Table_ID=t.AD_Table_ID) "
+ "WHERE rt.AD_Reference_ID=?";
String displayColumnName = null;
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(query, null);
pstmt.setInt(1, AD_Reference_ID);
ResultSet rs = pstmt.executeQuery();
if (rs.next())
{
m_keyColumnName = rs.getString(1);
displayColumnName = rs.getString(2);
m_tableName = rs.getString(3);
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
log.log(Level.SEVERE, query, e);
}
try
{
if (pstmt != null)
pstmt.close();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
if (displayColumnName != null)
{
sql = new StringBuffer();
sql.append("SELECT ").append(m_keyColumnName)
.append(" FROM ").append(m_tableName)
.append(" WHERE UPPER(").append(displayColumnName)
.append(") LIKE ").append(DB.TO_STRING(text))
.append(" AND IsActive='Y'");
String wc = getWhereClause();
if (wc != null && wc.length() > 0)
sql.append(" AND ").append(wc);
// ***
log.finest(m_columnName + " (Table) " + sql.toString());
return MRole.getDefault().addAccessSQL(sql.toString(),
m_tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
}
} // Table Reference
} // MLookup
/** Check Well Known Columns of Table - assumes TableDir **/
String query = "SELECT t.TableName, c.ColumnName "
+ "FROM AD_Column c "
+ " INNER JOIN AD_Table t ON (c.AD_Table_ID=t.AD_Table_ID AND t.IsView='N') "
+ "WHERE (c.ColumnName IN ('DocumentNo', 'Value', 'Name') OR c.IsIdentifier='Y')"
+ " AND c.AD_Reference_ID IN (10,14)"
+ " AND EXISTS (SELECT * FROM AD_Column cc WHERE cc.AD_Table_ID=t.AD_Table_ID"
+ " AND cc.IsKey='Y' AND cc.ColumnName=?)";
m_keyColumnName = m_columnName;
sql = new StringBuffer();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(query, null);
pstmt.setString(1, m_keyColumnName);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
if (sql.length() != 0)
sql.append(" OR ");
m_tableName = rs.getString(1);
sql.append("UPPER(").append(rs.getString(2)).append(") LIKE ").append(DB.TO_STRING(text));
}
rs.close();
pstmt.close();
pstmt = null;
}
catch (SQLException ex)
{
log.log(Level.SEVERE, query, ex);
}
try
{
if (pstmt != null)
pstmt.close();
}
catch (SQLException ex1)
{
}
pstmt = null;
//
if (sql.length() == 0)
{
log.log(Level.SEVERE, m_columnName + " (TableDir) - no standard/identifier columns");
return "";
}
//
StringBuffer retValue = new StringBuffer ("SELECT ")
.append(m_columnName).append(" FROM ").append(m_tableName)
.append(" WHERE ").append(sql)
.append(" AND IsActive='Y'");
String wc = getWhereClause();
if (wc != null && wc.length() > 0)
retValue.append(" AND ").append(wc);
// ***
log.finest(m_columnName + " (TableDir) " + sql.toString());
return MRole.getDefault().addAccessSQL(retValue.toString(),
m_tableName, MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
}
private String getWhereClause()
{
String whereClause = "";
if (lookup == null)
return "";
if (lookup.getZoomQuery() != null)
whereClause = lookup.getZoomQuery().getWhereClause();
String validation = lookup.getValidation();
if (validation == null)
validation = "";
if (whereClause.length() == 0)
whereClause = validation;
else if (validation.length() > 0)
whereClause += " AND " + validation;
// log.finest("ZoomQuery=" + (lookup.getZoomQuery()==null ? "" : lookup.getZoomQuery().getWhereClause())
// + ", Validation=" + lookup.getValidation());
if (whereClause.indexOf('@') != -1)
{
String validated = Env.parseContext(Env.getCtx(), lookup.getWindowNo(), whereClause, false);
if (validated.length() == 0)
log.severe(getColumnName() + " - Cannot Parse=" + whereClause);
else
{
log.fine(getColumnName() + " - Parsed: " + validated);
return validated;
}
}
return whereClause;
} // getWhereClause
public String[] getEvents()
{
return LISTENER_EVENTS;
}
public void valueChange(ValueChangeEvent evt)
{
if (getColumnName().equals(evt.getPropertyName()))
{
if (evt.getNewValue() != null)
{
actionCombo(evt.getNewValue());
}
}
else if ("zoom".equals(evt.getPropertyName()))
{
actionZoom(evt.getNewValue());
}
}
}

View File

@ -0,0 +1,141 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import org.adempiere.webui.component.Textbox;
import org.adempiere.webui.event.ContextMenuEvent;
import org.adempiere.webui.event.ValueChangeEvent;
import org.compiere.grid.ed.ValuePreference;
import org.compiere.model.GridField;
import org.compiere.model.MRole;
import org.compiere.util.DisplayType;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 11, 2007
* @version $Revision: 0.10 $
*/
public class WStringEditor extends WEditor
{
private static final String[] LISTENER_EVENTS = {Events.ON_CHANGE};
protected Textbox textbox;
private String oldText;
public WStringEditor(GridField gridField)
{
super(new Textbox(), gridField);
textbox = (Textbox)super.component;
init();
}
private void init()
{
textbox.setMaxlength(gridField.getFieldLength());
int displayLength = gridField.getDisplayLength();
if (displayLength <= 0 || displayLength > MAX_DISPLAY_LENGTH)
{
displayLength = MAX_DISPLAY_LENGTH;
}
textbox.setCols(displayLength);
if (gridField.getDisplayType() == DisplayType.Text)
{
textbox.setMultiline(true);
textbox.setRows(3);
}
else if (gridField.getDisplayType() == DisplayType.TextLong)
{
textbox.setMultiline(true);
textbox.setRows(5);
}
else if (gridField.getDisplayType() == DisplayType.Memo)
{
textbox.setMultiline(true);
textbox.setRows(8);
}
}
public void onEvent(Event event)
{
String newText = textbox.getValue();
ValueChangeEvent changeEvent = new ValueChangeEvent(this, this.getColumnName(), oldText, newText);
super.fireValueChange(changeEvent);
oldText = newText;
}
@Override
public String getDisplay()
{
return textbox.getValue();
}
@Override
public Object getValue()
{
return textbox.getValue();
}
@Override
public void setValue(Object value)
{
if (value != null)
{
textbox.setValue(value.toString());
}
else
{
textbox.setValue("");
}
oldText = textbox.getValue();
}
protected void setTypePassword(boolean password)
{
if (password)
{
textbox.setType("password");
}
else
{
textbox.setType("text");
}
}
@Override
public String[] getEvents()
{
return LISTENER_EVENTS;
}
public void onMenu(ContextMenuEvent evt)
{
if (WEditorPopupMenu.PREFERENCE_EVENT.equals(evt.getContextEvent()))
{
if (MRole.getDefault().isShowPreference())
ValuePreference.start (this.getGridField(), getValue());
return;
}
}
}

View File

@ -0,0 +1,269 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.beans.PropertyChangeEvent;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import org.adempiere.webui.apps.AEnv;
import org.adempiere.webui.component.ListItem;
import org.adempiere.webui.component.Listbox;
import org.adempiere.webui.event.ContextMenuEvent;
import org.adempiere.webui.event.ContextMenuListener;
import org.adempiere.webui.event.ValueChangeEvent;
import org.compiere.grid.ed.ValuePreference;
import org.compiere.model.GridField;
import org.compiere.model.Lookup;
import org.compiere.model.MRole;
import org.compiere.util.CLogger;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.ValueNamePair;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 12, 2007
* @version $Revision: 0.10 $
*/
public class WTableDirEditor extends WEditor implements ListDataListener,
ContextMenuListener
{
public final String[] LISTENER_EVENTS = {Events.ON_SELECT};
private static final CLogger logger;
static
{
logger = CLogger.getCLogger(WTableDirEditor.class);
}
private Lookup lookup;
private Listbox listbox;
private Object oldValue;
private WEditorPopupMenu popupMenu;
public WTableDirEditor(GridField gridField)
{
super(new Listbox(), gridField);
listbox = (Listbox)super.component;
lookup = gridField.getLookup();
init();
}
/**
* Constructor for use if a grid field is unavailable
*
* @param lookup Store of selectable data
* @param label column name (not displayed)
* @param description description of component
* @param mandatory whether a selection must be made
* @param readonly whether or not the editor is read only
* @param updateable whether the editor contents can be changed
*/
public WTableDirEditor(Lookup lookup, String label, String description, boolean mandatory, boolean readonly, boolean updateable)
{
super(new Listbox(), label, description, mandatory, readonly, updateable);
if (lookup == null)
{
throw new IllegalArgumentException("Lookup cannot be null");
}
this.listbox = (Listbox)super.component;
this.lookup = lookup;
super.setColumnName(lookup.getColumnName());
init();
}
private void init()
{
listbox.setRows(0);
listbox.setMultiple(false);
listbox.setMold("select");
listbox.setWidth("200px");
listbox.addPropertyChangeListener(this);
boolean zoom= false;
if (lookup != null)
{
lookup.addListDataListener(this);
if ((lookup.getDisplayType() == DisplayType.List && Env.getContextAsInt(Env.getCtx(), "#AD_Role_ID") == 0)
|| lookup.getDisplayType() != DisplayType.List)
{
zoom= true;
}
lookup.refresh();
refreshList();
}
popupMenu = new WEditorPopupMenu(zoom, true, true);
listbox.setContext(popupMenu.getId());
}
@Override
public String getDisplay()
{
String display = null;
ListItem selItem = listbox.getSelectedItem();
if (selItem != null)
{
display = selItem.getLabel();
}
return display;
}
@Override
public Object getValue()
{
Object retVal = null;
ListItem selItem = listbox.getSelectedItem();
if (selItem != null)
{
retVal = selItem.getValue();
}
return retVal;
}
public void setValue(Object value)
{
if (value != null && (value instanceof Integer || value instanceof String))
{
listbox.setValue(value);
if (listbox.getSelectedIndex() == -1 && lookup != null)
{
lookup.refresh();
oldValue = value;
refreshList();
}
}
else
{
listbox.setValue(null);
}
oldValue = value;
}
private void refreshList()
{
if (listbox.getItemCount() > 0)
listbox.getItems().clear();
if (lookup != null)
{
int size = lookup.getSize();
for (int i = 0; i < size; i++)
{
Object obj = lookup.getElementAt(i);
if (obj instanceof KeyNamePair)
{
KeyNamePair lookupKNPair = (KeyNamePair) obj;
listbox.appendItem(lookupKNPair.getName(), lookupKNPair.getKey());
}
else if (obj instanceof ValueNamePair)
{
ValueNamePair lookupKNPair = (ValueNamePair) obj;
listbox.appendItem(lookupKNPair.getName(), lookupKNPair.getValue());
}
}
}
listbox.setValue(oldValue);
}
public void onEvent(Event event)
{
Object newValue = getValue();
ValueChangeEvent changeEvent = new ValueChangeEvent(this, this.getColumnName(), oldValue, newValue);
super.fireValueChange(changeEvent);
oldValue = newValue;
}
public String[] getEvents()
{
return LISTENER_EVENTS;
}
public void contentsChanged(ListDataEvent e)
{
refreshList();
}
public void intervalAdded(ListDataEvent e)
{}
public void intervalRemoved(ListDataEvent e)
{}
public WEditorPopupMenu getPopupMenu()
{
return popupMenu;
}
private void actionRefresh()
{
Object curValue = getValue();
if (lookup != null)
{
lookup.refresh();
refreshList();
setValue(curValue);
}
}
private void actionZoom()
{
AEnv.actionZoom(lookup, getValue());
}
public void onMenu(ContextMenuEvent evt)
{
if (WEditorPopupMenu.REQUERY_EVENT.equals(evt.getContextEvent()))
{
actionRefresh();
}
else if (WEditorPopupMenu.ZOOM_EVENT.equals(evt.getContextEvent()))
{
actionZoom();
}
else if (WEditorPopupMenu.PREFERENCE_EVENT.equals(evt.getContextEvent()))
{
if (MRole.getDefault().isShowPreference())
ValuePreference.start (this.getGridField(), getValue());
return;
}
}
public void propertyChange(PropertyChangeEvent evt)
{
if ("FieldValue".equals(evt.getPropertyName()))
{
setValue(evt.getNewValue());
}
}
}

View File

@ -0,0 +1,40 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import org.compiere.model.GridField;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 12, 2007
* @version $Revision: 0.10 $
*/
public class WUnknownEditor extends WStringEditor
{
public WUnknownEditor(GridField gridField)
{
super(gridField);
init();
}
private void init()
{
super.textbox.setEnabled(false);
}
}

View File

@ -0,0 +1,104 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.net.URL;
import org.adempiere.webui.component.Urlbox;
import org.adempiere.webui.event.ValueChangeEvent;
import org.adempiere.webui.window.FDialog;
import org.compiere.model.GridField;
import org.compiere.util.Env;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
public class WUrlEditor extends WEditor
{
private static final String[] LISTENER_EVENTS = {Events.ON_CLICK, Events.ON_CHANGE};
private Urlbox urlbox;
public WUrlEditor(GridField gridField)
{
super(new Urlbox(), gridField);
this.urlbox = (Urlbox)super.component;
urlbox.setButtonImage("/images/Online16.gif");
}
@Override
public void setValue(Object value)
{
if (value == null)
{
urlbox.setText("");
}
else
{
urlbox.setText(String.valueOf(value));
}
}
@Override
public Object getValue()
{
return urlbox.getText();
}
@Override
public String getDisplay()
{
return urlbox.getText();
}
public void onEvent(Event event)
{
if (Events.ON_CHANGE.equals(event.getName()))
{
ValueChangeEvent changeEvent = new ValueChangeEvent(this, this.getColumnName(), urlbox.getText(), urlbox.getText());
fireValueChange(changeEvent);
}
else if (Events.ON_CLICK.equals(event.getName()))
{
String urlString =urlbox.getText();
String message = null;
if (urlString != null && urlString.length() > 0)
{
try
{
URL url = new URL(urlString);
Env.startBrowser(urlString);
return;
}
catch(Exception e)
{
message = e.getMessage();
}
}
FDialog.warn(0, this.getComponent(), "URLnotValid", message);
}
}
public String[] getEvents()
{
return LISTENER_EVENTS;
}
}

View File

@ -0,0 +1,125 @@
/******************************************************************************
* Product: Posterita Ajax UI *
* Copyright (C) 2007 Posterita Ltd. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Posterita Ltd., 3, Draper Avenue, Quatre Bornes, Mauritius *
* or via info@posterita.org or http://www.posterita.org/ *
*****************************************************************************/
package org.adempiere.webui.editor;
import java.beans.PropertyChangeEvent;
import java.util.logging.Level;
import org.adempiere.webui.component.Checkbox;
import org.adempiere.webui.event.ValueChangeEvent;
import org.compiere.model.GridField;
import org.compiere.util.CLogger;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
/**
*
* @author <a href="mailto:agramdass@gmail.com">Ashley G Ramdass</a>
* @date Mar 11, 2007
* @version $Revision: 0.10 $
*/
public class WYesNoEditor extends WEditor
{
public final String[] LISTENER_EVENTS = {Events.ON_CHECK};
private static final CLogger logger;
static
{
logger = CLogger.getCLogger(WYesNoEditor.class);
}
private Checkbox checkbox;
private boolean oldValue = false;
public WYesNoEditor(GridField gridField)
{
super(new Checkbox(), gridField);
checkbox = (Checkbox)super.component;
init();
}
private void init()
{
super.label.setValue("");
super.label.setTooltiptext("");
checkbox.setLabel(gridField.getHeader());
}
public void onEvent(Event event)
{
Boolean newValue = (Boolean)getValue();
ValueChangeEvent changeEvent = new ValueChangeEvent(this, this.getColumnName(), oldValue, newValue);
super.fireValueChange(changeEvent);
oldValue = newValue;
}
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
{
setValue(evt.getNewValue());
}
}
@Override
public String getDisplay()
{
String display = checkbox.isChecked() ? "Y" : "N";
return Msg.translate(Env.getCtx(), display);
}
@Override
public Object getValue()
{
return new Boolean(checkbox.isChecked());
}
@Override
public void setValue(Object value)
{
if (value == null || value instanceof Boolean)
{
Boolean val = ((value == null) ? false
: (Boolean) value);
checkbox.setChecked(val);
oldValue = val;
}
else if (value instanceof String)
{
Boolean val = value.equals("Y");
checkbox.setChecked(val);
oldValue = val;
}
else
{
logger.log(Level.SEVERE,
"New field value of unknown type, Type: "
+ value.getClass()
+ ", Value: " + value);
checkbox.setChecked(false);
}
}
public String[] getEvents()
{
return LISTENER_EVENTS;
}
}

Some files were not shown because too many files have changed in this diff Show More