From 8a0bf1e3c7b7cc7b0139dd3a5036b30d9d92e8a6 Mon Sep 17 00:00:00 2001 From: vpj-cd Date: Thu, 7 Dec 2006 03:22:38 +0000 Subject: [PATCH] Adempiere 3.1.2 --- client/src/org/compiere/apps/AArchive.java | 1 - client/src/org/compiere/apps/AEnv.java | 85 +- client/src/org/compiere/apps/ALogin.java | 1379 +++--- client/src/org/compiere/apps/AMenu.java | 1111 +++-- .../src/org/compiere/apps/AMenuStartItem.java | 544 ++- client/src/org/compiere/apps/APanel.java | 4034 ++++++++--------- client/src/org/compiere/apps/ARequest.java | 1 - client/src/org/compiere/apps/AWindow.java | 341 +- client/src/org/compiere/apps/AZoomAcross.java | 1 - client/src/org/compiere/apps/AppsAction.java | 552 +-- client/src/org/compiere/apps/Preference.bak | 662 +++ client/src/org/compiere/apps/Preference.java | 4 +- client/src/org/compiere/apps/ProcessCtl.java | 960 ++-- .../src/org/compiere/apps/ProcessDialog.java | 799 ++-- .../org/compiere/apps/ProcessParameter.java | 920 ++-- .../src/org/compiere/apps/WindowManager.java | 2 +- .../src/org/compiere/apps/form/FormFrame.java | 663 ++- .../org/compiere/apps/form/VFileImport.java | 2 +- .../src/org/compiere/apps/form/VPayPrint.java | 1048 ++--- .../org/compiere/apps/form/VPaySelect.java | 1363 +++--- .../org/compiere/apps/form/VTrxMaterial.java | 1 - client/src/org/compiere/apps/search/Info.java | 1 - .../src/org/compiere/apps/wf/WFActivity.java | 2 - client/src/org/compiere/apps/wf/WFPanel.java | 1 - .../compiere/grid/VCreateFromStatement.java | 476 +- client/src/org/compiere/grid/VPayment.java | 2685 ++++++----- .../src/org/compiere/grid/ed/VCellEditor.java | 375 +- .../org/compiere/grid/ed/VCellRenderer.java | 499 +- client/src/org/compiere/grid/ed/VColor.java | 668 +-- .../org/compiere/grid/ed/VHeaderRenderer.java | 37 +- client/src/org/compiere/grid/ed/VLocator.java | 1083 +++-- client/src/org/compiere/grid/ed/VLookup.java | 1 - client/src/org/compiere/grid/ed/VString.java | 631 ++- client/src/org/compiere/print/ReportCtl.java | 326 +- 34 files changed, 10807 insertions(+), 10451 deletions(-) create mode 100755 client/src/org/compiere/apps/Preference.bak diff --git a/client/src/org/compiere/apps/AArchive.java b/client/src/org/compiere/apps/AArchive.java index 3fd4c9252b..ad06876f15 100644 --- a/client/src/org/compiere/apps/AArchive.java +++ b/client/src/org/compiere/apps/AArchive.java @@ -171,7 +171,6 @@ public class AArchive implements ActionListener else // all Reports av.query(true, m_AD_Table_ID, 0); // - AEnv.addToWindowManager(ff); ff.pack(); AEnv.showCenterScreen(ff); ff = null; diff --git a/client/src/org/compiere/apps/AEnv.java b/client/src/org/compiere/apps/AEnv.java index 793aca293b..4cc926ab3c 100644 --- a/client/src/org/compiere/apps/AEnv.java +++ b/client/src/org/compiere/apps/AEnv.java @@ -257,8 +257,7 @@ public final class AEnv if (iconName == null) iconName = actionName; String text = Msg.getMsg(Env.getCtx(), actionName); - ImageIcon icon = Env.getImageIcon2(iconName + "16"); - CMenuItem mi = new CMenuItem(text, icon); + CMenuItem mi = new CMenuItem(text, Env.getImageIcon(iconName + "16.gif")); mi.setActionCommand(actionName); if (ks != null) mi.setAccelerator(ks); @@ -298,11 +297,6 @@ public final class AEnv if (ADialog.ask(WindowNo, c, "ExitApplication?")) Env.exitEnv(0); } - else if (actionCommand.equals("Logout")) - { - AMenu aMenu = (AMenu)Env.getWindow(WindowNo); - aMenu.logout(); - } // View Menu ------------------------ else if (actionCommand.equals("InfoProduct")) @@ -379,9 +373,8 @@ public final class AEnv } else if (actionCommand.equals("Preference")) { - if (role.isShowPreference()) { + if (role.isShowPreference()) AEnv.showCenterScreen(new Preference (Env.getFrame(c), WindowNo)); - } } // Help Menu ------------------------ @@ -485,7 +478,6 @@ public final class AEnv AWindow frame = new AWindow(); if (!frame.initWindow(AD_Window_ID, MQuery.getEqualQuery(TableName + "_ID", Record_ID))) return; - addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; } // zoom @@ -536,23 +528,11 @@ public final class AEnv AWindow frame = new AWindow(); if (!frame.initWindow(AD_Window_ID, query)) return; - addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; } // zoom - /** - * Track open frame in window manager - * @param frame - */ - public static void addToWindowManager(CFrame frame) - { - JFrame top = Env.getWindow(0); - if (top instanceof AMenu) - { - ((AMenu)top).getWindowManager().add(frame); - } - } + /** * Exit System * @param status System exit status (usually 0 for no error) @@ -572,26 +552,6 @@ public final class AEnv Env.exitEnv(status); } // exit - public static void logout() - { - if (s_server != null) - { - try - { - s_server.remove(); - } - catch (Exception ex) - { - } - } - Env.logout(); - - Splash.getSplash().setVisible(true); - - //reload - new AMenu(); - } - /** * Is Workflow Process view enabled. * @return true if enabled @@ -648,14 +608,7 @@ public final class AEnv 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); + AEnv.showCenterScreen(frame); frame = null; } // startWorkflowProcess @@ -908,33 +861,5 @@ public final class AEnv } } } // cacheReset - - /** - * Update all windows after look and feel changes. - * @since 2006-11-27 - */ - public static void updateUI() - { - Set updated = Env.updateUI(); - JFrame top = Env.getWindow(0); - if (top instanceof AMenu) - { - CFrame[] frames = ((AMenu)top).getWindowManager().getWindows(); - for (CFrame f : frames) - { - if (updated.contains(f)) continue; - SwingUtilities.updateComponentTreeUI(f); - f.validate(); - RepaintManager mgr = RepaintManager.currentManager(f); - Component childs[] = f.getComponents(); - for (Component c : childs) { - if (c instanceof JComponent) - mgr.markCompletelyDirty((JComponent)c); - } - f.repaint(); - updated.add(f); - } - } - } -} // AEnv \ No newline at end of file +} // AEnv diff --git a/client/src/org/compiere/apps/ALogin.java b/client/src/org/compiere/apps/ALogin.java index d98cefb331..557bf5b9fa 100644 --- a/client/src/org/compiere/apps/ALogin.java +++ b/client/src/org/compiere/apps/ALogin.java @@ -3,22 +3,22 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; -import java.sql.*; + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import java.sql.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; @@ -27,41 +27,41 @@ import org.adempiere.plaf.AdempierePLAF; import org.compiere.*; import org.compiere.db.*; import org.compiere.grid.ed.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.print.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Application Login Window - * - * @author Jorg Janke - * @version $Id: ALogin.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public final class ALogin extends CDialog - implements ActionListener, ChangeListener -{ - /** - * Construct the dialog. - * Need to call initLogin for dynamic start - * @param parent parent - */ - public ALogin (Frame parent) - { - super (parent, "Login", true); // Modal - log.finer(""); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - m_WindowNo = Env.createWindowNo (null); - res = ResourceBundle.getBundle(RESOURCE); - // - try - { - jbInit(); - } - catch(Exception e) - { - log.severe(e.toString()); +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.print.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Application Login Window + * + * @author Jorg Janke + * @version $Id: ALogin.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public final class ALogin extends CDialog + implements ActionListener, ChangeListener +{ + /** + * Construct the dialog. + * Need to call initLogin for dynamic start + * @param parent parent + */ + public ALogin (Frame parent) + { + super (parent, "Login", true); // Modal + log.finer(""); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + m_WindowNo = Env.createWindowNo (null); + res = ResourceBundle.getBundle(RESOURCE); + // + try + { + jbInit(); + } + catch(Exception e) + { + log.severe(e.toString()); } // Focus to OK this.getRootPane().setDefaultButton(confirmPanel.getOKButton()); @@ -69,81 +69,81 @@ public final class ALogin extends CDialog } // ALogin - protected static final String RESOURCE = "org.compiere.apps.ALoginRes"; - private static ResourceBundle res = ResourceBundle.getBundle(RESOURCE); - /** Logger */ - private static CLogger log = CLogger.getCLogger(ALogin.class); - - private CPanel mainPanel = new CPanel(new BorderLayout()); - private CTabbedPane loginTabPane = new CTabbedPane(); -// private BorderLayout conTabLayout = new BorderLayout(); - private CPanel connectionPanel = new CPanel(); - private CLabel hostLabel = new CLabel(); - private CConnectionEditor hostField = new CConnectionEditor(); - private CLabel userLabel = new CLabel(); - private CTextField userTextField = new CTextField(); - private CLabel passwordLabel = new CLabel(); - private JPasswordField passwordField = new JPasswordField(); - private CPanel defaultPanel = new CPanel(); -// private BorderLayout defaultLayout = new BorderLayout(); - private CLabel clientLabel = new CLabel(); - private CLabel orgLabel = new CLabel(); - private CLabel dateLabel = new CLabel(); - private VDate dateField = new VDate(DisplayType.Date); - private VComboBox orgCombo = new VComboBox(); - private VComboBox clientCombo = new VComboBox(); - private CLabel warehouseLabel = new CLabel(); - private VComboBox warehouseCombo = new VComboBox(); - private CLabel printerLabel = new CLabel(); - private CPrinter printerField = new CPrinter(); - private CLabel roleLabel = new CLabel(); - private VComboBox roleCombo = new VComboBox(); - private CLabel copy0Label = new CLabel(); - private CLabel titleLabel = new CLabel(); - private CLabel versionLabel = new CLabel(); - private CLabel copy1Label = new CLabel(); - private GridBagLayout connectionLayout = new GridBagLayout(); - private GridBagLayout defaultPanelLayout = new GridBagLayout(); - private CLabel languageLabel = new CLabel(); - private VComboBox languageCombo = new VComboBox(Language.getNames()); - private CLabel compileDate = new CLabel(); - private CPanel southPanel = new CPanel(); - private BorderLayout southLayout = new BorderLayout(); - private StatusBar statusBar = new StatusBar(); - private ConfirmPanel confirmPanel = new ConfirmPanel(true, false, false, false, false, false, false); - private OnlineHelp onlineHelp = new OnlineHelp(true); - private CPanel helpPanel = new CPanel(); - private JScrollPane helpScollPane = new JScrollPane(); - private BorderLayout helpLayout = new BorderLayout(); - - /** Server Connection */ - private CConnection m_cc; - /** Application User */ - private String m_user; - /** Application Password */ - private String m_pwd; - - /** Combo Active */ - private boolean m_comboActive = false; - /** Combo Active */ - private boolean m_okPressed = false; - /** Connection OK */ - private boolean m_connectionOK = false; - /** Window No */ - private int m_WindowNo; - /** Context */ - private Properties m_ctx = Env.getCtx(); - - private Login m_login = null; - - - /************************************************************************** - * Component initialization - * @throws Exception - */ - private void jbInit() throws Exception - { - this.setName("Login"); + protected static final String RESOURCE = "org.compiere.apps.ALoginRes"; + private static ResourceBundle res = ResourceBundle.getBundle(RESOURCE); + /** Logger */ + private static CLogger log = CLogger.getCLogger(ALogin.class); + + private CPanel mainPanel = new CPanel(new BorderLayout()); + private CTabbedPane loginTabPane = new CTabbedPane(); +// private BorderLayout conTabLayout = new BorderLayout(); + private CPanel connectionPanel = new CPanel(); + private CLabel hostLabel = new CLabel(); + private CConnectionEditor hostField = new CConnectionEditor(); + private CLabel userLabel = new CLabel(); + private CTextField userTextField = new CTextField(); + private CLabel passwordLabel = new CLabel(); + private JPasswordField passwordField = new JPasswordField(); + private CPanel defaultPanel = new CPanel(); +// private BorderLayout defaultLayout = new BorderLayout(); + private CLabel clientLabel = new CLabel(); + private CLabel orgLabel = new CLabel(); + private CLabel dateLabel = new CLabel(); + private VDate dateField = new VDate(DisplayType.Date); + private VComboBox orgCombo = new VComboBox(); + private VComboBox clientCombo = new VComboBox(); + private CLabel warehouseLabel = new CLabel(); + private VComboBox warehouseCombo = new VComboBox(); + private CLabel printerLabel = new CLabel(); + private CPrinter printerField = new CPrinter(); + private CLabel roleLabel = new CLabel(); + private VComboBox roleCombo = new VComboBox(); + private CLabel copy0Label = new CLabel(); + private CLabel titleLabel = new CLabel(); + private CLabel versionLabel = new CLabel(); + private CLabel copy1Label = new CLabel(); + private GridBagLayout connectionLayout = new GridBagLayout(); + private GridBagLayout defaultPanelLayout = new GridBagLayout(); + private CLabel languageLabel = new CLabel(); + private VComboBox languageCombo = new VComboBox(Language.getNames()); + private CLabel compileDate = new CLabel(); + private CPanel southPanel = new CPanel(); + private BorderLayout southLayout = new BorderLayout(); + private StatusBar statusBar = new StatusBar(); + private ConfirmPanel confirmPanel = new ConfirmPanel(true, false, false, false, false, false, false); + private OnlineHelp onlineHelp = new OnlineHelp(true); + private CPanel helpPanel = new CPanel(); + private JScrollPane helpScollPane = new JScrollPane(); + private BorderLayout helpLayout = new BorderLayout(); + + /** Server Connection */ + private CConnection m_cc; + /** Application User */ + private String m_user; + /** Application Password */ + private String m_pwd; + + /** Combo Active */ + private boolean m_comboActive = false; + /** Combo Active */ + private boolean m_okPressed = false; + /** Connection OK */ + private boolean m_connectionOK = false; + /** Window No */ + private int m_WindowNo; + /** Context */ + private Properties m_ctx = Env.getCtx(); + + private Login m_login = null; + + + /************************************************************************** + * Component initialization + * @throws Exception + */ + private void jbInit() throws Exception + { + this.setName("Login"); titleLabel.setFont(new java.awt.Font("Serif", 2, 10)); titleLabel.setForeground(Color.blue); titleLabel.setRequestFocusEnabled(false); @@ -155,25 +155,25 @@ public final class ALogin extends CDialog titleLabel.setVerticalTextPosition(SwingConstants.BOTTOM); versionLabel.setRequestFocusEnabled(false); versionLabel.setHorizontalAlignment(SwingConstants.RIGHT); - versionLabel.setHorizontalTextPosition(SwingConstants.RIGHT); - hostLabel.setRequestFocusEnabled(false); - hostLabel.setLabelFor(hostField); - hostField.addActionListener(this); - userLabel.setRequestFocusEnabled(false); - userLabel.setLabelFor(userTextField); - passwordLabel.setRequestFocusEnabled(false); - passwordLabel.setLabelFor(passwordField); - languageLabel.setLabelFor(languageCombo); - copy0Label.setFont(new java.awt.Font("Serif", 2, 10)); - copy0Label.setForeground(Color.blue); - copy0Label.setRequestFocusEnabled(false); - copy1Label.setRequestFocusEnabled(false); - roleLabel.setRequestFocusEnabled(false); - roleLabel.setLabelFor(roleCombo); - clientLabel.setRequestFocusEnabled(false); - orgLabel.setRequestFocusEnabled(false); - dateLabel.setRequestFocusEnabled(false); - warehouseLabel.setRequestFocusEnabled(false); + versionLabel.setHorizontalTextPosition(SwingConstants.RIGHT); + hostLabel.setRequestFocusEnabled(false); + hostLabel.setLabelFor(hostField); + hostField.addActionListener(this); + userLabel.setRequestFocusEnabled(false); + userLabel.setLabelFor(userTextField); + passwordLabel.setRequestFocusEnabled(false); + passwordLabel.setLabelFor(passwordField); + languageLabel.setLabelFor(languageCombo); + copy0Label.setFont(new java.awt.Font("Serif", 2, 10)); + copy0Label.setForeground(Color.blue); + copy0Label.setRequestFocusEnabled(false); + copy1Label.setRequestFocusEnabled(false); + roleLabel.setRequestFocusEnabled(false); + roleLabel.setLabelFor(roleCombo); + clientLabel.setRequestFocusEnabled(false); + orgLabel.setRequestFocusEnabled(false); + dateLabel.setRequestFocusEnabled(false); + warehouseLabel.setRequestFocusEnabled(false); printerLabel.setRequestFocusEnabled(false); compileDate.setHorizontalAlignment(SwingConstants.RIGHT); compileDate.setHorizontalTextPosition(SwingConstants.RIGHT); @@ -182,7 +182,7 @@ public final class ALogin extends CDialog southPanel.setLayout(southLayout); loginTabPane.addChangeListener(this); - // ConnectionTab + // ConnectionTab connectionPanel.setLayout(connectionLayout); // titleLabel.setHorizontalAlignment(SwingConstants.CENTER); @@ -191,30 +191,30 @@ public final class ALogin extends CDialog hostLabel.setHorizontalAlignment(SwingConstants.RIGHT); hostLabel.setText("Host"); connectionPanel.add(hostLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - connectionPanel.add(hostField, new GridBagConstraints(1, 2, 3, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - userLabel.setHorizontalAlignment(SwingConstants.RIGHT); - userLabel.setText("User"); - connectionPanel.add(userLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - userTextField.setText("System"); // default - connectionPanel.add(userTextField, new GridBagConstraints(1, 3, 3, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - passwordLabel.setHorizontalAlignment(SwingConstants.RIGHT); - passwordLabel.setText("Password"); - connectionPanel.add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - passwordField.setText("System"); // default - connectionPanel.add(passwordField, new GridBagConstraints(1, 4, 3, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - languageLabel.setHorizontalAlignment(SwingConstants.RIGHT); - languageLabel.setText("Language"); - connectionPanel.add(languageLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - languageCombo.addActionListener(this); - connectionPanel.add(languageCombo, new GridBagConstraints(1, 5, 3, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + connectionPanel.add(hostField, new GridBagConstraints(1, 2, 3, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + userLabel.setHorizontalAlignment(SwingConstants.RIGHT); + userLabel.setText("User"); + connectionPanel.add(userLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + userTextField.setText("System"); // default + connectionPanel.add(userTextField, new GridBagConstraints(1, 3, 3, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + passwordLabel.setHorizontalAlignment(SwingConstants.RIGHT); + passwordLabel.setText("Password"); + connectionPanel.add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + passwordField.setText("System"); // default + connectionPanel.add(passwordField, new GridBagConstraints(1, 4, 3, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + languageLabel.setHorizontalAlignment(SwingConstants.RIGHT); + languageLabel.setText("Language"); + connectionPanel.add(languageLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + languageCombo.addActionListener(this); + connectionPanel.add(languageCombo, new GridBagConstraints(1, 5, 3, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); copy0Label.setHorizontalAlignment(SwingConstants.RIGHT); connectionPanel.add(copy0Label, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); @@ -223,82 +223,82 @@ public final class ALogin extends CDialog connectionPanel.add(copy1Label, new GridBagConstraints(1, 6, 2, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 12, 12), 0, 0)); connectionPanel.add(compileDate, new GridBagConstraints(2, 1, 2, 1, 0.0, 0.0 - ,GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(2, 0, 0, 12), 0, 0)); - connectionPanel.add(titleLabel, new GridBagConstraints(0, 0, 2, 2, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); - connectionPanel.add(versionLabel, new GridBagConstraints(2, 0, 2, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 5, 0, 12), 0, 0)); - - loginTabPane.add(connectionPanel, res.getString("Connection")); - - // DefaultTab - defaultPanel.setLayout(defaultPanelLayout); - // - roleLabel.setText("Role"); - roleLabel.setHorizontalAlignment(SwingConstants.RIGHT); - roleCombo.addActionListener(this); - defaultPanel.add(roleLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); - defaultPanel.add(roleCombo, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 0, 5, 12), 0, 0)); - clientLabel.setText("Client"); - clientLabel.setHorizontalAlignment(SwingConstants.RIGHT); - defaultPanel.add(clientLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - clientCombo.addActionListener(this); - defaultPanel.add(clientCombo, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - orgLabel.setText("Organization"); - orgLabel.setHorizontalAlignment(SwingConstants.RIGHT); - defaultPanel.add(orgLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - orgCombo.addActionListener(this); - defaultPanel.add(orgCombo, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - dateLabel.setText("Date"); - dateLabel.setHorizontalAlignment(SwingConstants.RIGHT); - defaultPanel.add(dateLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - defaultPanel.add(dateField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - // - warehouseLabel.setText("Warehouse"); - warehouseLabel.setHorizontalAlignment(SwingConstants.RIGHT); - printerLabel.setText("Printer"); - printerLabel.setHorizontalAlignment(SwingConstants.RIGHT); - defaultPanel.add(printerLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 12, 5), 0, 0)); - defaultPanel.add(printerField, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 12, 12), 0, 0)); - defaultPanel.add(warehouseLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); - defaultPanel.add(warehouseCombo, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); - // - loginTabPane.add(defaultPanel, res.getString("Defaults")); - - // Help - helpPanel.setLayout(helpLayout); - helpPanel.setPreferredSize(new Dimension (100,100)); - helpPanel.add(helpScollPane, BorderLayout.CENTER); - loginTabPane.add(helpPanel, "?"); - // - this.getContentPane().add(mainPanel); - mainPanel.add(loginTabPane, BorderLayout.CENTER); - mainPanel.setName("loginMainPanel"); - mainPanel.add(southPanel, BorderLayout.SOUTH); - // - southPanel.add(confirmPanel, BorderLayout.NORTH); - southPanel.add(statusBar, BorderLayout.SOUTH); - helpScollPane.getViewport().add(onlineHelp, null); - confirmPanel.addActionListener(this); - statusBar.setStatusDB(null); - } // jbInit - - /** - * Set Initial & Ini Parameters - * Optional Automatic login - * @return true, if connected & parameters set + ,GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(2, 0, 0, 12), 0, 0)); + connectionPanel.add(titleLabel, new GridBagConstraints(0, 0, 2, 2, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); + connectionPanel.add(versionLabel, new GridBagConstraints(2, 0, 2, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 5, 0, 12), 0, 0)); + + loginTabPane.add(connectionPanel, res.getString("Connection")); + + // DefaultTab + defaultPanel.setLayout(defaultPanelLayout); + // + roleLabel.setText("Role"); + roleLabel.setHorizontalAlignment(SwingConstants.RIGHT); + roleCombo.addActionListener(this); + defaultPanel.add(roleLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); + defaultPanel.add(roleCombo, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 0, 5, 12), 0, 0)); + clientLabel.setText("Client"); + clientLabel.setHorizontalAlignment(SwingConstants.RIGHT); + defaultPanel.add(clientLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + clientCombo.addActionListener(this); + defaultPanel.add(clientCombo, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + orgLabel.setText("Organization"); + orgLabel.setHorizontalAlignment(SwingConstants.RIGHT); + defaultPanel.add(orgLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + orgCombo.addActionListener(this); + defaultPanel.add(orgCombo, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + dateLabel.setText("Date"); + dateLabel.setHorizontalAlignment(SwingConstants.RIGHT); + defaultPanel.add(dateLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + defaultPanel.add(dateField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + // + warehouseLabel.setText("Warehouse"); + warehouseLabel.setHorizontalAlignment(SwingConstants.RIGHT); + printerLabel.setText("Printer"); + printerLabel.setHorizontalAlignment(SwingConstants.RIGHT); + defaultPanel.add(printerLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 12, 5), 0, 0)); + defaultPanel.add(printerField, new GridBagConstraints(1, 5, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 12, 12), 0, 0)); + defaultPanel.add(warehouseLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 12, 5, 5), 0, 0)); + defaultPanel.add(warehouseCombo, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 0, 5, 12), 0, 0)); + // + loginTabPane.add(defaultPanel, res.getString("Defaults")); + + // Help + helpPanel.setLayout(helpLayout); + helpPanel.setPreferredSize(new Dimension (100,100)); + helpPanel.add(helpScollPane, BorderLayout.CENTER); + loginTabPane.add(helpPanel, "?"); + // + this.getContentPane().add(mainPanel); + mainPanel.add(loginTabPane, BorderLayout.CENTER); + mainPanel.setName("loginMainPanel"); + mainPanel.add(southPanel, BorderLayout.SOUTH); + // + southPanel.add(confirmPanel, BorderLayout.NORTH); + southPanel.add(statusBar, BorderLayout.SOUTH); + helpScollPane.getViewport().add(onlineHelp, null); + confirmPanel.addActionListener(this); + statusBar.setStatusDB(null); + } // jbInit + + /** + * Set Initial & Ini Parameters + * Optional Automatic login + * @return true, if connected & parameters set */ public boolean initLogin() { @@ -311,36 +311,36 @@ public final class ALogin extends CDialog // Application/PWD userTextField.setText(Ini.getProperty(Ini.P_UID)); - if (Ini.isPropertyBool(Ini.P_STORE_PWD)) - passwordField.setText(Ini.getProperty(Ini.P_PWD)); - else - passwordField.setText(""); - // - languageCombo.setSelectedItem(Ini.getProperty(Ini.P_LANGUAGE)); - - // AutoLogin - assumes that connection is OK - if (Ini.isPropertyBool(Ini.P_A_LOGIN)) - { - connectionOK (); - defaultsOK (); - if (m_connectionOK) // simulate - m_okPressed = true; - return m_connectionOK; - } - return false; - } // initLogin - - /** - * Window Events - requestFocus - * @param e event - */ - protected void processWindowEvent(WindowEvent e) - { - super.processWindowEvent(e); - if (e.getID() == WindowEvent.WINDOW_OPENED) - { - this.toFront(); - confirmPanel.getOKButton().requestFocusInWindow(); + if (Ini.isPropertyBool(Ini.P_STORE_PWD)) + passwordField.setText(Ini.getProperty(Ini.P_PWD)); + else + passwordField.setText(""); + // + languageCombo.setSelectedItem(Ini.getProperty(Ini.P_LANGUAGE)); + + // AutoLogin - assumes that connection is OK + if (Ini.isPropertyBool(Ini.P_A_LOGIN)) + { + connectionOK (); + defaultsOK (); + if (m_connectionOK) // simulate + m_okPressed = true; + return m_connectionOK; + } + return false; + } // initLogin + + /** + * Window Events - requestFocus + * @param e event + */ + protected void processWindowEvent(WindowEvent e) + { + super.processWindowEvent(e); + if (e.getID() == WindowEvent.WINDOW_OPENED) + { + this.toFront(); + confirmPanel.getOKButton().requestFocusInWindow(); } } // processWindowEvent @@ -366,189 +366,188 @@ public final class ALogin extends CDialog // hostField.setDisplay(); } // validateConnection - - - /************************************************************************* - * Exit action performed - */ - private void appExit() - { - m_connectionOK = false; - dispose(); - } // appExit_actionPerformed - - - /** - * Return true, if logged in - * @return true if connected - */ - public boolean isConnected() - { - return m_connectionOK; - } // isConnected - - /** - * Did the user press OK - * @return true if user pressed final OK button - */ - public boolean isOKpressed() - { - return m_okPressed; - } // isOKpressed - - /************************************************************************** - * Action Event handler - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - if (e.getActionCommand().equals(ConfirmPanel.A_OK)) - { - if (loginTabPane.getSelectedIndex() == 0) + + + /************************************************************************* + * Exit action performed + */ + private void appExit() + { + m_connectionOK = false; + dispose(); + } // appExit_actionPerformed + + + /** + * Return true, if logged in + * @return true if connected + */ + public boolean isConnected() + { + return m_connectionOK; + } // isConnected + + /** + * Did the user press OK + * @return true if user pressed final OK button + */ + public boolean isOKpressed() + { + return m_okPressed; + } // isOKpressed + + /************************************************************************** + * Action Event handler + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals(ConfirmPanel.A_OK)) + { + if (loginTabPane.getSelectedIndex() == 0) connectionOK(); // first ok else { - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); m_okPressed = true; defaultsOK(); // disposes } - } - else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) - appExit(); - // - else if (e.getSource() == hostField) - validateConnection(); - else if (e.getSource() == languageCombo) - languageComboChanged(); - // - else if (e.getSource() == roleCombo) - roleComboChanged(); - else if (e.getSource() == clientCombo) - clientComboChanged(); - else if (e.getSource() == orgCombo) - orgComboChanged(); - } // actionPerformed - - - /************************************************************************** - * Connection OK pressed - */ - private void connectionOK () - { - log.info(""); - // - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - confirmPanel.getOKButton().setEnabled(false); - - m_connectionOK = tryConnection(); - - if (m_connectionOK) - { - // Verify Language & Load Msg - Language l = Language.getLoginLanguage(); - Env.verifyLanguage (m_ctx, l); - Env.setContext(m_ctx, Env.LANGUAGE, l.getAD_Language()); - Msg.getMsg(m_ctx, "0"); - - // Migration - MSystem system = MSystem.get(m_ctx); - if (system.isJustMigrated()) - { - statusBar.setStatusLine("Running: After Migration ....", true); - ADialog.info (m_WindowNo, this, "AfterMigration"); - Thread.yield(); - DB.afterMigration(m_ctx); - } - // Set Defaults - printerField.setValue(Ini.getProperty(Ini.P_PRINTER)); - // Change Tab to Default - loginTabPane.setSelectedIndex(1); - } - - confirmPanel.getOKButton().setEnabled(true); - setCursor(Cursor.getDefaultCursor()); - } // connectionOK - - - /** - * Change of tab <-> - * @param e event - */ - public void stateChanged(ChangeEvent e) - { - if (loginTabPane.getSelectedIndex() == 2) // allow access to help - return; - - if (!(String.valueOf(passwordField.getPassword()).equals(m_pwd) - && userTextField.getText().equals(m_user))) - m_connectionOK = false; - // - if (m_connectionOK) - statusBar.setStatusLine(txt_LoggedIn); - else - { - statusBar.setStatusLine(txt_NotConnected, true); - loginTabPane.setSelectedIndex(0); - } - confirmPanel.getOKButton().requestFocus(); - } // loginTabPane - - - /************************************************************************** - * Defaults OK pressed - * @return true if ok - */ - private boolean defaultsOK () - { - log.info(""); - - KeyNamePair org = (KeyNamePair)orgCombo.getSelectedItem(); - if (org == null) - return false; - - // Set Properties - Ini.setProperty(Ini.P_CONNECTION, CConnection.get().toStringLong()); - Ini.setProperty(Ini.P_LANGUAGE, (String)languageCombo.getSelectedItem()); - - String error = m_login.validateLogin(org); - if (error != null && error.length() > 0) - { - ADialog.info(m_WindowNo, this, error); - appExit(); - return false; - } - - // Load Properties and save Ini values - statusBar.setStatusLine("Loading Preferences"); - String msg = m_login.loadPreferences (org, - (KeyNamePair)warehouseCombo.getSelectedItem(), - dateField.getTimestamp(), printerField.getDisplay()); - if (msg.length() > 0) - ADialog.info(m_WindowNo, this, msg); - - // Check Apps Server - DB Checked in Menu - checkVersion(); // exits if conflict - - // Close - we are done - if (m_connectionOK) - this.dispose(); - return m_connectionOK; - } // defaultsOK - - - /************************************************************************** - * Try to connect. - * - Get Connection - * - Compare User info - * @return true if connected - */ - private boolean tryConnection() - { - m_user = userTextField.getText(); + } + else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) + appExit(); + // + else if (e.getSource() == hostField) + validateConnection(); + else if (e.getSource() == languageCombo) + languageComboChanged(); + // + else if (e.getSource() == roleCombo) + roleComboChanged(); + else if (e.getSource() == clientCombo) + clientComboChanged(); + else if (e.getSource() == orgCombo) + orgComboChanged(); + } // actionPerformed + + + /************************************************************************** + * Connection OK pressed + */ + private void connectionOK () + { + log.info(""); + // + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + confirmPanel.getOKButton().setEnabled(false); + + m_connectionOK = tryConnection(); + + if (m_connectionOK) + { + // Verify Language & Load Msg + Language l = Language.getLoginLanguage(); + Env.verifyLanguage (m_ctx, l); + Env.setContext(m_ctx, Env.LANGUAGE, l.getAD_Language()); + Msg.getMsg(m_ctx, "0"); + + // Migration + MSystem system = MSystem.get(m_ctx); + if (system.isJustMigrated()) + { + statusBar.setStatusLine("Running: After Migration ....", true); + ADialog.info (m_WindowNo, this, "AfterMigration"); + Thread.yield(); + DB.afterMigration(m_ctx); + } + // Set Defaults + printerField.setValue(Ini.getProperty(Ini.P_PRINTER)); + // Change Tab to Default + loginTabPane.setSelectedIndex(1); + } + + confirmPanel.getOKButton().setEnabled(true); + setCursor(Cursor.getDefaultCursor()); + } // connectionOK + + + /** + * Change of tab <-> + * @param e event + */ + public void stateChanged(ChangeEvent e) + { + if (loginTabPane.getSelectedIndex() == 2) // allow access to help + return; + + if (!(String.valueOf(passwordField.getPassword()).equals(m_pwd) + && userTextField.getText().equals(m_user))) + m_connectionOK = false; + // + if (m_connectionOK) + statusBar.setStatusLine(txt_LoggedIn); + else + { + statusBar.setStatusLine(txt_NotConnected, true); + loginTabPane.setSelectedIndex(0); + } + confirmPanel.getOKButton().requestFocus(); + } // loginTabPane + + + /************************************************************************** + * Defaults OK pressed + * @return true if ok + */ + private boolean defaultsOK () + { + log.info(""); + + KeyNamePair org = (KeyNamePair)orgCombo.getSelectedItem(); + if (org == null) + return false; + + // Set Properties + Ini.setProperty(Ini.P_CONNECTION, CConnection.get().toStringLong()); + Ini.setProperty(Ini.P_LANGUAGE, (String)languageCombo.getSelectedItem()); + + String error = m_login.validateLogin(org); + if (error != null && error.length() > 0) + { + ADialog.info(m_WindowNo, this, error); + appExit(); + return false; + } + + // Load Properties and save Ini values + statusBar.setStatusLine("Loading Preferences"); + String msg = m_login.loadPreferences (org, + (KeyNamePair)warehouseCombo.getSelectedItem(), + dateField.getTimestamp(), printerField.getDisplay()); + if (msg.length() > 0) + ADialog.info(m_WindowNo, this, msg); + + // Check Apps Server - DB Checked in Menu + checkVersion(); // exits if conflict + + // Close - we are done + if (m_connectionOK) + this.dispose(); + return m_connectionOK; + } // defaultsOK + + + /************************************************************************** + * Try to connect. + * - Get Connection + * - Compare User info + * @return true if connected + */ + private boolean tryConnection() + { + m_user = userTextField.getText(); m_pwd = new String (passwordField.getPassword()); // Establish connection - connectToDatabase(); + DB.setDBTarget(CConnection.get()); if (!DB.isConnected()) { statusBar.setStatusLine(txt_NoDatabase, true); @@ -561,7 +560,7 @@ public final class ALogin extends CDialog // Get Roles m_login = new Login(m_ctx); - KeyNamePair[] roles = m_login.getRoles(m_user, m_pwd); + KeyNamePair[] roles = m_login.getRoles(m_user, m_pwd); if (roles == null || roles.length == 0) { statusBar.setStatusLine(txt_UserPwdError, true); @@ -570,22 +569,22 @@ public final class ALogin extends CDialog return false; } - // Delete existing role items - m_comboActive = true; - if (roleCombo.getItemCount() > 0) - roleCombo.removeAllItems(); - - // Initial role - KeyNamePair iniValue = null; - String iniDefault = Ini.getProperty(Ini.P_ROLE); - - // fill roles - for (int i = 0; i < roles.length; i++) - { - roleCombo.addItem(roles[i]); - if (roles[i].getName().equals(iniDefault)) - iniValue = roles[i]; - } + // Delete existing role items + m_comboActive = true; + if (roleCombo.getItemCount() > 0) + roleCombo.removeAllItems(); + + // Initial role + KeyNamePair iniValue = null; + String iniDefault = Ini.getProperty(Ini.P_ROLE); + + // fill roles + for (int i = 0; i < roles.length; i++) + { + roleCombo.addItem(roles[i]); + if (roles[i].getName().equals(iniDefault)) + iniValue = roles[i]; + } if (iniValue != null) roleCombo.setSelectedItem(iniValue); @@ -594,150 +593,150 @@ public final class ALogin extends CDialog // statusBar.setStatusLine(txt_LoggedIn); m_comboActive = false; - roleComboChanged(); - return true; - } // tryConnection - - - /** - * Role changed - fill Client List - */ - private void roleComboChanged () - { - KeyNamePair role = (KeyNamePair)roleCombo.getSelectedItem(); - if (role == null || m_comboActive) - return; - log.config(": " + role); - m_comboActive = true; - // - KeyNamePair[] clients = m_login.getClients(role); - // delete existing client/org items - if (clientCombo.getItemCount() > 0) - clientCombo.removeAllItems(); - if (orgCombo.getItemCount() > 0) - orgCombo.removeAllItems(); - // No Clients - if (clients == null || clients.length == 0) - { - statusBar.setStatusLine(txt_RoleError, true); - m_comboActive = false; - return; - } - // initial client - KeyNamePair iniValue = null; - String iniDefault = Ini.getProperty(Ini.P_CLIENT); - - // fill clients - for (int i = 0; i < clients.length; i++) - { - clientCombo.addItem(clients[i]); - if (clients[i].getName().equals(iniDefault)) - iniValue = clients[i]; - } - // fini - if (iniValue != null) - clientCombo.setSelectedItem(iniValue); - // - m_comboActive = false; - clientComboChanged(); - } // roleComboChanged - - - /** - * Client changed - fill Org & Warehouse List - */ - private void clientComboChanged() - { - KeyNamePair client = (KeyNamePair)clientCombo.getSelectedItem(); - if (client == null || m_comboActive) - return; - log.config(": " + client); - m_comboActive = true; - // - KeyNamePair[] orgs = m_login.getOrgs(client); - // delete existing cleint items - if (orgCombo.getItemCount() > 0) - orgCombo.removeAllItems(); - - // No Orgs - if (orgs == null || orgs.length == 0) - { - statusBar.setStatusLine(txt_RoleError, true); - m_comboActive = false; - return; - } - // initial client - KeyNamePair orgValue = null; - KeyNamePair orgValue2 = null; - String iniDefault = Ini.getProperty(Ini.P_ORG); - - // fill orgs - for (int i = 0; i < orgs.length; i++) - { - orgCombo.addItem(orgs[i]); - if (orgs[i].getName().equals(iniDefault)) - orgValue = orgs[i]; - if (orgValue2 == null && orgs[i].getKey() != 0) - orgValue2 = orgs[i]; // first non-0 org - } - // Non-0 Org exists and last login was with 0 - if (orgValue2 != null && orgValue != null && orgValue.getKey() == 0) - orgValue = orgValue2; - // Last Org - if (orgValue != null) - orgCombo.setSelectedItem(orgValue); - // Get first Org - else - orgValue = (KeyNamePair)orgCombo.getSelectedItem(); - // - m_comboActive = false; - orgComboChanged(); - } // clientComboChanged - - /** - * Org changed - fill Warehouse List - */ - private void orgComboChanged() - { - KeyNamePair org = (KeyNamePair)orgCombo.getSelectedItem(); - if (org == null || m_comboActive) - return; - log.config(": " + org); - m_comboActive = true; - // - KeyNamePair[] whs = m_login.getWarehouses(org); - // Delete existing warehouse items - if (warehouseCombo.getItemCount() > 0) - warehouseCombo.removeAllItems(); - - // fill warehouses - if (whs != null) - { - // initial warehouse - KeyNamePair iniValue = null; - String iniDefault = Ini.getProperty(Ini.P_WAREHOUSE); - for (int i = 0; i < whs.length; i++) - { - warehouseCombo.addItem(whs[i]); - if (whs[i].getName().equals(iniDefault)) - iniValue = whs[i]; - } - if (iniValue != null) - warehouseCombo.setSelectedItem(iniValue); - } - m_comboActive = false; - } // orgComboChanged - - - /** - * Check Version - * @return true if version is OK and - * false if version could not be checked or is not the same - * @see AEnv#getServerVersion - */ - private boolean checkVersion() - { - boolean retValue = false; + roleComboChanged(); + return true; + } // tryConnection + + + /** + * Role changed - fill Client List + */ + private void roleComboChanged () + { + KeyNamePair role = (KeyNamePair)roleCombo.getSelectedItem(); + if (role == null || m_comboActive) + return; + log.config(": " + role); + m_comboActive = true; + // + KeyNamePair[] clients = m_login.getClients(role); + // delete existing client/org items + if (clientCombo.getItemCount() > 0) + clientCombo.removeAllItems(); + if (orgCombo.getItemCount() > 0) + orgCombo.removeAllItems(); + // No Clients + if (clients == null || clients.length == 0) + { + statusBar.setStatusLine(txt_RoleError, true); + m_comboActive = false; + return; + } + // initial client + KeyNamePair iniValue = null; + String iniDefault = Ini.getProperty(Ini.P_CLIENT); + + // fill clients + for (int i = 0; i < clients.length; i++) + { + clientCombo.addItem(clients[i]); + if (clients[i].getName().equals(iniDefault)) + iniValue = clients[i]; + } + // fini + if (iniValue != null) + clientCombo.setSelectedItem(iniValue); + // + m_comboActive = false; + clientComboChanged(); + } // roleComboChanged + + + /** + * Client changed - fill Org & Warehouse List + */ + private void clientComboChanged() + { + KeyNamePair client = (KeyNamePair)clientCombo.getSelectedItem(); + if (client == null || m_comboActive) + return; + log.config(": " + client); + m_comboActive = true; + // + KeyNamePair[] orgs = m_login.getOrgs(client); + // delete existing cleint items + if (orgCombo.getItemCount() > 0) + orgCombo.removeAllItems(); + + // No Orgs + if (orgs == null || orgs.length == 0) + { + statusBar.setStatusLine(txt_RoleError, true); + m_comboActive = false; + return; + } + // initial client + KeyNamePair orgValue = null; + KeyNamePair orgValue2 = null; + String iniDefault = Ini.getProperty(Ini.P_ORG); + + // fill orgs + for (int i = 0; i < orgs.length; i++) + { + orgCombo.addItem(orgs[i]); + if (orgs[i].getName().equals(iniDefault)) + orgValue = orgs[i]; + if (orgValue2 == null && orgs[i].getKey() != 0) + orgValue2 = orgs[i]; // first non-0 org + } + // Non-0 Org exists and last login was with 0 + if (orgValue2 != null && orgValue != null && orgValue.getKey() == 0) + orgValue = orgValue2; + // Last Org + if (orgValue != null) + orgCombo.setSelectedItem(orgValue); + // Get first Org + else + orgValue = (KeyNamePair)orgCombo.getSelectedItem(); + // + m_comboActive = false; + orgComboChanged(); + } // clientComboChanged + + /** + * Org changed - fill Warehouse List + */ + private void orgComboChanged() + { + KeyNamePair org = (KeyNamePair)orgCombo.getSelectedItem(); + if (org == null || m_comboActive) + return; + log.config(": " + org); + m_comboActive = true; + // + KeyNamePair[] whs = m_login.getWarehouses(org); + // Delete existing warehouse items + if (warehouseCombo.getItemCount() > 0) + warehouseCombo.removeAllItems(); + + // fill warehouses + if (whs != null) + { + // initial warehouse + KeyNamePair iniValue = null; + String iniDefault = Ini.getProperty(Ini.P_WAREHOUSE); + for (int i = 0; i < whs.length; i++) + { + warehouseCombo.addItem(whs[i]); + if (whs[i].getName().equals(iniDefault)) + iniValue = whs[i]; + } + if (iniValue != null) + warehouseCombo.setSelectedItem(iniValue); + } + m_comboActive = false; + } // orgComboChanged + + + /** + * Check Version + * @return true if version is OK and + * false if version could not be checked or is not the same + * @see AEnv#getServerVersion + */ + private boolean checkVersion() + { + boolean retValue = false; try { String version = AEnv.getServerVersion(); @@ -745,10 +744,10 @@ public final class ALogin extends CDialog { log.config("Server = Client - " + version); retValue = true; - } - else if (version != null) - { - StringBuffer msg = new StringBuffer (">>\n"); + } + else if (version != null) + { + StringBuffer msg = new StringBuffer (">>\n"); msg.append(res.getString("VersionConflict")).append("\n") .append(res.getString("VersionInfo")).append("\n"); msg.append(version == null ? "null" : version).append(" <> ") @@ -759,78 +758,78 @@ public final class ALogin extends CDialog JOptionPane.ERROR_MESSAGE); AEnv.exit(1); } - } - catch (Exception e) - { - log.severe("Contact Server failed - " - + e.getClass().toString() + ": " + e.getMessage()); - } - return retValue; - } // checkVersion - - - /************************************************************************** - * Language issues - */ - private String // txt_Connected, - txt_NotConnected, txt_NoDatabase, - txt_UserPwdError, txt_RoleError, txt_LoggedIn; - - /** - * Change Language - */ - private void languageComboChanged () - { - String langName = (String)languageCombo.getSelectedItem(); - // log.info( "Language: " + langName); - Language language = Language.getLanguage(langName); - Language.setLoginLanguage(language); - Env.setContext(m_ctx, Env.LANGUAGE, language.getAD_Language()); - - // Locales - Locale loc = language.getLocale(); - Locale.setDefault(loc); - this.setLocale(loc); - res = ResourceBundle.getBundle(RESOURCE, loc); - // - this.setTitle(res.getString("Login")); - hostLabel.setText(res.getString("Host")); - userLabel.setText(res.getString("User")); - userLabel.setToolTipText(res.getString("EnterUser")); - passwordLabel.setText(res.getString("Password")); - passwordLabel.setToolTipText(res.getString("EnterPassword")); - languageLabel.setText(res.getString("Language")); - languageLabel.setToolTipText(res.getString("SelectLanguage")); - // - roleLabel.setText(res.getString("Role")); - clientLabel.setText(res.getString("Client")); - orgLabel.setText(res.getString("Organization")); - dateLabel.setText(res.getString("Date")); - warehouseLabel.setText(res.getString("Warehouse")); - printerLabel.setText(res.getString("Printer")); - defaultPanel.setToolTipText(res.getString("Defaults")); - connectionPanel.setToolTipText(res.getString("Connection")); - // - // txt_Connected = res.getString("Connected"); - txt_NotConnected = res.getString("NotConnected"); - txt_NoDatabase = res.getString("DatabaseNotFound"); - txt_UserPwdError = res.getString("UserPwdError"); - txt_RoleError = res.getString("RoleNotFound"); - txt_LoggedIn = res.getString("Authorized"); - // - loginTabPane.setTitleAt(0, res.getString("Connection")); - loginTabPane.setTitleAt(1, res.getString("Defaults")); - confirmPanel.getOKButton().setToolTipText(res.getString("Ok")); - confirmPanel.getCancelButton().setToolTipText(res.getString("Cancel")); - - // DateField with new format - dateField.setFormat(); - dateField.setValue(new Timestamp(System.currentTimeMillis())); - // - if (m_connectionOK) - statusBar.setStatusLine(txt_LoggedIn); - else - statusBar.setStatusLine(txt_NotConnected, true); - } // languageCombo_actionPerformed - -} // ALogin + } + catch (Exception e) + { + log.severe("Contact Server failed - " + + e.getClass().toString() + ": " + e.getMessage()); + } + return retValue; + } // checkVersion + + + /************************************************************************** + * Language issues + */ + private String // txt_Connected, + txt_NotConnected, txt_NoDatabase, + txt_UserPwdError, txt_RoleError, txt_LoggedIn; + + /** + * Change Language + */ + private void languageComboChanged () + { + String langName = (String)languageCombo.getSelectedItem(); + // log.info( "Language: " + langName); + Language language = Language.getLanguage(langName); + Language.setLoginLanguage(language); + Env.setContext(m_ctx, Env.LANGUAGE, language.getAD_Language()); + + // Locales + Locale loc = language.getLocale(); + Locale.setDefault(loc); + this.setLocale(loc); + res = ResourceBundle.getBundle(RESOURCE, loc); + // + this.setTitle(res.getString("Login")); + hostLabel.setText(res.getString("Host")); + userLabel.setText(res.getString("User")); + userLabel.setToolTipText(res.getString("EnterUser")); + passwordLabel.setText(res.getString("Password")); + passwordLabel.setToolTipText(res.getString("EnterPassword")); + languageLabel.setText(res.getString("Language")); + languageLabel.setToolTipText(res.getString("SelectLanguage")); + // + roleLabel.setText(res.getString("Role")); + clientLabel.setText(res.getString("Client")); + orgLabel.setText(res.getString("Organization")); + dateLabel.setText(res.getString("Date")); + warehouseLabel.setText(res.getString("Warehouse")); + printerLabel.setText(res.getString("Printer")); + defaultPanel.setToolTipText(res.getString("Defaults")); + connectionPanel.setToolTipText(res.getString("Connection")); + // + // txt_Connected = res.getString("Connected"); + txt_NotConnected = res.getString("NotConnected"); + txt_NoDatabase = res.getString("DatabaseNotFound"); + txt_UserPwdError = res.getString("UserPwdError"); + txt_RoleError = res.getString("RoleNotFound"); + txt_LoggedIn = res.getString("Authorized"); + // + loginTabPane.setTitleAt(0, res.getString("Connection")); + loginTabPane.setTitleAt(1, res.getString("Defaults")); + confirmPanel.getOKButton().setToolTipText(res.getString("Ok")); + confirmPanel.getCancelButton().setToolTipText(res.getString("Cancel")); + + // DateField with new format + dateField.setFormat(); + dateField.setValue(new Timestamp(System.currentTimeMillis())); + // + if (m_connectionOK) + statusBar.setStatusLine(txt_LoggedIn); + else + statusBar.setStatusLine(txt_NotConnected, true); + } // languageCombo_actionPerformed + +} // ALogin diff --git a/client/src/org/compiere/apps/AMenu.java b/client/src/org/compiere/apps/AMenu.java index a3b4a82929..aebb913df0 100644 --- a/client/src/org/compiere/apps/AMenu.java +++ b/client/src/org/compiere/apps/AMenu.java @@ -3,50 +3,51 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; -import java.beans.*; -import java.math.*; -import java.sql.*; -import java.text.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; -import javax.swing.event.*; -// -import org.compiere.*; -import org.compiere.apps.wf.*; -import org.compiere.apps.graph.*; -import org.compiere.db.*; -import org.compiere.grid.tree.*; + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import java.beans.*; +import java.math.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; +import javax.swing.event.*; +// +import org.compiere.*; +import org.compiere.apps.wf.*; +import org.compiere.apps.graph.*; +import org.compiere.db.*; +import org.compiere.grid.tree.*; import org.compiere.model.*; import org.compiere.swing.*; import org.compiere.util.*; + /** * Application Menu Controller * - * @author Jorg Janke - * @version $Id: AMenu.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public final class AMenu extends CFrame - implements ActionListener, PropertyChangeListener, ChangeListener -{ - /** - * Application Start and Menu - */ + * @author Jorg Janke + * @version $Id: AMenu.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public final class AMenu extends CFrame + implements ActionListener, PropertyChangeListener, ChangeListener +{ + /** + * Application Start and Menu + */ public AMenu () { super(); @@ -57,56 +58,53 @@ public final class AMenu extends CFrame // Login initSystem (splash); // login splash.setText(Msg.getMsg(m_ctx, "Loading")); - splash.toFront(); - splash.paint(splash.getGraphics()); - // Adempiere.startupEnvironment(true); // Load Environment MSession.get (Env.getCtx(), true); // Start Session // Preparation - setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - wfActivity = new WFActivity(this); - wfPanel = new WFPanel(this); - treePanel = new VTreePanel (m_WindowNo, true, false); // !editable & hasBar - - try - { - jbInit(); - createMenu(); - } - catch(Exception ex) - { - log.log(Level.SEVERE, "AMenu", ex); - } - - // initialize & load tree - int AD_Role_ID = Env.getAD_Role_ID(Env.getCtx()); - int AD_Tree_ID = DB.getSQLValue(null, - "SELECT COALESCE(r.AD_Tree_Menu_ID, ci.AD_Tree_Menu_ID)" - + "FROM AD_ClientInfo ci" - + " INNER JOIN AD_Role r ON (ci.AD_Client_ID=r.AD_Client_ID) " - + "WHERE AD_Role_ID=?", AD_Role_ID); - if (AD_Tree_ID <= 0) - AD_Tree_ID = 10; // Menu - treePanel.initTree(AD_Tree_ID); - - // Translate - Env.setContext(m_ctx, m_WindowNo, "WindowName", Msg.getMsg(m_ctx, "Menu")); - setTitle(Env.getHeader(m_ctx, m_WindowNo)); - - progressBar.setString(Msg.getMsg(m_ctx, "SelectProgram")); - - // Finish UI - Point loc = Ini.getWindowLocation(0); - if (loc == null) - loc = new Point(0,0); - this.setLocation(loc); - this.pack(); - this.setVisible(true); - this.setState(Frame.NORMAL); - m_AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); - m_AD_Role_ID = Env.getContextAsInt(m_ctx, "#AD_Role_ID"); + setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + wfActivity = new WFActivity(this); + wfPanel = new WFPanel(this); + treePanel = new VTreePanel (m_WindowNo, true, false); // !editable & hasBar + + try + { + jbInit(); + createMenu(); + } + catch(Exception ex) + { + log.log(Level.SEVERE, "AMenu", ex); + } + + // initialize & load tree + int AD_Role_ID = Env.getAD_Role_ID(Env.getCtx()); + int AD_Tree_ID = DB.getSQLValue(null, + "SELECT COALESCE(r.AD_Tree_Menu_ID, ci.AD_Tree_Menu_ID)" + + "FROM AD_ClientInfo ci" + + " INNER JOIN AD_Role r ON (ci.AD_Client_ID=r.AD_Client_ID) " + + "WHERE AD_Role_ID=?", AD_Role_ID); + if (AD_Tree_ID <= 0) + AD_Tree_ID = 10; // Menu + treePanel.initTree(AD_Tree_ID); + + // Translate + Env.setContext(m_ctx, m_WindowNo, "WindowName", Msg.getMsg(m_ctx, "Menu")); + setTitle(Env.getHeader(m_ctx, m_WindowNo)); + + progressBar.setString(Msg.getMsg(m_ctx, "SelectProgram")); + + // Finish UI + Point loc = Ini.getWindowLocation(0); + if (loc == null) + loc = new Point(0,0); + this.setLocation(loc); + this.pack(); + this.setVisible(true); + this.setState(Frame.NORMAL); + m_AD_User_ID = Env.getContextAsInt(m_ctx, "#AD_User_ID"); + m_AD_Role_ID = Env.getContextAsInt(m_ctx, "#AD_Role_ID"); updateInfo(); // splash.dispose(); @@ -114,39 +112,37 @@ public final class AMenu extends CFrame } // AMenu private int m_WindowNo; - private Properties m_ctx = Env.getCtx(); - private boolean m_startingItem = false; - /** The User */ - private int m_AD_User_ID; - /** The Role */ - private int m_AD_Role_ID; - - /** Center Tabbed Pane index: Menu */ - private int m_tabMenu = 0; - /** Center Tabbed Pane index: Activities */ - private int m_tabActivities = 1; - /** Center Tabbed Pane index: Workflow */ - private int m_tabWorkflow = 2; - - // Links - private int m_request_Menu_ID = 0; - private int m_note_Menu_ID = 0; - private String m_requestSQL = null; - private DecimalFormat m_memoryFormat = DisplayType.getNumberFormat(DisplayType.Integer); + private Properties m_ctx = Env.getCtx(); + private boolean m_startingItem = false; + /** The User */ + private int m_AD_User_ID; + /** The Role */ + private int m_AD_Role_ID; + + /** Center Tabbed Pane index: Menu */ + private int m_tabMenu = 0; + /** Center Tabbed Pane index: Activities */ + private int m_tabActivities = 1; + /** Center Tabbed Pane index: Workflow */ + private int m_tabWorkflow = 2; + + // Links + private int m_request_Menu_ID = 0; + private int m_note_Menu_ID = 0; + private String m_requestSQL = null; + private DecimalFormat m_memoryFormat = DisplayType.getNumberFormat(DisplayType.Integer); /** Logger */ private static CLogger log = CLogger.getCLogger(AMenu.class); - private WindowManager windowManager = new WindowManager(); - /************************************************************************** * Init System. - * -- do not get Msg as environment not initialized yet -- - *
-	 *	- Login - in not successful, exit
-	 *  
- * @param splash splash window - */ + * -- do not get Msg as environment not initialized yet -- + *
+	 *	- Login - in not successful, exit
+	 *  
+ * @param splash splash window + */ private void initSystem (Splash splash) { // Default Image @@ -154,491 +150,474 @@ public final class AMenu extends CFrame // Focus Traversal KeyboardFocusManager.setCurrentKeyboardFocusManager(AKeyboardFocusManager.get()); - // FocusManager.getCurrentManager().setDefaultFocusTraversalPolicy(AFocusTraversalPolicy.get()); - // this.setFocusTraversalPolicy(AFocusTraversalPolicy.get()); - - /** - * Show Login Screen - if not successful - exit - */ - log.finer("Login"); - ALogin login = new ALogin(splash); - if (!login.initLogin()) // no automatic login - { - // Center the window - try - { - AEnv.showCenterScreen(login); // HTML load errors - } - catch (Exception ex) - { - log.severe(ex.toString()); - } - if (!login.isConnected() || !login.isOKpressed()) - AEnv.exit(1); - } - - // Check DB (AppsServer Version checked in Login) - boolean dbOK = DB.isDatabaseOK(m_ctx); - // if (!dbOK) - // AEnv.exit(1); - } // initSystem - - // UI - private CPanel mainPanel = new CPanel(); - private BorderLayout mainLayout = new BorderLayout(); - private CTabbedPane centerPane = new CTabbedPane(); - private CPanel southPanel = new CPanel(); - private BorderLayout southLayout = new BorderLayout(); - private JMenuBar menuBar = new JMenuBar(); - protected JProgressBar progressBar = new JProgressBar(0,100); - private CPanel infoPanel = new CPanel(); - private CButton bNotes = new CButton(); - private CButton bRequests = new CButton(); - private GridLayout infoLayout = new GridLayout(); - private JProgressBar memoryBar = new JProgressBar(); - // Tabs - private PAPanel paPanel = null; - private VTreePanel treePanel = null; - private WFActivity wfActivity = null; - private WFPanel wfPanel = null; - - /** - * Static Init. - *
-	 *  - mainPanel
-	 * 		- centerPane
-	 *      	- treePanel
-	 * 			- wfActivity
-	 * 			- wfPanel
-	 *      - southPanel
-	 *          - infoPanel
-	 *              - bNotes
-	 *              - bTask
-	 *              - memoryBar
-	 *          - wfPanel
-	 *          - progressBar
-	 *  
- * @throws Exception - */ - void jbInit() throws Exception - { - this.setName("Menu"); - this.setLocale(Language.getLoginLanguage().getLocale()); - this.setJMenuBar(menuBar); - // - mainPanel.setLayout(mainLayout); - mainLayout.setHgap(0); - mainLayout.setVgap(2); - // - treePanel.addPropertyChangeListener(VTreePanel.NODE_SELECTION, this); - // - infoPanel.setLayout(infoLayout); - infoLayout.setColumns(2); - infoLayout.setHgap(4); - infoLayout.setVgap(0); - // bNotes.setRequestFocusEnabled(false); - bNotes.setToolTipText(""); - bNotes.setActionCommand("Notes"); - bNotes.addActionListener(this); - bNotes.setIcon(Env.getImageIcon("GetMail24.gif")); - bNotes.setMargin(new Insets(0, 0, 0, 0)); - // bRequests.setRequestFocusEnabled(false); - bRequests.setActionCommand("Requests"); - bRequests.addActionListener(this); - bRequests.setIcon(Env.getImageIcon("Request24.gif")); - bRequests.setMargin(new Insets(0, 0, 0, 0)); - // - southLayout.setHgap(0); - southLayout.setVgap(1); - // - memoryBar.setStringPainted(true); - memoryBar.setOpaque(false); - memoryBar.setBorderPainted(false); - memoryBar.addMouseListener(new AMenu_MouseAdapter()); - // - progressBar.setStringPainted(true); - progressBar.setOpaque(false); - // - getContentPane().add(mainPanel); - mainPanel.add(centerPane, BorderLayout.CENTER); - mainPanel.add(southPanel, BorderLayout.SOUTH); - mainPanel.add(Box.createHorizontalStrut(3), BorderLayout.EAST); - mainPanel.add(Box.createHorizontalStrut(3), BorderLayout.WEST); - - // Tabs - paPanel = PAPanel.get(); - if (paPanel != null) - { - centerPane.add(paPanel, Msg.getMsg(m_ctx, "PAPanel")); - m_tabMenu++; + // FocusManager.getCurrentManager().setDefaultFocusTraversalPolicy(AFocusTraversalPolicy.get()); + // this.setFocusTraversalPolicy(AFocusTraversalPolicy.get()); + + /** + * Show Login Screen - if not successful - exit + */ + log.finer("Login"); + ALogin login = new ALogin(splash); + if (!login.initLogin()) // no automatic login + { + // Center the window + try + { + AEnv.showCenterScreen(login); // HTML load errors + } + catch (Exception ex) + { + log.severe(ex.toString()); + } + if (!login.isConnected() || !login.isOKpressed()) + AEnv.exit(1); + } + + // Check DB (AppsServer Version checked in Login) + boolean dbOK = DB.isDatabaseOK(m_ctx); + // if (!dbOK) + // AEnv.exit(1); + } // initSystem + + // UI + private CPanel mainPanel = new CPanel(); + private BorderLayout mainLayout = new BorderLayout(); + private CTabbedPane centerPane = new CTabbedPane(); + private CPanel southPanel = new CPanel(); + private BorderLayout southLayout = new BorderLayout(); + private JMenuBar menuBar = new JMenuBar(); + protected JProgressBar progressBar = new JProgressBar(0,100); + private CPanel infoPanel = new CPanel(); + private CButton bNotes = new CButton(); + private CButton bRequests = new CButton(); + private GridLayout infoLayout = new GridLayout(); + private JProgressBar memoryBar = new JProgressBar(); + // Tabs + private PAPanel paPanel = null; + private VTreePanel treePanel = null; + private WFActivity wfActivity = null; + private WFPanel wfPanel = null; + + /** + * Static Init. + *
+	 *  - mainPanel
+	 * 		- centerPane
+	 *      	- treePanel
+	 * 			- wfActivity
+	 * 			- wfPanel
+	 *      - southPanel
+	 *          - infoPanel
+	 *              - bNotes
+	 *              - bTask
+	 *              - memoryBar
+	 *          - wfPanel
+	 *          - progressBar
+	 *  
+ * @throws Exception + */ + void jbInit() throws Exception + { + this.setName("Menu"); + this.setLocale(Language.getLoginLanguage().getLocale()); + this.setJMenuBar(menuBar); + // + mainPanel.setLayout(mainLayout); + mainLayout.setHgap(0); + mainLayout.setVgap(2); + // + treePanel.addPropertyChangeListener(VTreePanel.NODE_SELECTION, this); + // + infoPanel.setLayout(infoLayout); + infoLayout.setColumns(2); + infoLayout.setHgap(4); + infoLayout.setVgap(0); + // bNotes.setRequestFocusEnabled(false); + bNotes.setToolTipText(""); + bNotes.setActionCommand("Notes"); + bNotes.addActionListener(this); + bNotes.setIcon(Env.getImageIcon("GetMail24.gif")); + bNotes.setMargin(new Insets(0, 0, 0, 0)); + // bRequests.setRequestFocusEnabled(false); + bRequests.setActionCommand("Requests"); + bRequests.addActionListener(this); + bRequests.setIcon(Env.getImageIcon("Request24.gif")); + bRequests.setMargin(new Insets(0, 0, 0, 0)); + // + southLayout.setHgap(0); + southLayout.setVgap(1); + // + memoryBar.setStringPainted(true); + memoryBar.setOpaque(false); + memoryBar.setBorderPainted(false); + memoryBar.addMouseListener(new AMenu_MouseAdapter()); + // + progressBar.setStringPainted(true); + progressBar.setOpaque(false); + // + getContentPane().add(mainPanel); + mainPanel.add(centerPane, BorderLayout.CENTER); + mainPanel.add(southPanel, BorderLayout.SOUTH); + mainPanel.add(Box.createHorizontalStrut(3), BorderLayout.EAST); + mainPanel.add(Box.createHorizontalStrut(3), BorderLayout.WEST); + + // Tabs + paPanel = PAPanel.get(); + if (paPanel != null) + { + centerPane.add(paPanel, Msg.getMsg(m_ctx, "PAPanel")); + m_tabMenu++; m_tabActivities++; m_tabWorkflow++; } - treePanel.setBorder(BorderFactory.createEmptyBorder(2,3,2,3)); centerPane.add(treePanel, Msg.getMsg(m_ctx, "Menu")); centerPane.add(new CScrollPane(wfActivity), Msg.getMsg (m_ctx, "WorkflowActivities") + ": 0"); centerPane.add(new CScrollPane(wfPanel), Msg.getMsg (m_ctx, "WorkflowPanel")); - centerPane.addChangeListener (this); - // - southPanel.setLayout(southLayout); - southPanel.add(infoPanel, BorderLayout.NORTH); - southPanel.add(progressBar, BorderLayout.SOUTH); - // - infoPanel.add(bNotes, null); - infoPanel.add(bRequests, null); - infoPanel.add(memoryBar, null); - // - int loc = Ini.getDividerLocation(); - if (loc > 0) - treePanel.setDividerLocation(loc); - } // jbInit - - /** - * Get Preferred Size - * @return preferred Size - */ - public Dimension getPreferredSize() - { - Dimension dim = Ini.getWindowDimension(0); - if (dim == null) - dim = new Dimension (350, 500); - return dim; - } // getPreferredSize - - - /** - * Create Menu - */ - private void createMenu() - { - // File - JMenu mFile = AEnv.getMenu("File"); - menuBar.add(mFile); + centerPane.addChangeListener (this); + // + southPanel.setLayout(southLayout); + southPanel.add(infoPanel, BorderLayout.NORTH); + southPanel.add(progressBar, BorderLayout.SOUTH); + // + infoPanel.add(bNotes, null); + infoPanel.add(bRequests, null); + infoPanel.add(memoryBar, null); + // + int loc = Ini.getDividerLocation(); + if (loc > 0) + treePanel.setDividerLocation(loc); + } // jbInit + + /** + * Get Preferred Size + * @return preferred Size + */ + public Dimension getPreferredSize() + { + Dimension dim = Ini.getWindowDimension(0); + if (dim == null) + dim = new Dimension (350, 500); + return dim; + } // getPreferredSize + + + /** + * Create Menu + */ + private void createMenu() + { + // File + JMenu mFile = AEnv.getMenu("File"); + menuBar.add(mFile); AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, KeyEvent.SHIFT_MASK), mFile, this); mFile.addSeparator(); - AEnv.addMenuItem("Logout", null, KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.SHIFT_MASK+Event.ALT_MASK), mFile, this); AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.SHIFT_MASK+Event.ALT_MASK), mFile, this); // View - JMenu mView = AEnv.getMenu("View"); - menuBar.add(mView); - AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK), mView, this); - AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), mView, this); - if (MRole.getDefault().isShowAcct()) - AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), mView, this); - AEnv.addMenuItem("InfoSchedule", null, null, mView, this); - mView.addSeparator(); - AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); - AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); - AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); - AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); - AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); - AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); - AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); - - // Tools - JMenu mTools = AEnv.getMenu("Tools"); - menuBar.add(mTools); - AEnv.addMenuItem("Calculator", null, null, mTools, this); - AEnv.addMenuItem("Calendar", null, null, mTools, this); - AEnv.addMenuItem("Editor", null, null, mTools, this); - AEnv.addMenuItem("Script", null, null, mTools, this); - if (AEnv.isWorkflowProcess()) - AEnv.addMenuItem("WorkFlow", null, null, mTools, this); - if (MRole.getDefault().isShowPreference()) - { + JMenu mView = AEnv.getMenu("View"); + menuBar.add(mView); + AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK), mView, this); + AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), mView, this); + if (MRole.getDefault().isShowAcct()) + AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), mView, this); + AEnv.addMenuItem("InfoSchedule", null, null, mView, this); + mView.addSeparator(); + AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); + AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); + AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); + AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); + AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); + AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); + AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); + + // Tools + JMenu mTools = AEnv.getMenu("Tools"); + menuBar.add(mTools); + AEnv.addMenuItem("Calculator", null, null, mTools, this); + AEnv.addMenuItem("Calendar", null, null, mTools, this); + AEnv.addMenuItem("Editor", null, null, mTools, this); + AEnv.addMenuItem("Script", null, null, mTools, this); + if (AEnv.isWorkflowProcess()) + AEnv.addMenuItem("WorkFlow", null, null, mTools, this); + if (MRole.getDefault().isShowPreference()) + { mTools.addSeparator(); AEnv.addMenuItem("Preference", null, null, mTools, this); } - - //Window Menu - JMenu mWindow = new WindowMenu(windowManager, this); - menuBar.add(mWindow); // Help JMenu mHelp = AEnv.getMenu("Help"); - menuBar.add(mHelp); - AEnv.addMenuItem("Online", null, null, mHelp, this); - AEnv.addMenuItem("EMailSupport", null, null, mHelp, this); - AEnv.addMenuItem("About", null, null, mHelp, this); - } // createMenu - - /** - * Dispose - end system - */ - public void dispose() - { - // clean up - close windows - Ini.setWindowDimension(0, getSize()); - Ini.setDividerLocation(treePanel.getDividerLocation()); - Ini.setWindowLocation(0, getLocation()); - Ini.saveProperties(true); + menuBar.add(mHelp); + AEnv.addMenuItem("Online", null, null, mHelp, this); + AEnv.addMenuItem("EMailSupport", null, null, mHelp, this); + AEnv.addMenuItem("About", null, null, mHelp, this); + } // createMenu + + /** + * Dispose - end system + */ + public void dispose() + { + // clean up - close windows + Ini.setWindowDimension(0, getSize()); + Ini.setDividerLocation(treePanel.getDividerLocation()); + Ini.setWindowLocation(0, getLocation()); + Ini.saveProperties(true); super.dispose(); AEnv.exit(0); } // dispose - - public void logout() - { - windowManager.close(); - Ini.saveProperties(true); - super.dispose(); - AEnv.logout(); - } /** * Window Events - requestFocus - * @param e event - */ - protected void processWindowEvent(WindowEvent e) - { - super.processWindowEvent(e); - if (e.getID() == WindowEvent.WINDOW_OPENED) - { - treePanel.getSearchField().requestFocusInWindow(); - // this.toFront(); - } - } // processWindowEvent - - /** - * Set Busy - * @param value true if buzy - */ - protected void setBusy (boolean value) - { - m_startingItem = value; - if (value) - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - else - setCursor(Cursor.getDefaultCursor()); - // setEnabled (!value); // causes flicker - } // setBusy - - /** - * Selection in tree - launch Application - * @param e PropertyChangeEvent - */ - public void propertyChange(PropertyChangeEvent e) - { - MTreeNode nd = (MTreeNode)e.getNewValue(); - log.info(nd.getNode_ID() + " - " + nd.toString()); - - // ignore summary items & when loading - if (m_startingItem || nd.isSummary()) - return; - - String sta = nd.toString(); - progressBar.setString(sta); - int cmd = nd.getNode_ID(); - - (new AMenuStartItem(cmd, true, sta, this)).start(); // async load - updateInfo(); - } // propertyChange - - - /************************************************************************** - * ActionListener - * @param e ActionEvent - */ - public void actionPerformed(ActionEvent e) - { - // Buttons - if (e.getSource() == bNotes) - gotoNotes(); - else if (e.getSource() == bRequests) - gotoRequests(); - else if (!AEnv.actionPerformed(e.getActionCommand(), m_WindowNo, this)) - log.log(Level.SEVERE, "unknown action=" + e.getActionCommand()); - updateInfo(); - } // actionPerformed - - /** - * Get number of open Notes - * @return bumber of notes - */ - private int getNotes() - { - int retValue = 0; - String sql = "SELECT COUNT(*) FROM AD_Note " - + "WHERE AD_Client_ID=? AND AD_User_ID IN (0,?)" - + " AND Processed='N'"; - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, Env.getAD_Client_ID(Env.getCtx())); - pstmt.setInt(2, m_AD_User_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - return retValue; - } // getNotes - - /** - * Open Note Window - */ - private void gotoNotes() - { - // AD_Table_ID for AD_Note = 389 HARDCODED - if (m_note_Menu_ID == 0) - m_note_Menu_ID = DB.getSQLValue(null, "SELECT AD_Menu_ID " - + "FROM AD_Menu m" - + " INNER JOIN AD_TABLE t ON (t.AD_Window_ID=m.AD_Window_ID) " - + "WHERE t.AD_Table_ID=?", 389); - if (m_note_Menu_ID == 0) - m_note_Menu_ID = 233; // fallback HARDCODED - (new AMenuStartItem (m_note_Menu_ID, true, Msg.translate(m_ctx, "AD_Note_ID"), this)).start(); // async load - } // gotoMessage - - /** - * Ger Number of open Requests - * @return number of requests - */ - private int getRequests() - { - int retValue = 0; - if (m_requestSQL == null) - m_requestSQL = MRole.getDefault().addAccessSQL ("SELECT COUNT(*) FROM R_Request " - + "WHERE (SalesRep_ID=? OR AD_Role_ID=?) AND Processed='N'" - + " AND (DateNextAction IS NULL OR TRUNC(DateNextAction) <= TRUNC(SysDate))" - + " AND (R_Status_ID IS NULL OR R_Status_ID IN (SELECT R_Status_ID FROM R_Status WHERE IsClosed='N'))", - "R_Request", false, true); // not qualified - RW - try - { - PreparedStatement pstmt = DB.prepareStatement(m_requestSQL, null); - pstmt.setInt(1, m_AD_User_ID); - pstmt.setInt(2, m_AD_Role_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, m_requestSQL, e); - } - return retValue; - } // getRequests - - /** - * Open Request Window - */ - private void gotoRequests() - { - // AD_Table_ID for R_Request = 417 HARDCODED - // if (m_request_Menu_ID == 0) // Goes to Request (all) - // m_request_Menu_ID = DB.getSQLValue (null, "SELECT AD_Menu_ID " - // + "FROM AD_Menu m" - // + " INNER JOIN AD_TABLE t ON (t.AD_Window_ID=m.AD_Window_ID) " - // + "WHERE t.AD_Table_ID=?", 417); - if (m_request_Menu_ID == 0) - m_request_Menu_ID = 237; // My Requests - (new AMenuStartItem (m_request_Menu_ID, true, Msg.translate(m_ctx, "R_Request_ID"), this)).start(); // async load - } // gotoRequests - - /** - * Show Memory Info - run GC if required - Update Requests/Memos/Activities - */ - public void updateInfo() - { - double total = Runtime.getRuntime().totalMemory() / 1024; - double free = Runtime.getRuntime().freeMemory() / 1024; - double used = total - free; - double percent = used * 100 / total; - // - memoryBar.setMaximum((int)total); - memoryBar.setValue((int)used); - String msg = MessageFormat.format("{0,number,integer} MB - {1,number,integer}%", - new Object[] {new BigDecimal(total / 1024), new BigDecimal(percent)}); - memoryBar.setString(msg); - // - // msg = MessageFormat.format("Total Memory {0,number,integer} kB - Free {1,number,integer} kB", - msg = Msg.getMsg(m_ctx, "MemoryInfo", - new Object[] {new BigDecimal(total), new BigDecimal(free)}); - memoryBar.setToolTipText(msg); - // progressBar.repaint(); - - // - if (percent > 50) - System.gc(); - - // Requests - int requests = getRequests(); - bRequests.setText(Msg.translate(m_ctx, "R_Request_ID") + ": " + requests); - // Memo - int notes = getNotes(); - bNotes.setText(Msg.translate(m_ctx, "AD_Note_ID") + ": " + notes); - // Activities - int activities = wfActivity.loadActivities(); - centerPane.setTitleAt(m_tabActivities, Msg.getMsg (m_ctx, "WorkflowActivities") + ": " + activities); - // - log.config(msg - + ", Processors=" + Runtime.getRuntime().availableProcessors() - + ", Requests=" + requests + ", Notes=" + notes + ", Activities=" + activities - + "," + CConnection.get().getStatus() - ); - MSystem.get(m_ctx).info(); - } // updateInfo - - - /************************************************************************* - * Start Workflow Activity - * @param AD_Workflow_ID id - */ - protected void startWorkFlow (int AD_Workflow_ID) - { - centerPane.setSelectedIndex(m_tabWorkflow); // switch - wfPanel.load(AD_Workflow_ID, false); - } // startWorkFlow - - - /** - * Change Listener (tab) - * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent) - * @param e event - */ - public void stateChanged (ChangeEvent e) - { - // show activities - if (centerPane.getSelectedIndex() == m_tabActivities) + * @param e event + */ + protected void processWindowEvent(WindowEvent e) + { + super.processWindowEvent(e); + if (e.getID() == WindowEvent.WINDOW_OPENED) + { + treePanel.getSearchField().requestFocusInWindow(); + // this.toFront(); + } + } // processWindowEvent + + /** + * Set Busy + * @param value true if buzy + */ + protected void setBusy (boolean value) + { + m_startingItem = value; + if (value) + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + else + setCursor(Cursor.getDefaultCursor()); + // setEnabled (!value); // causes flicker + } // setBusy + + /** + * Selection in tree - launch Application + * @param e PropertyChangeEvent + */ + public void propertyChange(PropertyChangeEvent e) + { + MTreeNode nd = (MTreeNode)e.getNewValue(); + log.info(nd.getNode_ID() + " - " + nd.toString()); + + // ignore summary items & when loading + if (m_startingItem || nd.isSummary()) + return; + + String sta = nd.toString(); + progressBar.setString(sta); + int cmd = nd.getNode_ID(); + + (new AMenuStartItem(cmd, true, sta, this)).start(); // async load + updateInfo(); + } // propertyChange + + + /************************************************************************** + * ActionListener + * @param e ActionEvent + */ + public void actionPerformed(ActionEvent e) + { + // Buttons + if (e.getSource() == bNotes) + gotoNotes(); + else if (e.getSource() == bRequests) + gotoRequests(); + else if (!AEnv.actionPerformed(e.getActionCommand(), m_WindowNo, this)) + log.log(Level.SEVERE, "unknown action=" + e.getActionCommand()); + updateInfo(); + } // actionPerformed + + /** + * Get number of open Notes + * @return bumber of notes + */ + private int getNotes() + { + int retValue = 0; + String sql = "SELECT COUNT(*) FROM AD_Note " + + "WHERE AD_Client_ID=? AND AD_User_ID IN (0,?)" + + " AND Processed='N'"; + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, Env.getAD_Client_ID(Env.getCtx())); + pstmt.setInt(2, m_AD_User_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + return retValue; + } // getNotes + + /** + * Open Note Window + */ + private void gotoNotes() + { + // AD_Table_ID for AD_Note = 389 HARDCODED + if (m_note_Menu_ID == 0) + m_note_Menu_ID = DB.getSQLValue(null, "SELECT AD_Menu_ID " + + "FROM AD_Menu m" + + " INNER JOIN AD_TABLE t ON (t.AD_Window_ID=m.AD_Window_ID) " + + "WHERE t.AD_Table_ID=?", 389); + if (m_note_Menu_ID == 0) + m_note_Menu_ID = 233; // fallback HARDCODED + (new AMenuStartItem (m_note_Menu_ID, true, Msg.translate(m_ctx, "AD_Note_ID"), this)).start(); // async load + } // gotoMessage + + /** + * Ger Number of open Requests + * @return number of requests + */ + private int getRequests() + { + int retValue = 0; + if (m_requestSQL == null) + m_requestSQL = MRole.getDefault().addAccessSQL ("SELECT COUNT(*) FROM R_Request " + + "WHERE (SalesRep_ID=? OR AD_Role_ID=?) AND Processed='N'" + + " AND (DateNextAction IS NULL OR TRUNC(DateNextAction) <= TRUNC(SysDate))" + + " AND (R_Status_ID IS NULL OR R_Status_ID IN (SELECT R_Status_ID FROM R_Status WHERE IsClosed='N'))", + "R_Request", false, true); // not qualified - RW + try + { + PreparedStatement pstmt = DB.prepareStatement(m_requestSQL, null); + pstmt.setInt(1, m_AD_User_ID); + pstmt.setInt(2, m_AD_Role_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, m_requestSQL, e); + } + return retValue; + } // getRequests + + /** + * Open Request Window + */ + private void gotoRequests() + { + // AD_Table_ID for R_Request = 417 HARDCODED + // if (m_request_Menu_ID == 0) // Goes to Request (all) + // m_request_Menu_ID = DB.getSQLValue (null, "SELECT AD_Menu_ID " + // + "FROM AD_Menu m" + // + " INNER JOIN AD_TABLE t ON (t.AD_Window_ID=m.AD_Window_ID) " + // + "WHERE t.AD_Table_ID=?", 417); + if (m_request_Menu_ID == 0) + m_request_Menu_ID = 237; // My Requests + (new AMenuStartItem (m_request_Menu_ID, true, Msg.translate(m_ctx, "R_Request_ID"), this)).start(); // async load + } // gotoRequests + + /** + * Show Memory Info - run GC if required - Update Requests/Memos/Activities + */ + public void updateInfo() + { + double total = Runtime.getRuntime().totalMemory() / 1024; + double free = Runtime.getRuntime().freeMemory() / 1024; + double used = total - free; + double percent = used * 100 / total; + // + memoryBar.setMaximum((int)total); + memoryBar.setValue((int)used); + String msg = MessageFormat.format("{0,number,integer} MB - {1,number,integer}%", + new Object[] {new BigDecimal(total / 1024), new BigDecimal(percent)}); + memoryBar.setString(msg); + // + // msg = MessageFormat.format("Total Memory {0,number,integer} kB - Free {1,number,integer} kB", + msg = Msg.getMsg(m_ctx, "MemoryInfo", + new Object[] {new BigDecimal(total), new BigDecimal(free)}); + memoryBar.setToolTipText(msg); + // progressBar.repaint(); + + // + if (percent > 50) + System.gc(); + + // Requests + int requests = getRequests(); + bRequests.setText(Msg.translate(m_ctx, "R_Request_ID") + ": " + requests); + // Memo + int notes = getNotes(); + bNotes.setText(Msg.translate(m_ctx, "AD_Note_ID") + ": " + notes); + // Activities + int activities = wfActivity.loadActivities(); + centerPane.setTitleAt(m_tabActivities, Msg.getMsg (m_ctx, "WorkflowActivities") + ": " + activities); + // + log.config(msg + + ", Processors=" + Runtime.getRuntime().availableProcessors() + + ", Requests=" + requests + ", Notes=" + notes + ", Activities=" + activities + + "," + CConnection.get().getStatus() + ); + MSystem.get(m_ctx).info(); + } // updateInfo + + + /************************************************************************* + * Start Workflow Activity + * @param AD_Workflow_ID id + */ + protected void startWorkFlow (int AD_Workflow_ID) + { + centerPane.setSelectedIndex(m_tabWorkflow); // switch + wfPanel.load(AD_Workflow_ID, false); + } // startWorkFlow + + + /** + * Change Listener (tab) + * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent) + * @param e event + */ + public void stateChanged (ChangeEvent e) + { + // show activities + if (centerPane.getSelectedIndex() == m_tabActivities) wfActivity.display(); } // stateChanged - public WindowManager getWindowManager() { - return windowManager; - } /************************************************************************** * Mouse Listener - */ - class AMenu_MouseAdapter extends MouseAdapter - { - /** - * Invoked when the mouse has been clicked on a component. - * @param e evant - */ - public void mouseClicked(MouseEvent e) - { - if (e.getClickCount() > 1) - { - System.gc(); - updateInfo(); - } - } - } // AMenu_MouseAdapter - - - /************************************************************************** - * OS Start - * @param args Array of String arguments (ignored) - */ + */ + class AMenu_MouseAdapter extends MouseAdapter + { + /** + * Invoked when the mouse has been clicked on a component. + * @param e evant + */ + public void mouseClicked(MouseEvent e) + { + if (e.getClickCount() > 1) + { + System.gc(); + updateInfo(); + } + } + } // AMenu_MouseAdapter + + + /************************************************************************** + * OS Start + * @param args Array of String arguments (ignored) + */ public static void main(String[] args) { Splash splash = Splash.getSplash(); @@ -646,4 +625,4 @@ public final class AMenu extends CFrame AMenu menu = new AMenu(); } // main -} // AMenu \ No newline at end of file +} // AMenu diff --git a/client/src/org/compiere/apps/AMenuStartItem.java b/client/src/org/compiere/apps/AMenuStartItem.java index bffd9c83a4..40902e31d8 100644 --- a/client/src/org/compiere/apps/AMenuStartItem.java +++ b/client/src/org/compiere/apps/AMenuStartItem.java @@ -3,16 +3,16 @@ * 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 * + * 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 * *****************************************************************************/ package org.compiere.apps; @@ -20,325 +20,287 @@ import java.awt.Frame; import java.awt.event.*; import java.sql.*; import java.util.logging.*; -import javax.swing.*; -import org.compiere.apps.form.*; -import org.compiere.model.*; -import org.compiere.util.*; - - -/** - * Start Menu Item & UpdateProgress Bar - * - * @author Jorg Janke - * @version $Id: AMenuStartItem.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public class AMenuStartItem extends Thread implements ActionListener -{ - /** - * Start Menu Item - * - * @param ID ID - * @param isMenu false if Workflow - * @param name Name - * @param menu Menu - */ - public AMenuStartItem (int ID, boolean isMenu, String name, AMenu menu) - { - m_ID = ID; - m_isMenu = isMenu; - m_name = name; - m_menu = menu; - if (menu != null) - m_increment = (menu.progressBar.getMaximum()-menu.progressBar.getMinimum()) / 5; - } // UpdateProgress - - /** The ID */ - private int m_ID = 0; - private boolean m_isMenu = false; - private String m_name; - private AMenu m_menu; - /** Logger */ - private static CLogger log = CLogger.getCLogger(AMenuStartItem.class); - - // Reset Progress Bar - private Runnable m_resetPB = new Runnable() - { - public void run() - { - m_value = 0; - if (m_menu != null) - m_menu.progressBar.setValue(0); - } - }; - // Progress Bar tick - private Runnable m_tickPB = new Runnable() - { - public void run() - { - if (m_menu == null) - return; - // 100/5 => 20 ticks - every .5 sec => 10 seconds loadtime - final int tick = 5; - if (m_menu.progressBar.getValue() < (m_menu.progressBar.getMaximum() - tick)) - m_menu.progressBar.setValue(m_menu.progressBar.getValue() + tick); - } - }; - // Progress Bar max state - private Runnable m_updatePB = new Runnable() - { - public void run() - { - if (m_menu == null) - return; - m_value += m_increment; - if (m_menu.progressBar.getValue() > m_value) // max value - m_menu.progressBar.setValue(m_value); - } - }; - private int m_value = 0; - private int m_increment = 20; - private javax.swing.Timer m_timer = new javax.swing.Timer(500, this); // every 1/2 second - - - /** - * Start Menu Item - */ - public void run() - { - if (m_menu != null) - m_menu.setBusy (true); - SwingUtilities.invokeLater(m_resetPB); - m_timer.start(); - SwingUtilities.invokeLater(m_updatePB); - try - { - String sql = "SELECT * FROM AD_Menu WHERE AD_Menu_ID=?"; - if (!m_isMenu) - sql = "SELECT * FROM AD_WF_Node WHERE AD_WF_Node_ID=?"; - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, m_ID); - ResultSet rs = pstmt.executeQuery(); - - SwingUtilities.invokeLater(m_updatePB); - if (rs.next()) // should only be one - { - String Action = rs.getString("Action"); - String IsSOTrx = "Y"; - if (m_isMenu) - IsSOTrx = rs.getString("IsSOTrx"); - int cmd; - if (Action.equals("W")) // Window - { - cmd = rs.getInt("AD_Window_ID"); - startWindow(0, cmd); - } - else if (Action.equals("P") || Action.equals("R")) // Process & Report - { - cmd = rs.getInt("AD_Process_ID"); - startProcess(cmd, IsSOTrx); - } - else if (Action.equals("B")) // Workbench - { - cmd = rs.getInt("AD_Workbench_ID"); - startWindow (cmd, 0); - } - else if (Action.equals("F")) // WorkFlow - { - if (m_isMenu) - cmd = rs.getInt("AD_Workflow_ID"); - else - cmd = rs.getInt("Workflow_ID"); - if (m_menu != null) - m_menu.startWorkFlow(cmd); - } - else if (Action.equals("T")) // Task - { - cmd = rs.getInt("AD_Task_ID"); - startTask(cmd); - } - else if (Action.equals("X")) // Form - { - cmd = rs.getInt("AD_Form_ID"); - startForm(cmd); - } - else - log.log(Level.SEVERE, "No valid Action in ID=" + m_ID); - } // for all records - - SwingUtilities.invokeLater(m_updatePB); - rs.close(); - pstmt.close(); - } - catch (Exception e) - { - log.log(Level.SEVERE, "ID=" + m_ID, e); - ADialog.error(0, null, "Error", Msg.parseTranslation(Env.getCtx(), e.getMessage())); - } - - try {Thread.sleep(1000);} // 1 sec - catch (InterruptedException ie) {} - - // ready for next - m_timer.stop(); - SwingUtilities.invokeLater(m_resetPB); - if (m_menu != null) - { - m_menu.updateInfo(); - m_menu.setBusy(false); - } - } // run - - - /** - * Actlion Listener for Timer - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - SwingUtilities.invokeLater(m_tickPB); - } // actionPerformed - - /** - * Start Window - * - * @param AD_Workbench_ID workbench - * @param AD_Window_ID window +import javax.swing.*; +import org.compiere.apps.form.*; +import org.compiere.model.*; +import org.compiere.util.*; + + +/** + * Start Menu Item & UpdateProgress Bar + * + * @author Jorg Janke + * @version $Id: AMenuStartItem.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public class AMenuStartItem extends Thread implements ActionListener +{ + /** + * Start Menu Item + * + * @param ID ID + * @param isMenu false if Workflow + * @param name Name + * @param menu Menu + */ + public AMenuStartItem (int ID, boolean isMenu, String name, AMenu menu) + { + m_ID = ID; + m_isMenu = isMenu; + m_name = name; + m_menu = menu; + if (menu != null) + m_increment = (menu.progressBar.getMaximum()-menu.progressBar.getMinimum()) / 5; + } // UpdateProgress + + /** The ID */ + private int m_ID = 0; + private boolean m_isMenu = false; + private String m_name; + private AMenu m_menu; + /** Logger */ + private static CLogger log = CLogger.getCLogger(AMenuStartItem.class); + + // Reset Progress Bar + private Runnable m_resetPB = new Runnable() + { + public void run() + { + m_value = 0; + if (m_menu != null) + m_menu.progressBar.setValue(0); + } + }; + // Progress Bar tick + private Runnable m_tickPB = new Runnable() + { + public void run() + { + if (m_menu == null) + return; + // 100/5 => 20 ticks - every .5 sec => 10 seconds loadtime + final int tick = 5; + if (m_menu.progressBar.getValue() < (m_menu.progressBar.getMaximum() - tick)) + m_menu.progressBar.setValue(m_menu.progressBar.getValue() + tick); + } + }; + // Progress Bar max state + private Runnable m_updatePB = new Runnable() + { + public void run() + { + if (m_menu == null) + return; + m_value += m_increment; + if (m_menu.progressBar.getValue() > m_value) // max value + m_menu.progressBar.setValue(m_value); + } + }; + private int m_value = 0; + private int m_increment = 20; + private javax.swing.Timer m_timer = new javax.swing.Timer(500, this); // every 1/2 second + + + /** + * Start Menu Item + */ + public void run() + { + if (m_menu != null) + m_menu.setBusy (true); + SwingUtilities.invokeLater(m_resetPB); + m_timer.start(); + SwingUtilities.invokeLater(m_updatePB); + try + { + String sql = "SELECT * FROM AD_Menu WHERE AD_Menu_ID=?"; + if (!m_isMenu) + sql = "SELECT * FROM AD_WF_Node WHERE AD_WF_Node_ID=?"; + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, m_ID); + ResultSet rs = pstmt.executeQuery(); + + SwingUtilities.invokeLater(m_updatePB); + if (rs.next()) // should only be one + { + String Action = rs.getString("Action"); + String IsSOTrx = "Y"; + if (m_isMenu) + IsSOTrx = rs.getString("IsSOTrx"); + int cmd; + if (Action.equals("W")) // Window + { + cmd = rs.getInt("AD_Window_ID"); + startWindow(0, cmd); + } + else if (Action.equals("P") || Action.equals("R")) // Process & Report + { + cmd = rs.getInt("AD_Process_ID"); + startProcess(cmd, IsSOTrx); + } + else if (Action.equals("B")) // Workbench + { + cmd = rs.getInt("AD_Workbench_ID"); + startWindow (cmd, 0); + } + else if (Action.equals("F")) // WorkFlow + { + if (m_isMenu) + cmd = rs.getInt("AD_Workflow_ID"); + else + cmd = rs.getInt("Workflow_ID"); + if (m_menu != null) + m_menu.startWorkFlow(cmd); + } + else if (Action.equals("T")) // Task + { + cmd = rs.getInt("AD_Task_ID"); + startTask(cmd); + } + else if (Action.equals("X")) // Form + { + cmd = rs.getInt("AD_Form_ID"); + startForm(cmd); + } + else + log.log(Level.SEVERE, "No valid Action in ID=" + m_ID); + } // for all records + + SwingUtilities.invokeLater(m_updatePB); + rs.close(); + pstmt.close(); + } + catch (Exception e) + { + log.log(Level.SEVERE, "ID=" + m_ID, e); + ADialog.error(0, null, "Error", Msg.parseTranslation(Env.getCtx(), e.getMessage())); + } + + try {Thread.sleep(1000);} // 1 sec + catch (InterruptedException ie) {} + + // ready for next + m_timer.stop(); + SwingUtilities.invokeLater(m_resetPB); + if (m_menu != null) + { + m_menu.updateInfo(); + m_menu.setBusy(false); + } + } // run + + + /** + * Actlion Listener for Timer + * @param e event + */ + public void actionPerformed (ActionEvent e) + { + SwingUtilities.invokeLater(m_tickPB); + } // actionPerformed + + /** + * Start Window + * + * @param AD_Workbench_ID workbench + * @param AD_Window_ID window */ private void startWindow(int AD_Workbench_ID, int AD_Window_ID) { - AWindow frame = (AWindow)Env.showWindow(AD_Window_ID); - if (frame != null) { - m_menu.getWindowManager().add(frame); + if (Env.showWindow(AD_Window_ID)) return; - } - - if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW)) { - frame = m_menu.getWindowManager().find(AD_Window_ID); - if ( frame != null ) { - frame.toFront(); - return; - } - } SwingUtilities.invokeLater(m_updatePB); // 1 - frame = new AWindow(); + AWindow frame = new AWindow(); boolean OK = false; if (AD_Workbench_ID != 0) OK = frame.initWorkbench(AD_Workbench_ID); - else - OK = frame.initWindow(AD_Window_ID, null); // No Query Value - if (!OK) - return; + else + OK = frame.initWindow(AD_Window_ID, null); // No Query Value + if (!OK) + return; SwingUtilities.invokeLater(m_updatePB); // 2 frame.pack(); - if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED) ) - frame.setExtendedState(Frame.MAXIMIZED_BOTH); - + // Center the window SwingUtilities.invokeLater(m_updatePB); // 3 - if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED) ) { - frame.setVisible(true); - frame.toFront(); - } else - AEnv.showCenterScreen(frame); - - m_menu.getWindowManager().add(frame); - + AEnv.showCenterScreen(frame); // if (wfPanel.isVisible()) // m_WF_Window = frame; // maintain one reference frame = null; - } // startWindow - - /** - * Start Process. - * Start/show Process Dialog which calls ProcessCtl - * @param AD_Process_ID process - * @param IsSOTrx is SO trx - */ - private void startProcess (int AD_Process_ID, String IsSOTrx) - { - SwingUtilities.invokeLater(m_updatePB); // 1 - boolean isSO = false; - if (IsSOTrx != null && IsSOTrx.equals("Y")) - isSO = true; - m_timer.stop(); - ProcessDialog pd = new ProcessDialog (AD_Process_ID, isSO); + } // startWindow + + /** + * Start Process. + * Start/show Process Dialog which calls ProcessCtl + * @param AD_Process_ID process + * @param IsSOTrx is SO trx + */ + private void startProcess (int AD_Process_ID, String IsSOTrx) + { + SwingUtilities.invokeLater(m_updatePB); // 1 + boolean isSO = false; + if (IsSOTrx != null && IsSOTrx.equals("Y")) + isSO = true; + m_timer.stop(); + ProcessDialog pd = new ProcessDialog (AD_Process_ID, isSO); if (!pd.init()) return; m_timer.start(); - m_menu.getWindowManager().add(pd); SwingUtilities.invokeLater(m_updatePB); // 2 - pd.getContentPane().invalidate(); - pd.getContentPane().validate(); pd.pack(); // Center the window SwingUtilities.invokeLater(m_updatePB); // 3 - AEnv.showCenterScreen(pd); - } // startProcess - - /** - * Start OS Task - * @param AD_Task_ID task - */ - private void startTask (int AD_Task_ID) - { - SwingUtilities.invokeLater(m_updatePB); // 1 - // Get Command - MTask task = null; - String sql = "SELECT * FROM AD_Task WHERE AD_Task_ID=?"; - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, AD_Task_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - task = new MTask (Env.getCtx(), rs, null); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - if (task == null) + AEnv.showCenterScreen(pd); + } // startProcess + + /** + * Start OS Task + * @param AD_Task_ID task + */ + private void startTask (int AD_Task_ID) + { + SwingUtilities.invokeLater(m_updatePB); // 1 + // Get Command + MTask task = null; + String sql = "SELECT * FROM AD_Task WHERE AD_Task_ID=?"; + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, AD_Task_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + task = new MTask (Env.getCtx(), rs, null); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + if (task == null) return; SwingUtilities.invokeLater(m_updatePB); // 2 - m_menu.getWindowManager().add(new ATask(m_name, task)); + new ATask(m_name, task); // ATask.start(m_name, task); } // startTask - /** - * Start Form - * @param AD_Form_ID form + /** + * Start Form + * @param AD_Form_ID form */ private void startForm (int AD_Form_ID) { - FormFrame ff = null; - if (Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW)) { - ff = m_menu.getWindowManager().findForm(AD_Form_ID); - if ( ff != null ) { - ff.toFront(); - return; - } - } - ff = new FormFrame(); - m_menu.getWindowManager().add(ff); + FormFrame ff = new FormFrame(); SwingUtilities.invokeLater(m_updatePB); // 1 ff.openForm(AD_Form_ID); SwingUtilities.invokeLater(m_updatePB); // 2 - + ff.pack(); // Center the window SwingUtilities.invokeLater(m_updatePB); // 3 - if (Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED) ) { - ff.pack(); - ff.setExtendedState(Frame.MAXIMIZED_BOTH); - ff.setVisible(true); - ff.toFront(); - } else - AEnv.showCenterScreen(ff); + AEnv.showCenterScreen(ff); } // startForm -} // StartItem \ No newline at end of file +} // StartItem diff --git a/client/src/org/compiere/apps/APanel.java b/client/src/org/compiere/apps/APanel.java index d77720cc50..14c5f2ae81 100644 --- a/client/src/org/compiere/apps/APanel.java +++ b/client/src/org/compiere/apps/APanel.java @@ -1,2033 +1,2001 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; -import javax.swing.event.*; -import org.compiere.apps.search.*; -import org.compiere.grid.*; -import org.compiere.grid.ed.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.print.*; -import org.compiere.process.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Main Application Panel. - *
- *  Structure:
- *      (MenuBar) -> to be added to owning window
- *		northPanel  (ToolBar)
- *		tabPanel
- *		southPanel  (StatusBar)
- *  
- * - * @author Jorg Janke - * @version $Id: APanel.java,v 1.4 2006/07/30 00:51:27 jjanke Exp $ - */ -public final class APanel extends CPanel - implements DataStatusListener, ChangeListener, ActionListener, ASyncProcess -{ - /** - * Constructs a new instance. - * Need to call initPanel for dynamic initialization - */ - public APanel(AWindow window) - { - super(); - m_window = window; - - m_ctx = Env.getCtx(); - // - try - { - jbInit(); - } - catch (Exception e) - { - log.log(Level.SEVERE, "", e); - } - createMenu(); - } // APanel - - /** Logger */ - private static CLogger log = CLogger.getCLogger(APanel.class); - - private AWindow m_window; - - /** - * Dispose - */ - public void dispose() - { - // log.config(""); - // ignore changes - m_disposing = true; - // - if (m_curAPanelTab != null) - { - m_curAPanelTab.unregisterPanel(); - m_curAPanelTab = null; - } - // close panels - tabPanel.dispose(this); - tabPanel = null; - // All Workbenches - for (int i = 0; i < m_mWorkbench.getWindowCount(); i++) - { - m_curWindowNo = m_mWorkbench.getWindowNo(i); - log.info("#" + m_curWindowNo); - Env.setAutoCommit(m_ctx, m_curWindowNo, false); - m_mWorkbench.dispose(i); - Env.clearWinContext(m_ctx, m_curWindowNo); - } // all Workbenchens - - // Get rid of remaining model - if (m_mWorkbench != null) - m_mWorkbench.dispose(); - m_mWorkbench = null; - // MenuBar - if (menuBar != null) - menuBar.removeAll(); - menuBar = null; - // ToolBar - if (toolBar != null) - toolBar.removeAll(); - toolBar = null; - // Prepare GC - this.removeAll(); - } // dispose - - /** - * The Layout. - */ - private BorderLayout mainLayout = new BorderLayout(); - private VTabbedPane tabPanel = new VTabbedPane(true); - private StatusBar statusBar = new StatusBar(); - private CPanel northPanel = new CPanel(); - private JToolBar toolBar = new JToolBar(); - private JMenuBar menuBar = new JMenuBar(); - private FlowLayout northLayout = new FlowLayout(); - - /** - * Initializes the state of this instance. - * @throws Exception - */ - private void jbInit() throws Exception - { - this.setLocale(Language.getLoginLanguage().getLocale()); - this.setLayout(mainLayout); - - // tabPanel - mainLayout.setHgap(2); - mainLayout.setVgap(2); - this.add(tabPanel, BorderLayout.CENTER); - // southPanel - this.add(statusBar, BorderLayout.SOUTH); - // northPanel - this.add(northPanel, BorderLayout.NORTH); - northPanel.setLayout(northLayout); - northLayout.setAlignment(FlowLayout.LEFT); - toolBar.putClientProperty("JToolBar.isRollover", Boolean.TRUE); - toolBar.setBorderPainted(false); - northPanel.add(toolBar, null); - } // jbInit - - private AppsAction aPrevious, aNext, aParent, aDetail, aFirst, aLast, - aNew, aCopy, aDelete, aIgnore, aPrint, - aRefresh, aHistory, aAttachment, aChat, aMulti, aFind, - aWorkflow, aZoomAcross, aRequest, aWinSize, aArchive; - /** Save Button */ - public AppsAction aSave; - /** Private Lock Button */ - public AppsAction aLock; - // Local (added to toolbar) - private AppsAction aReport, aEnd, aHome, aHelp, aProduct, aLogout, - aAccount, aCalculator, aCalendar, aEditor, aPreference, aScript, - aOnline, aMailSupport, aAbout, aPrintScr, aScrShot, aExit, aBPartner, aDeleteSelection; - - - /************************************************************************** - * Create Menu and Toolbar and registers keyboard actions. - * - started from constructor - */ - private void createMenu() - { - /** - * Menu - */ - // menuBar.setHelpMenu(); - // File - JMenu mFile = AEnv.getMenu("File"); - menuBar.add(mFile); - aPrintScr = addAction("PrintScreen", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), false); - aScrShot = addAction("ScreenShot", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, Event.SHIFT_MASK), false); - aReport = addAction("Report", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), false); - aPrint = addAction("Print", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), false); - mFile.addSeparator(); - aEnd = addAction("End", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.ALT_MASK), false); - aLogout = addAction("Logout", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.SHIFT_MASK+Event.ALT_MASK), false); - aExit = addAction("Exit", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.SHIFT_MASK+Event.ALT_MASK), false); - // Edit - JMenu mEdit = AEnv.getMenu("Edit"); - menuBar.add(mEdit); - aNew = addAction("New", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), false); - aSave = addAction("Save", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), false); - mEdit.addSeparator(); - aCopy = addAction("Copy", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F2, Event.SHIFT_MASK), false); - aDelete = addAction("Delete", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), false); - aDeleteSelection = addAction("DeleteSelection", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK), false); - aIgnore = addAction("Ignore", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), false); - aRefresh = addAction("Refresh", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), false); - mEdit.addSeparator(); - aFind = addAction("Find", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), true); // toggle - if (m_isPersonalLock) - aLock = addAction("Lock", mEdit, null, true); // toggle - // View - JMenu mView = AEnv.getMenu("View"); - menuBar.add(mView); - aProduct = addAction("InfoProduct", mView, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK), false); - aBPartner = addAction("InfoBPartner", mView, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.SHIFT_MASK+Event.ALT_MASK), false); - if (MRole.getDefault().isShowAcct()) - aAccount = addAction("InfoAccount",mView, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), false); - AEnv.addMenuItem("InfoSchedule", null, null, mView, this); - mView.addSeparator(); - AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); - AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); - AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); - AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); - AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); - AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); - AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); - mView.addSeparator(); - aAttachment = addAction("Attachment", mView, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0), true); // toggle - aChat = addAction("Chat", mView, null, true); // toggle - aHistory = addAction("History", mView, KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0), true); // toggle - mView.addSeparator(); - aMulti = addAction("Multi", mView, KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0), true); // toggle - // Go - JMenu mGo = AEnv.getMenu("Go"); - menuBar.add(mGo); - aFirst = addAction("First", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, Event.ALT_MASK), false); - aPrevious = addAction("Previous", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.ALT_MASK), false); - aNext = addAction("Next", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.ALT_MASK), false); - aLast = addAction("Last", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.ALT_MASK), false); - mGo.addSeparator(); - aParent = addAction("Parent", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.ALT_MASK), false); - aDetail = addAction("Detail", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.ALT_MASK), false); - mGo.addSeparator(); - aZoomAcross = addAction("ZoomAcross", mGo, null, false); - aRequest = addAction("Request", mGo, null, false); - aArchive = addAction("Archive", mGo, null, false); - aHome = addAction("Home", mGo, null, false); - // Tools - JMenu mTools = AEnv.getMenu("Tools"); - menuBar.add(mTools); - aCalculator = addAction("Calculator", mTools, null, false); - aCalendar = addAction("Calendar", mTools, null, false); - aEditor = addAction("Editor", mTools, null, false); - aScript = addAction("Script", mTools, null, false); - if ("Y".equals(Env.getContext(m_ctx, "#SysAdmin"))) // set in DB.loginDB - aWinSize = addAction("WinSize", mTools, null, false); - if (AEnv.isWorkflowProcess()) - aWorkflow = addAction("WorkFlow", mTools, null, false); - if (MRole.getDefault().isShowPreference()) - { - mTools.addSeparator(); - aPreference = addAction("Preference", mTools, null, false); - } - - //Window - AMenu aMenu = (AMenu)Env.getWindow(0); - JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), m_window); - menuBar.add(mWindow); - - // Help - JMenu mHelp = AEnv.getMenu("Help"); - menuBar.add(mHelp); - aHelp = addAction("Help", mHelp, KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), false); - aOnline = addAction("Online", mHelp, null, false); - aMailSupport = addAction("EMailSupport", mHelp, null, false); - aAbout = addAction("About", mHelp, null, false); - - /** - * ToolBar - */ - toolBar.add(aIgnore.getButton()); // ESC - toolBar.addSeparator(); - toolBar.add(aHelp.getButton()); // F1 - toolBar.add(aNew.getButton()); - toolBar.add(aDelete.getButton()); - toolBar.add(aDeleteSelection.getButton()); - toolBar.add(aSave.getButton()); - toolBar.addSeparator(); - toolBar.add(aRefresh.getButton()); // F5 - toolBar.add(aFind.getButton()); - toolBar.add(aAttachment.getButton()); - toolBar.add(aChat.getButton()); - toolBar.add(aMulti.getButton()); - toolBar.addSeparator(); - toolBar.add(aHistory.getButton()); // F9 - toolBar.add(aHome.getButton()); // F10 is Windows Menu Key - toolBar.add(aParent.getButton()); - toolBar.add(aDetail.getButton()); - toolBar.addSeparator(); - toolBar.add(aFirst.getButton()); - toolBar.add(aPrevious.getButton()); - toolBar.add(aNext.getButton()); - toolBar.add(aLast.getButton()); - toolBar.addSeparator(); - toolBar.add(aReport.getButton()); - toolBar.add(aArchive.getButton()); - toolBar.add(aPrint.getButton()); - toolBar.addSeparator(); - if (m_isPersonalLock) - toolBar.add(aLock.getButton()); - toolBar.add(aZoomAcross.getButton()); - if (aWorkflow != null) - toolBar.add(aWorkflow.getButton()); - toolBar.add(aRequest.getButton()); - toolBar.add(aProduct.getButton()); - toolBar.addSeparator(); - toolBar.add(aEnd.getButton()); - // - if (CLogMgt.isLevelAll()) - Util.printActionInputMap(this); - } // createMenu - - - /** - * Add (Toggle) Action to Toolbar and Menu - * @param actionName action name - * @param menu manu - * @param accelerator accelerator - * @param toggle toggle button - * @return AppsAction - */ - private AppsAction addAction (String actionName, JMenu menu, KeyStroke accelerator, boolean toggle) - { - AppsAction action = new AppsAction(actionName, accelerator, toggle); - if (menu != null) - menu.add(action.getMenuItem()); - action.setDelegate(this); - AbstractButton b = action.getButton(); - String s = null; - if (b != null) - s = b.getToolTipText(); - - // Key Strokes - if (accelerator != null) - { - getInputMap(WHEN_IN_FOCUSED_WINDOW).put(accelerator, actionName); - getActionMap().put(actionName, action); - } - // - return action; - } // addAction - - /** - * Return MenuBar - * @return JMenuBar - */ - public JMenuBar getMenuBar() - { - return menuBar; - } // getMenuBar - - /** - * Get Title of Window - * @return String with Title - */ - public String getTitle() - { - if (m_mWorkbench.getWindowCount() > 1) - { - StringBuffer sb = new StringBuffer(); - sb.append(m_mWorkbench.getName()).append(" ") - .append(Env.getContext(m_ctx, "#AD_User_Name")).append("@") - .append(Env.getContext(m_ctx, "#AD_Client_Name")).append(".") - .append(Env.getContext(m_ctx, "#AD_Org_Name")).append(" [") - .append(Env.getContext(m_ctx, "#DB_UID")).append("]"); - return sb.toString(); - } - return Env.getHeader(m_ctx, m_curWindowNo); - } // getTitle - - - private Properties m_ctx; - - /** Workbench Model */ - private GridWorkbench m_mWorkbench; - /** Current MTab */ - private GridTab m_curTab; - /** Current GridController */ - private GridController m_curGC; - /** Current Window Panel */ - private JTabbedPane m_curWinTab = null; - /** Current Window No */ - private int m_curWindowNo; - /** Current Window Panel Index */ - private int m_curTabIndex = -1; - /** Current Tab Order */ - private APanelTab m_curAPanelTab = null; - - /** Dispose active */ - private boolean m_disposing = false; - /** Save Error Message indicator */ - private boolean m_errorDisplayed = false; - /** Only current row flag */ - private boolean m_onlyCurrentRows = true; - /** Number of days to show 0=all */ - private int m_onlyCurrentDays = 0; - /** Process Info */ - private boolean m_isLocked = false; - /** Show Personal Lock */ - private boolean m_isPersonalLock = MRole.getDefault().isPersonalLock(); - /** Last Modifier of Action Event */ - private int m_lastModifiers; - - - /************************************************************************** - * Dynamic Panel Initialization - either single window or workbench. - *
-	 *  either
-	 *  - Workbench tabPanel    (VTabbedPane)
-	 *      - Tab               (GridController)
-	 *  or
-	 *  - Workbench tabPanel    (VTabbedPane)
-	 *      - Window            (VTabbedPane)
-	 *          - Tab           (GridController)
-	 *  
- * tabPanel - * @param AD_Workbench_ID if > 0 this is a workbench, AD_Window_ID ignored - * @param AD_Window_ID if not a workbench, Window ID - * @param query if not a Workbench, Zoom Query - additional SQL where clause - * @return true if Panel is initialized successfully - */ - public boolean initPanel (int AD_Workbench_ID, int AD_Window_ID, MQuery query) - { - log.info("WB=" + AD_Workbench_ID + ", Win=" + AD_Window_ID + ", Query=" + query); - this.setName("APanel" + AD_Window_ID); - - // Single Window - if (AD_Workbench_ID == 0) - m_mWorkbench = new GridWorkbench(m_ctx, AD_Window_ID); - else - // Workbench - { - // m_mWorkbench = new MWorkbench(m_ctx); - // if (!m_mWorkbench.initWorkbench (AD_Workbench_ID)) - // { - // log.log(Level.SEVERE, "APanel.initWindow - No Workbench Model"); - // return false; - // } - // tabPanel.setWorkbench(true); - // tabPanel.addChangeListener(this); - ADialog.warn(0, this, "","Not implemented yet"); - return false; - } - - Dimension windowSize = m_mWorkbench.getWindowSize(); - - /** - * WorkBench Loop - */ - for (int wb = 0; wb < m_mWorkbench.getWindowCount(); wb++) - { - // Get/set WindowNo - m_curWindowNo = Env.createWindowNo (this); // Timing: ca. 1.5 sec - m_mWorkbench.setWindowNo(wb, m_curWindowNo); - // Set AutoCommit for this Window - Env.setAutoCommit(m_ctx, m_curWindowNo, Env.isAutoCommit(m_ctx)); - boolean autoNew = Env.isAutoNew(m_ctx); - Env.setAutoNew(m_ctx, m_curWindowNo, autoNew); - - // Workbench Window - VTabbedPane window = null; - // just one window - if (m_mWorkbench.getWindowCount() == 1) - { - window = tabPanel; - window.setWorkbench(false); - } - else - { - VTabbedPane tp = new VTabbedPane(false); - window = tp; - } - // Window Init - window.addChangeListener(this); - - /** - * Init Model - */ - int wbType = m_mWorkbench.getWindowType(wb); - - /** - * Window - */ - if (wbType == GridWorkbench.TYPE_WINDOW) - { - HashMap includedMap = new HashMap(4); - // - GridWindowVO wVO = AEnv.getMWindowVO(m_curWindowNo, m_mWorkbench.getWindowID(wb), 0); - if (wVO == null) - { - ADialog.error(0, null, "AccessTableNoView", "(No Window Model Info)"); - return false; - } - GridWindow mWindow = new GridWindow (wVO); // Timing: ca. 0.3-1 sec - // Set SO/AutoNew for Window - Env.setContext(m_ctx, m_curWindowNo, "IsSOTrx", mWindow.isSOTrx()); - if (!autoNew && mWindow.isTransaction()) - Env.setAutoNew(m_ctx, m_curWindowNo, true); - m_mWorkbench.setMWindow(wb, mWindow); - if (wb == 0) - m_onlyCurrentRows = mWindow.isTransaction(); // default = only current - if (windowSize == null) - windowSize = mWindow.getWindowSize(); - - /** - * Window Tabs - */ - int tabSize = mWindow.getTabCount(); - boolean goSingleRow = query != null; // Zoom Query - for (int tab = 0; tab < tabSize; tab++) - { - boolean included = false; - // MTab - GridTab gTab = m_mWorkbench.getMWindow(wb).getTab(tab); - // Query first tab - if (tab == 0) - { - // initial user query for single workbench tab - if (m_mWorkbench.getWindowCount() == 1) - { - query = initialQuery (query, gTab); - if (query != null && query.getRecordCount() <= 1) - goSingleRow = true; - } - else if (wb != 0) - // workbench dynamic query for dependent windows - { - query = m_mWorkbench.getQuery(); - } - // Set initial Query on first tab - if (query != null) - { - m_onlyCurrentRows = false; // Query might involve history - gTab.setQuery(query); - } - if (wb == 0) - m_curTab = gTab; - } // query on first tab - - Component tabElement = null; - // GridController - if (gTab.isSortTab()) - { - VSortTab st = new VSortTab(m_curWindowNo, gTab.getAD_Table_ID(), - gTab.getAD_ColumnSortOrder_ID(), gTab.getAD_ColumnSortYesNo_ID()); - st.setTabLevel(gTab.getTabLevel()); - tabElement = st; - } - else // normal tab - { - GridController gc = new GridController(); // Timing: ca. .1 sec - CompiereColor cc = mWindow.getColor(); - if (cc != null) - gc.setBackgroundColor(cc); // set color on Window level - gc.initGrid(gTab, false, m_curWindowNo, this, mWindow); // will set color on Tab level - // Timing: ca. 6-7 sec for first .2 for next - gc.addDataStatusListener(this); - gc.registerESCAction(aIgnore); // register Escape Key - // Set First Tab - if (wb == 0 && tab == 0) - { - m_curGC = gc; - Dimension size = gc.getPreferredSize(); // Screen Sizing - size.width += 4; - size.height += 4; - gc.setPreferredSize(size); - } - tabElement = gc; - // If we have a zoom query, switch to single row - if (tab == 0 && goSingleRow) - gc.switchSingleRow(); - - // Store GC if it has a included Tab - if (gTab.getIncluded_Tab_ID() != 0) - includedMap.put(new Integer(gTab.getIncluded_Tab_ID()), gc); - - // Is this tab included? - if (includedMap.size() > 0) - { - GridController parent = (GridController)includedMap.get(new Integer(gTab.getAD_Tab_ID())); - if (parent != null) - { - included = parent.includeTab(gc); - if (!included) - log.log(Level.SEVERE, "Not Included = " + gc); - } - } - } // normal tab - - if (!included) // Add to TabbedPane - { - StringBuffer tabName = new StringBuffer (); - tabName.append (""); - if (gTab.isReadOnly()) - tabName.append(""); - int pos = gTab.getName ().indexOf (" "); - if (pos == -1) - tabName.append (gTab.getName ()).append ("
 "); - else - { - tabName.append (gTab.getName().substring (0, pos)) - .append ("
") - .append (gTab.getName().substring(pos + 1)); - } - if (gTab.isReadOnly()) - tabName.append("
"); - tabName.append (""); - // Add Tab - sets ALT- and Shift-ALT- - window.addTab (tabName.toString(), gTab, tabElement); - } - } // Tab Loop - // Tab background - // window.setBackgroundColor(new AdempiereColor(Color.magenta, Color.green)); - } // Type-MWindow - - // Single Workbench Window Tab - if (m_mWorkbench.getWindowCount() == 1) - { - window.setToolTipText(m_mWorkbench.getDescription(wb)); - } - else - // Add Workbench Window Tab - { - tabPanel.addTab(m_mWorkbench.getName(wb), m_mWorkbench.getIcon(wb), window, m_mWorkbench.getDescription(wb)); - } - // Used for Env.getHeader - Env.setContext(m_ctx, m_curWindowNo, "WindowName", m_mWorkbench.getName(wb)); - - } // Workbench Loop - - // stateChanged (<->) triggered - toolBar.setName(getTitle()); - m_curTab.getTableModel().setChanged(false); - // Set Detail Button - aDetail.setEnabled(0 != m_curWinTab.getTabCount()-1); - - // Enable/Disable Tabs dynamically - if (m_curWinTab instanceof VTabbedPane) - ((VTabbedPane)m_curWinTab).evaluate(null); - // Size - if (windowSize != null) - setPreferredSize(windowSize); - Dimension size = getPreferredSize(); - log.info( "fini - " + size); - m_curWinTab.requestFocusInWindow(); - return true; - } // initPanel - - /** - * Get Current Window No - * @return win no - */ - public int getWindowNo() - { - return m_curWindowNo; - } // getWindowNo - - /** - * Initial Query - * @param query initial query - * @param mTab tab - * @return query or null - */ - private MQuery initialQuery (MQuery query, GridTab mTab) - { - // We have a (Zoom) query - if (query != null && query.isActive() && query.getRecordCount() < 10) - return query; - // - StringBuffer where = new StringBuffer(); - // Query automatically if high volume and no query - boolean require = mTab.isHighVolume(); - if (!require && !m_onlyCurrentRows) // No Trx Window - { - String wh1 = mTab.getWhereExtended(); - if (wh1 == null || wh1.length() == 0) - wh1 = mTab.getWhereClause(); - if (wh1 != null && wh1.length() > 0) - where.append(wh1); - // - if (query != null) - { - String wh2 = query.getWhereClause(); - if (wh2.length() > 0) - { - if (where.length() > 0) - where.append (" AND "); - where.append(wh2); - } - } - // - StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM ") - .append(mTab.getTableName()); - if (where.length() > 0) - sql.append(" WHERE ").append(where); - // Does not consider security - int no = DB.getSQLValue(null, sql.toString()); - // - require = MRole.getDefault().isQueryRequire(no); - } - // Show Query - if (require) - { - GridField[] findFields = mTab.getFields(); - Find find = new Find (Env.getFrame(this), m_curWindowNo, mTab.getName(), - mTab.getAD_Table_ID(), mTab.getTableName(), - where.toString(), findFields, 10); // no query below 10 - query = find.getQuery(); - find = null; - } - return query; - } // initialQuery - - - /** - * Get Window Index - * @return Window Index - */ - private int getWindowIndex() - { - // only one window - if (m_mWorkbench.getWindowCount() == 1) - return 0; - // workbench - return tabPanel.getSelectedIndex(); - } // getWindowIndex - - /** - * Is first Tab (on Window) - * @return true if the panel displays the first tab - */ - private boolean isFirstTab() - { - return m_curWinTab.getSelectedIndex() == 0; - } // isFirstTab - - /** - * Get Window Image - * @return image or null - */ - public Image getImage() - { - return m_mWorkbench.getImage(getWindowIndex()); - } // getImage - - - /************************************************************************** - * Data Status Listener (row change) ^ | v - * @param e event - */ - public void dataStatusChanged (DataStatusEvent e) - { - if (m_disposing) - return; - log.info(e.getMessage()); - String dbInfo = e.getMessage(); - if (m_curTab != null && m_curTab.isQueryActive()) - dbInfo = "[ " + dbInfo + " ]"; - statusBar.setStatusDB(dbInfo, e); - - // Set Message / Info - if (e.getAD_Message() != null || e.getInfo() != null) - { - StringBuffer sb = new StringBuffer(); - String msg = e.getMessage(); - if (msg != null && msg.length() > 0) - sb.append(Msg.getMsg(m_ctx, e.getAD_Message())); - String info = e.getInfo(); - if (info != null && info.length() > 0) - { - if (sb.length() > 0 && !sb.toString().trim().endsWith(":")) - sb.append(": "); - sb.append(info); - } - if (sb.length() > 0) - { - int pos = sb.indexOf("\n"); - if (pos != -1) // replace CR/NL - sb.replace(pos, pos+1, " - "); - setStatusLine (sb.toString (), e.isError ()); - } - } - - // Confirm Error - if (e.isError() && !e.isConfirmed()) - { - ADialog.error(m_curWindowNo, this, e.getAD_Message(), e.getInfo()); - e.setConfirmed(true); // show just once - if MTable.setCurrentRow is involved the status event is re-issued - m_errorDisplayed = true; - } - // Confirm Warning - else if (e.isWarning() && !e.isConfirmed()) - { - ADialog.warn(m_curWindowNo, this, e.getAD_Message(), e.getInfo()); - e.setConfirmed(true); // show just once - if MTable.setCurrentRow is involved the status event is re-issued - } - - // update Navigation - boolean firstRow = e.isFirstRow(); - aFirst.setEnabled(!firstRow); - aPrevious.setEnabled(!firstRow); - boolean lastRow = e.isLastRow(); - aNext.setEnabled(!lastRow); - aLast.setEnabled(!lastRow); - - // update Change - boolean changed = e.isChanged() || e.isInserting(); - boolean readOnly = m_curTab.isReadOnly(); - boolean insertRecord = !readOnly; - if (insertRecord) - insertRecord = m_curTab.isInsertRecord(); - aNew.setEnabled(!changed && insertRecord); - aCopy.setEnabled(!changed && insertRecord); - aRefresh.setEnabled(!changed); - aDelete.setEnabled(!changed && !readOnly); - // - if (readOnly && m_curTab.isAlwaysUpdateField()) - readOnly = false; - aIgnore.setEnabled(changed && !readOnly); - aSave.setEnabled(changed && !readOnly); - // - // No Rows - if (e.getTotalRows() == 0 && insertRecord) { - aNew.setEnabled(true); - aDelete.setEnabled(false); - aDeleteSelection.setEnabled(false); - } else { - aDeleteSelection.setEnabled(true); - } - - // Single-Multi - aMulti.setPressed(!m_curGC.isSingleRow()); - - // History (on first Tab only) - if (isFirstTab()) - aHistory.setPressed(!m_curTab.isOnlyCurrentRows()); - - // Transaction info - String trxInfo = m_curTab.getTrxInfo(); - if (trxInfo != null) - statusBar.setInfo(trxInfo); - - // Check Attachment - boolean canHaveAttachment = m_curTab.canHaveAttachment(); // not single _ID column - // - if (canHaveAttachment && e.isLoading() && m_curTab.getCurrentRow() > e.getLoadedRows()) - canHaveAttachment = false; - if (canHaveAttachment && m_curTab.getRecord_ID() == -1) // No Key - canHaveAttachment = false; - if (canHaveAttachment) - { - aAttachment.setEnabled(true); - aAttachment.setPressed(m_curTab.hasAttachment()); - aChat.setEnabled(true); - aChat.setPressed(m_curTab.hasChat()); - } - else - { - aAttachment.setEnabled(false); - aChat.setEnabled(false); - } - // Lock Indicator - if (m_isPersonalLock) - aLock.setPressed(m_curTab.isLocked()); - - if (m_curWinTab instanceof VTabbedPane) - ((VTabbedPane)m_curWinTab).evaluate(e); - // log.info("- fini", e.getMessage()); - } // dataStatusChanged - - /** - * Set Status Line to text - * @param text clear text - * @param error error flag - */ - public void setStatusLine (String text, boolean error) - { - log.fine(text); - statusBar.setStatusLine(text, error); - } // setStatusLine - - /** - * Indicate Busy - * @param busy busy - * @param focus request focus - */ - private void setBusy (boolean busy, boolean focus) - { - m_isLocked = busy; - // - JFrame frame = Env.getFrame(this); - if (frame == null) // during init - return; - if (frame instanceof AWindow) - ((AWindow)frame).setBusy(busy); - // String processing = Msg.getMsg(m_ctx, "Processing"); - if (busy) - { - // setStatusLine(processing); - this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } - else - { - this.setCursor(Cursor.getDefaultCursor()); - frame.setCursor(Cursor.getDefaultCursor()); - if (focus) - m_curGC.requestFocus(); - // if (statusBar.getStatusLine().equals(processing)) - // statusBar.setStatusLine(""); - } - } // set Busy - - - /************************************************************************** - * Change Listener - (tab change) <-> - * @param e event - */ - public void stateChanged (ChangeEvent e) - { - if (m_disposing) - return; - log.info(e.toString()); - setBusy(true, true); - - VTabbedPane tp = (VTabbedPane)e.getSource(); - boolean back = false; - boolean isAPanelTab = false; - - int previousIndex = 0; - - // Workbench Tab Change - if (tp.isWorkbench()) - { - int WBIndex = tabPanel.getSelectedIndex(); - m_curWindowNo = m_mWorkbench.getWindowNo(WBIndex); - // Window Change - log.info("curWin=" + m_curWindowNo + " - Win=" + tp); - if (tp.getSelectedComponent() instanceof JTabbedPane) - m_curWinTab = (JTabbedPane)tp.getSelectedComponent(); - else - throw new java.lang.IllegalArgumentException("Window does not contain Tabs"); - if (m_curWinTab.getSelectedComponent() instanceof GridController) - m_curGC = (GridController)m_curWinTab.getSelectedComponent(); - // else if (m_curWinTab.getSelectedComponent() instanceof APanelTab) - // isAPanelTab = true; - else - throw new java.lang.IllegalArgumentException("Window-Tab does not contain GridControler"); - // change pointers - m_curTabIndex = m_curWinTab.getSelectedIndex(); - } - else - { - // Just a Tab Change - log.info("Tab=" + tp); - m_curWinTab = tp; - int tpIndex = m_curWinTab.getSelectedIndex(); - // detect no tab change - if (tpIndex == m_curTabIndex) return; - back = tpIndex < m_curTabIndex; - GridController gc = null; - if (m_curWinTab.getSelectedComponent() instanceof GridController) - gc = (GridController)m_curWinTab.getSelectedComponent(); - else if (m_curWinTab.getSelectedComponent() instanceof APanelTab) - isAPanelTab = true; - else - throw new java.lang.IllegalArgumentException("Tab does not contain GridControler"); - // Save old Tab - if (m_curGC != null) - { - m_curGC.stopEditor(true); - // has anything changed? - if (m_curTab.needSave(true, false)) - { // do we have real change - if (m_curTab.needSave(true, true)) - { - // Automatic Save - if (Env.isAutoCommit(m_ctx, m_curWindowNo)) - { - if (!m_curTab.dataSave(true)) - { // there is a problem, so we go back - m_curWinTab.setSelectedIndex(m_curTabIndex); - setBusy(false, true); - return; - } - } - // explicitly ask when changing tabs - else if (ADialog.ask(m_curWindowNo, this, "SaveChanges?", m_curTab.getCommitWarning())) - { // yes we want to save - if (!m_curTab.dataSave(true)) - { // there is a problem, so we go back - m_curWinTab.setSelectedIndex(m_curTabIndex); - setBusy(false, true); - return; - } - } - else // Don't save - m_curTab.dataIgnore(); - } - else // new record, but nothing changed - m_curTab.dataIgnore(); - } // there is a change - } - if (m_curAPanelTab != null) - { - m_curAPanelTab.saveData(); - m_curAPanelTab.unregisterPanel(); - m_curAPanelTab = null; - } - - // new tab - // if (m_curTabIndex >= 0) - // m_curWinTab.setForegroundAt(m_curTabIndex, AdempierePLAF.getTextColor_Normal()); - // m_curWinTab.setForegroundAt(tpIndex, AdempierePLAF.getTextColor_OK()); - previousIndex = m_curTabIndex; - m_curTabIndex = tpIndex; - if (!isAPanelTab) - m_curGC = gc; - } - - // Sort Tab Handling - if (isAPanelTab) - { - m_curAPanelTab = (APanelTab)m_curWinTab.getSelectedComponent(); - m_curAPanelTab.registerAPanel(this); - m_curAPanelTab.loadData(); - } - else // Cur Tab Setting - { - m_curGC.activate(); - m_curTab = m_curGC.getMTab(); - - // Refresh only current row when tab is current - if (back && m_curTab.isCurrent()) - m_curTab.dataRefresh(); - else // Requery & autoSize - { - MRole role = MRole.getDefault(); - m_curGC.query (m_onlyCurrentRows, m_onlyCurrentDays, role.getMaxQueryRecords()); - if (m_curGC.isNeedToSaveParent()) - { - // there is a problem, so we go back - ADialog.error(m_curWindowNo, this, "SaveParentFirst"); - m_curWinTab.setSelectedIndex(previousIndex); - setBusy(false, true); - return; - } - } - - // Set initial record - if (m_curTab.getRowCount() == 0) - { - // Automatically create New Record, if none & tab not RO - if (!m_curTab.isReadOnly() - && (Env.isAutoNew(m_ctx, m_curWindowNo) || m_curTab.isQueryNewRecord())) - { - log.config("No record - New - AutoNew=" + Env.isAutoNew(m_ctx, m_curWindowNo) - + " - QueryNew=" + m_curTab.isQueryNewRecord()); - m_curTab.dataNew(false); - } - else // No Records found - { - aSave.setEnabled(false); - aDelete.setEnabled(false); - aDeleteSelection.setEnabled(false); - } - m_curTab.navigateCurrent(); // updates counter - m_curGC.dynamicDisplay(0); - } - // else ##CHANGE - // m_curTab.navigateCurrent(); - } - - // Update <-> Navigation - aDetail.setEnabled(m_curTabIndex != m_curWinTab.getTabCount()-1); - aParent.setEnabled(m_curTabIndex != 0 && m_curWinTab.getTabCount() > 1); - - // History (on first tab only) - if (m_mWorkbench.getMWindow(getWindowIndex()).isTransaction()) - aHistory.setEnabled(isFirstTab()); - else - { - aHistory.setPressed(false); - aHistory.setEnabled(false); - } - // Document Print - aPrint.setEnabled(m_curTab.isPrinted()); - // Query - aFind.setPressed(m_curTab.isQueryActive()); - - // Order Tab - if (isAPanelTab) - { - aMulti.setPressed(false); - aMulti.setEnabled(false); - aNew.setEnabled(false); - aDelete.setEnabled(false); - aDeleteSelection.setEnabled(false); - aFind.setEnabled(false); - aRefresh.setEnabled(false); - aAttachment.setEnabled(false); - aChat.setEnabled(false); - } - else // Grid Tab - { - aMulti.setEnabled(true); - aMulti.setPressed(!m_curGC.isSingleRow()); - aFind.setEnabled(true); - aRefresh.setEnabled(true); - aAttachment.setEnabled(true); - aChat.setEnabled(true); - } - // - m_curWinTab.requestFocusInWindow(); - setBusy(false, true); - log.config( "fini"); - } // stateChanged - - /** - * Navigate to Detail Tab -> - */ - private void cmd_detail() - { - int index = m_curWinTab.getSelectedIndex(); - if (index == m_curWinTab.getTabCount()-1) - return; - m_curGC.getTable().removeEditor(); - m_curWinTab.setSelectedIndex(index+1); - } // navigateDetail - - /** - * Navigate to Parent Tab <- - */ - private void cmd_parent() - { - int index = m_curWinTab.getSelectedIndex(); - if (index == 0) - return; - m_curGC.getTable().removeEditor(); - m_curWinTab.setSelectedIndex(index-1); - } // navigateParent - - - /************************************************************************** - * Action Listener - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - log.info(e.getActionCommand() + " - " + e.getModifiers()); - // + " - " + new Timestamp(e.getWhen()) + " " + isUILocked()); - if (m_disposing || isUILocked()) - return; - - m_lastModifiers = e.getModifiers(); - String cmd = e.getActionCommand(); - // Do ScreenShot w/o busy - if (cmd.equals("ScreenShot")) - { - AEnv.actionPerformed (e.getActionCommand(), m_curWindowNo, this); - return; - } - - // Problem: doubleClick detection - can't disable button as clicking button may change button status - setBusy (true, true); - // Command Buttons - if (e.getSource() instanceof VButton) - { - actionButton((VButton)e.getSource()); - setBusy(false, true); - return; - } - - try - { - // File - if (cmd.equals(aReport.getName())) - cmd_report(); - else if (cmd.equals(aPrint.getName())) - cmd_print(); - else if (cmd.equals(aEnd.getName())) - cmd_end(false); - else if (cmd.equals(aExit.getName())) - cmd_end(true); - // Edit - else if (cmd.equals(aNew.getName())) - cmd_new(false); - else if (cmd.equals(aSave.getName())) - cmd_save(true); - else if (cmd.equals(aCopy.getName())) - cmd_new(true); - else if (cmd.equals(aDelete.getName())) - cmd_delete(); - else if (cmd.equals(aDeleteSelection.getName())) - cmd_deleteSelection(); - else if (cmd.equals(aIgnore.getName())) - cmd_ignore(); - else if (cmd.equals(aRefresh.getName())) - cmd_refresh(); - else if (cmd.equals(aFind.getName())) - cmd_find(); - else if (m_isPersonalLock && cmd.equals(aLock.getName())) - cmd_lock(); - // View - else if (cmd.equals(aAttachment.getName())) - cmd_attachment(); - else if (cmd.equals(aChat.getName())) - cmd_chat(); - else if (cmd.equals(aHistory.getName())) - cmd_history(); - else if (cmd.equals(aMulti.getName())) - m_curGC.switchRowPresentation(); - // Go - else if (cmd.equals(aFirst.getName())) - { /*cmd_save(false);*/ - m_curGC.getTable().removeEditor(); - m_curTab.navigate(0); - } - else if (cmd.equals(aPrevious.getName())) - { /*cmd_save(false);*/ - m_curGC.getTable().removeEditor(); - m_curTab.navigateRelative(-1); - } - else if (cmd.equals(aNext.getName())) - { /*cmd_save(false); */ - m_curGC.getTable().removeEditor(); - m_curTab.navigateRelative(+1); - } - else if (cmd.equals(aLast.getName())) - { /*cmd_save(false);*/ - m_curGC.getTable().removeEditor(); - m_curTab.navigate(m_curTab.getRowCount()-1); - } - else if (cmd.equals(aParent.getName())) - cmd_parent(); - else if (cmd.equals(aDetail.getName())) - cmd_detail(); - else if (cmd.equals(aZoomAcross.getName())) - cmd_zoomAcross(); - else if (cmd.equals(aRequest.getName())) - cmd_request(); - else if (cmd.equals(aArchive.getName())) - cmd_archive(); - // Tools - else if (aWorkflow != null && cmd.equals(aWorkflow.getName())) - { - if (m_curTab.getRecord_ID() <= 0) - ; - else if (m_curTab.getTabNo() == 0 && m_mWorkbench.getMWindow(getWindowIndex()).isTransaction()) - AEnv.startWorkflowProcess(m_curTab.getAD_Table_ID(), m_curTab.getRecord_ID()); - else - AEnv.startWorkflowProcess(m_curTab.getAD_Table_ID(), m_curTab.getRecord_ID()); - } - else if (aWinSize != null && cmd.equals(aWinSize.getName())) - cmd_winSize(); - // Help - else if (cmd.equals(aHelp.getName())) - cmd_help(); - // General Commands (Environment) - else if (cmd.equals(aLogout.getName())) - cmd_logout(); - else if (!AEnv.actionPerformed (e.getActionCommand(), m_curWindowNo, this)) - log.log(Level.SEVERE, "No action for: " + cmd); - } - catch (Exception ex) - { - log.log(Level.SEVERE, cmd, ex); - String msg = ex.getMessage(); - if (msg == null || msg.length() == 0) - msg = ex.toString(); - msg = Msg.parseTranslation(m_ctx, msg); - ADialog.error(m_curWindowNo, this, "Error", msg); - } - // - m_curWinTab.requestFocusInWindow(); - setBusy(false, true); - } // actionPerformed - - private void cmd_logout() { - JFrame top = Env.getWindow(0); - if (top instanceof AMenu) { - ((AMenu)top).logout(); - } - - } - - - /** - * Create New Record - * @param copy true if current record is to be copied - */ - private void cmd_new (boolean copy) - { - log.config("copy=" + copy); - if (!m_curTab.isInsertRecord()) - { - log.warning("Insert Record disabled for Tab"); - return; - } - cmd_save(false); - m_curTab.dataNew (copy); - m_curGC.dynamicDisplay(0); - // m_curTab.getTableModel().setChanged(false); - } // cmd_new - - /** - * Confirm & delete record - */ - private void cmd_delete() - { - if (m_curTab.isReadOnly()) - return; - int keyID = m_curTab.getRecord_ID(); - if (ADialog.ask(m_curWindowNo, this, "DeleteRecord?")) - if (m_curTab.dataDelete()) - m_curGC.rowChanged(false, keyID); - m_curGC.dynamicDisplay(0); - } // cmd_delete - - /** - * Show a list to select one or more items to delete. - */ - private void cmd_deleteSelection(){ - if (m_curTab.isReadOnly()) - return; - //show table with deletion rows -> value, name... - JPanel messagePanel = new JPanel(); - JList list = new JList(); - JScrollPane scrollPane = new JScrollPane(list); - Vector data = new Vector(); - int noOfRows = m_curTab.getRowCount(); - for(int i=0; i" + vButton.getText() + "
" + - vButton.getDescription() + "\n" + vButton.getHelp())) - return; - // - String title = vButton.getDescription(); - if (title == null || title.length() == 0) - title = vButton.getName(); - ProcessInfo pi = new ProcessInfo (title, vButton.getProcess_ID(), table_ID, record_ID); - pi.setAD_User_ID (Env.getAD_User_ID(m_ctx)); - pi.setAD_Client_ID (Env.getAD_Client_ID(m_ctx)); - pi.setIsBatch(batch); - - // Trx trx = Trx.get(Trx.createTrxName("AppsPanel"), true); - ProcessCtl.process(this, m_curWindowNo, pi, null); // calls lockUI, unlockUI - } // actionButton - - - /************************************************************************** - * Lock User Interface. - * Called from the Worker before processing - * @param pi process info - */ - public void lockUI (ProcessInfo pi) - { - // log.fine("" + pi); - setBusy(true, false); - } // lockUI - - /** - * Unlock User Interface. - * Called from the Worker when processing is done - * @param pi of execute ASync call - */ - public void unlockUI (ProcessInfo pi) - { - // log.fine("" + pi); - boolean notPrint = pi != null - && pi.getAD_Process_ID() != m_curTab.getAD_Process_ID(); - // - setBusy(false, notPrint); - // Process Result - if (notPrint) // refresh if not print - { - // Refresh data - m_curTab.dataRefresh(); - // Timeout - if (pi.isTimeout()) // set temporarily to R/O - Env.setContext(m_ctx, m_curWindowNo, "Processed", "Y"); - m_curGC.dynamicDisplay(0); - // Update Status Line - setStatusLine(pi.getSummary(), pi.isError()); - // Get Log Info - ProcessInfoUtil.setLogFromDB(pi); - String logInfo = pi.getLogInfo(); - if (logInfo.length() > 0) - ADialog.info(m_curWindowNo, this, Env.getHeader(m_ctx, m_curWindowNo), - pi.getTitle(), logInfo); // clear text - } - } // unlockUI - - /** - * Is the UI locked (Internal method) - * @return true, if UI is locked - */ - public boolean isUILocked() - { - return m_isLocked; - } // isLoacked - - /** - * Method to be executed async. - * Called from the ASyncProcess worker - * @param pi process info - */ - public void executeASync (ProcessInfo pi) - { - log.config("-"); - } // executeASync - - /** - * Get Current Tab - * @return current tab - */ - protected GridTab getCurrentTab() - { - return m_curTab; - } // getCurrentTab - - /** - * String representation - * @return String representation - */ - public String toString() - { - String s = "APanel[curWindowNo=" + m_curWindowNo; - if (m_mWorkbench != null) - s += ",WB=" + m_mWorkbench.toString(); - s += "]"; - return s; - } // toString - -} // APanel \ No newline at end of file +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; +import javax.swing.event.*; +import org.compiere.apps.search.*; +import org.compiere.grid.*; +import org.compiere.grid.ed.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.print.*; +import org.compiere.process.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Main Application Panel. + *
+ *  Structure:
+ *      (MenuBar) -> to be added to owning window
+ *		northPanel  (ToolBar)
+ *		tabPanel
+ *		southPanel  (StatusBar)
+ *  
+ * + * @author Jorg Janke + * @version $Id: APanel.java,v 1.4 2006/07/30 00:51:27 jjanke Exp $ + */ +public final class APanel extends CPanel + implements DataStatusListener, ChangeListener, ActionListener, ASyncProcess +{ + /** + * Constructs a new instance. + * Need to call initPanel for dynamic initialization + */ + public APanel() + { + super(); + m_ctx = Env.getCtx(); + // + try + { + jbInit(); + } + catch (Exception e) + { + log.log(Level.SEVERE, "", e); + } + createMenu(); + } // APanel + + /** Logger */ + private static CLogger log = CLogger.getCLogger(APanel.class); + + /** + * Dispose + */ + public void dispose() + { + // log.config(""); + // ignore changes + m_disposing = true; + // + if (m_curAPanelTab != null) + { + m_curAPanelTab.unregisterPanel(); + m_curAPanelTab = null; + } + // close panels + tabPanel.dispose(this); + tabPanel = null; + // All Workbenches + for (int i = 0; i < m_mWorkbench.getWindowCount(); i++) + { + m_curWindowNo = m_mWorkbench.getWindowNo(i); + log.info("#" + m_curWindowNo); + Env.setAutoCommit(m_ctx, m_curWindowNo, false); + m_mWorkbench.dispose(i); + Env.clearWinContext(m_ctx, m_curWindowNo); + } // all Workbenchens + + // Get rid of remaining model + if (m_mWorkbench != null) + m_mWorkbench.dispose(); + m_mWorkbench = null; + // MenuBar + if (menuBar != null) + menuBar.removeAll(); + menuBar = null; + // ToolBar + if (toolBar != null) + toolBar.removeAll(); + toolBar = null; + // Prepare GC + this.removeAll(); + } // dispose + + /** + * The Layout. + */ + private BorderLayout mainLayout = new BorderLayout(); + private VTabbedPane tabPanel = new VTabbedPane(true); + private StatusBar statusBar = new StatusBar(); + private CPanel northPanel = new CPanel(); + private JToolBar toolBar = new JToolBar(); + private JMenuBar menuBar = new JMenuBar(); + private FlowLayout northLayout = new FlowLayout(); + + /** + * Initializes the state of this instance. + * @throws Exception + */ + private void jbInit() throws Exception + { + this.setLocale(Language.getLoginLanguage().getLocale()); + this.setLayout(mainLayout); + + // tabPanel + mainLayout.setHgap(2); + mainLayout.setVgap(2); + this.add(tabPanel, BorderLayout.CENTER); + // southPanel + this.add(statusBar, BorderLayout.SOUTH); + // northPanel + this.add(northPanel, BorderLayout.NORTH); + northPanel.setLayout(northLayout); + northLayout.setAlignment(FlowLayout.LEFT); + northPanel.add(toolBar, null); + } // jbInit + + private AppsAction aPrevious, aNext, aParent, aDetail, aFirst, aLast, + aNew, aCopy, aDelete, aIgnore, aPrint, + aRefresh, aHistory, aAttachment, aChat, aMulti, aFind, + aWorkflow, aZoomAcross, aRequest, aWinSize, aArchive; + /** Save Button */ + public AppsAction aSave; + /** Private Lock Button */ + public AppsAction aLock; + // Local (added to toolbar) + private AppsAction aReport, aEnd, aHome, aHelp, aProduct, aLogout, + aAccount, aCalculator, aCalendar, aEditor, aPreference, aScript, + aOnline, aMailSupport, aAbout, aPrintScr, aScrShot, aExit, aBPartner, aDeleteSelection; + + + /************************************************************************** + * Create Menu and Toolbar and registers keyboard actions. + * - started from constructor + */ + private void createMenu() + { + /** + * Menu + */ + // menuBar.setHelpMenu(); + // File + JMenu mFile = AEnv.getMenu("File"); + menuBar.add(mFile); + aPrintScr = addAction("PrintScreen", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), false); + aScrShot = addAction("ScreenShot", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, Event.SHIFT_MASK), false); + aReport = addAction("Report", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), false); + aPrint = addAction("Print", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), false); + mFile.addSeparator(); + aEnd = addAction("End", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.ALT_MASK), false); + aExit = addAction("Exit", mFile, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.SHIFT_MASK+Event.ALT_MASK), false); + // Edit + JMenu mEdit = AEnv.getMenu("Edit"); + menuBar.add(mEdit); + aNew = addAction("New", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), false); + aSave = addAction("Save", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), false); + mEdit.addSeparator(); + aCopy = addAction("Copy", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F2, Event.SHIFT_MASK), false); + aDelete = addAction("Delete", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), false); + aDeleteSelection = addAction("DeleteSelection", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK), false); + aIgnore = addAction("Ignore", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), false); + aRefresh = addAction("Refresh", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), false); + mEdit.addSeparator(); + aFind = addAction("Find", mEdit, KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), true); // toggle + if (m_isPersonalLock) + aLock = addAction("Lock", mEdit, null, true); // toggle + // View + JMenu mView = AEnv.getMenu("View"); + menuBar.add(mView); + aProduct = addAction("InfoProduct", mView, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK), false); + aBPartner = addAction("InfoBPartner", mView, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.SHIFT_MASK+Event.ALT_MASK), false); + if (MRole.getDefault().isShowAcct()) + aAccount = addAction("InfoAccount",mView, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), false); + AEnv.addMenuItem("InfoSchedule", null, null, mView, this); + mView.addSeparator(); + AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); + AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); + AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); + AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); + AEnv.addMenuItem("InfoCashLine", "Info", null, mView, this); + AEnv.addMenuItem("InfoAssignment", "Info", null, mView, this); + AEnv.addMenuItem("InfoAsset", "Info", null, mView, this); + mView.addSeparator(); + aAttachment = addAction("Attachment", mView, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0), true); // toggle + aChat = addAction("Chat", mView, null, true); // toggle + aHistory = addAction("History", mView, KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0), true); // toggle + mView.addSeparator(); + aMulti = addAction("Multi", mView, KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0), true); // toggle + // Go + JMenu mGo = AEnv.getMenu("Go"); + menuBar.add(mGo); + aFirst = addAction("First", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, Event.ALT_MASK), false); + aPrevious = addAction("Previous", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_UP, Event.ALT_MASK), false); + aNext = addAction("Next", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Event.ALT_MASK), false); + aLast = addAction("Last", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, Event.ALT_MASK), false); + mGo.addSeparator(); + aParent = addAction("Parent", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Event.ALT_MASK), false); + aDetail = addAction("Detail", mGo, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Event.ALT_MASK), false); + mGo.addSeparator(); + aZoomAcross = addAction("ZoomAcross", mGo, null, false); + aRequest = addAction("Request", mGo, null, false); + aArchive = addAction("Archive", mGo, null, false); + aHome = addAction("Home", mGo, null, false); + // Tools + JMenu mTools = AEnv.getMenu("Tools"); + menuBar.add(mTools); + aCalculator = addAction("Calculator", mTools, null, false); + aCalendar = addAction("Calendar", mTools, null, false); + aEditor = addAction("Editor", mTools, null, false); + aScript = addAction("Script", mTools, null, false); + if ("Y".equals(Env.getContext(m_ctx, "#SysAdmin"))) // set in DB.loginDB + aWinSize = addAction("WinSize", mTools, null, false); + if (AEnv.isWorkflowProcess()) + aWorkflow = addAction("WorkFlow", mTools, null, false); + if (MRole.getDefault().isShowPreference()) + { + mTools.addSeparator(); + aPreference = addAction("Preference", mTools, null, false); + } + // Help + JMenu mHelp = AEnv.getMenu("Help"); + menuBar.add(mHelp); + aHelp = addAction("Help", mHelp, KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), false); + aOnline = addAction("Online", mHelp, null, false); + aMailSupport = addAction("EMailSupport", mHelp, null, false); + aAbout = addAction("About", mHelp, null, false); + + /** + * ToolBar + */ + toolBar.add(aIgnore.getButton()); // ESC + toolBar.addSeparator(); + toolBar.add(aHelp.getButton()); // F1 + toolBar.add(aNew.getButton()); + toolBar.add(aDelete.getButton()); + toolBar.add(aDeleteSelection.getButton()); + toolBar.add(aSave.getButton()); + toolBar.addSeparator(); + toolBar.add(aRefresh.getButton()); // F5 + toolBar.add(aFind.getButton()); + toolBar.add(aAttachment.getButton()); + toolBar.add(aChat.getButton()); + toolBar.add(aMulti.getButton()); + toolBar.addSeparator(); + toolBar.add(aHistory.getButton()); // F9 + toolBar.add(aHome.getButton()); // F10 is Windows Menu Key + toolBar.add(aParent.getButton()); + toolBar.add(aDetail.getButton()); + toolBar.addSeparator(); + toolBar.add(aFirst.getButton()); + toolBar.add(aPrevious.getButton()); + toolBar.add(aNext.getButton()); + toolBar.add(aLast.getButton()); + toolBar.addSeparator(); + toolBar.add(aReport.getButton()); + toolBar.add(aArchive.getButton()); + toolBar.add(aPrint.getButton()); + toolBar.addSeparator(); + if (m_isPersonalLock) + toolBar.add(aLock.getButton()); + toolBar.add(aZoomAcross.getButton()); + if (aWorkflow != null) + toolBar.add(aWorkflow.getButton()); + toolBar.add(aRequest.getButton()); + toolBar.add(aProduct.getButton()); + toolBar.addSeparator(); + toolBar.add(aEnd.getButton()); + // + if (CLogMgt.isLevelAll()) + Util.printActionInputMap(this); + } // createMenu + + + /** + * Add (Toggle) Action to Toolbar and Menu + * @param actionName action name + * @param menu manu + * @param accelerator accelerator + * @param toggle toggle button + * @return AppsAction + */ + private AppsAction addAction (String actionName, JMenu menu, KeyStroke accelerator, boolean toggle) + { + AppsAction action = new AppsAction(actionName, accelerator, toggle); + if (menu != null) + menu.add(action.getMenuItem()); + action.setDelegate(this); + // AbstractButton b = action.getButton(); + // String s = null; + // if (b != null) + // s = b.getToolTipText(); + + // Key Strokes + if (accelerator != null) + { + getInputMap(WHEN_IN_FOCUSED_WINDOW).put(accelerator, actionName); + getActionMap().put(actionName, action); + } + // + return action; + } // addAction + + /** + * Return MenuBar + * @return JMenuBar + */ + public JMenuBar getMenuBar() + { + return menuBar; + } // getMenuBar + + /** + * Get Title of Window + * @return String with Title + */ + public String getTitle() + { + if (m_mWorkbench.getWindowCount() > 1) + { + StringBuffer sb = new StringBuffer(); + sb.append(m_mWorkbench.getName()).append(" ") + .append(Env.getContext(m_ctx, "#AD_User_Name")).append("@") + .append(Env.getContext(m_ctx, "#AD_Client_Name")).append(".") + .append(Env.getContext(m_ctx, "#AD_Org_Name")).append(" [") + .append(Env.getContext(m_ctx, "#DB_UID")).append("]"); + return sb.toString(); + } + return Env.getHeader(m_ctx, m_curWindowNo); + } // getTitle + + + private Properties m_ctx; + + /** Workbench Model */ + private GridWorkbench m_mWorkbench; + /** Current MTab */ + private GridTab m_curTab; + /** Current GridController */ + private GridController m_curGC; + /** Current Window Panel */ + private JTabbedPane m_curWinTab = null; + /** Current Window No */ + private int m_curWindowNo; + /** Current Window Panel Index */ + private int m_curTabIndex = -1; + /** Current Tab Order */ + private APanelTab m_curAPanelTab = null; + + /** Dispose active */ + private boolean m_disposing = false; + /** Save Error Message indicator */ + private boolean m_errorDisplayed = false; + /** Only current row flag */ + private boolean m_onlyCurrentRows = true; + /** Number of days to show 0=all */ + private int m_onlyCurrentDays = 0; + /** Process Info */ + private boolean m_isLocked = false; + /** Show Personal Lock */ + private boolean m_isPersonalLock = MRole.getDefault().isPersonalLock(); + /** Last Modifier of Action Event */ + private int m_lastModifiers; + + + /************************************************************************** + * Dynamic Panel Initialization - either single window or workbench. + *
+	 *  either
+	 *  - Workbench tabPanel    (VTabbedPane)
+	 *      - Tab               (GridController)
+	 *  or
+	 *  - Workbench tabPanel    (VTabbedPane)
+	 *      - Window            (VTabbedPane)
+	 *          - Tab           (GridController)
+	 *  
+ * tabPanel + * @param AD_Workbench_ID if > 0 this is a workbench, AD_Window_ID ignored + * @param AD_Window_ID if not a workbench, Window ID + * @param query if not a Workbench, Zoom Query - additional SQL where clause + * @return true if Panel is initialized successfully + */ + public boolean initPanel (int AD_Workbench_ID, int AD_Window_ID, MQuery query) + { + log.info("WB=" + AD_Workbench_ID + ", Win=" + AD_Window_ID + ", Query=" + query); + this.setName("APanel" + AD_Window_ID); + + // Single Window + if (AD_Workbench_ID == 0) + m_mWorkbench = new GridWorkbench(m_ctx, AD_Window_ID); + else + // Workbench + { + // m_mWorkbench = new MWorkbench(m_ctx); + // if (!m_mWorkbench.initWorkbench (AD_Workbench_ID)) + // { + // log.log(Level.SEVERE, "APanel.initWindow - No Workbench Model"); + // return false; + // } + // tabPanel.setWorkbench(true); + // tabPanel.addChangeListener(this); + ADialog.warn(0, this, "","Not implemented yet"); + return false; + } + + Dimension windowSize = m_mWorkbench.getWindowSize(); + + /** + * WorkBench Loop + */ + for (int wb = 0; wb < m_mWorkbench.getWindowCount(); wb++) + { + // Get/set WindowNo + m_curWindowNo = Env.createWindowNo (this); // Timing: ca. 1.5 sec + m_mWorkbench.setWindowNo(wb, m_curWindowNo); + // Set AutoCommit for this Window + Env.setAutoCommit(m_ctx, m_curWindowNo, Env.isAutoCommit(m_ctx)); + boolean autoNew = Env.isAutoNew(m_ctx); + Env.setAutoNew(m_ctx, m_curWindowNo, autoNew); + + // Workbench Window + VTabbedPane window = null; + // just one window + if (m_mWorkbench.getWindowCount() == 1) + { + window = tabPanel; + window.setWorkbench(false); + } + else + { + VTabbedPane tp = new VTabbedPane(false); + window = tp; + } + // Window Init + window.addChangeListener(this); + + /** + * Init Model + */ + int wbType = m_mWorkbench.getWindowType(wb); + + /** + * Window + */ + if (wbType == GridWorkbench.TYPE_WINDOW) + { + HashMap includedMap = new HashMap(4); + // + GridWindowVO wVO = AEnv.getMWindowVO(m_curWindowNo, m_mWorkbench.getWindowID(wb), 0); + if (wVO == null) + { + ADialog.error(0, null, "AccessTableNoView", "(No Window Model Info)"); + return false; + } + GridWindow mWindow = new GridWindow (wVO); // Timing: ca. 0.3-1 sec + // Set SO/AutoNew for Window + Env.setContext(m_ctx, m_curWindowNo, "IsSOTrx", mWindow.isSOTrx()); + if (!autoNew && mWindow.isTransaction()) + Env.setAutoNew(m_ctx, m_curWindowNo, true); + m_mWorkbench.setMWindow(wb, mWindow); + if (wb == 0) + m_onlyCurrentRows = mWindow.isTransaction(); // default = only current + if (windowSize == null) + windowSize = mWindow.getWindowSize(); + + /** + * Window Tabs + */ + int tabSize = mWindow.getTabCount(); + boolean goSingleRow = query != null; // Zoom Query + for (int tab = 0; tab < tabSize; tab++) + { + boolean included = false; + // MTab + GridTab gTab = m_mWorkbench.getMWindow(wb).getTab(tab); + // Query first tab + if (tab == 0) + { + // initial user query for single workbench tab + if (m_mWorkbench.getWindowCount() == 1) + { + query = initialQuery (query, gTab); + if (query != null && query.getRecordCount() <= 1) + goSingleRow = true; + } + else if (wb != 0) + // workbench dynamic query for dependent windows + { + query = m_mWorkbench.getQuery(); + } + // Set initial Query on first tab + if (query != null) + { + m_onlyCurrentRows = false; // Query might involve history + gTab.setQuery(query); + } + if (wb == 0) + m_curTab = gTab; + } // query on first tab + + Component tabElement = null; + // GridController + if (gTab.isSortTab()) + { + VSortTab st = new VSortTab(m_curWindowNo, gTab.getAD_Table_ID(), + gTab.getAD_ColumnSortOrder_ID(), gTab.getAD_ColumnSortYesNo_ID()); + st.setTabLevel(gTab.getTabLevel()); + tabElement = st; + } + else // normal tab + { + GridController gc = new GridController(); // Timing: ca. .1 sec + CompiereColor cc = mWindow.getColor(); + if (cc != null) + gc.setBackgroundColor(cc); // set color on Window level + gc.initGrid(gTab, false, m_curWindowNo, this, mWindow); // will set color on Tab level + // Timing: ca. 6-7 sec for first .2 for next + gc.addDataStatusListener(this); + gc.registerESCAction(aIgnore); // register Escape Key + // Set First Tab + if (wb == 0 && tab == 0) + { + m_curGC = gc; + Dimension size = gc.getPreferredSize(); // Screen Sizing + size.width += 4; + size.height += 4; + gc.setPreferredSize(size); + } + tabElement = gc; + // If we have a zoom query, switch to single row + if (tab == 0 && goSingleRow) + gc.switchSingleRow(); + + // Store GC if it has a included Tab + if (gTab.getIncluded_Tab_ID() != 0) + includedMap.put(new Integer(gTab.getIncluded_Tab_ID()), gc); + + // Is this tab included? + if (includedMap.size() > 0) + { + GridController parent = (GridController)includedMap.get(new Integer(gTab.getAD_Tab_ID())); + if (parent != null) + { + included = parent.includeTab(gc); + if (!included) + log.log(Level.SEVERE, "Not Included = " + gc); + } + } + } // normal tab + + if (!included) // Add to TabbedPane + { + StringBuffer tabName = new StringBuffer (); + tabName.append (""); + if (gTab.isReadOnly()) + tabName.append(""); + int pos = gTab.getName ().indexOf (" "); + if (pos == -1) + tabName.append (gTab.getName ()).append ("
 "); + else + { + tabName.append (gTab.getName().substring (0, pos)) + .append ("
") + .append (gTab.getName().substring(pos + 1)); + } + if (gTab.isReadOnly()) + tabName.append("
"); + tabName.append (""); + // Add Tab - sets ALT- and Shift-ALT- + window.addTab (tabName.toString(), gTab, tabElement); + } + } // Tab Loop + // Tab background + // window.setBackgroundColor(new AdempiereColor(Color.magenta, Color.green)); + } // Type-MWindow + + // Single Workbench Window Tab + if (m_mWorkbench.getWindowCount() == 1) + { + window.setToolTipText(m_mWorkbench.getDescription(wb)); + } + else + // Add Workbench Window Tab + { + tabPanel.addTab(m_mWorkbench.getName(wb), m_mWorkbench.getIcon(wb), window, m_mWorkbench.getDescription(wb)); + } + // Used for Env.getHeader + Env.setContext(m_ctx, m_curWindowNo, "WindowName", m_mWorkbench.getName(wb)); + + } // Workbench Loop + + // stateChanged (<->) triggered + toolBar.setName(getTitle()); + m_curTab.getTableModel().setChanged(false); + // Set Detail Button + aDetail.setEnabled(0 != m_curWinTab.getTabCount()-1); + + // Enable/Disable Tabs dynamically + if (m_curWinTab instanceof VTabbedPane) + ((VTabbedPane)m_curWinTab).evaluate(null); + // Size + if (windowSize != null) + setPreferredSize(windowSize); + Dimension size = getPreferredSize(); + log.info( "fini - " + size); + m_curWinTab.requestFocusInWindow(); + return true; + } // initPanel + + /** + * Get Current Window No + * @return win no + */ + public int getWindowNo() + { + return m_curWindowNo; + } // getWindowNo + + /** + * Initial Query + * @param query initial query + * @param mTab tab + * @return query or null + */ + private MQuery initialQuery (MQuery query, GridTab mTab) + { + // We have a (Zoom) query + if (query != null && query.isActive() && query.getRecordCount() < 10) + return query; + // + StringBuffer where = new StringBuffer(); + // Query automatically if high volume and no query + boolean require = mTab.isHighVolume(); + if (!require && !m_onlyCurrentRows) // No Trx Window + { + String wh1 = mTab.getWhereExtended(); + if (wh1 == null || wh1.length() == 0) + wh1 = mTab.getWhereClause(); + if (wh1 != null && wh1.length() > 0) + where.append(wh1); + // + if (query != null) + { + String wh2 = query.getWhereClause(); + if (wh2.length() > 0) + { + if (where.length() > 0) + where.append (" AND "); + where.append(wh2); + } + } + // + StringBuffer sql = new StringBuffer("SELECT COUNT(*) FROM ") + .append(mTab.getTableName()); + if (where.length() > 0) + sql.append(" WHERE ").append(where); + // Does not consider security + int no = DB.getSQLValue(null, sql.toString()); + // + require = MRole.getDefault().isQueryRequire(no); + } + // Show Query + if (require) + { + GridField[] findFields = mTab.getFields(); + Find find = new Find (Env.getFrame(this), m_curWindowNo, mTab.getName(), + mTab.getAD_Table_ID(), mTab.getTableName(), + where.toString(), findFields, 10); // no query below 10 + query = find.getQuery(); + find = null; + } + return query; + } // initialQuery + + + /** + * Get Window Index + * @return Window Index + */ + private int getWindowIndex() + { + // only one window + if (m_mWorkbench.getWindowCount() == 1) + return 0; + // workbench + return tabPanel.getSelectedIndex(); + } // getWindowIndex + + /** + * Is first Tab (on Window) + * @return true if the panel displays the first tab + */ + private boolean isFirstTab() + { + return m_curWinTab.getSelectedIndex() == 0; + } // isFirstTab + + /** + * Get Window Image + * @return image or null + */ + public Image getImage() + { + return m_mWorkbench.getImage(getWindowIndex()); + } // getImage + + + /************************************************************************** + * Data Status Listener (row change) ^ | v + * @param e event + */ + public void dataStatusChanged (DataStatusEvent e) + { + if (m_disposing) + return; + log.info(e.getMessage()); + String dbInfo = e.getMessage(); + if (m_curTab != null && m_curTab.isQueryActive()) + dbInfo = "[ " + dbInfo + " ]"; + statusBar.setStatusDB(dbInfo, e); + + // Set Message / Info + if (e.getAD_Message() != null || e.getInfo() != null) + { + StringBuffer sb = new StringBuffer(); + String msg = e.getMessage(); + if (msg != null && msg.length() > 0) + sb.append(Msg.getMsg(m_ctx, e.getAD_Message())); + String info = e.getInfo(); + if (info != null && info.length() > 0) + { + if (sb.length() > 0 && !sb.toString().trim().endsWith(":")) + sb.append(": "); + sb.append(info); + } + if (sb.length() > 0) + { + int pos = sb.indexOf("\n"); + if (pos != -1) // replace CR/NL + sb.replace(pos, pos+1, " - "); + setStatusLine (sb.toString (), e.isError ()); + } + } + + // Confirm Error + if (e.isError() && !e.isConfirmed()) + { + ADialog.error(m_curWindowNo, this, e.getAD_Message(), e.getInfo()); + e.setConfirmed(true); // show just once - if MTable.setCurrentRow is involved the status event is re-issued + m_errorDisplayed = true; + } + // Confirm Warning + else if (e.isWarning() && !e.isConfirmed()) + { + ADialog.warn(m_curWindowNo, this, e.getAD_Message(), e.getInfo()); + e.setConfirmed(true); // show just once - if MTable.setCurrentRow is involved the status event is re-issued + } + + // update Navigation + boolean firstRow = e.isFirstRow(); + aFirst.setEnabled(!firstRow); + aPrevious.setEnabled(!firstRow); + boolean lastRow = e.isLastRow(); + aNext.setEnabled(!lastRow); + aLast.setEnabled(!lastRow); + + // update Change + boolean changed = e.isChanged() || e.isInserting(); + boolean readOnly = m_curTab.isReadOnly(); + boolean insertRecord = !readOnly; + if (insertRecord) + insertRecord = m_curTab.isInsertRecord(); + aNew.setEnabled(!changed && insertRecord); + aCopy.setEnabled(!changed && insertRecord); + aRefresh.setEnabled(!changed); + aDelete.setEnabled(!changed && !readOnly); + // + if (readOnly && m_curTab.isAlwaysUpdateField()) + readOnly = false; + aIgnore.setEnabled(changed && !readOnly); + aSave.setEnabled(changed && !readOnly); + // + // No Rows + if (e.getTotalRows() == 0 && insertRecord) + { + aNew.setEnabled(true); + aDelete.setEnabled(false); + aDeleteSelection.setEnabled(false); + } else { + aDeleteSelection.setEnabled(true); + } + + // Single-Multi + aMulti.setPressed(!m_curGC.isSingleRow()); + + // History (on first Tab only) + if (isFirstTab()) + aHistory.setPressed(!m_curTab.isOnlyCurrentRows()); + + // Transaction info + String trxInfo = m_curTab.getTrxInfo(); + if (trxInfo != null) + statusBar.setInfo(trxInfo); + + // Check Attachment + boolean canHaveAttachment = m_curTab.canHaveAttachment(); // not single _ID column + // + if (canHaveAttachment && e.isLoading() && m_curTab.getCurrentRow() > e.getLoadedRows()) + canHaveAttachment = false; + if (canHaveAttachment && m_curTab.getRecord_ID() == -1) // No Key + canHaveAttachment = false; + if (canHaveAttachment) + { + aAttachment.setEnabled(true); + aAttachment.setPressed(m_curTab.hasAttachment()); + aChat.setEnabled(true); + aChat.setPressed(m_curTab.hasChat()); + } + else + { + aAttachment.setEnabled(false); + aChat.setEnabled(false); + } + // Lock Indicator + if (m_isPersonalLock) + aLock.setPressed(m_curTab.isLocked()); + + if (m_curWinTab instanceof VTabbedPane) + ((VTabbedPane)m_curWinTab).evaluate(e); + // log.info("- fini", e.getMessage()); + } // dataStatusChanged + + /** + * Set Status Line to text + * @param text clear text + * @param error error flag + */ + public void setStatusLine (String text, boolean error) + { + log.fine(text); + statusBar.setStatusLine(text, error); + } // setStatusLine + + /** + * Indicate Busy + * @param busy busy + * @param focus request focus + */ + private void setBusy (boolean busy, boolean focus) + { + m_isLocked = busy; + // + JFrame frame = Env.getFrame(this); + if (frame == null) // during init + return; + if (frame instanceof AWindow) + ((AWindow)frame).setBusy(busy); + // String processing = Msg.getMsg(m_ctx, "Processing"); + if (busy) + { + // setStatusLine(processing); + this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } + else + { + this.setCursor(Cursor.getDefaultCursor()); + frame.setCursor(Cursor.getDefaultCursor()); + if (focus) + m_curGC.requestFocus(); + // if (statusBar.getStatusLine().equals(processing)) + // statusBar.setStatusLine(""); + } + } // set Busy + + + /************************************************************************** + * Change Listener - (tab change) <-> + * @param e event + */ + public void stateChanged (ChangeEvent e) + { + if (m_disposing) + return; + log.info(e.toString()); + setBusy(true, true); + + VTabbedPane tp = (VTabbedPane)e.getSource(); + boolean back = false; + boolean isAPanelTab = false; + + // Workbench Tab Change + if (tp.isWorkbench()) + { + int WBIndex = tabPanel.getSelectedIndex(); + m_curWindowNo = m_mWorkbench.getWindowNo(WBIndex); + // Window Change + log.info("curWin=" + m_curWindowNo + " - Win=" + tp); + if (tp.getSelectedComponent() instanceof JTabbedPane) + m_curWinTab = (JTabbedPane)tp.getSelectedComponent(); + else + throw new java.lang.IllegalArgumentException("Window does not contain Tabs"); + if (m_curWinTab.getSelectedComponent() instanceof GridController) + m_curGC = (GridController)m_curWinTab.getSelectedComponent(); + // else if (m_curWinTab.getSelectedComponent() instanceof APanelTab) + // isAPanelTab = true; + else + throw new java.lang.IllegalArgumentException("Window-Tab does not contain GridControler"); + // change pointers + m_curTabIndex = m_curWinTab.getSelectedIndex(); + } + else + { + // Just a Tab Change + log.info("Tab=" + tp); + m_curWinTab = tp; + int tpIndex = m_curWinTab.getSelectedIndex(); + back = tpIndex < m_curTabIndex; + GridController gc = null; + if (m_curWinTab.getSelectedComponent() instanceof GridController) + gc = (GridController)m_curWinTab.getSelectedComponent(); + else if (m_curWinTab.getSelectedComponent() instanceof APanelTab) + isAPanelTab = true; + else + throw new java.lang.IllegalArgumentException("Tab does not contain GridControler"); + // Save old Tab + if (m_curGC != null) + { + m_curGC.stopEditor(true); + // has anything changed? + if (m_curTab.needSave(true, false)) + { // do we have real change + if (m_curTab.needSave(true, true)) + { + // Automatic Save + if (Env.isAutoCommit(m_ctx, m_curWindowNo)) + { + if (!m_curTab.dataSave(true)) + { // there is a problem, so we go back + m_curWinTab.setSelectedIndex(m_curTabIndex); + setBusy(false, true); + return; + } + } + // explicitly ask when changing tabs + else if (ADialog.ask(m_curWindowNo, this, "SaveChanges?", m_curTab.getCommitWarning())) + { // yes we want to save + if (!m_curTab.dataSave(true)) + { // there is a problem, so we go back + m_curWinTab.setSelectedIndex(m_curTabIndex); + setBusy(false, true); + return; + } + } + else // Don't save + m_curTab.dataIgnore(); + } + else // new record, but nothing changed + m_curTab.dataIgnore(); + } // there is a change + } + if (m_curAPanelTab != null) + { + m_curAPanelTab.saveData(); + m_curAPanelTab.unregisterPanel(); + m_curAPanelTab = null; + } + + // new tab + // if (m_curTabIndex >= 0) + // m_curWinTab.setForegroundAt(m_curTabIndex, AdempierePLAF.getTextColor_Normal()); + // m_curWinTab.setForegroundAt(tpIndex, AdempierePLAF.getTextColor_OK()); + m_curTabIndex = tpIndex; + if (!isAPanelTab) + m_curGC = gc; + } + + // Sort Tab Handling + if (isAPanelTab) + { + m_curAPanelTab = (APanelTab)m_curWinTab.getSelectedComponent(); + m_curAPanelTab.registerAPanel(this); + m_curAPanelTab.loadData(); + } + else // Cur Tab Setting + { + m_curGC.activate(); + m_curTab = m_curGC.getMTab(); + + // Refresh only current row when tab is current + if (back && m_curTab.isCurrent()) + m_curTab.dataRefresh(); + else // Requery & autoSize + { + MRole role = MRole.getDefault(); + m_curGC.query (m_onlyCurrentRows, m_onlyCurrentDays, role.getMaxQueryRecords()); + } + + // Set initial record + if (m_curTab.getRowCount() == 0) + { + // Automatically create New Record, if none & tab not RO + if (!m_curTab.isReadOnly() + && (Env.isAutoNew(m_ctx, m_curWindowNo) || m_curTab.isQueryNewRecord())) + { + log.config("No record - New - AutoNew=" + Env.isAutoNew(m_ctx, m_curWindowNo) + + " - QueryNew=" + m_curTab.isQueryNewRecord()); + m_curTab.dataNew(false); + } + else // No Records found + { + aSave.setEnabled(false); + aDelete.setEnabled(false); + aDeleteSelection.setEnabled(false); + } + m_curTab.navigateCurrent(); // updates counter + m_curGC.dynamicDisplay(0); + } + // else ##CHANGE + // m_curTab.navigateCurrent(); + } + + // Update <-> Navigation + aDetail.setEnabled(m_curTabIndex != m_curWinTab.getTabCount()-1); + aParent.setEnabled(m_curTabIndex != 0 && m_curWinTab.getTabCount() > 1); + + // History (on first tab only) + if (m_mWorkbench.getMWindow(getWindowIndex()).isTransaction()) + aHistory.setEnabled(isFirstTab()); + else + { + aHistory.setPressed(false); + aHistory.setEnabled(false); + } + // Document Print + aPrint.setEnabled(m_curTab.isPrinted()); + // Query + aFind.setPressed(m_curTab.isQueryActive()); + + // Order Tab + if (isAPanelTab) + { + aMulti.setPressed(false); + aMulti.setEnabled(false); + aNew.setEnabled(false); + aDelete.setEnabled(false); + aDeleteSelection.setEnabled(false); + aFind.setEnabled(false); + aRefresh.setEnabled(false); + aAttachment.setEnabled(false); + aChat.setEnabled(false); + } + else // Grid Tab + { + aMulti.setEnabled(true); + aMulti.setPressed(!m_curGC.isSingleRow()); + aFind.setEnabled(true); + aRefresh.setEnabled(true); + aAttachment.setEnabled(true); + aChat.setEnabled(true); + } + // + m_curWinTab.requestFocusInWindow(); + setBusy(false, true); + log.config( "fini"); + } // stateChanged + + /** + * Navigate to Detail Tab -> + */ + private void cmd_detail() + { + int index = m_curWinTab.getSelectedIndex(); + if (index == m_curWinTab.getTabCount()-1) + return; + m_curGC.getTable().removeEditor(); + m_curWinTab.setSelectedIndex(index+1); + } // navigateDetail + + /** + * Navigate to Parent Tab <- + */ + private void cmd_parent() + { + int index = m_curWinTab.getSelectedIndex(); + if (index == 0) + return; + m_curGC.getTable().removeEditor(); + m_curWinTab.setSelectedIndex(index-1); + } // navigateParent + + + /************************************************************************** + * Action Listener + * @param e event + */ + public void actionPerformed (ActionEvent e) + { + log.info(e.getActionCommand() + " - " + e.getModifiers()); + // + " - " + new Timestamp(e.getWhen()) + " " + isUILocked()); + if (m_disposing || isUILocked()) + return; + + m_lastModifiers = e.getModifiers(); + String cmd = e.getActionCommand(); + // Do ScreenShot w/o busy + if (cmd.equals("ScreenShot")) + { + AEnv.actionPerformed (e.getActionCommand(), m_curWindowNo, this); + return; + } + + // Problem: doubleClick detection - can't disable button as clicking button may change button status + setBusy (true, true); + // Command Buttons + if (e.getSource() instanceof VButton) + { + actionButton((VButton)e.getSource()); + setBusy(false, true); + return; + } + + try + { + // File + if (cmd.equals(aReport.getName())) + cmd_report(); + else if (cmd.equals(aPrint.getName())) + cmd_print(); + else if (cmd.equals(aEnd.getName())) + cmd_end(false); + else if (cmd.equals(aExit.getName())) + cmd_end(true); + // Edit + else if (cmd.equals(aNew.getName())) + cmd_new(false); + else if (cmd.equals(aSave.getName())) + cmd_save(true); + else if (cmd.equals(aCopy.getName())) + cmd_new(true); + else if (cmd.equals(aDelete.getName())) + cmd_delete(); + else if (cmd.equals(aDeleteSelection.getName())) + cmd_deleteSelection(); + else if (cmd.equals(aIgnore.getName())) + cmd_ignore(); + else if (cmd.equals(aRefresh.getName())) + cmd_refresh(); + else if (cmd.equals(aFind.getName())) + cmd_find(); + else if (m_isPersonalLock && cmd.equals(aLock.getName())) + cmd_lock(); + // View + else if (cmd.equals(aAttachment.getName())) + cmd_attachment(); + else if (cmd.equals(aChat.getName())) + cmd_chat(); + else if (cmd.equals(aHistory.getName())) + cmd_history(); + else if (cmd.equals(aMulti.getName())) + m_curGC.switchRowPresentation(); + // Go + else if (cmd.equals(aFirst.getName())) + { /*cmd_save(false);*/ + m_curGC.getTable().removeEditor(); + m_curTab.navigate(0); + } + else if (cmd.equals(aPrevious.getName())) + { /*cmd_save(false);*/ + m_curGC.getTable().removeEditor(); + m_curTab.navigateRelative(-1); + } + else if (cmd.equals(aNext.getName())) + { /*cmd_save(false); */ + m_curGC.getTable().removeEditor(); + m_curTab.navigateRelative(+1); + } + else if (cmd.equals(aLast.getName())) + { /*cmd_save(false);*/ + m_curGC.getTable().removeEditor(); + m_curTab.navigate(m_curTab.getRowCount()-1); + } + else if (cmd.equals(aParent.getName())) + cmd_parent(); + else if (cmd.equals(aDetail.getName())) + cmd_detail(); + else if (cmd.equals(aZoomAcross.getName())) + cmd_zoomAcross(); + else if (cmd.equals(aRequest.getName())) + cmd_request(); + else if (cmd.equals(aArchive.getName())) + cmd_archive(); + // Tools + else if (aWorkflow != null && cmd.equals(aWorkflow.getName())) + { + if (m_curTab.getRecord_ID() <= 0) + ; + else if (m_curTab.getTabNo() == 0 && m_mWorkbench.getMWindow(getWindowIndex()).isTransaction()) + AEnv.startWorkflowProcess(m_curTab.getAD_Table_ID(), m_curTab.getRecord_ID()); + else + AEnv.startWorkflowProcess(m_curTab.getAD_Table_ID(), m_curTab.getRecord_ID()); + } + else if (aWinSize != null && cmd.equals(aWinSize.getName())) + cmd_winSize(); + // Help + else if (cmd.equals(aHelp.getName())) + cmd_help(); + // General Commands (Environment) + else if (!AEnv.actionPerformed (e.getActionCommand(), m_curWindowNo, this)) + log.log(Level.SEVERE, "No action for: " + cmd); + } + catch (Exception ex) + { + log.log(Level.SEVERE, cmd, ex); + String msg = ex.getMessage(); + if (msg == null || msg.length() == 0) + msg = ex.toString(); + msg = Msg.parseTranslation(m_ctx, msg); + ADialog.error(m_curWindowNo, this, "Error", msg); + } + // + m_curWinTab.requestFocusInWindow(); + setBusy(false, true); + } // actionPerformed + + /** + * Create New Record + * @param copy true if current record is to be copied + */ + private void cmd_new (boolean copy) + { + log.config("copy=" + copy); + if (!m_curTab.isInsertRecord()) + { + log.warning("Insert Record disabled for Tab"); + return; + } + cmd_save(false); + m_curTab.dataNew (copy); + m_curGC.dynamicDisplay(0); + // m_curTab.getTableModel().setChanged(false); + } // cmd_new + + /** + * Confirm & delete record + */ + private void cmd_delete() + { + if (m_curTab.isReadOnly()) + return; + int keyID = m_curTab.getRecord_ID(); + if (ADialog.ask(m_curWindowNo, this, "DeleteRecord?")) + if (m_curTab.dataDelete()) + m_curGC.rowChanged(false, keyID); + m_curGC.dynamicDisplay(0); + } // cmd_delete + + /** + * Show a list to select one or more items to delete. + */ + private void cmd_deleteSelection(){ + if (m_curTab.isReadOnly()) + return; + //show table with deletion rows -> value, name... + JPanel messagePanel = new JPanel(); + JList list = new JList(); + JScrollPane scrollPane = new JScrollPane(list); + Vector data = new Vector(); + int noOfRows = m_curTab.getRowCount(); + for(int i=0; i" + vButton.getText() + "
" + + vButton.getDescription() + "\n" + vButton.getHelp())) + return; + // + String title = vButton.getDescription(); + if (title == null || title.length() == 0) + title = vButton.getName(); + ProcessInfo pi = new ProcessInfo (title, vButton.getProcess_ID(), table_ID, record_ID); + pi.setAD_User_ID (Env.getAD_User_ID(m_ctx)); + pi.setAD_Client_ID (Env.getAD_Client_ID(m_ctx)); + pi.setIsBatch(batch); + + // Trx trx = Trx.get(Trx.createTrxName("AppsPanel"), true); + ProcessCtl.process(this, m_curWindowNo, pi, null); // calls lockUI, unlockUI + } // actionButton + + + /************************************************************************** + * Lock User Interface. + * Called from the Worker before processing + * @param pi process info + */ + public void lockUI (ProcessInfo pi) + { + // log.fine("" + pi); + setBusy(true, false); + } // lockUI + + /** + * Unlock User Interface. + * Called from the Worker when processing is done + * @param pi of execute ASync call + */ + public void unlockUI (ProcessInfo pi) + { + // log.fine("" + pi); + boolean notPrint = pi != null + && pi.getAD_Process_ID() != m_curTab.getAD_Process_ID(); + // + setBusy(false, notPrint); + // Process Result + if (notPrint) // refresh if not print + { + // Refresh data + m_curTab.dataRefresh(); + // Timeout + if (pi.isTimeout()) // set temporarily to R/O + Env.setContext(m_ctx, m_curWindowNo, "Processed", "Y"); + m_curGC.dynamicDisplay(0); + // Update Status Line + setStatusLine(pi.getSummary(), pi.isError()); + // Get Log Info + ProcessInfoUtil.setLogFromDB(pi); + String logInfo = pi.getLogInfo(); + if (logInfo.length() > 0) + ADialog.info(m_curWindowNo, this, Env.getHeader(m_ctx, m_curWindowNo), + pi.getTitle(), logInfo); // clear text + } + } // unlockUI + + /** + * Is the UI locked (Internal method) + * @return true, if UI is locked + */ + public boolean isUILocked() + { + return m_isLocked; + } // isLoacked + + /** + * Method to be executed async. + * Called from the ASyncProcess worker + * @param pi process info + */ + public void executeASync (ProcessInfo pi) + { + log.config("-"); + } // executeASync + + /** + * Get Current Tab + * @return current tab + */ + protected GridTab getCurrentTab() + { + return m_curTab; + } // getCurrentTab + + /** + * String representation + * @return String representation + */ + public String toString() + { + String s = "APanel[curWindowNo=" + m_curWindowNo; + if (m_mWorkbench != null) + s += ",WB=" + m_mWorkbench.toString(); + s += "]"; + return s; + } // toString + +} // APanel diff --git a/client/src/org/compiere/apps/ARequest.java b/client/src/org/compiere/apps/ARequest.java index 38de7e7282..43a054b3f2 100644 --- a/client/src/org/compiere/apps/ARequest.java +++ b/client/src/org/compiere/apps/ARequest.java @@ -184,7 +184,6 @@ public class ARequest implements ActionListener AWindow frame = new AWindow(); if (!frame.initWindow(AD_Window_ID, query)) return; - AEnv.addToWindowManager(frame); // New - set Table/Record if (e.getSource() == m_new) { diff --git a/client/src/org/compiere/apps/AWindow.java b/client/src/org/compiere/apps/AWindow.java index df24935644..6eebf47484 100644 --- a/client/src/org/compiere/apps/AWindow.java +++ b/client/src/org/compiere/apps/AWindow.java @@ -3,41 +3,41 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; - -import org.compiere.model.*; -import org.compiere.util.*; -import org.compiere.swing.*; -import org.compiere.db.*; - -/** - * Main Application Window. - * - Constructs, initializes and positions JFrame - * - Gets content, menu, title from APanel - * - * @author Jorg Janke - * @version $Id: AWindow.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public class AWindow extends CFrame -{ - /** - * Standard Constructor - requires initWindow - */ - public AWindow () + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; + +import org.compiere.model.*; +import org.compiere.util.*; +import org.compiere.swing.*; +import org.compiere.db.*; + +/** + * Main Application Window. + * - Constructs, initializes and positions JFrame + * - Gets content, menu, title from APanel + * + * @author Jorg Janke + * @version $Id: AWindow.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public class AWindow extends CFrame +{ + /** + * Standard Constructor - requires initWindow + */ + public AWindow () { super(); // Set UI Components @@ -45,148 +45,147 @@ public class AWindow extends CFrame this.getContentPane().add(m_APanel, BorderLayout.CENTER); this.setGlassPane(m_glassPane); } // AWindow - + /** The GlassPane */ private AGlassPane m_glassPane = new AGlassPane(); /** Application Window */ - private APanel m_APanel = new APanel(this); - + private APanel m_APanel = new APanel(); /** Logger */ private static CLogger log = CLogger.getCLogger(AWindow.class); - /** - * Dynamic Initialization Workbench - * @param AD_Workbench_ID workbench - * @return true if loaded OK - */ - protected boolean initWorkbench (int AD_Workbench_ID) - { - this.setName("AWindow_WB_" + AD_Workbench_ID); - boolean loadedOK = m_APanel.initPanel (AD_Workbench_ID, 0, null); - // - commonInit(); - return loadedOK; - } // initWorkbench - - /** - * Dynamic Initialization Single Window - * @param AD_Window_ID window - * @param query query - * @return true if loaded OK - */ - public boolean initWindow (int AD_Window_ID, MQuery query) - { - this.setName("AWindow_" + AD_Window_ID); - setAD_Window_ID(AD_Window_ID); - // - boolean loadedOK = m_APanel.initPanel (0, AD_Window_ID, query); - commonInit(); - return loadedOK; - } // initWindow - - /** - * Common Init. - * After APanel loaded - */ - private void commonInit() - { - this.setJMenuBar(m_APanel.getMenuBar()); - this.setTitle(m_APanel.getTitle()); - // - Image image = m_APanel.getImage(); - if (image != null) - setIconImage(image); - } // commonInit - - - /************************************************************************* - * Set Window Busy - * @param busy busy - */ - public void setBusy (boolean busy) - { - if (busy == m_glassPane.isVisible() - || CConnection.get().isTerminalServer()) - return; - log.config(getName() + " - " + busy); - m_glassPane.setMessage(null); - m_glassPane.setVisible(busy); - if (busy) - m_glassPane.requestFocus(); - } // setBusy - - /** - * Set Busy Message - * @param AD_Message message - */ - public void setBusyMessage (String AD_Message) - { - m_glassPane.setMessage(AD_Message); - } // setBusyMessage - - /** - * Set and start Busy Counter - * @param time in seconds - */ - public void setBusyTimer (int time) - { - m_glassPane.setBusyTimer (time); - } // setBusyTimer - - /** - * Window Events - * @param e event - */ - protected void processWindowEvent(WindowEvent e) - { - super.processWindowEvent(e); -// System.out.println(">> Apps WE_" + e.getID() // + " Frames=" + getFrames().length -// + " " + e); - } // processWindowEvent - - /** - * Get Application Panel - * @return application panel - */ - protected APanel getAPanel() - { - return m_APanel; - } // getAPanel - - /** - * Dispose - */ - public void dispose() - { - if (Env.hideWindow(this)) - return; - log.info(toString()); - if (m_APanel != null) - m_APanel.dispose(); - m_APanel = null; - this.removeAll(); - super.dispose(); - // System.gc(); - } // dispose - - /** - * Get Window No of Panel - * @return window no - */ - public int getWindowNo() - { - if (m_APanel != null) - return m_APanel.getWindowNo(); - return 0; - } // getWindowNo - - /** - * String Representation - * @return Name - */ - public String toString() - { + /** + * Dynamic Initialization Workbench + * @param AD_Workbench_ID workbench + * @return true if loaded OK + */ + protected boolean initWorkbench (int AD_Workbench_ID) + { + this.setName("AWindow_WB_" + AD_Workbench_ID); + boolean loadedOK = m_APanel.initPanel (AD_Workbench_ID, 0, null); + // + commonInit(); + return loadedOK; + } // initWorkbench + + /** + * Dynamic Initialization Single Window + * @param AD_Window_ID window + * @param query query + * @return true if loaded OK + */ + public boolean initWindow (int AD_Window_ID, MQuery query) + { + this.setName("AWindow_" + AD_Window_ID); + setAD_Window_ID(AD_Window_ID); + // + boolean loadedOK = m_APanel.initPanel (0, AD_Window_ID, query); + commonInit(); + return loadedOK; + } // initWindow + + /** + * Common Init. + * After APanel loaded + */ + private void commonInit() + { + this.setJMenuBar(m_APanel.getMenuBar()); + this.setTitle(m_APanel.getTitle()); + // + Image image = m_APanel.getImage(); + if (image != null) + setIconImage(image); + } // commonInit + + + /************************************************************************* + * Set Window Busy + * @param busy busy + */ + public void setBusy (boolean busy) + { + if (busy == m_glassPane.isVisible() + || CConnection.get().isTerminalServer()) + return; + log.config(getName() + " - " + busy); + m_glassPane.setMessage(null); + m_glassPane.setVisible(busy); + if (busy) + m_glassPane.requestFocus(); + } // setBusy + + /** + * Set Busy Message + * @param AD_Message message + */ + public void setBusyMessage (String AD_Message) + { + m_glassPane.setMessage(AD_Message); + } // setBusyMessage + + /** + * Set and start Busy Counter + * @param time in seconds + */ + public void setBusyTimer (int time) + { + m_glassPane.setBusyTimer (time); + } // setBusyTimer + + /** + * Window Events + * @param e event + */ + protected void processWindowEvent(WindowEvent e) + { + super.processWindowEvent(e); +// System.out.println(">> Apps WE_" + e.getID() // + " Frames=" + getFrames().length +// + " " + e); + } // processWindowEvent + + /** + * Get Application Panel + * @return application panel + */ + protected APanel getAPanel() + { + return m_APanel; + } // getAPanel + + /** + * Dispose + */ + public void dispose() + { + if (Env.hideWindow(this)) + return; + log.info(toString()); + if (m_APanel != null) + m_APanel.dispose(); + m_APanel = null; + this.removeAll(); + super.dispose(); + // System.gc(); + } // dispose + + /** + * Get Window No of Panel + * @return window no + */ + public int getWindowNo() + { + if (m_APanel != null) + return m_APanel.getWindowNo(); + return 0; + } // getWindowNo + + /** + * String Representation + * @return Name + */ + public String toString() + { return getName() + "_" + getWindowNo(); } // toString -} // AWindow \ No newline at end of file +} // AWindow diff --git a/client/src/org/compiere/apps/AZoomAcross.java b/client/src/org/compiere/apps/AZoomAcross.java index d4f299dfa0..1da146509d 100644 --- a/client/src/org/compiere/apps/AZoomAcross.java +++ b/client/src/org/compiere/apps/AZoomAcross.java @@ -190,7 +190,6 @@ public class AZoomAcross implements ActionListener AWindow frame = new AWindow(); if (!frame.initWindow(AD_Window_ID, m_query)) return; - AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; } // launchZoom diff --git a/client/src/org/compiere/apps/AppsAction.java b/client/src/org/compiere/apps/AppsAction.java index 6f9c06ddf8..3d4a628b57 100644 --- a/client/src/org/compiere/apps/AppsAction.java +++ b/client/src/org/compiere/apps/AppsAction.java @@ -3,291 +3,291 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Application Action. - * Creates Action with MenuItem and Button - * The ActionCommand is translated for display - * If translated text contains &, the next character is the Mnemonic - * - * @author Jorg Janke - * @version $Id: AppsAction.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public final class AppsAction extends AbstractAction -{ - /** - * 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 AppsAction (String action, KeyStroke accelerator, boolean toggle) - { - this (action, accelerator, null, toggle); - } - /** - * Application Action - * - * @param action base action command - used as AD_Message for Text and Icon name - * @param accelerator optional keystroke for accelerator - * @param text text, if null defered from action - */ - public AppsAction (String action, KeyStroke accelerator, String text) - { - this (action, accelerator, text, false); - } // AppsAction - - /** - * 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 AppsAction (String action, KeyStroke accelerator, String toolTipText, boolean toggle) - { - super(); - m_action = action; - m_accelerator = accelerator; - m_toggle = toggle; - - // Data - if (toolTipText == null) - toolTipText = Msg.getMsg(Env.getCtx(), action); - int pos = toolTipText.indexOf("&"); - if (pos != -1 && toolTipText.length() > pos) // We have a nemonic - creates ALT-_ - { - Character ch = new Character(toolTipText.toUpperCase().charAt(pos+1)); - if (ch != ' ') - { - toolTipText = toolTipText.substring(0, pos) + toolTipText.substring(pos+1); - putValue(Action.MNEMONIC_KEY, new Integer(ch.hashCode())); - } - } - // - Icon small = getIcon(action, true); - Icon large = getIcon(action, false); - Icon largePressed = null; - - // ToggleIcons have the pressed name with X - if (m_toggle) - { - m_smallPressed = getIcon(action+"X", true); - if (m_smallPressed == null) - m_smallPressed = small; - largePressed = getIcon(action+"X", false); - if (largePressed == null) - largePressed = large; - } - - // Attributes - putValue(Action.NAME, toolTipText); // Display - putValue(Action.SMALL_ICON, small); // Icon - putValue(Action.SHORT_DESCRIPTION, toolTipText); // Tooltip - putValue(Action.ACTION_COMMAND_KEY, m_action); // ActionCammand - putValue(Action.ACCELERATOR_KEY, accelerator); // KeyStroke - // putValue(Action.MNEMONIC_KEY, new Integer(0)); // Mnemonic - // putValue(Action.DEFAULT, text); // Not Used - - // Create Button - if (toggle) - { - m_button = new CToggleButton(this); - m_button.setSelectedIcon(largePressed); - } - else - m_button = new CButton(this); - m_button.setName(action); - // Correcting Action items - if (large != null) - { - m_button.setIcon(large); - m_button.setText(null); - } - m_button.setActionCommand(m_action); - m_button.setMargin(BUTTON_INSETS); - m_button.setSize(BUTTON_SIZE); + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Application Action. + * Creates Action with MenuItem and Button + * The ActionCommand is translated for display + * If translated text contains &, the next character is the Mnemonic + * + * @author Jorg Janke + * @version $Id: AppsAction.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public final class AppsAction extends AbstractAction +{ + /** + * 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 AppsAction (String action, KeyStroke accelerator, boolean toggle) + { + this (action, accelerator, null, toggle); + } + /** + * Application Action + * + * @param action base action command - used as AD_Message for Text and Icon name + * @param accelerator optional keystroke for accelerator + * @param text text, if null defered from action + */ + public AppsAction (String action, KeyStroke accelerator, String text) + { + this (action, accelerator, text, false); + } // AppsAction + + /** + * 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 AppsAction (String action, KeyStroke accelerator, String toolTipText, boolean toggle) + { + super(); + m_action = action; + m_accelerator = accelerator; + m_toggle = toggle; + + // Data + if (toolTipText == null) + toolTipText = Msg.getMsg(Env.getCtx(), action); + int pos = toolTipText.indexOf("&"); + if (pos != -1 && toolTipText.length() > pos) // We have a nemonic - creates ALT-_ + { + Character ch = new Character(toolTipText.toUpperCase().charAt(pos+1)); + if (ch != ' ') + { + toolTipText = toolTipText.substring(0, pos) + toolTipText.substring(pos+1); + putValue(Action.MNEMONIC_KEY, new Integer(ch.hashCode())); + } + } + // + Icon small = getIcon(action, true); + Icon large = getIcon(action, false); + Icon largePressed = null; + + // ToggleIcons have the pressed name with X + if (m_toggle) + { + m_smallPressed = getIcon(action+"X", true); + if (m_smallPressed == null) + m_smallPressed = small; + largePressed = getIcon(action+"X", false); + if (largePressed == null) + largePressed = large; + } + + // Attributes + putValue(Action.NAME, toolTipText); // Display + putValue(Action.SMALL_ICON, small); // Icon + putValue(Action.SHORT_DESCRIPTION, toolTipText); // Tooltip + putValue(Action.ACTION_COMMAND_KEY, m_action); // ActionCammand + putValue(Action.ACCELERATOR_KEY, accelerator); // KeyStroke + // putValue(Action.MNEMONIC_KEY, new Integer(0)); // Mnemonic + // putValue(Action.DEFAULT, text); // Not Used + + // Create Button + if (toggle) + { + m_button = new CToggleButton(this); + m_button.setSelectedIcon(largePressed); + } + else + m_button = new CButton(this); + m_button.setName(action); + // Correcting Action items + if (large != null) + { + m_button.setIcon(large); + m_button.setText(null); + } + m_button.setActionCommand(m_action); + m_button.setMargin(BUTTON_INSETS); + m_button.setSize(BUTTON_SIZE); // if (accelerator != null) { - m_button.getInputMap(CButton.WHEN_IN_FOCUSED_WINDOW).put(accelerator, action); + m_button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(accelerator, action); m_button.getActionMap().put(action, this); } } // Action - - /** Button Size */ - public static final Dimension BUTTON_SIZE = new Dimension(28,28); - /** Button Insets */ - public static final Insets BUTTON_INSETS = new Insets(0, 0, 0, 0); - /** CButton or CToggelButton */ - private AbstractButton m_button; - /** Menu */ - private JMenuItem m_menu; - - private String m_action = null; - private KeyStroke m_accelerator = null; - private Icon m_smallPressed = null; - private ActionListener m_delegate = null; - private boolean m_toggle = false; - private boolean m_pressed = false; - - /** - * Get Icon with name action - * @param name name - * @param small small - * @return Icon + + /** Button Size */ + public static final Dimension BUTTON_SIZE = new Dimension(28,28); + /** Button Insets */ + public static final Insets BUTTON_INSETS = new Insets(0, 0, 0, 0); + /** CButton or CToggelButton */ + private AbstractButton m_button; + /** Menu */ + private JMenuItem m_menu; + + private String m_action = null; + private KeyStroke m_accelerator = null; + private Icon m_smallPressed = null; + private ActionListener m_delegate = null; + private boolean m_toggle = false; + private boolean m_pressed = false; + + /** + * Get Icon with name action + * @param name name + * @param small small + * @return Icon */ private ImageIcon getIcon(String name, boolean small) { - String fullName = name + (small ? "16" : "24"); - return Env.getImageIcon2(fullName); + String fullName = name + (small ? "16.gif" : "24.gif"); + return Env.getImageIcon(fullName); } // getIcon /** - * Get Name/ActionCommand - * @return ActionName - */ - public String getName() - { - return m_action; - } // getName - - /** - * Return Button - * @return Button - */ - public AbstractButton getButton() - { - return m_button; - } // getButton - - /** - * Return MenuItem - * @return MenuItem - */ - public JMenuItem getMenuItem() - { - if (m_menu == null) - { - if (m_toggle) - { - m_menu = new CCheckBoxMenuItem(this); - m_menu.setSelectedIcon(m_smallPressed); - } - else - m_menu = new CMenuItem(this); - m_menu.setAccelerator(m_accelerator); - m_menu.setActionCommand(m_action); - } - return m_menu; - } // getMenuItem - - /** - * Set Delegate to receive the actionPerformed calls - * @param al listener - */ - public void setDelegate(ActionListener al) - { - m_delegate = al; - } // setDelegate - - /** - * Toggle - * @param pressed pressed - */ - public void setPressed (boolean pressed) - { - if (!m_toggle) - return; - m_pressed = pressed; - - // Set Button - m_button.setSelected(pressed); - // Set Menu - m_menu.setSelected(pressed); - } // setPressed - - /** - * IsPressed - * @return true if pressed - */ - public boolean isPressed() - { - return m_pressed; - } // isPressed - - /** - * Get Mnemonic character - * @return character - */ - public Character getMnemonic() - { - Object oo = getValue(Action.MNEMONIC_KEY); - if (oo instanceof Integer) - return (char)((Integer)oo).intValue(); - return null; - } // getMnemonic - - /** - * ActionListener - * @param e Event - */ - public void actionPerformed(ActionEvent e) - { - // log.info( "AppsAction.actionPerformed", e.getActionCommand()); - // Toggle Items - if (m_toggle) - setPressed(!m_pressed); - // Inform - if (m_delegate != null) - m_delegate.actionPerformed(e); - } // actionPerformed - - /** - * Dispose - */ - public void dispose() - { - m_button = null; - m_menu = null; - } // dispose - - /** - * String Info - * @return String Representation - */ - public String toString() - { - StringBuffer sb = new StringBuffer("AppsAction["); - sb.append(m_action); - Object oo = getValue(Action.ACCELERATOR_KEY); - if (oo != null) - sb.append(",Accelerator=").append(oo); - oo = getMnemonic(); - if (oo != null) - sb.append(",MnemonicKey=").append(oo); - sb.append("]"); - return sb.toString(); - } // toString - -} // AppsAction + * Get Name/ActionCommand + * @return ActionName + */ + public String getName() + { + return m_action; + } // getName + + /** + * Return Button + * @return Button + */ + public AbstractButton getButton() + { + return m_button; + } // getButton + + /** + * Return MenuItem + * @return MenuItem + */ + public JMenuItem getMenuItem() + { + if (m_menu == null) + { + if (m_toggle) + { + m_menu = new CCheckBoxMenuItem(this); + m_menu.setSelectedIcon(m_smallPressed); + } + else + m_menu = new CMenuItem(this); + m_menu.setAccelerator(m_accelerator); + m_menu.setActionCommand(m_action); + } + return m_menu; + } // getMenuItem + + /** + * Set Delegate to receive the actionPerformed calls + * @param al listener + */ + public void setDelegate(ActionListener al) + { + m_delegate = al; + } // setDelegate + + /** + * Toggle + * @param pressed pressed + */ + public void setPressed (boolean pressed) + { + if (!m_toggle) + return; + m_pressed = pressed; + + // Set Button + m_button.setSelected(pressed); + // Set Menu + m_menu.setSelected(pressed); + } // setPressed + + /** + * IsPressed + * @return true if pressed + */ + public boolean isPressed() + { + return m_pressed; + } // isPressed + + /** + * Get Mnemonic character + * @return character + */ + public Character getMnemonic() + { + Object oo = getValue(Action.MNEMONIC_KEY); + if (oo instanceof Integer) + return (char)((Integer)oo).intValue(); + return null; + } // getMnemonic + + /** + * ActionListener + * @param e Event + */ + public void actionPerformed(ActionEvent e) + { + // log.info( "AppsAction.actionPerformed", e.getActionCommand()); + // Toggle Items + if (m_toggle) + setPressed(!m_pressed); + // Inform + if (m_delegate != null) + m_delegate.actionPerformed(e); + } // actionPerformed + + /** + * Dispose + */ + public void dispose() + { + m_button = null; + m_menu = null; + } // dispose + + /** + * String Info + * @return String Representation + */ + public String toString() + { + StringBuffer sb = new StringBuffer("AppsAction["); + sb.append(m_action); + Object oo = getValue(Action.ACCELERATOR_KEY); + if (oo != null) + sb.append(",Accelerator=").append(oo); + oo = getMnemonic(); + if (oo != null) + sb.append(",MnemonicKey=").append(oo); + sb.append("]"); + return sb.toString(); + } // toString + +} // AppsAction diff --git a/client/src/org/compiere/apps/Preference.bak b/client/src/org/compiere/apps/Preference.bak new file mode 100755 index 0000000000..2cf80239db --- /dev/null +++ b/client/src/org/compiere/apps/Preference.bak @@ -0,0 +1,662 @@ +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import java.io.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; +import javax.swing.border.Border; +import javax.swing.event.*; +import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.MetalTheme; +import javax.swing.table.*; +// +import org.adempiere.plaf.PLAFEditor; +import org.adempiere.plaf.PLAFEditorPanel; +import org.adempiere.plaf.AdempierePLAF; +import org.compiere.db.*; +import org.compiere.grid.ed.*; +import org.compiere.minigrid.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.print.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Customize settings like L&F, AutoCommit, etc. & Diagnostics + * + * @author Jorg Janke + * @version $Id: Preference.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + * + * @author Low Heng Sin + * @version 2006-11-27 + */ +public final class Preference extends CDialog + implements ActionListener, ListSelectionListener +{ + /** + * Standard Constructor + * @param frame frame + * @param WindowNo window + */ + public Preference(Frame frame, int WindowNo) + { + super(frame, Msg.getMsg(Env.getCtx(), "Preference"), true); + log.config("Preference"); + try + { + jbInit(); + } + catch(Exception ex) + { + log.log(Level.SEVERE, ex.getMessage()); + } + load(); + // + StringBuffer sta = new StringBuffer("#"); + sta.append(Env.getCtx().size()).append(" - ") + .append(Msg.translate(Env.getCtx(), "AD_Window_ID")) + .append("=").append(WindowNo); + statusBar.setStatusLine(sta.toString()); + statusBar.setStatusDB(""); + AEnv.positionCenterWindow(frame, this); + } // Preference + + /** Logger */ + private static CLogger log = CLogger.getCLogger(Preference.class); + + private CPanel panel = new CPanel(); + private BorderLayout panelLayout = new BorderLayout(); + private CTabbedPane tabPane = new CTabbedPane(); + private CPanel customizePane = new CPanel(); + private CPanel contextPane = new CPanel(); + private GridBagLayout customizeLayout = new GridBagLayout(); + private CCheckBox autoCommit = new CCheckBox(); + private CCheckBox autoNew = new CCheckBox(); + private CCheckBox printPreview = new CCheckBox(); + private CCheckBox validateConnectionOnStartup = new CCheckBox(); + private CCheckBox singleInstancePerWindow = new CCheckBox(); + private CCheckBox openWindowMaximized = new CCheckBox(); + private CPanel southPanel = new CPanel(); + private BorderLayout southLayout = new BorderLayout(); + private BorderLayout icontextLayout = new BorderLayout(); + private JList infoList = new JList(); + private JScrollPane contextListScrollPane = new JScrollPane(infoList); + private CPanel contextSouthPanel = new CPanel(); + private CTextArea contextHeader = new CTextArea(4,15); + private CTextArea contextDetail = new CTextArea(4,35); + private CTextArea infoArea = new CTextArea(5, 30); + private BorderLayout contextSouthLayout = new BorderLayout(); + private StatusBar statusBar = new StatusBar(); + private ConfirmPanel confirm = new ConfirmPanel(true); + private CComboBox traceLevel = new CComboBox(CLogMgt.LEVELS); + private CLabel traceLabel = new CLabel(); + private CCheckBox traceFile = new CCheckBox(); + private CCheckBox autoLogin = new CCheckBox(); + private CCheckBox adempiereSys = new CCheckBox(); + private CCheckBox storePassword = new CCheckBox(); + private CCheckBox showTrl = new CCheckBox(); + private CCheckBox showAcct = new CCheckBox(); + private CCheckBox showAdvanced = new CCheckBox(); + private CCheckBox cacheWindow = new CCheckBox(); + private CButton uiTheme = new CButton(); + private CLabel lPrinter = new CLabel(); + private CPrinter fPrinter = new CPrinter(); + private CLabel lDate = new CLabel(); + private VDate fDate = new VDate(); + private CComboBox connectionProfile = new CComboBox(CConnection.CONNECTIONProfiles); + private CLabel connectionProfileLabel = new CLabel(); + private CPanel errorPane = new CPanel(); + private BorderLayout errorLayout = new BorderLayout(); + private JScrollPane errorScrollPane = new JScrollPane(); + private MiniTable errorTable = new MiniTable(); + private CPanel errorPanel = new CPanel(new FlowLayout(FlowLayout.TRAILING)); + private CToggleButton bErrorsOnly = new CToggleButton(Msg.getMsg(Env.getCtx(), "ErrorsOnly")); + private CButton bErrorReset = new CButton(Msg.getMsg(Env.getCtx(), "Reset")); + private CButton bErrorEMail = new CButton(Msg.getMsg(Env.getCtx(), "SendEMail")); + private CButton bErrorSave = new CButton(Msg.getMsg(Env.getCtx(), "SaveFile")); + private CButton bRoleInfo = new CButton(Msg.translate(Env.getCtx(), "AD_Role_ID")); + + private CPanel configPanel = new CPanel(); + + private PLAFEditorPanel plafEditor = new PLAFEditorPanel(); + + /** + * Static Init. + *
+	 *  - panel
+	 *      - tabPane
+	 *          - customizePane
+	 *              - infoArea
+	 *              - fields ...
+	 *          - contextPane
+	 *              - contextList
+	 *              - contextSouthPanel
+	 *                  - contextHeader
+	 *                  - contextDetail
+	 * 			- errorPane
+	 * 				- errorScollPane
+	 * 					- errorTable
+	 *      - southPanel
+	 *  
+ * @throws Exception + */ + void jbInit() throws Exception + { + traceLabel.setRequestFocusEnabled(false); + traceLabel.setText(Msg.getMsg(Env.getCtx(), "TraceLevel", true)); + traceLabel.setToolTipText(Msg.getMsg(Env.getCtx(), "TraceLevel", false)); + traceFile.setText(Msg.getMsg(Env.getCtx(), "TraceFile", true)); + traceFile.setToolTipText(Msg.getMsg(Env.getCtx(), "TraceFile", false)); + + uiTheme.setText(Msg.getMsg(Env.getCtx(), "UITheme", true)); + uiTheme.setToolTipText(Msg.getMsg(Env.getCtx(), "UITheme", false)); + autoCommit.setText(Msg.getMsg(Env.getCtx(), "AutoCommit", true)); + autoCommit.setToolTipText(Msg.getMsg(Env.getCtx(), "AutoCommit", false)); + autoNew.setText(Msg.getMsg(Env.getCtx(), "AutoNew", true)); + autoNew.setToolTipText(Msg.getMsg(Env.getCtx(), "AutoNew", false)); + adempiereSys.setText(Msg.getMsg(Env.getCtx(), "AdempiereSys", true)); + adempiereSys.setToolTipText(Msg.getMsg(Env.getCtx(), "AdempiereSys", false)); + printPreview.setText(Msg.getMsg(Env.getCtx(), "AlwaysPrintPreview", true)); + printPreview.setToolTipText(Msg.getMsg(Env.getCtx(), "AlwaysPrintPreview", false)); + validateConnectionOnStartup.setText(Msg.getMsg(Env.getCtx(), "ValidateConnectionOnStartup", true)); + validateConnectionOnStartup.setToolTipText(Msg.getMsg(Env.getCtx(), "ValidateConnectionOnStartup", false)); + singleInstancePerWindow.setText(Msg.getMsg(Env.getCtx(), "SingleInstancePerWindow", true)); + singleInstancePerWindow.setToolTipText(Msg.getMsg(Env.getCtx(), "SingleInstancePerWindow", false)); + openWindowMaximized.setText(Msg.getMsg(Env.getCtx(), "OpenWindowMaximized", true)); + openWindowMaximized.setToolTipText(Msg.getMsg(Env.getCtx(), "OpenWindowMaximized", false)); + autoLogin.setText(Msg.getMsg(Env.getCtx(), "AutoLogin", true)); + autoLogin.setToolTipText(Msg.getMsg(Env.getCtx(), "AutoLogin", false)); + storePassword.setText(Msg.getMsg(Env.getCtx(), "StorePassword", true)); + storePassword.setToolTipText(Msg.getMsg(Env.getCtx(), "StorePassword", false)); + showTrl.setText(Msg.getMsg(Env.getCtx(), "ShowTrlTab", true)); + showTrl.setToolTipText(Msg.getMsg(Env.getCtx(), "ShowTrlTab", false)); + showAcct.setText(Msg.getMsg(Env.getCtx(), "ShowAcctTab", true)); + showAcct.setToolTipText(Msg.getMsg(Env.getCtx(), "ShowAcctTab", false)); + showAdvanced.setText(Msg.getMsg(Env.getCtx(), "ShowAdvancedTab", true)); + showAdvanced.setToolTipText(Msg.getMsg(Env.getCtx(), "ShowAdvancedTab", false)); + connectionProfileLabel.setText(Msg.getElement(Env.getCtx(), "ConnectionProfile")); + cacheWindow.setText(Msg.getMsg(Env.getCtx(), "CacheWindow", true)); + cacheWindow.setToolTipText(Msg.getMsg(Env.getCtx(), "CacheWindow", false)); + lPrinter.setText(Msg.getMsg(Env.getCtx(), "Printer")); + lDate.setText(Msg.getMsg(Env.getCtx(), "Date")); + infoArea.setReadWrite(false); + getContentPane().add(panel); + panel.setLayout(panelLayout); + panel.add(tabPane, BorderLayout.CENTER); + // Customize +// tabPane.add(customizePane, Msg.getMsg(Env.getCtx(), "Preference")); + tabPane.add(customizePane, Msg.getMsg(Env.getCtx(), "Preference")); + customizePane.setLayout(customizeLayout); + customizePane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + Border insetBorder = BorderFactory.createEmptyBorder(2, 2, 2, 0); + CPanel loginPanel = new CPanel(); + loginPanel.setBorder(BorderFactory.createTitledBorder(Msg.getMsg(Env.getCtx(), "Login"))); + loginPanel.setLayout(new GridLayout(1, 2)); + autoLogin.setBorder(insetBorder); + storePassword.setBorder(insetBorder); + loginPanel.add(autoLogin); + loginPanel.add(storePassword); + customizePane.add(loginPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); + + CPanel windowPanel = new CPanel(); + windowPanel.setBorder(BorderFactory.createTitledBorder(Msg.getMsg(Env.getCtx(), "Window"))); + windowPanel.setLayout(new GridLayout(4, 2)); + windowPanel.add(showAcct);showAcct.setBorder(insetBorder); + windowPanel.add(showTrl);showTrl.setBorder(insetBorder); + windowPanel.add(showAdvanced);showAdvanced.setBorder(insetBorder); + windowPanel.add(autoCommit);autoCommit.setBorder(insetBorder); + windowPanel.add(autoNew);autoNew.setBorder(insetBorder); + windowPanel.add(cacheWindow);cacheWindow.setBorder(insetBorder); + windowPanel.add(openWindowMaximized);openWindowMaximized.setBorder(insetBorder); + windowPanel.add(singleInstancePerWindow);singleInstancePerWindow.setBorder(insetBorder); + customizePane.add(windowPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); + + CPanel connPanel = new CPanel(); + connPanel.setBorder(BorderFactory.createTitledBorder(Msg.getMsg(Env.getCtx(), "Connection"))); + connPanel.setLayout(new GridBagLayout()); + connPanel.add(connectionProfileLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + connPanel.add(connectionProfile, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + connPanel.add(validateConnectionOnStartup, new GridBagConstraints(0, 1, 2, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + customizePane.add(connPanel, new GridBagConstraints(0, 2, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); + + CPanel tracePanel = new CPanel(); + tracePanel.setBorder(BorderFactory.createTitledBorder(Msg.getMsg(Env.getCtx(), "TraceInfo"))); + tracePanel.setLayout(new GridBagLayout()); + tracePanel.add(traceLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + tracePanel.add(traceLevel, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + tracePanel.add(traceFile, new GridBagConstraints(0, 1, 2, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + customizePane.add(tracePanel, new GridBagConstraints(0, 3, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); + + CPanel printPanel = new CPanel(); + printPanel.setBorder(BorderFactory.createTitledBorder(Msg.getMsg(Env.getCtx(), "Printing"))); + printPanel.setLayout(new GridBagLayout()); + printPanel.add(lPrinter, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + printPanel.add(fPrinter, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + printPanel.add(printPreview, new GridBagConstraints(0, 1, 2, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 0), 0, 0)); + customizePane.add(printPanel, new GridBagConstraints(0, 4, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); + + CPanel otherPanel = new CPanel(); + otherPanel.setBorder(BorderFactory.createEmptyBorder()); + otherPanel.setLayout(new GridLayout()); + CPanel datePanel = new CPanel(); + datePanel.setLayout(new FlowLayout()); + ((FlowLayout)datePanel.getLayout()).setAlignment(FlowLayout.LEFT); + datePanel.add(lDate); + datePanel.add(fDate); + otherPanel.add(datePanel);datePanel.setBorder(insetBorder); + otherPanel.add(adempiereSys);adempiereSys.setBorder(insetBorder); + customizePane.add(otherPanel, new GridBagConstraints(0, 5, 1, 1, 1.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); + + CPanel themePanel = new CPanel(); + themePanel.setLayout(new GridLayout(1, 1)); + + themePanel.add(plafEditor); + tabPane.add(themePanel, Msg.getMsg(Env.getCtx(), "UITheme", true)); + + configPanel.setLayout(new BorderLayout()); + configPanel.add(infoArea, BorderLayout.CENTER); + CPanel configSouth = new CPanel(); + configSouth.setLayout(new FlowLayout()); + ((FlowLayout)configSouth.getLayout()).setAlignment(FlowLayout.RIGHT); + configSouth.add(bRoleInfo); + configPanel.add(configSouth, BorderLayout.SOUTH); + tabPane.add(configPanel, Msg.getMsg(Env.getCtx(), "Info")); + + customizePane.add(lDate, new GridBagConstraints(0, 9, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + customizePane.add(fDate, new GridBagConstraints(1, 9, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + customizePane.add(printPreview, new GridBagConstraints(2, 9, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + // Info +// tabPane.add(contextPane, Msg.getMsg(Env.getCtx(), "Context")); + tabPane.add(contextPane, Msg.getMsg(Env.getCtx(), "Context")); + contextPane.setLayout(icontextLayout); + contextPane.add(contextListScrollPane, BorderLayout.CENTER); + contextListScrollPane.setPreferredSize(new Dimension(200, 300)); + infoList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); + infoList.setBackground(AdempierePLAF.getFieldBackground_Inactive()); + infoList.addListSelectionListener(this); + infoList.setFixedCellWidth(30); + contextPane.add(contextSouthPanel, BorderLayout.SOUTH); + contextSouthPanel.setLayout(contextSouthLayout); + contextSouthPanel.add(contextHeader, BorderLayout.WEST); + contextHeader.setBackground(SystemColor.info); + contextHeader.setReadWrite(false); + contextHeader.setLineWrap(true); + contextHeader.setWrapStyleWord(true); + contextHeader.setBorder(BorderFactory.createLoweredBevelBorder()); + contextSouthPanel.add(contextDetail, BorderLayout.CENTER); + contextDetail.setBackground(SystemColor.info); + contextDetail.setReadWrite(false); + contextDetail.setLineWrap(true); + contextDetail.setWrapStyleWord(true); + contextDetail.setBorder(BorderFactory.createLoweredBevelBorder()); + // Error Pane + errorPane.setLayout(errorLayout); +// tabPane.add(errorPane, Msg.getMsg(Env.getCtx(), "Errors")); + tabPane.add(errorPane, "Errors"); + errorPane.add(errorScrollPane, BorderLayout.CENTER); + errorScrollPane.getViewport().add(errorTable, null); + // + errorPanel.add(bErrorsOnly); + errorPanel.add(bErrorReset); + errorPanel.add(bErrorEMail); + errorPanel.add(bErrorSave); + errorPane.add(errorPanel, BorderLayout.SOUTH); + // South + panel.add(southPanel, BorderLayout.SOUTH); + southPanel.setLayout(southLayout); + southPanel.add(statusBar, BorderLayout.SOUTH); + southPanel.add(confirm, BorderLayout.CENTER); + // + bRoleInfo.addActionListener(this); + confirm.addActionListener(this); + } // jbInit + + + /** + * List Selection Listener - show info in header/detail fields + * @param e evant + */ + public void valueChanged(ListSelectionEvent e) + { + if (e.getValueIsAdjusting()) + return; + + String value = (String)infoList.getSelectedValue(); + if (value == null) + return; + int pos = value.indexOf("=="); + if (pos == -1) + { + contextHeader.setText(""); + contextDetail.setText(value); + } + else + { + contextHeader.setText(value.substring(0, pos).replace('|','\n')); + contextDetail.setText(value.substring(pos+3)); + } + } // valueChanged + + + /** + * ActionListener + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + // UI Change + /*if (e.getSource() == uiTheme) + { + new AdempierePLAFEditor(this, false); + } + else */ if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) + dispose(); + else if (e.getActionCommand().equals(ConfirmPanel.A_OK)) + cmd_save(); + // + else if (e.getSource() == bErrorsOnly) + cmd_displayErrors(); + else if (e.getSource() == bErrorReset) + cmd_errorReset(); + else if (e.getSource() == bErrorEMail) + cmd_errorEMail(); + else if (e.getSource() == bErrorSave) + cmd_errorSave(); + // + else if (e.getSource() == bRoleInfo) + ADialog.info(0, this, "RoleInfo", MRole.getDefault().toStringX(Env.getCtx())); + } // actionPerformed + + + /** + * Load Settings - and Context + */ + private void load() + { + log.config(""); + infoArea.setText(CLogMgt.getInfo(null).toString()); + infoArea.setCaretPosition(0); + + // -- Load Settings -- + // UI + uiTheme.addActionListener(this); + // AutoCommit + autoCommit.setSelected(Env.isAutoCommit(Env.getCtx())); + autoNew.setSelected(Env.isAutoNew(Env.getCtx())); + // AdempiereSys + adempiereSys.setSelected(Ini.isPropertyBool(Ini.P_ADEMPIERESYS)); + if (Env.getAD_Client_ID(Env.getCtx()) > 20) + { + adempiereSys.setSelected(false); + adempiereSys.setEnabled(false); + } + // AutoLogin + autoLogin.setSelected(Ini.isPropertyBool(Ini.P_A_LOGIN)); + // Save Password + storePassword.setSelected(Ini.isPropertyBool(Ini.P_STORE_PWD)); + // Show Acct Tab + if (MRole.getDefault().isShowAcct()) + showAcct.setSelected(Ini.isPropertyBool(Ini.P_SHOW_ACCT)); + else + { + showAcct.setSelected(false); + showAcct.setReadWrite(false); + } + // Show Trl/Advanced Tab + showTrl.setSelected(Ini.isPropertyBool(Ini.P_SHOW_TRL)); + showAdvanced.setSelected(Ini.isPropertyBool(Ini.P_SHOW_ADVANCED)); + + // Connection Profile + MUser user = MUser.get(Env.getCtx()); + String cp = user.getConnectionProfile(); + if (cp == null) + cp = MRole.getDefault().getConnectionProfile(); + if (cp != null) + { + CConnection.get().setConnectionProfile(cp); + connectionProfile.setReadWrite(false); + } + connectionProfile.setSelectedItem(CConnection.get().getConnectionProfilePair()); + cacheWindow.setSelected(Ini.isCacheWindow()); + + // Print Preview + printPreview.setSelected(Ini.isPropertyBool(Ini.P_PRINTPREVIEW)); + + // Validate Connection on Startup + validateConnectionOnStartup.setSelected(Ini.isPropertyBool(Ini.P_VALIDATE_CONNECTION_ON_STARTUP)); + + // Single Instance per Window + singleInstancePerWindow.setSelected(Ini.isPropertyBool(Ini.P_SINGLE_INSTANCE_PER_WINDOW)); + + // Open Window Maximized + openWindowMaximized.setSelected(Ini.isPropertyBool(Ini.P_OPEN_WINDOW_MAXIMIZED)); + + // TraceLevel + traceLevel.setSelectedItem(CLogMgt.getLevel()); + traceFile.setSelected(Ini.isPropertyBool(Ini.P_TRACEFILE)); + // Printer + fPrinter.setValue(Env.getContext(Env.getCtx(), "#Printer")); + // Date + fDate.setValue(Env.getContextAsDate(Env.getCtx(), "#Date")); + + // -- Load and sort Context -- + String[] context = Env.getEntireContext(Env.getCtx()); + Arrays.sort(context); + infoList.setListData(context); + + // Load Errors + // CLogMgt mgt = new CLogMgt(); // creates test trace + bErrorsOnly.setSelected(true); + errorTable.setCellSelectionEnabled(true); + cmd_displayErrors(); + // for (int i = 2; i < 6; i++) + // errorTable.setColumnReadOnly(i, false); + // + bErrorsOnly.addActionListener(this); + bErrorReset.addActionListener(this); + bErrorSave.addActionListener(this); + bErrorEMail.addActionListener(this); + } // load + + /** + * Save Settings + */ + private void cmd_save() + { + log.config(""); + // UI + // AutoCommit + Ini.setProperty(Ini.P_A_COMMIT, (autoCommit.isSelected())); + Env.setAutoCommit(Env.getCtx(), autoCommit.isSelected()); + Ini.setProperty(Ini.P_A_NEW, (autoNew.isSelected())); + Env.setAutoNew(Env.getCtx(), autoNew.isSelected()); + // AdempiereSys + Ini.setProperty(Ini.P_ADEMPIERESYS, adempiereSys.isSelected()); + // AutoLogin + Ini.setProperty(Ini.P_A_LOGIN, (autoLogin.isSelected())); + // Save Password + Ini.setProperty(Ini.P_STORE_PWD, (storePassword.isSelected())); + // Show Acct Tab + Ini.setProperty(Ini.P_SHOW_ACCT, (showAcct.isSelected())); + Env.setContext(Env.getCtx(), "#ShowAcct", (showAcct.isSelected())); + // Show Trl Tab + Ini.setProperty(Ini.P_SHOW_TRL, (showTrl.isSelected())); + Env.setContext(Env.getCtx(), "#ShowTrl", (showTrl.isSelected())); + // Show Advanced Tab + Ini.setProperty(Ini.P_SHOW_ADVANCED, (showAdvanced.isSelected())); + Env.setContext(Env.getCtx(), "#ShowAdvanced", (showAdvanced.isSelected())); + + // ConnectionProfile + ValueNamePair ppNew = (ValueNamePair)connectionProfile.getSelectedItem(); + String cpNew = ppNew.getValue(); + String cpOld = CConnection.get().getConnectionProfile(); + CConnection.get().setConnectionProfile(cpNew); + if (!cpNew.equals(cpOld) + && (cpNew.equals(CConnection.PROFILE_WAN) || cpOld.equals(CConnection.PROFILE_WAN))) + ADialog.info(0, this, "ConnectionProfileChange"); + Ini.setProperty(Ini.P_CACHE_WINDOW, cacheWindow.isSelected()); + + // Print Preview + Ini.setProperty(Ini.P_PRINTPREVIEW, (printPreview.isSelected())); + // Validate Connection on Startup + Ini.setProperty(Ini.P_VALIDATE_CONNECTION_ON_STARTUP, (validateConnectionOnStartup.isSelected())); + // Single Instance per Window + Ini.setProperty(Ini.P_SINGLE_INSTANCE_PER_WINDOW, (singleInstancePerWindow.isSelected())); + // Open Window Maximized + Ini.setProperty(Ini.P_OPEN_WINDOW_MAXIMIZED, (openWindowMaximized.isSelected())); + // TraceLevel/File + Level level = (Level)traceLevel.getSelectedItem(); + CLogMgt.setLevel(level); + Ini.setProperty(Ini.P_TRACELEVEL, level.getName()); + Ini.setProperty(Ini.P_TRACEFILE, traceFile.isSelected()); + // Printer + String printer = (String)fPrinter.getSelectedItem(); + Env.setContext(Env.getCtx(), "#Printer", printer); + Ini.setProperty(Ini.P_PRINTER, printer); + // Date (remove seconds) + java.sql.Timestamp ts = (java.sql.Timestamp)fDate.getValue(); + if (ts != null) + Env.setContext(Env.getCtx(), "#Date", ts); + + //UI + ValueNamePair laf = plafEditor.getSelectedLook(); + ValueNamePair theme = plafEditor.getSelectedTheme(); + if ( laf != null ) { + String clazz = laf.getValue(); + String currentLaf = UIManager.getLookAndFeel().getClass().getName(); + if (clazz != null && clazz.length() > 0 && !currentLaf.equals(clazz)) + { + //laf changed + AdempierePLAF.setPLAF(laf, theme, true); + //AEnv.updateUI(); + } + else + { + if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel) + { + MetalTheme currentTheme = MetalLookAndFeel.getCurrentTheme(); + String themeClass = currentTheme.getClass().getName(); + String sTheme = theme.getValue(); + if (sTheme != null && sTheme.length() > 0 && !sTheme.equals(themeClass)) + { + ValueNamePair plaf = new ValueNamePair( + UIManager.getLookAndFeel().getClass().getName(), + UIManager.getLookAndFeel().getName()); + AdempierePLAF.setPLAF(plaf, theme, true); + //AEnv.updateUI(); + } + } + } + } + + Ini.saveProperties(Ini.isClient()); + dispose(); + } // cmd_save + + /** + * (Re)Display Errors + */ + private void cmd_displayErrors() + { + Vector data = CLogErrorBuffer.get(true).getLogData(bErrorsOnly.isSelected()); + Vector columnNames = CLogErrorBuffer.get(true).getColumnNames(Env.getCtx()); + DefaultTableModel model = new DefaultTableModel(data, columnNames); + errorTable.setModel(model); + // + if (bErrorsOnly.isSelected()) + tabPane.setTitleAt(2, Msg.getMsg(Env.getCtx(), "Errors") + " (" + data.size() + ")"); + else + tabPane.setTitleAt(2, Msg.getMsg(Env.getCtx(), "TraceInfo") + " (" + data.size() + ")"); + errorTable.autoSize(); + } // cmd_errorsOnly + + /** + * Reset Errors + */ + private void cmd_errorReset() + { + CLogErrorBuffer.get(true).resetBuffer(bErrorsOnly.isSelected()); + cmd_displayErrors(); + } // cmd_errorReset + + /** + * EMail Errors + */ + private void cmd_errorEMail() + { + EMailDialog emd = new EMailDialog(this, + "EMail Trace", + MUser.get(Env.getCtx()), + "", // to + "Adempiere Trace Info", + CLogErrorBuffer.get(true).getErrorInfo(Env.getCtx(), bErrorsOnly.isSelected()), + null); + + } // cmd_errorEMail + + /** + * Save Error to File + */ + private void cmd_errorSave() + { + JFileChooser chooser = new JFileChooser(); + chooser.setDialogType(JFileChooser.SAVE_DIALOG); + chooser.setDialogTitle("Adempiere Trace File"); + chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); + chooser.setSelectedFile(new File ("traceInfo.log")); + int returnVal = chooser.showSaveDialog(this); + if(returnVal != JFileChooser.APPROVE_OPTION) + return; + try + { + File file = chooser.getSelectedFile(); + FileWriter writer = new FileWriter(file); + writer.write(CLogErrorBuffer.get(true).getErrorInfo(Env.getCtx(), bErrorsOnly.isSelected())); + writer.flush(); + writer.close(); + } + catch (Exception e) + { + log.log(Level.SEVERE, "", e); + } + } // cmd_errorSave + +} // Preference diff --git a/client/src/org/compiere/apps/Preference.java b/client/src/org/compiere/apps/Preference.java index af44ab6ea5..b8c8035249 100644 --- a/client/src/org/compiere/apps/Preference.java +++ b/client/src/org/compiere/apps/Preference.java @@ -548,7 +548,7 @@ public final class Preference extends CDialog { //laf changed AdempierePLAF.setPLAF(laf, theme, true); - AEnv.updateUI(); + //AEnv.updateUI(); } else { @@ -563,7 +563,7 @@ public final class Preference extends CDialog UIManager.getLookAndFeel().getClass().getName(), UIManager.getLookAndFeel().getName()); AdempierePLAF.setPLAF(plaf, theme, true); - AEnv.updateUI(); + //AEnv.updateUI(); } } } diff --git a/client/src/org/compiere/apps/ProcessCtl.java b/client/src/org/compiere/apps/ProcessCtl.java index 85e48c796a..902d9c76ed 100644 --- a/client/src/org/compiere/apps/ProcessCtl.java +++ b/client/src/org/compiere/apps/ProcessCtl.java @@ -3,89 +3,89 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.io.*; -import java.lang.reflect.*; -import java.rmi.*; -import java.sql.*; -import java.util.logging.*; -import javax.swing.*; -import org.compiere.db.*; -import org.compiere.interfaces.*; -import org.compiere.model.*; -import org.compiere.print.*; -import org.compiere.process.*; -import org.compiere.util.*; -import org.compiere.wf.*; - -/** - * Process Interface Controller. - * - * @author Jorg Janke - * @version $Id: ProcessCtl.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public class ProcessCtl extends Thread -{ - /** - * Async Process - Do it all. - * - * - Get Instance ID - * - Get Parameters - * - execute (lock - start process - unlock) - * + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.io.*; +import java.lang.reflect.*; +import java.rmi.*; +import java.sql.*; +import java.util.logging.*; +import javax.swing.*; +import org.compiere.db.*; +import org.compiere.interfaces.*; +import org.compiere.model.*; +import org.compiere.print.*; +import org.compiere.process.*; +import org.compiere.util.*; +import org.compiere.wf.*; + +/** + * Process Interface Controller. + * + * @author Jorg Janke + * @version $Id: ProcessCtl.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public class ProcessCtl extends Thread +{ + /** + * Async Process - Do it all. + * + * - Get Instance ID + * - Get Parameters + * - execute (lock - start process - unlock) + * * Creates a ProcessCtl instance, which calls * lockUI and unlockUI if parent is a ASyncProcess *
- * Called from ProcessCtl.startProcess, APanel.cmd_print, - * APanel.actionButton, VPaySelect.cmd_generate + * Called from ProcessCtl.startProcess, ProcessDialog.actionPerformed, + * APanel.cmd_print, APanel.actionButton, VPaySelect.cmd_generate * * @param parent ASyncProcess & Container * @param WindowNo window no - * @param pi ProcessInfo process info - * @param trx Transaction - * @return worker started ProcessCtl instance or null for workflow - */ - public static ProcessCtl process (ASyncProcess parent, int WindowNo, ProcessInfo pi, Trx trx) - { - log.fine("WindowNo=" + WindowNo + " - " + pi); - - MPInstance instance = new MPInstance(Env.getCtx(), pi.getAD_Process_ID(), pi.getRecord_ID()); - if (!instance.save()) - { - pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoInstance")); - pi.setError (true); - return null; - } - pi.setAD_PInstance_ID (instance.getAD_PInstance_ID()); - - // Get Parameters (Dialog) - ProcessParameter para = new ProcessParameter (Env.getFrame((Container)parent), WindowNo, pi); - if (para.initDialog()) - { - para.setVisible(true); - if (!para.isOK()) - { - pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessCancelled")); - pi.setError (true); - return null; - } - } - - // execute - ProcessCtl worker = new ProcessCtl(parent, pi, trx); + * @param pi ProcessInfo process info + * @param trx Transaction + * @return worker started ProcessCtl instance or null for workflow + */ + public static ProcessCtl process (ASyncProcess parent, int WindowNo, ProcessInfo pi, Trx trx) + { + log.fine("WindowNo=" + WindowNo + " - " + pi); + + MPInstance instance = new MPInstance(Env.getCtx(), pi.getAD_Process_ID(), pi.getRecord_ID()); + if (!instance.save()) + { + pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoInstance")); + pi.setError (true); + return null; + } + pi.setAD_PInstance_ID (instance.getAD_PInstance_ID()); + + // Get Parameters (Dialog) + ProcessParameter para = new ProcessParameter (Env.getFrame((Container)parent), WindowNo, pi); + if (para.initDialog()) + { + para.setVisible(true); + if (!para.isOK()) + { + pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessCancelled")); + pi.setError (true); + return null; + } + } + + // execute + ProcessCtl worker = new ProcessCtl(parent, pi, trx); worker.start(); // MUST be start! return worker; } // execute @@ -138,303 +138,303 @@ public class ProcessCtl extends Thread - /************************************************************************** - * Constructor - * @param parent Container & ASyncProcess - * @param pi Process info - * @param trx Transaction - * Created in process(), VInvoiceGen.generateInvoices - */ - public ProcessCtl (ASyncProcess parent, ProcessInfo pi, Trx trx) - { - m_parent = parent; - m_pi = pi; - m_trx = trx; // handeled correctly - } // ProcessCtl - - private ASyncProcess m_parent; - private ProcessInfo m_pi; - private Trx m_trx; - private Waiting m_waiting; - private boolean m_IsServerProcess = false; - - /** Static Logger */ - private static CLogger log = CLogger.getCLogger (ProcessCtl.class); - - /** - * Execute Process Instance and Lock UI. - * Calls lockUI and unlockUI if parent is a ASyncProcess - *
-	 *		- Get Process Information
-	 *      - Call Class
-	 *		- Submit SQL Procedure
-	 *		- Run SQL Procedure
-	 *	
- */ - public void run () - { - log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() - + ", Record_ID=" + m_pi.getRecord_ID()); - - // Lock - lock(); - // try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");} catch (Exception e) {} - - // Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint - String ProcedureName = ""; - int AD_ReportView_ID = 0; - int AD_Workflow_ID = 0; - boolean IsReport = false; - boolean IsDirectPrint = false; - // - String sql = "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 - + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 - + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," - + " p.IsServerProcess " - + "FROM AD_Process p" - + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " - + "WHERE p.IsActive='Y'" - + " AND i.AD_PInstance_ID=?"; - if (!Env.isBaseLanguage(Env.getCtx(), "AD_Process")) - sql = "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 - + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 - + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," - + " p.IsServerProcess " - + "FROM AD_Process p" - + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " - + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID" - + " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "') " - + "WHERE p.IsActive='Y'" - + " AND i.AD_PInstance_ID=?"; - // - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, - ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); - pstmt.setInt(1, m_pi.getAD_PInstance_ID()); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - m_pi.setTitle (rs.getString(1)); - if (m_waiting != null) - m_waiting.setTitle(m_pi.getTitle()); - ProcedureName = rs.getString(2); - m_pi.setClassName (rs.getString(3)); - m_pi.setAD_Process_ID (rs.getInt(4)); - // Report - if ("Y".equals(rs.getString(5))) - { - IsReport = true; - if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW)) - IsDirectPrint = true; - } - AD_ReportView_ID = rs.getInt(7); - AD_Workflow_ID = rs.getInt(8); - // - int estimate = rs.getInt(9); - if (estimate != 0) - { - m_pi.setEstSeconds (estimate + 1); // admin overhead - if (m_waiting != null) - m_waiting.setTimerEstimate(m_pi.getEstSeconds()); - } - m_IsServerProcess = "Y".equals(rs.getString(10)); - } - else - log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID()); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true); - unlock(); - log.log(Level.SEVERE, "run", e); - return; - } - - // No PL/SQL Procedure - if (ProcedureName == null) - ProcedureName = ""; - - - /********************************************************************** - * Workflow - */ - if (AD_Workflow_ID > 0) - { - startWorkflow (AD_Workflow_ID); - unlock(); - return; - } - - /********************************************************************** - * Start Optional Class - */ - if (m_pi.getClassName() != null) - { - // Run Class - if (!startProcess()) - { - unlock(); - return; - } - - // No Optional SQL procedure ... done - if (!IsReport && ProcedureName.length() == 0) - { - unlock (); - return; - } - // No Optional Report ... done - if (IsReport && AD_ReportView_ID == 0) - { - unlock (); - return; - } - } - - // If not a report, we need a prodedure name - if (!IsReport && ProcedureName.length() == 0) - { - m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoProcedure"), true); - unlock(); - return; - } - - /********************************************************************** - * Report submission - */ - if (IsReport) - { - // Optional Pre-Report Process - if (ProcedureName.length() > 0) - { - if (!startDBProcess(ProcedureName)) - { - unlock(); - return; - } - } // Pre-Report - - // Start Report ----------------------------------------------- - boolean ok = ReportCtl.start(m_pi, IsDirectPrint); - m_pi.setSummary("Report", !ok); - unlock (); - } - /********************************************************************** - * Process submission - */ - else - { - if (!startDBProcess (ProcedureName)) - { - unlock(); - return; - } - // Success - getResult - ProcessInfoUtil.setSummaryFromDB(m_pi); - unlock(); - } // *** Process submission *** - // log.fine(Log.l3_Util, "ProcessCtl.run - done"); - } // run - - /** - * Lock UI & show Waiting - */ - private void lock () - { - // log.info("..."); - JFrame frame = Env.getFrame((Container)m_parent); - if (frame instanceof AWindow) - ((AWindow)frame).setBusyTimer(m_pi.getEstSeconds()); - else - m_waiting = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, m_pi.getEstSeconds()); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - log.finer("lock"); - m_parent.lockUI(m_pi); - } - }); - if (m_waiting != null) - { - m_waiting.toFront(); - m_waiting.setVisible(true); - } - } // lock - - /** - * Unlock UI & dispose Waiting. - * Called from run() - */ - private void unlock () - { - // log.info("..."); - if (m_pi.isBatch()) - m_pi.setIsTimeout(true); - SwingUtilities.invokeLater(new Runnable() - { - public void run() - { - String summary = m_pi.getSummary(); - log.finer("unlock - " + summary); - if (summary != null && summary.indexOf("@") != -1) - m_pi.setSummary(Msg.parseTranslation(Env.getCtx(), summary)); - m_parent.unlockUI(m_pi); - } - }); - // Remove Waiting/Processing Indicator - if (m_waiting != null) - m_waiting.dispose(); - m_waiting = null; - } // unlock - - - /************************************************************************** - * Start Workflow. - * - * @param AD_Workflow_ID workflow - * @return true if started - */ - private boolean startWorkflow (int AD_Workflow_ID) - { - log.fine(AD_Workflow_ID + " - " + m_pi); - boolean started = false; - if (DB.isRemoteProcess()) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - m_pi = server.workflow (Env.getCtx(), m_pi, AD_Workflow_ID); - log.finest("server => " + m_pi); - started = true; - } - } - catch (RemoteException ex) - { - log.log(Level.SEVERE, "AppsServer error", ex); - started = false; - } - } - // Run locally - if (!started && !m_IsServerProcess) - { - MWorkflow wf = MWorkflow.get (Env.getCtx(), AD_Workflow_ID); - MWFProcess wfProcess = null; - if (m_pi.isBatch()) - wfProcess = wf.start(m_pi); // may return null - else - wfProcess = wf.startWait(m_pi); // may return null - started = wfProcess != null; - } - return started; - } // startWorkflow - - /************************************************************************** + /************************************************************************** + * Constructor + * @param parent Container & ASyncProcess + * @param pi Process info + * @param trx Transaction + * Created in process(), VInvoiceGen.generateInvoices + */ + public ProcessCtl (ASyncProcess parent, ProcessInfo pi, Trx trx) + { + m_parent = parent; + m_pi = pi; + m_trx = trx; // handeled correctly + } // ProcessCtl + + private ASyncProcess m_parent; + private ProcessInfo m_pi; + private Trx m_trx; + private Waiting m_waiting; + private boolean m_IsServerProcess = false; + + /** Static Logger */ + private static CLogger log = CLogger.getCLogger (ProcessCtl.class); + + /** + * Execute Process Instance and Lock UI. + * Calls lockUI and unlockUI if parent is a ASyncProcess + *
+	 *		- Get Process Information
+	 *      - Call Class
+	 *		- Submit SQL Procedure
+	 *		- Run SQL Procedure
+	 *	
+ */ + public void run () + { + log.fine("AD_PInstance_ID=" + m_pi.getAD_PInstance_ID() + + ", Record_ID=" + m_pi.getRecord_ID()); + + // Lock + lock(); + // try {System.out.println(">> sleeping ..");sleep(20000);System.out.println(".. sleeping <<");} catch (Exception e) {} + + // Get Process Information: Name, Procedure Name, ClassName, IsReport, IsDirectPrint + String ProcedureName = ""; + int AD_ReportView_ID = 0; + int AD_Workflow_ID = 0; + boolean IsReport = false; + boolean IsDirectPrint = false; + // + String sql = "SELECT p.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 + + " p.isReport,p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 + + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," + + " p.IsServerProcess " + + "FROM AD_Process p" + + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " + + "WHERE p.IsActive='Y'" + + " AND i.AD_PInstance_ID=?"; + if (!Env.isBaseLanguage(Env.getCtx(), "AD_Process")) + sql = "SELECT t.Name, p.ProcedureName,p.ClassName, p.AD_Process_ID," // 1..4 + + " p.isReport, p.IsDirectPrint,p.AD_ReportView_ID,p.AD_Workflow_ID," // 5..8 + + " CASE WHEN COALESCE(p.Statistic_Count,0)=0 THEN 0 ELSE p.Statistic_Seconds/p.Statistic_Count END CASE," + + " p.IsServerProcess " + + "FROM AD_Process p" + + " INNER JOIN AD_PInstance i ON (p.AD_Process_ID=i.AD_Process_ID) " + + " INNER JOIN AD_Process_Trl t ON (p.AD_Process_ID=t.AD_Process_ID" + + " AND t.AD_Language='" + Env.getAD_Language(Env.getCtx()) + "') " + + "WHERE p.IsActive='Y'" + + " AND i.AD_PInstance_ID=?"; + // + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, + ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, null); + pstmt.setInt(1, m_pi.getAD_PInstance_ID()); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + m_pi.setTitle (rs.getString(1)); + if (m_waiting != null) + m_waiting.setTitle(m_pi.getTitle()); + ProcedureName = rs.getString(2); + m_pi.setClassName (rs.getString(3)); + m_pi.setAD_Process_ID (rs.getInt(4)); + // Report + if ("Y".equals(rs.getString(5))) + { + IsReport = true; + if ("Y".equals(rs.getString(6)) && !Ini.isPropertyBool(Ini.P_PRINTPREVIEW)) + IsDirectPrint = true; + } + AD_ReportView_ID = rs.getInt(7); + AD_Workflow_ID = rs.getInt(8); + // + int estimate = rs.getInt(9); + if (estimate != 0) + { + m_pi.setEstSeconds (estimate + 1); // admin overhead + if (m_waiting != null) + m_waiting.setTimerEstimate(m_pi.getEstSeconds()); + } + m_IsServerProcess = "Y".equals(rs.getString(10)); + } + else + log.log(Level.SEVERE, "No AD_PInstance_ID=" + m_pi.getAD_PInstance_ID()); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoProcedure") + " " + e.getLocalizedMessage(), true); + unlock(); + log.log(Level.SEVERE, "run", e); + return; + } + + // No PL/SQL Procedure + if (ProcedureName == null) + ProcedureName = ""; + + + /********************************************************************** + * Workflow + */ + if (AD_Workflow_ID > 0) + { + startWorkflow (AD_Workflow_ID); + unlock(); + return; + } + + /********************************************************************** + * Start Optional Class + */ + if (m_pi.getClassName() != null) + { + // Run Class + if (!startProcess()) + { + unlock(); + return; + } + + // No Optional SQL procedure ... done + if (!IsReport && ProcedureName.length() == 0) + { + unlock (); + return; + } + // No Optional Report ... done + if (IsReport && AD_ReportView_ID == 0) + { + unlock (); + return; + } + } + + // If not a report, we need a prodedure name + if (!IsReport && ProcedureName.length() == 0) + { + m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessNoProcedure"), true); + unlock(); + return; + } + + /********************************************************************** + * Report submission + */ + if (IsReport) + { + // Optional Pre-Report Process + if (ProcedureName.length() > 0) + { + if (!startDBProcess(ProcedureName)) + { + unlock(); + return; + } + } // Pre-Report + + // Start Report ----------------------------------------------- + boolean ok = ReportCtl.start(m_pi, IsDirectPrint); + m_pi.setSummary("Report", !ok); + unlock (); + } + /********************************************************************** + * Process submission + */ + else + { + if (!startDBProcess (ProcedureName)) + { + unlock(); + return; + } + // Success - getResult + ProcessInfoUtil.setSummaryFromDB(m_pi); + unlock(); + } // *** Process submission *** + // log.fine(Log.l3_Util, "ProcessCtl.run - done"); + } // run + + /** + * Lock UI & show Waiting + */ + private void lock () + { + // log.info("..."); + JFrame frame = Env.getFrame((Container)m_parent); + if (frame instanceof AWindow) + ((AWindow)frame).setBusyTimer(m_pi.getEstSeconds()); + else + m_waiting = new Waiting (frame, Msg.getMsg(Env.getCtx(), "Processing"), false, m_pi.getEstSeconds()); + SwingUtilities.invokeLater(new Runnable() + { + public void run() + { + log.finer("lock"); + m_parent.lockUI(m_pi); + } + }); + if (m_waiting != null) + { + m_waiting.toFront(); + m_waiting.setVisible(true); + } + } // lock + + /** + * Unlock UI & dispose Waiting. + * Called from run() + */ + private void unlock () + { + // log.info("..."); + if (m_pi.isBatch()) + m_pi.setIsTimeout(true); + SwingUtilities.invokeLater(new Runnable() + { + public void run() + { + String summary = m_pi.getSummary(); + log.finer("unlock - " + summary); + if (summary != null && summary.indexOf("@") != -1) + m_pi.setSummary(Msg.parseTranslation(Env.getCtx(), summary)); + m_parent.unlockUI(m_pi); + } + }); + // Remove Waiting/Processing Indicator + if (m_waiting != null) + m_waiting.dispose(); + m_waiting = null; + } // unlock + + + /************************************************************************** + * Start Workflow. + * + * @param AD_Workflow_ID workflow + * @return true if started + */ + private boolean startWorkflow (int AD_Workflow_ID) + { + log.fine(AD_Workflow_ID + " - " + m_pi); + boolean started = false; + if (DB.isRemoteProcess()) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + m_pi = server.workflow (Env.getCtx(), m_pi, AD_Workflow_ID); + log.finest("server => " + m_pi); + started = true; + } + } + catch (RemoteException ex) + { + log.log(Level.SEVERE, "AppsServer error", ex); + started = false; + } + } + // Run locally + if (!started && !m_IsServerProcess) + { + MWorkflow wf = MWorkflow.get (Env.getCtx(), AD_Workflow_ID); + MWFProcess wfProcess = null; + if (m_pi.isBatch()) + wfProcess = wf.start(m_pi); // may return null + else + wfProcess = wf.startWait(m_pi); // may return null + started = wfProcess != null; + } + return started; + } // startWorkflow + + /************************************************************************** * Start Java Process Class. * instanciate the class implementing the interface ProcessCall. * The class can be a Server/Client class (when in Package @@ -442,109 +442,109 @@ public class ProcessCtl extends Thread * (e.g. in org.compiere.report) * * @return true if success - */ - private boolean startProcess () - { - log.fine(m_pi.toString()); - boolean started = false; - if (DB.isRemoteProcess()) - { - Server server = CConnection.get().getServer(); - try - { - if (server != null) - { // See ServerBean - m_pi = server.process (Env.getCtx(), m_pi); - log.finest("server => " + m_pi); - started = true; - } - } - catch (UndeclaredThrowableException ex) - { - Throwable cause = ex.getCause(); - if (cause != null) - { - if (cause instanceof InvalidClassException) - log.log(Level.SEVERE, "Version Server <> Client: " - + cause.toString() + " - " + m_pi, ex); - else - log.log(Level.SEVERE, "AppsServer error(1b): " - + cause.toString() + " - " + m_pi, ex); - } - else - log.log(Level.SEVERE, " AppsServer error(1) - " - + m_pi, ex); - started = false; - } - catch (RemoteException ex) - { - Throwable cause = ex.getCause(); - if (cause == null) - cause = ex; - log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); - started = false; - } - } - // Run locally - if (!started && !m_IsServerProcess) - { - ProcessCall myObject = null; - try - { - Class myClass = Class.forName(m_pi.getClassName()); - myObject = (ProcessCall)myClass.newInstance(); - if (myObject == null) - m_pi.setSummary("No Instance for " + m_pi.getClassName(), true); - else - myObject.startProcess(Env.getCtx(), m_pi, m_trx); - if (m_trx != null) - { - m_trx.commit(); - m_trx.close(); - } - } - catch (Exception e) - { - if (m_trx != null) - { - m_trx.rollback(); - m_trx.close(); - } - m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true); - log.log(Level.SEVERE, m_pi.getClassName(), e); - } - } - return !m_pi.isError(); - } // startProcess - - - /************************************************************************** - * Start Database Process - * @param ProcedureName PL/SQL procedure name - * @return true if success - */ - private boolean startDBProcess (String ProcedureName) - { - // execute on this thread/connection - log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")"); - String sql = "{call " + ProcedureName + "(?)}"; - try - { - CallableStatement cstmt = DB.prepareCall(sql); // ro?? - cstmt.setInt(1, m_pi.getAD_PInstance_ID()); - cstmt.executeUpdate(); - cstmt.close(); - } - catch (Exception e) - { - log.log(Level.SEVERE, sql, e); - m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + e.getLocalizedMessage()); - m_pi.setError (true); - return false; - } - // log.fine(Log.l4_Data, "ProcessCtl.startProcess - done"); - return true; - } // startDBProcess - - -} // ProcessCtl + */ + private boolean startProcess () + { + log.fine(m_pi.toString()); + boolean started = false; + if (DB.isRemoteProcess()) + { + Server server = CConnection.get().getServer(); + try + { + if (server != null) + { // See ServerBean + m_pi = server.process (Env.getCtx(), m_pi); + log.finest("server => " + m_pi); + started = true; + } + } + catch (UndeclaredThrowableException ex) + { + Throwable cause = ex.getCause(); + if (cause != null) + { + if (cause instanceof InvalidClassException) + log.log(Level.SEVERE, "Version Server <> Client: " + + cause.toString() + " - " + m_pi, ex); + else + log.log(Level.SEVERE, "AppsServer error(1b): " + + cause.toString() + " - " + m_pi, ex); + } + else + log.log(Level.SEVERE, " AppsServer error(1) - " + + m_pi, ex); + started = false; + } + catch (RemoteException ex) + { + Throwable cause = ex.getCause(); + if (cause == null) + cause = ex; + log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause); + started = false; + } + } + // Run locally + if (!started && !m_IsServerProcess) + { + ProcessCall myObject = null; + try + { + Class myClass = Class.forName(m_pi.getClassName()); + myObject = (ProcessCall)myClass.newInstance(); + if (myObject == null) + m_pi.setSummary("No Instance for " + m_pi.getClassName(), true); + else + myObject.startProcess(Env.getCtx(), m_pi, m_trx); + if (m_trx != null) + { + m_trx.commit(); + m_trx.close(); + } + } + catch (Exception e) + { + if (m_trx != null) + { + m_trx.rollback(); + m_trx.close(); + } + m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true); + log.log(Level.SEVERE, m_pi.getClassName(), e); + } + } + return !m_pi.isError(); + } // startProcess + + + /************************************************************************** + * Start Database Process + * @param ProcedureName PL/SQL procedure name + * @return true if success + */ + private boolean startDBProcess (String ProcedureName) + { + // execute on this thread/connection + log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")"); + String sql = "{call " + ProcedureName + "(?)}"; + try + { + CallableStatement cstmt = DB.prepareCall(sql); // ro?? + cstmt.setInt(1, m_pi.getAD_PInstance_ID()); + cstmt.executeUpdate(); + cstmt.close(); + } + catch (Exception e) + { + log.log(Level.SEVERE, sql, e); + m_pi.setSummary (Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + e.getLocalizedMessage()); + m_pi.setError (true); + return false; + } + // log.fine(Log.l4_Data, "ProcessCtl.startProcess - done"); + return true; + } // startDBProcess + + +} // ProcessCtl diff --git a/client/src/org/compiere/apps/ProcessDialog.java b/client/src/org/compiere/apps/ProcessDialog.java index 46a009bdb7..c97f87c7bc 100644 --- a/client/src/org/compiere/apps/ProcessDialog.java +++ b/client/src/org/compiere/apps/ProcessDialog.java @@ -1,421 +1,378 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; -import java.sql.*; -import java.util.logging.*; -import javax.swing.*; - -import org.adempiere.plaf.AdempierePLAF; -import org.compiere.plaf.*; -import org.compiere.print.*; -import org.compiere.process.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * 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 Jorg Janke - * @version $Id: ProcessDialog.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public class ProcessDialog extends CFrame - implements ActionListener, ASyncProcess -{ - /** - * Dialog to start Process - * - * @param AD_Process_ID process - * @param isSOTrx is sales trx - */ - public ProcessDialog (int AD_Process_ID, boolean isSOTrx) - { - super(); - log.info("Process=" + AD_Process_ID + "; SOTrx=" + isSOTrx); - enableEvents(AWTEvent.WINDOW_EVENT_MASK); - m_AD_Process_ID = AD_Process_ID; - m_WindowNo = Env.createWindowNo (this); - Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", isSOTrx ? "Y" : "N"); - try - { - jbInit(); - } - catch(Exception ex) - { - log.log(Level.SEVERE, "", ex); - } - } // ProcessDialog - - private int m_AD_Process_ID; - private int m_WindowNo; - private String m_Name = null; - private boolean m_IsReport = false; - private int[] m_ids = null; - private boolean m_isLocked = false; - private StringBuffer m_messageText = new StringBuffer(); - /** Logger */ - private static CLogger log = CLogger.getCLogger(ProcessDialog.class); - // - - private CPanel dialog = new CPanel() - { - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - Dimension m = getMinimumSize(); - if ( d.height < m.height || d.width < m.width ) { - Dimension d1 = new Dimension(); - d1.height = Math.max(d.height, m.height); - d1.width = Math.max(d.width, m.width); - return d1; - } else - return d; - } - }; - private BorderLayout mainLayout = new BorderLayout(); - private CPanel southPanel = new CPanel(); - private CButton bOK = ConfirmPanel.createOKButton(true); - private FlowLayout southLayout = new FlowLayout(); - private JEditorPane message = new JEditorPane() - { - public Dimension getPreferredSize() { - Dimension d = super.getPreferredSize(); - Dimension m = getMaximumSize(); - if ( d.height > m.height || d.width > m.width ) { - Dimension d1 = new Dimension(); - d1.height = Math.min(d.height, m.height); - d1.width = Math.min(d.width, m.width); - return d1; - } else - return d; - } - }; - private JScrollPane messagePane = new JScrollPane(message); - private CButton bPrint = ConfirmPanel.createPrintButton(true); - - private CPanel centerPanel = null; - private ProcessParameterPanel parameterPanel = null; - private JSeparator separator = new JSeparator(); - private ProcessInfo m_pi = null; - - /** - * Static Layout - * @throws Exception - */ - private void jbInit() throws Exception - { - setIconImage(Env.getImage("mProcess.gif")); - // - dialog.setLayout(mainLayout); - dialog.setMinimumSize(new Dimension(500, 200)); - bOK.addActionListener(this); - bPrint.addActionListener(this); - // - southPanel.setLayout(southLayout); - southLayout.setAlignment(FlowLayout.RIGHT); - message.setContentType("text/html"); - message.setEditable(false); - message.setBackground(Color.white); - message.setFocusable(false); - getContentPane().add(dialog); - dialog.add(southPanel, BorderLayout.SOUTH); - southPanel.add(bPrint, null); - southPanel.add(bOK, null); - dialog.add(messagePane, BorderLayout.NORTH); - messagePane.setBorder(null); - message.setMaximumSize(new Dimension(600, 300)); - centerPanel = new CPanel(); - centerPanel.setBorder(null); - centerPanel.setLayout(new BorderLayout()); - dialog.add(centerPanel, BorderLayout.CENTER); - // - this.getRootPane().setDefaultButton(bOK); - } // jbInit - - /** - * Set Visible - * (set focus to OK if visible) - * @param visible true if visible - */ - public void setVisible (boolean visible) - { - super.setVisible(visible); - if (visible) { - bOK.requestFocus(); - } - } // setVisible - - /** - * Dispose - */ - public void dispose() - { - Env.clearWinContext(m_WindowNo); - super.dispose(); - } // dispose - - - /** - * Dynamic Init - * @return true, if there is something to process (start from menu) - */ - public boolean init() - { - log.config(""); - // - boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Process"); - String sql = "SELECT Name, Description, Help, IsReport " - + "FROM AD_Process " - + "WHERE AD_Process_ID=?"; - if (trl) - sql = "SELECT t.Name, t.Description, t.Help, p.IsReport " - + "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(Env.getCtx())); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - m_Name = rs.getString(1); - m_IsReport = rs.getString(4).equals("Y"); - // - m_messageText.append(""); - String s = rs.getString(2); // Description - if (rs.wasNull()) - m_messageText.append(Msg.getMsg(Env.getCtx(), "StartProcess?")); - else - m_messageText.append(s); - m_messageText.append(""); - s = rs.getString(3); // Help - if (!rs.wasNull()) - m_messageText.append("

").append(s).append("

"); - } - - 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.setText(m_messageText.toString()); - bOK.setText(Msg.getMsg(Env.getCtx(), "Start")); - - /** Start Reports w/o asking - if (m_IsReport) - { - bOK.doClick(); - return false; // don't show - } - **/ - // Similar to 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.removeAll(); - if (parameterPanel.init()) { - centerPanel.add(separator, BorderLayout.NORTH); - centerPanel.add(parameterPanel, BorderLayout.CENTER); - } - dialog.revalidate(); - return true; - } // init - - /** - * ActionListener (Start) - * @param e ActionEvent - */ - public void actionPerformed (ActionEvent e) - { - if (e.getSource() == bOK) - { - if (bOK.getText().length() == 0) - dispose(); - else - { - // Trx trx = Trx.get(Trx.createTrxName("ProcessDialog"), true); - ProcessCtl.process(this, m_WindowNo, parameterPanel, m_pi, null); - } - } - - else if (e.getSource() == bPrint) - printScreen(); - } // actionPerformed - - - /** - * Lock User Interface - * Called from the Worker before processing - * @param pi process info - */ - public void lockUI (ProcessInfo pi) - { - bOK.setText(""); - bOK.setEnabled(false); - this.setEnabled(false); - m_isLocked = true; - } // lockUI - - /** - * Unlock User Interface. - * Called from the Worker when processing is done - * @param pi process info - */ - public void unlockUI (ProcessInfo pi) - { - ProcessInfoUtil.setLogFromDB(pi); - m_messageText.append("

** ") - .append(pi.getSummary()) - .append("

"); - m_messageText.append(pi.getLogInfo(true)); - message.setText(m_messageText.toString()); - message.setCaretPosition(message.getDocument().getLength()); // scroll down - m_ids = pi.getIDs(); - // - bOK.setEnabled(true); - this.setEnabled(true); - m_isLocked = false; - // - afterProcessTask(); - // Close automatically - if (m_IsReport && !pi.isError()) - bOK.doClick(); - } // unlockUI - - /** - * Is the UI locked (Internal method) - * @return true, if UI is locked - */ - public boolean isUILocked() - { - return m_isLocked; - } // isLoacked - - /** - * Method to be executed async. - * Called from the ASyncProcess worker - * @param pi process info - */ - public void executeASync (ProcessInfo pi) - { - log.config("-"); - } // executeASync - - - /************************************************************************** - * 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("

").append(Msg.getMsg(Env.getCtx(), "PrintShipments")).append("

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

").append(Msg.getMsg(Env.getCtx(), "PrintInvoices")).append("

"); - 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, 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 Screen - */ - private void printScreen() - { - PrintScreenPainter.printScreen (this); - } // printScreen - -} // ProcessDialog +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import java.sql.*; +import java.util.logging.*; +import javax.swing.*; + +import org.adempiere.plaf.AdempierePLAF; +import org.compiere.plaf.*; +import org.compiere.print.*; +import org.compiere.process.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * 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 Jorg Janke + * @version $Id: ProcessDialog.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public class ProcessDialog extends CFrame + implements ActionListener, ASyncProcess +{ + /** + * Dialog to start Process + * + * @param AD_Process_ID process + * @param isSOTrx is sales trx + */ + public ProcessDialog (int AD_Process_ID, boolean isSOTrx) + { + super(); + log.info("Process=" + AD_Process_ID + "; SOTrx=" + isSOTrx); + enableEvents(AWTEvent.WINDOW_EVENT_MASK); + m_AD_Process_ID = AD_Process_ID; + m_WindowNo = Env.createWindowNo (this); + Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", isSOTrx ? "Y" : "N"); + try + { + jbInit(); + } + catch(Exception ex) + { + log.log(Level.SEVERE, "", ex); + } + } // ProcessDialog + + private int m_AD_Process_ID; + private int m_WindowNo; + private String m_Name = null; + private boolean m_IsReport = false; + private int[] m_ids = null; + private boolean m_isLocked = false; + private StringBuffer m_messageText = new StringBuffer(); + /** Logger */ + private static CLogger log = CLogger.getCLogger(ProcessDialog.class); + // + + private CPanel dialog = new CPanel(); + private BorderLayout mainLayout = new BorderLayout(); + private CPanel southPanel = new CPanel(); + private CButton bOK = ConfirmPanel.createOKButton(true); + private FlowLayout southLayout = new FlowLayout(); + private JEditorPane message = new JEditorPane(); + private JScrollPane messagePane = new JScrollPane(message); + private CButton bPrint = ConfirmPanel.createPrintButton(true); + + /** + * Static Layout + * @throws Exception + */ + private void jbInit() throws Exception + { + setIconImage(Env.getImage("mProcess.gif")); + // + dialog.setLayout(mainLayout); + bOK.addActionListener(this); + bPrint.addActionListener(this); + // + southPanel.setLayout(southLayout); + southLayout.setAlignment(FlowLayout.RIGHT); + dialog.setPreferredSize(new Dimension(500, 150)); + message.setContentType("text/html"); + message.setEditable(false); + message.setBackground(AdempierePLAF.getFieldBackground_Inactive()); + message.setFocusable(false); + getContentPane().add(dialog); + dialog.add(southPanel, BorderLayout.SOUTH); + southPanel.add(bPrint, null); + southPanel.add(bOK, null); + dialog.add(messagePane, BorderLayout.CENTER); + // + this.getRootPane().setDefaultButton(bOK); + } // jbInit + + /** + * Set Visible + * (set focus to OK if visible) + * @param visible true if visible + */ + public void setVisible (boolean visible) + { + super.setVisible(visible); + if (visible) + bOK.requestFocus(); + } // setVisible + + /** + * Dispose + */ + public void dispose() + { + Env.clearWinContext(m_WindowNo); + super.dispose(); + } // dispose + + + /** + * Dynamic Init + * @return true, if there is something to process (start from menu) + */ + public boolean init() + { + log.config(""); + // + boolean trl = !Env.isBaseLanguage(Env.getCtx(), "AD_Process"); + String sql = "SELECT Name, Description, Help, IsReport " + + "FROM AD_Process " + + "WHERE AD_Process_ID=?"; + if (trl) + sql = "SELECT t.Name, t.Description, t.Help, p.IsReport " + + "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(Env.getCtx())); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + m_Name = rs.getString(1); + m_IsReport = rs.getString(4).equals("Y"); + // + m_messageText.append(""); + String s = rs.getString(2); // Description + if (rs.wasNull()) + m_messageText.append(Msg.getMsg(Env.getCtx(), "StartProcess?")); + else + m_messageText.append(s); + m_messageText.append(""); + s = rs.getString(3); // Help + if (!rs.wasNull()) + m_messageText.append("

").append(s).append("

"); + } + + 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.setText(m_messageText.toString()); + bOK.setText(Msg.getMsg(Env.getCtx(), "Start")); + + /** Start Reports w/o asking + if (m_IsReport) + { + bOK.doClick(); + return false; // don't show + } + **/ + return true; + } // init + + /** + * ActionListener (Start) + * @param e ActionEvent + */ + public void actionPerformed (ActionEvent e) + { + if (e.getSource() == bOK) + { + if (bOK.getText().length() == 0) + dispose(); + else + { + // Similar to APanel.actionButton + ProcessInfo pi = new ProcessInfo(m_Name, m_AD_Process_ID); + pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx())); + pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx())); + m_messageText.append("

** ").append(m_Name).append("

"); + message.setText(m_messageText.toString()); + // Trx trx = Trx.get(Trx.createTrxName("ProcessDialog"), true); + ProcessCtl.process(this, m_WindowNo, pi, null); + } + } + + else if (e.getSource() == bPrint) + printScreen(); + } // actionPerformed + + + /** + * Lock User Interface + * Called from the Worker before processing + * @param pi process info + */ + public void lockUI (ProcessInfo pi) + { + bOK.setText(""); + bOK.setEnabled(false); + this.setEnabled(false); + m_isLocked = true; + } // lockUI + + /** + * Unlock User Interface. + * Called from the Worker when processing is done + * @param pi process info + */ + public void unlockUI (ProcessInfo pi) + { + ProcessInfoUtil.setLogFromDB(pi); + m_messageText.append("

** ") + .append(pi.getSummary()) + .append("

"); + m_messageText.append(pi.getLogInfo(true)); + message.setText(m_messageText.toString()); + message.setCaretPosition(message.getDocument().getLength()); // scroll down + m_ids = pi.getIDs(); + // + bOK.setEnabled(true); + this.setEnabled(true); + m_isLocked = false; + // + afterProcessTask(); + // Close automatically + if (m_IsReport && !pi.isError()) + bOK.doClick(); + } // unlockUI + + /** + * Is the UI locked (Internal method) + * @return true, if UI is locked + */ + public boolean isUILocked() + { + return m_isLocked; + } // isLoacked + + /** + * Method to be executed async. + * Called from the ASyncProcess worker + * @param pi process info + */ + public void executeASync (ProcessInfo pi) + { + log.config("-"); + } // executeASync + + + /************************************************************************** + * 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("

").append(Msg.getMsg(Env.getCtx(), "PrintShipments")).append("

"); + 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, 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("

").append(Msg.getMsg(Env.getCtx(), "PrintInvoices")).append("

"); + 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, 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 Screen + */ + private void printScreen() + { + PrintScreenPainter.printScreen (this); + } // printScreen + +} // ProcessDialog diff --git a/client/src/org/compiere/apps/ProcessParameter.java b/client/src/org/compiere/apps/ProcessParameter.java index b3a1835318..813329af61 100644 --- a/client/src/org/compiere/apps/ProcessParameter.java +++ b/client/src/org/compiere/apps/ProcessParameter.java @@ -3,476 +3,470 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps; - -import java.awt.*; -import java.awt.event.*; -import java.beans.*; -import java.math.*; -import java.sql.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; -import org.compiere.grid.ed.*; -import org.compiere.model.*; -import org.compiere.process.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Parameter Dialog. - * - called from ProcessCtl - * - checks, if parameters exist and inquires and saves them - * - * @author Jorg Janke - * @version $Id: ProcessParameter.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public class ProcessParameter extends CDialog - implements ActionListener, VetoableChangeListener -{ - /** - * Dynamic generated Parameter Dialog screen. - * Called from ProcessCtl.process - * - * @param frame frame - * @param WindowNo window - * @param pi process info - */ - public ProcessParameter (Frame frame, int WindowNo, ProcessInfo pi) - { - super(frame, pi.getTitle(), true); - m_frame = frame; - try - { - jbInit(); - } - catch(Exception ex) - { - log.log(Level.SEVERE, ex.getMessage()); - } - // - m_WindowNo = WindowNo; - m_processInfo = pi; - // - } // ProcessParameter - - private Frame m_frame; - private int m_WindowNo; - private ProcessInfo m_processInfo; - private boolean m_isOK = false; - /** Logger */ - private static CLogger log = CLogger.getCLogger(ProcessParameter.class); - // - private GridBagConstraints gbc = new GridBagConstraints(); - private Insets nullInset = new Insets(0,0,0,0); - private Insets labelInset = new Insets(2,12,2,0); // top,left,bottom,right - private Insets fieldInset = new Insets(2,5,2,0); // top,left,bottom,right - private Insets fieldInsetRight = new Insets(2,5,2,12); // top,left,bottom,right - private int m_line = 0; - // - private ArrayList m_vEditors = new ArrayList(); - private ArrayList m_vEditors2 = new ArrayList(); // for ranges - private ArrayList m_mFields = new ArrayList(); - private ArrayList m_mFields2 = new ArrayList(); - // - private CPanel mainPanel = new CPanel(); - private BorderLayout mainLayout = new BorderLayout(); - private CPanel centerPanel = new CPanel(); - private GridBagLayout centerLayout = new GridBagLayout(); - private ConfirmPanel confirmPanel = new ConfirmPanel(true); - - /** - * Static Layout - * @throws Exception - */ - void jbInit() throws Exception - { - mainPanel.setLayout(mainLayout); - centerPanel.setLayout(centerLayout); - this.getContentPane().add(mainPanel); - mainPanel.add(centerPanel, BorderLayout.CENTER); - mainPanel.add(confirmPanel, BorderLayout.SOUTH); - confirmPanel.addActionListener(this); - } // jbInit - - /** - * Dispose - */ - public void dispose() - { - m_vEditors.clear(); - m_vEditors2.clear(); - m_mFields.clear(); - m_mFields2.clear(); - this.removeAll(); - super.dispose(); - } // dispose - - /** - * Read Fields to display - * @return true if loaded OK - */ - public boolean initDialog() - { - log.config(""); - - // Prepare panel - gbc.anchor = GridBagConstraints.NORTHWEST; - gbc.weightx = 0; - gbc.weighty = 0; - gbc.gridy = m_line++; - gbc.gridx = 0; - gbc.gridwidth = 1; - gbc.insets = nullInset; - gbc.fill = GridBagConstraints.HORIZONTAL; - centerPanel.add(Box.createVerticalStrut(10), gbc); // top gap 10+2=12 - - // - 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; - 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); - } - 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_vEditors.size() - || m_mFields2.size() != m_vEditors2.size()) - log.log(Level.SEVERE, "View & Model vector size is different"); - - // clean up - if (hasFields) - { - gbc.gridy = m_line++; - centerPanel.add(Box.createVerticalStrut(10), gbc); // bottom gap - gbc.gridx = 3; - centerPanel.add(Box.createHorizontalStrut(12), gbc); // right gap - AEnv.positionCenterWindow(m_frame, this); - } - 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. - *

- * 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) - { - // Create Field - GridFieldVO voF = GridFieldVO.createParameter(Env.getCtx(), m_WindowNo, rs); - GridField mField = new GridField (voF); - m_mFields.add(mField); // add to Fields - - // Label Preparation - gbc.gridy = m_line++; - gbc.gridwidth = 1; - gbc.fill = GridBagConstraints.HORIZONTAL; // required for right justified - gbc.gridx = 0; - gbc.weightx = 0; - JLabel label = VEditorFactory.getLabel(mField); - if (label == null) - { - gbc.insets = nullInset; - centerPanel.add(Box.createHorizontalStrut(12), gbc); // left gap - } - else - { - gbc.insets = labelInset; - centerPanel.add(label, gbc); - } - - // Field Preparation - gbc.insets = fieldInset; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.gridwidth = 1; - gbc.gridx = 1; - gbc.weightx = 1; - - // The Editor - VEditor vEditor = VEditorFactory.getEditor(mField, false); - vEditor.addVetoableChangeListener(this); - // MField => VEditor - New Field value to be updated to editor - mField.addPropertyChangeListener(vEditor); - // Set Default - Object defaultObject = mField.getDefault(); - mField.setValue (defaultObject, true); - // - centerPanel.add ((Component)vEditor, gbc); - m_vEditors.add (vEditor); // add to Editors - // - if (voF.isRange) + * 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 * + *****************************************************************************/ +package org.compiere.apps; + +import java.awt.*; +import java.awt.event.*; +import java.beans.*; +import java.math.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; +import org.compiere.grid.ed.*; +import org.compiere.model.*; +import org.compiere.process.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Parameter Dialog. + * - called from ProcessCtl + * - checks, if parameters exist and inquires and saves them + * + * @author Jorg Janke + * @version $Id: ProcessParameter.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public class ProcessParameter extends CDialog + implements ActionListener, VetoableChangeListener +{ + /** + * Dynamic generated Parameter Dialog screen. + * Called from ProcessCtl.process + * + * @param frame frame + * @param WindowNo window + * @param pi process info + */ + public ProcessParameter (Frame frame, int WindowNo, ProcessInfo pi) + { + super(frame, pi.getTitle(), true); + m_frame = frame; + try + { + jbInit(); + } + catch(Exception ex) + { + log.log(Level.SEVERE, ex.getMessage()); + } + // + m_WindowNo = WindowNo; + m_processInfo = pi; + // + } // ProcessParameter + + private Frame m_frame; + private int m_WindowNo; + private ProcessInfo m_processInfo; + private boolean m_isOK = false; + /** Logger */ + private static CLogger log = CLogger.getCLogger(ProcessParameter.class); + // + private GridBagConstraints gbc = new GridBagConstraints(); + private Insets nullInset = new Insets(0,0,0,0); + private Insets labelInset = new Insets(2,12,2,0); // top,left,bottom,right + private Insets fieldInset = new Insets(2,5,2,0); // top,left,bottom,right + private Insets fieldInsetRight = new Insets(2,5,2,12); // top,left,bottom,right + private int m_line = 0; + // + private ArrayList m_vEditors = new ArrayList(); + private ArrayList m_vEditors2 = new ArrayList(); // for ranges + private ArrayList m_mFields = new ArrayList(); + private ArrayList m_mFields2 = new ArrayList(); + // + private CPanel mainPanel = new CPanel(); + private BorderLayout mainLayout = new BorderLayout(); + private CPanel centerPanel = new CPanel(); + private GridBagLayout centerLayout = new GridBagLayout(); + private ConfirmPanel confirmPanel = new ConfirmPanel(true); + + /** + * Static Layout + * @throws Exception + */ + void jbInit() throws Exception + { + mainPanel.setLayout(mainLayout); + centerPanel.setLayout(centerLayout); + this.getContentPane().add(mainPanel); + mainPanel.add(centerPanel, BorderLayout.CENTER); + mainPanel.add(confirmPanel, BorderLayout.SOUTH); + confirmPanel.addActionListener(this); + } // jbInit + + /** + * Dispose + */ + public void dispose() + { + m_vEditors.clear(); + m_vEditors2.clear(); + m_mFields.clear(); + m_mFields2.clear(); + this.removeAll(); + super.dispose(); + } // dispose + + /** + * Read Fields to display + * @return true if loaded OK + */ + public boolean initDialog() + { + log.config(""); + + // Prepare panel + gbc.anchor = GridBagConstraints.NORTHWEST; + gbc.weightx = 0; + gbc.weighty = 0; + gbc.gridy = m_line++; + gbc.gridx = 0; + gbc.gridwidth = 1; + gbc.insets = nullInset; + gbc.fill = GridBagConstraints.HORIZONTAL; + centerPanel.add(Box.createVerticalStrut(10), gbc); // top gap 10+2=12 + + // + 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; + 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); + } + 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_vEditors.size() + || m_mFields2.size() != m_vEditors2.size()) + log.log(Level.SEVERE, "View & Model vector size is different"); + + // clean up + if (hasFields) + { + gbc.gridy = m_line++; + centerPanel.add(Box.createVerticalStrut(10), gbc); // bottom gap + gbc.gridx = 3; + centerPanel.add(Box.createHorizontalStrut(12), gbc); // right gap + AEnv.positionCenterWindow(m_frame, this); + } + 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. + *

+ * 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) + { + // Create Field + GridFieldVO voF = GridFieldVO.createParameter(Env.getCtx(), m_WindowNo, rs); + GridField mField = new GridField (voF); + m_mFields.add(mField); // add to Fields + + // Label Preparation + gbc.gridy = m_line++; + gbc.gridwidth = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; // required for right justified + gbc.gridx = 0; + gbc.weightx = 0; + JLabel label = VEditorFactory.getLabel(mField); + if (label == null) + { + gbc.insets = nullInset; + centerPanel.add(Box.createHorizontalStrut(12), gbc); // left gap + } + else + { + gbc.insets = labelInset; + centerPanel.add(label, gbc); + } + + // Field Preparation + gbc.insets = fieldInset; + gbc.fill = GridBagConstraints.HORIZONTAL; + gbc.gridwidth = 1; + gbc.gridx = 1; + gbc.weightx = 1; + + // The Editor + VEditor vEditor = VEditorFactory.getEditor(mField, false); + vEditor.addVetoableChangeListener(this); + // MField => VEditor - New Field value to be updated to editor + mField.addPropertyChangeListener(vEditor); + // Set Default + Object defaultObject = mField.getDefault(); + mField.setValue (defaultObject, true); + // + centerPanel.add ((Component)vEditor, gbc); + m_vEditors.add (vEditor); // add to Editors + // + if (voF.isRange) { // To Label gbc.gridx = 2; - gbc.weightx = 0; - gbc.fill = GridBagConstraints.NONE; centerPanel.add (new JLabel(" - "), gbc); // To Field gbc.gridx = 3; gbc.insets = fieldInsetRight; - gbc.weightx = 1; - gbc.fill = GridBagConstraints.HORIZONTAL; - gbc.anchor = GridBagConstraints.WEST; - // GridFieldVO voF2 = GridFieldVO.createParameter(voF); GridField mField2 = new GridField (voF2); - m_mFields2.add (mField2); - // The Editor - VEditor vEditor2 = VEditorFactory.getEditor(mField2, false); - // New Field value to be updated to editor - mField2.addPropertyChangeListener(vEditor2); - // Set Default - Object defaultObject2 = mField2.getDefault(); - mField2.setValue (defaultObject2, true); - // - centerPanel.add ((Component)vEditor2, gbc); - m_vEditors2.add (vEditor2); - } - else - { - m_mFields2.add (null); - m_vEditors2.add (null); - } - } // createField - - /** - * Action Listener - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - m_isOK = false; - if (e.getActionCommand().equals(ConfirmPanel.A_OK)) - { - // check if saving parameters is complete - if (saveParameters()) - { - m_isOK = true; - dispose(); - } - } - else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) - dispose(); - } // actionPerformed - - /** - * Editor Listener - * @param evt Event - * @exception PropertyVetoException if the recipient wishes to roll back. - */ - public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException - { - // log.fine( "ProcessParameter.vetoableChange"); - String value = evt.getNewValue() == null ? "" : evt.getNewValue().toString(); - Env.setContext(Env.getCtx(), m_WindowNo, evt.getPropertyName(), value); - } // vetoableChange - - /** - * Save Parameter values - * @return true if parameters saved - */ - private 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 - { - VEditor vEditor = (VEditor)m_vEditors.get(i); - Object data = vEditor.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 - VEditor vEditor2 = (VEditor)m_vEditors2.get(i); - if (vEditor2 != null) - { - Object data2 = vEditor.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 - VEditor editor = (VEditor)m_vEditors.get(i); - VEditor editor2 = (VEditor)m_vEditors2.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 - - /** - * Is everything OK? - * @return true if parameters saved correctly - */ - public boolean isOK() - { - return m_isOK; - } // isOK - -} // ProcessParameter + m_mFields2.add (mField2); + // The Editor + VEditor vEditor2 = VEditorFactory.getEditor(mField2, false); + // New Field value to be updated to editor + mField2.addPropertyChangeListener(vEditor2); + // Set Default + Object defaultObject2 = mField2.getDefault(); + mField2.setValue (defaultObject2, true); + // + centerPanel.add ((Component)vEditor2, gbc); + m_vEditors2.add (vEditor2); + } + else + { + m_mFields2.add (null); + m_vEditors2.add (null); + } + } // createField + + /** + * Action Listener + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + m_isOK = false; + if (e.getActionCommand().equals(ConfirmPanel.A_OK)) + { + // check if saving parameters is complete + if (saveParameters()) + { + m_isOK = true; + dispose(); + } + } + else if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) + dispose(); + } // actionPerformed + + /** + * Editor Listener + * @param evt Event + * @exception PropertyVetoException if the recipient wishes to roll back. + */ + public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException + { + // log.fine( "ProcessParameter.vetoableChange"); + String value = evt.getNewValue() == null ? "" : evt.getNewValue().toString(); + Env.setContext(Env.getCtx(), m_WindowNo, evt.getPropertyName(), value); + } // vetoableChange + + /** + * Save Parameter values + * @return true if parameters saved + */ + private 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 + { + VEditor vEditor = (VEditor)m_vEditors.get(i); + Object data = vEditor.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 + VEditor vEditor2 = (VEditor)m_vEditors2.get(i); + if (vEditor2 != null) + { + Object data2 = vEditor.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 + VEditor editor = (VEditor)m_vEditors.get(i); + VEditor editor2 = (VEditor)m_vEditors2.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 + + /** + * Is everything OK? + * @return true if parameters saved correctly + */ + public boolean isOK() + { + return m_isOK; + } // isOK + +} // ProcessParameter diff --git a/client/src/org/compiere/apps/WindowManager.java b/client/src/org/compiere/apps/WindowManager.java index fb8b4c5226..f0c3276920 100644 --- a/client/src/org/compiere/apps/WindowManager.java +++ b/client/src/org/compiere/apps/WindowManager.java @@ -123,7 +123,7 @@ public class WindowManager { for ( CFrame w : windows ) { if ( w instanceof FormFrame ) { FormFrame ff = (FormFrame)w; - if ( ff.getAD_Form_ID() == AD_FORM_ID ) + //if ( ff.getAD_Form_ID() == AD_FORM_ID ) return ff; } } diff --git a/client/src/org/compiere/apps/form/FormFrame.java b/client/src/org/compiere/apps/form/FormFrame.java index 6189a37846..e56584c742 100644 --- a/client/src/org/compiere/apps/form/FormFrame.java +++ b/client/src/org/compiere/apps/form/FormFrame.java @@ -3,88 +3,85 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps.form; - -import java.awt.*; -import java.awt.event.*; -import java.sql.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; - -import org.compiere.apps.*; -import org.compiere.model.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Form Framework - * - * @author Jorg Janke - * @version $Id: FormFrame.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class FormFrame extends CFrame - implements ActionListener -{ - /** - * Create Form. - * Need to call openForm - */ - public FormFrame () - { - super(); - addWindowListener(new java.awt.event.WindowAdapter() - { - public void windowOpened(java.awt.event.WindowEvent evt) - { - formWindowOpened(evt); - } - }); - - m_WindowNo = Env.createWindowNo (this); - setGlassPane(m_glassPane); - try - { - jbInit(); - createMenu(); - } - catch(Exception e) - { - log.log(Level.SEVERE, "", e); - } - } // FormFrame - - /** WindowNo */ - private int m_WindowNo; - /** The GlassPane */ - private AGlassPane m_glassPane = new AGlassPane(); - /** Description */ - private String m_Description = null; - /** Help */ - private String m_Help = null; - /** Menu Bar */ - private JMenuBar menuBar = new JMenuBar(); - /** The Panel to be displayed */ - private FormPanel m_panel = null; - /** Maximize Window */ + * 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 * + *****************************************************************************/ +package org.compiere.apps.form; + +import java.awt.*; +import java.awt.event.*; +import java.sql.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; + +import org.compiere.apps.*; +import org.compiere.model.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Form Framework + * + * @author Jorg Janke + * @version $Id: FormFrame.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public class FormFrame extends CFrame + implements ActionListener +{ + /** + * Create Form. + * Need to call openForm + */ + public FormFrame () + { + super(); + addWindowListener(new java.awt.event.WindowAdapter() + { + public void windowOpened(java.awt.event.WindowEvent evt) + { + formWindowOpened(evt); + } + }); + + m_WindowNo = Env.createWindowNo (this); + setGlassPane(m_glassPane); + try + { + jbInit(); + createMenu(); + } + catch(Exception e) + { + log.log(Level.SEVERE, "", e); + } + } // FormFrame + + /** WindowNo */ + private int m_WindowNo; + /** The GlassPane */ + private AGlassPane m_glassPane = new AGlassPane(); + /** Description */ + private String m_Description = null; + /** Help */ + private String m_Help = null; + /** Menu Bar */ + private JMenuBar menuBar = new JMenuBar(); + /** The Panel to be displayed */ + private FormPanel m_panel = null; + /** Maximize Window */ public boolean m_maximize = false; /** Logger */ private static CLogger log = CLogger.getCLogger(FormFrame.class); - - /** Form ID */ - private int p_AD_Form_ID = 0; - + /** * Static Init * @throws Exception @@ -95,280 +92,266 @@ public class FormFrame extends CFrame this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setJMenuBar(menuBar); } // jbInit - - /** - * Create Menu - */ - private void createMenu() - { - // File - JMenu mFile = AEnv.getMenu("File"); - menuBar.add(mFile); - AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); - AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, Event.SHIFT_MASK), mFile, this); - AEnv.addMenuItem("Report", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.ALT_MASK), mFile, this); - mFile.addSeparator(); - AEnv.addMenuItem("End", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.ALT_MASK), mFile, this); - AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.SHIFT_MASK+Event.ALT_MASK), mFile, this); - - // View - JMenu mView = AEnv.getMenu("View"); - menuBar.add(mView); - AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK), mView, this); - AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.SHIFT_MASK+Event.CTRL_MASK), mView, this); - AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), mView, this); - mView.addSeparator(); - AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); - AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); - AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); - AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); - AEnv.addMenuItem("InfoSchedule", "Info", null, mView, this); - - // Tools - JMenu mTools = AEnv.getMenu("Tools"); - menuBar.add(mTools); - AEnv.addMenuItem("Calculator", null, null, mTools, this); - AEnv.addMenuItem("Calendar", null, null, mTools, this); - AEnv.addMenuItem("Editor", null, null, mTools, this); - AEnv.addMenuItem("Script", null, null, mTools, this); - if (MRole.getDefault().isShowPreference()) - { + + /** + * Create Menu + */ + private void createMenu() + { + // File + JMenu mFile = AEnv.getMenu("File"); + menuBar.add(mFile); + AEnv.addMenuItem("PrintScreen", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, 0), mFile, this); + AEnv.addMenuItem("ScreenShot", null, KeyStroke.getKeyStroke(KeyEvent.VK_PRINTSCREEN, Event.SHIFT_MASK), mFile, this); + AEnv.addMenuItem("Report", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.ALT_MASK), mFile, this); + mFile.addSeparator(); + AEnv.addMenuItem("End", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.ALT_MASK), mFile, this); + AEnv.addMenuItem("Exit", null, KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.SHIFT_MASK+Event.ALT_MASK), mFile, this); + + // View + JMenu mView = AEnv.getMenu("View"); + menuBar.add(mView); + AEnv.addMenuItem("InfoProduct", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK), mView, this); + AEnv.addMenuItem("InfoBPartner", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.SHIFT_MASK+Event.CTRL_MASK), mView, this); + AEnv.addMenuItem("InfoAccount", null, KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK+Event.CTRL_MASK), mView, this); + mView.addSeparator(); + AEnv.addMenuItem("InfoOrder", "Info", null, mView, this); + AEnv.addMenuItem("InfoInvoice", "Info", null, mView, this); + AEnv.addMenuItem("InfoInOut", "Info", null, mView, this); + AEnv.addMenuItem("InfoPayment", "Info", null, mView, this); + AEnv.addMenuItem("InfoSchedule", "Info", null, mView, this); + + // Tools + JMenu mTools = AEnv.getMenu("Tools"); + menuBar.add(mTools); + AEnv.addMenuItem("Calculator", null, null, mTools, this); + AEnv.addMenuItem("Calendar", null, null, mTools, this); + AEnv.addMenuItem("Editor", null, null, mTools, this); + AEnv.addMenuItem("Script", null, null, mTools, this); + if (MRole.getDefault().isShowPreference()) + { mTools.addSeparator(); AEnv.addMenuItem("Preference", null, null, mTools, this); } - - // Window - AMenu aMenu = (AMenu)Env.getWindow(0); - JMenu mWindow = new WindowMenu(aMenu.getWindowManager(), this); - menuBar.add(mWindow); // Help JMenu mHelp = AEnv.getMenu("Help"); - menuBar.add(mHelp); - AEnv.addMenuItem("Help", "Help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), mHelp, this); - AEnv.addMenuItem("Online", null, null, mHelp, this); - AEnv.addMenuItem("EMailSupport", null, null, mHelp, this); - AEnv.addMenuItem("About", null, null, mHelp, this); - } // createMenu - - /** - * Dispose - */ - public void dispose() - { - log.config(""); - // recursive calls - if (Trace.isCalledFrom("JFrame")) // [x] close window pressed - m_panel.dispose(); - m_panel = null; - Env.clearWinContext(m_WindowNo); - super.dispose(); - } // dispose - - /** - * Open Form - * @param AD_Form_ID form - * @return true if form opened - */ - public boolean openForm (int AD_Form_ID) - { - Properties ctx = Env.getCtx(); - // - String name = null; - String className = null; - String sql = "SELECT Name, Description, ClassName, Help FROM AD_Form WHERE AD_Form_ID=?"; - boolean trl = !Env.isBaseLanguage(ctx, "AD_Form"); - if (trl) - sql = "SELECT t.Name, t.Description, f.ClassName, t.Help " - + "FROM AD_Form f INNER JOIN AD_Form_Trl t" - + " ON (f.AD_Form_ID=t.AD_Form_ID AND AD_Language=?)" - + "WHERE f.AD_Form_ID=?"; - - try - { - PreparedStatement pstmt = DB.prepareStatement (sql, null); - if (trl) - { - pstmt.setString(1, Env.getAD_Language(ctx)); - pstmt.setInt(2, AD_Form_ID); - } - else - pstmt.setInt(1, AD_Form_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - name = rs.getString(1); - m_Description = rs.getString(2); - className = rs.getString(3); - m_Help = rs.getString(4); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - if (className == null) - return false; - // - return openForm(AD_Form_ID, className, name); - } // openForm - - /** - * Open Form - * @param AD_Form_ID Form - * @param className class name - * @param name title - * @return true if started - */ - protected boolean openForm (int AD_Form_ID, String className, String name) - { - log.info("AD_Form_ID=" + AD_Form_ID + " - Class=" + className); - Properties ctx = Env.getCtx(); - Env.setContext(ctx, m_WindowNo, "WindowName", name); - setTitle(Env.getHeader(ctx, m_WindowNo)); - - try - { - // Create instance w/o parameters - m_panel = (FormPanel)Class.forName(className).newInstance(); - } - catch (Exception e) - { - log.log(Level.SEVERE, "Class=" + className + ", AD_Form_ID=" + AD_Form_ID, e); - return false; + menuBar.add(mHelp); + AEnv.addMenuItem("Help", "Help", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), mHelp, this); + AEnv.addMenuItem("Online", null, null, mHelp, this); + AEnv.addMenuItem("EMailSupport", null, null, mHelp, this); + AEnv.addMenuItem("About", null, null, mHelp, this); + } // createMenu + + /** + * Dispose + */ + public void dispose() + { + log.config(""); + // recursive calls + if (Trace.isCalledFrom("JFrame")) // [x] close window pressed + m_panel.dispose(); + m_panel = null; + Env.clearWinContext(m_WindowNo); + super.dispose(); + } // dispose + + /** + * Open Form + * @param AD_Form_ID form + * @return true if form opened + */ + public boolean openForm (int AD_Form_ID) + { + Properties ctx = Env.getCtx(); + // + String name = null; + String className = null; + String sql = "SELECT Name, Description, ClassName, Help FROM AD_Form WHERE AD_Form_ID=?"; + boolean trl = !Env.isBaseLanguage(ctx, "AD_Form"); + if (trl) + sql = "SELECT t.Name, t.Description, f.ClassName, t.Help " + + "FROM AD_Form f INNER JOIN AD_Form_Trl t" + + " ON (f.AD_Form_ID=t.AD_Form_ID AND AD_Language=?)" + + "WHERE f.AD_Form_ID=?"; + + try + { + PreparedStatement pstmt = DB.prepareStatement (sql, null); + if (trl) + { + pstmt.setString(1, Env.getAD_Language(ctx)); + pstmt.setInt(2, AD_Form_ID); + } + else + pstmt.setInt(1, AD_Form_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + name = rs.getString(1); + m_Description = rs.getString(2); + className = rs.getString(3); + m_Help = rs.getString(4); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + if (className == null) + return false; + // + return openForm(AD_Form_ID, className, name); + } // openForm + + /** + * Open Form + * @param AD_Form_ID Form + * @param className class name + * @param name title + * @return true if started + */ + protected boolean openForm (int AD_Form_ID, String className, String name) + { + log.info("AD_Form_ID=" + AD_Form_ID + " - Class=" + className); + Properties ctx = Env.getCtx(); + Env.setContext(ctx, m_WindowNo, "WindowName", name); + setTitle(Env.getHeader(ctx, m_WindowNo)); + + try + { + // Create instance w/o parameters + m_panel = (FormPanel)Class.forName(className).newInstance(); + } + catch (Exception e) + { + log.log(Level.SEVERE, "Class=" + className + ", AD_Form_ID=" + AD_Form_ID, e); + return false; } // m_panel.init(m_WindowNo, this); - p_AD_Form_ID = AD_Form_ID; return true; } // openForm - /** - * Get Form Panel - * @return form panel - */ - public FormPanel getFormPanel() - { - return m_panel; - } // getFormPanel - - /** - * Action Listener - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - String cmd = e.getActionCommand(); - if (cmd.equals("End")) - dispose(); - else if (cmd.equals("Help")) - actionHelp(); - else if (!AEnv.actionPerformed(cmd, m_WindowNo, this)) - log.log(Level.SEVERE, "Not handeled=" + cmd); - } // actionPerformed - - /** - * Show Help - */ - private void actionHelp() - { - StringBuffer sb = new StringBuffer(); - sb.append("

").append(m_Description).append("

") - .append(m_Help); - Help hlp = new Help (Env.getFrame(this), this.getTitle(), sb.toString()); - hlp.setVisible(true); - } // actionHelp - - - /************************************************************************* - * Set Window Busy - * @param busy busy - */ - public void setBusy (boolean busy) - { - if (busy == m_glassPane.isVisible()) - return; - log.info("Busy=" + busy); - if (busy) - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - else - setCursor(Cursor.getDefaultCursor()); - m_glassPane.setMessage(null); - m_glassPane.setVisible(busy); - m_glassPane.requestFocus(); - } // setBusy - - /** - * Set Busy Message - * @param AD_Message message - */ - public void setBusyMessage (String AD_Message) - { - m_glassPane.setMessage(AD_Message); - } // setBusyMessage - - /** - * Set and start Busy Counter - * @param time in seconds - */ - public void setBusyTimer (int time) - { - m_glassPane.setBusyTimer (time); - } // setBusyTimer - - - /** - * Set Maximize Window - * @param max maximize - */ - public void setMaximize (boolean max) - { - m_maximize = max; - } // setMaximize - - - /** - * Form Window Opened. - * Maximize window if required - * @param evt event - */ - private void formWindowOpened(java.awt.event.WindowEvent evt) - { - if (m_maximize == true) - { - super.setVisible(true); - super.setExtendedState(JFrame.MAXIMIZED_BOTH); - } - } // formWindowOpened - - /** - * Start Batch - * @param process - * @return running thread - */ - public Thread startBatch (final Runnable process) - { - Thread worker = new Thread() - { - public void run() - { - setBusy(true); - process.run(); - setBusy(false); - } - }; + /** + * Get Form Panel + * @return form panel + */ + public FormPanel getFormPanel() + { + return m_panel; + } // getFormPanel + + /** + * Action Listener + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + String cmd = e.getActionCommand(); + if (cmd.equals("End")) + dispose(); + else if (cmd.equals("Help")) + actionHelp(); + else if (!AEnv.actionPerformed(cmd, m_WindowNo, this)) + log.log(Level.SEVERE, "Not handeled=" + cmd); + } // actionPerformed + + /** + * Show Help + */ + private void actionHelp() + { + StringBuffer sb = new StringBuffer(); + sb.append("

").append(m_Description).append("

") + .append(m_Help); + Help hlp = new Help (Env.getFrame(this), this.getTitle(), sb.toString()); + hlp.setVisible(true); + } // actionHelp + + + /************************************************************************* + * Set Window Busy + * @param busy busy + */ + public void setBusy (boolean busy) + { + if (busy == m_glassPane.isVisible()) + return; + log.info("Busy=" + busy); + if (busy) + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + else + setCursor(Cursor.getDefaultCursor()); + m_glassPane.setMessage(null); + m_glassPane.setVisible(busy); + m_glassPane.requestFocus(); + } // setBusy + + /** + * Set Busy Message + * @param AD_Message message + */ + public void setBusyMessage (String AD_Message) + { + m_glassPane.setMessage(AD_Message); + } // setBusyMessage + + /** + * Set and start Busy Counter + * @param time in seconds + */ + public void setBusyTimer (int time) + { + m_glassPane.setBusyTimer (time); + } // setBusyTimer + + + /** + * Set Maximize Window + * @param max maximize + */ + public void setMaximize (boolean max) + { + m_maximize = max; + } // setMaximize + + + /** + * Form Window Opened. + * Maximize window if required + * @param evt event + */ + private void formWindowOpened(java.awt.event.WindowEvent evt) + { + if (m_maximize == true) + { + super.setVisible(true); + super.setExtendedState(JFrame.MAXIMIZED_BOTH); + } + } // formWindowOpened + + /** + * Start Batch + * @param process + * @return running thread + */ + public Thread startBatch (final Runnable process) + { + Thread worker = new Thread() + { + public void run() + { + setBusy(true); + process.run(); + setBusy(false); + } + }; worker.start(); return worker; } // startBatch - - /** - * @return Returns the AD_Form_ID. - */ - public int getAD_Form_ID () - { - return p_AD_Form_ID; - } // getAD_Window_ID - + } // FormFrame diff --git a/client/src/org/compiere/apps/form/VFileImport.java b/client/src/org/compiere/apps/form/VFileImport.java index bfad0880b2..695e834144 100644 --- a/client/src/org/compiere/apps/form/VFileImport.java +++ b/client/src/org/compiere/apps/form/VFileImport.java @@ -209,7 +209,7 @@ public class VFileImport extends CPanel confirmPanel.setEnabled(false); m_frame.setBusy(true); // - SwingWorker worker = new SwingWorker() + org.compiere.apps.SwingWorker worker = new org.compiere.apps.SwingWorker() { public Object construct() { diff --git a/client/src/org/compiere/apps/form/VPayPrint.java b/client/src/org/compiere/apps/form/VPayPrint.java index d5063efa7c..0934362da0 100644 --- a/client/src/org/compiere/apps/form/VPayPrint.java +++ b/client/src/org/compiere/apps/form/VPayPrint.java @@ -3,551 +3,551 @@ * 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 * - *****************************************************************************/ -package org.compiere.apps.form; - -import java.awt.*; -import java.awt.event.*; -import java.sql.*; -import java.util.logging.*; -import javax.swing.*; -import org.compiere.apps.*; -import org.compiere.grid.ed.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.print.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Payment Print & Export - * - * @author Jorg Janke - * @version $Id: VPayPrint.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class VPayPrint extends CPanel - implements FormPanel, ActionListener -{ - /** - * Initialize Panel - * @param WindowNo window - * @param frame frame + * 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 * + *****************************************************************************/ +package org.compiere.apps.form; + +import java.awt.*; +import java.awt.event.*; +import java.sql.*; +import java.util.logging.*; +import javax.swing.*; +import org.compiere.apps.*; +import org.compiere.grid.ed.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.print.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Payment Print & Export + * + * @author Jorg Janke + * @version $Id: VPayPrint.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public class VPayPrint extends CPanel + implements FormPanel, ActionListener +{ + /** + * Initialize Panel + * @param WindowNo window + * @param frame frame */ public void init (int WindowNo, FormFrame frame) { - log.info( "VPayPrint.init"); + log.info(""); m_WindowNo = WindowNo; m_frame = frame; try - { - jbInit(); - dynInit(); - frame.getContentPane().add(centerPanel, BorderLayout.CENTER); - frame.getContentPane().add(southPanel, BorderLayout.SOUTH); - } - catch(Exception e) - { - log.log(Level.SEVERE, "", e); - } - } // init - - /** Window No */ - private int m_WindowNo = 0; - /** FormFrame */ - private FormFrame m_frame; - /** 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(VPayPrint.class); - - // Static Variables - private CPanel centerPanel = new CPanel(); - private CPanel southPanel = new CPanel(); - private FlowLayout southLayout = new FlowLayout(); - private GridBagLayout centerLayout = new GridBagLayout(); - private JButton bPrint = ConfirmPanel.createPrintButton(true); - private JButton bExport = ConfirmPanel.createExportButton(true); - private JButton bCancel = ConfirmPanel.createCancelButton(true); - private JButton bProcess = ConfirmPanel.createProcessButton(Msg.getMsg(Env.getCtx(), "VPayPrintProcess")); - private CLabel lPaySelect = new CLabel(); - private CComboBox fPaySelect = new CComboBox(); - private CLabel lBank = new CLabel(); - private CLabel fBank = new CLabel(); - private CLabel lPaymentRule = new CLabel(); - private CComboBox fPaymentRule = new CComboBox(); - private CLabel lDocumentNo = new CLabel(); - private VNumber fDocumentNo = new VNumber(); - private CLabel lNoPayments = new CLabel(); - private CLabel fNoPayments = new CLabel(); - private CLabel lBalance = new CLabel(); - private VNumber fBalance = new VNumber(); - private CLabel lCurrency = new CLabel(); - private CLabel fCurrency = new CLabel(); - - /** - * Static Init - * @throws Exception - */ - private void jbInit() throws Exception - { - CompiereColor.setBackground(this); - // - southPanel.setLayout(southLayout); - southLayout.setAlignment(FlowLayout.RIGHT); - centerPanel.setLayout(centerLayout); - // - bPrint.addActionListener(this); - bExport.addActionListener(this); - bCancel.addActionListener(this); - // - bProcess.setText(Msg.getMsg(Env.getCtx(), "EFT")); - bProcess.setEnabled(false); - bProcess.addActionListener(this); - // - lPaySelect.setText(Msg.translate(Env.getCtx(), "C_PaySelection_ID")); - fPaySelect.addActionListener(this); - // - lBank.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); - // - lPaymentRule.setText(Msg.translate(Env.getCtx(), "PaymentRule")); - fPaymentRule.addActionListener(this); - // - lDocumentNo.setText(Msg.translate(Env.getCtx(), "DocumentNo")); - fDocumentNo.setDisplayType(DisplayType.Integer); - lNoPayments.setText(Msg.getMsg(Env.getCtx(), "NoOfPayments")); - fNoPayments.setText("0"); - lBalance.setText(Msg.translate(Env.getCtx(), "CurrentBalance")); - fBalance.setReadWrite(false); - fBalance.setDisplayType(DisplayType.Amount); - lCurrency.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); - // - southPanel.add(bCancel, null); - southPanel.add(bExport, null); - southPanel.add(bPrint, null); - southPanel.add(bProcess, null); - // - centerPanel.add(lPaySelect, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); - centerPanel.add(fPaySelect, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 0, 5, 12), 0, 0)); - centerPanel.add(lBank, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fBank, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(lPaymentRule, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fPaymentRule, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(lDocumentNo, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fDocumentNo, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(lNoPayments, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fNoPayments, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(lBalance, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); - centerPanel.add(fBalance, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); - centerPanel.add(lCurrency, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 12, 5), 0, 0)); - centerPanel.add(fCurrency, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 12, 12), 0, 0)); - } // VPayPrint - - /** - * 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.addItem(pp); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - if (fPaySelect.getItemCount() == 0) - ADialog.info(m_WindowNo, this, "VPayPrintNoRecords"); - } // dynInit - - /** - * Dispose - */ - public void dispose() - { - if (m_frame != null) - m_frame.dispose(); - m_frame = null; - } // dispose - - /** - * 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++) - { - KeyNamePair pp = (KeyNamePair)fPaySelect.getItemAt(i); - if (pp.getKey() == C_PaySelection_ID) - { - fPaySelect.setSelectedIndex(i); - return; - } - } - } // setsetPaySelection - - - /************************************************************************** - * Action Listener - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - // log.config( "VPayPrint.actionPerformed" + e.toString()); - if (e.getSource() == fPaySelect) - loadPaySelectInfo(); - else if (e.getSource() == fPaymentRule) - loadPaymentRuleInfo(); - // - else if (e.getSource() == bCancel) - dispose(); - else if (e.getSource() == bExport) - cmd_export(); - else if (e.getSource() == bProcess) - cmd_EFT(); - else if (e.getSource() == bPrint) - cmd_print(); - } // actionPerformed - - /** - * PaySelect changed - load Bank - */ - private void loadPaySelectInfo() - { - log.info( "VPayPrint.loadPaySelectInfo"); - if (fPaySelect.getSelectedIndex() == -1) - return; - - // load Banks from PaySelectLine - int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).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.setText(rs.getString(2)); - fCurrency.setText(rs.getString(3)); - fBalance.setValue(rs.getBigDecimal(4)); - } - else - { - m_C_BankAccount_ID = -1; - fBank.setText(""); - fCurrency.setText(""); - fBalance.setValue(Env.ZERO); - 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 - int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).getKey(); - fPaymentRule.removeAllItems(); - 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.addItem(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); - loadPaymentRuleInfo(); - } // loadPaymentRule - - /** - * PaymentRule changed - load DocumentNo, NoPayments, - * enable/disable EFT, Print - */ - private void loadPaymentRuleInfo() - { - ValueNamePair pp = (ValueNamePair)fPaymentRule.getSelectedItem(); - if (pp == null) - return; - String PaymentRule = pp.getValue(); - - log.info("PaymentRule=" + PaymentRule); - fNoPayments.setText(" "); - - int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).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.setText(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))); - else - { - log.log(Level.SEVERE, "VPayPrint.loadPaymentRuleInfo - No active BankAccountDoc for C_BankAccount_ID=" - + m_C_BankAccount_ID + " AND PaymentRule=" + PaymentRule); - ADialog.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() - { - String PaymentRule = ((ValueNamePair)fPaymentRule.getSelectedItem()).getValue(); - log.info(PaymentRule); - if (!getChecks(PaymentRule)) - return; - - // Get File Info - JFileChooser fc = new JFileChooser(); - fc.setDialogTitle(Msg.getMsg(Env.getCtx(), "Export")); - fc.setFileSelectionMode(JFileChooser.FILES_ONLY); - fc.setMultiSelectionEnabled(false); - fc.setSelectedFile(new java.io.File("paymentExport.txt")); - if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) - return; - - // Create File - int no = MPaySelectionCheck.exportToFile(m_checks, fc.getSelectedFile()); - ADialog.info(m_WindowNo, this, "Saved", - fc.getSelectedFile().getAbsolutePath() + "\n" - + Msg.getMsg(Env.getCtx(), "NoOfLines") + "=" + no); + { + jbInit(); + dynInit(); + frame.getContentPane().add(centerPanel, BorderLayout.CENTER); + frame.getContentPane().add(southPanel, BorderLayout.SOUTH); + } + catch(Exception e) + { + log.log(Level.SEVERE, "", e); + } + } // init + + /** Window No */ + private int m_WindowNo = 0; + /** FormFrame */ + private FormFrame m_frame; + /** 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(VPayPrint.class); + + // Static Variables + private CPanel centerPanel = new CPanel(); + private CPanel southPanel = new CPanel(); + private FlowLayout southLayout = new FlowLayout(); + private GridBagLayout centerLayout = new GridBagLayout(); + private JButton bPrint = ConfirmPanel.createPrintButton(true); + private JButton bExport = ConfirmPanel.createExportButton(true); + private JButton bCancel = ConfirmPanel.createCancelButton(true); + private JButton bProcess = ConfirmPanel.createProcessButton(Msg.getMsg(Env.getCtx(), "VPayPrintProcess")); + private CLabel lPaySelect = new CLabel(); + private CComboBox fPaySelect = new CComboBox(); + private CLabel lBank = new CLabel(); + private CLabel fBank = new CLabel(); + private CLabel lPaymentRule = new CLabel(); + private CComboBox fPaymentRule = new CComboBox(); + private CLabel lDocumentNo = new CLabel(); + private VNumber fDocumentNo = new VNumber(); + private CLabel lNoPayments = new CLabel(); + private CLabel fNoPayments = new CLabel(); + private CLabel lBalance = new CLabel(); + private VNumber fBalance = new VNumber(); + private CLabel lCurrency = new CLabel(); + private CLabel fCurrency = new CLabel(); + + /** + * Static Init + * @throws Exception + */ + private void jbInit() throws Exception + { + CompiereColor.setBackground(this); + // + southPanel.setLayout(southLayout); + southLayout.setAlignment(FlowLayout.RIGHT); + centerPanel.setLayout(centerLayout); + // + bPrint.addActionListener(this); + bExport.addActionListener(this); + bCancel.addActionListener(this); + // + bProcess.setText(Msg.getMsg(Env.getCtx(), "EFT")); + bProcess.setEnabled(false); + bProcess.addActionListener(this); + // + lPaySelect.setText(Msg.translate(Env.getCtx(), "C_PaySelection_ID")); + fPaySelect.addActionListener(this); + // + lBank.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); + // + lPaymentRule.setText(Msg.translate(Env.getCtx(), "PaymentRule")); + fPaymentRule.addActionListener(this); + // + lDocumentNo.setText(Msg.translate(Env.getCtx(), "DocumentNo")); + fDocumentNo.setDisplayType(DisplayType.Integer); + lNoPayments.setText(Msg.getMsg(Env.getCtx(), "NoOfPayments")); + fNoPayments.setText("0"); + lBalance.setText(Msg.translate(Env.getCtx(), "CurrentBalance")); + fBalance.setReadWrite(false); + fBalance.setDisplayType(DisplayType.Amount); + lCurrency.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); + // + southPanel.add(bCancel, null); + southPanel.add(bExport, null); + southPanel.add(bPrint, null); + southPanel.add(bProcess, null); + // + centerPanel.add(lPaySelect, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(12, 12, 5, 5), 0, 0)); + centerPanel.add(fPaySelect, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(12, 0, 5, 12), 0, 0)); + centerPanel.add(lBank, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fBank, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(lPaymentRule, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fPaymentRule, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(lDocumentNo, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fDocumentNo, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(lNoPayments, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fNoPayments, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(lBalance, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 5, 5), 0, 0)); + centerPanel.add(fBalance, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 5, 12), 0, 0)); + centerPanel.add(lCurrency, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 12, 12, 5), 0, 0)); + centerPanel.add(fCurrency, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 12, 12), 0, 0)); + } // VPayPrint + + /** + * 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.addItem(pp); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + if (fPaySelect.getItemCount() == 0) + ADialog.info(m_WindowNo, this, "VPayPrintNoRecords"); + } // dynInit + + /** + * Dispose + */ + public void dispose() + { + if (m_frame != null) + m_frame.dispose(); + m_frame = null; + } // dispose + + /** + * 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++) + { + KeyNamePair pp = (KeyNamePair)fPaySelect.getItemAt(i); + if (pp.getKey() == C_PaySelection_ID) + { + fPaySelect.setSelectedIndex(i); + return; + } + } + } // setsetPaySelection + + + /************************************************************************** + * Action Listener + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + // log.config( "VPayPrint.actionPerformed" + e.toString()); + if (e.getSource() == fPaySelect) + loadPaySelectInfo(); + else if (e.getSource() == fPaymentRule) + loadPaymentRuleInfo(); + // + else if (e.getSource() == bCancel) + dispose(); + else if (e.getSource() == bExport) + cmd_export(); + else if (e.getSource() == bProcess) + cmd_EFT(); + else if (e.getSource() == bPrint) + cmd_print(); + } // actionPerformed + + /** + * PaySelect changed - load Bank + */ + private void loadPaySelectInfo() + { + log.info( "VPayPrint.loadPaySelectInfo"); + if (fPaySelect.getSelectedIndex() == -1) + return; + + // load Banks from PaySelectLine + int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).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.setText(rs.getString(2)); + fCurrency.setText(rs.getString(3)); + fBalance.setValue(rs.getBigDecimal(4)); + } + else + { + m_C_BankAccount_ID = -1; + fBank.setText(""); + fCurrency.setText(""); + fBalance.setValue(Env.ZERO); + 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 + int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).getKey(); + fPaymentRule.removeAllItems(); + 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.addItem(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); + loadPaymentRuleInfo(); + } // loadPaymentRule + + /** + * PaymentRule changed - load DocumentNo, NoPayments, + * enable/disable EFT, Print + */ + private void loadPaymentRuleInfo() + { + ValueNamePair pp = (ValueNamePair)fPaymentRule.getSelectedItem(); + if (pp == null) + return; + String PaymentRule = pp.getValue(); + + log.info("PaymentRule=" + PaymentRule); + fNoPayments.setText(" "); + + int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).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.setText(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))); + else + { + log.log(Level.SEVERE, "VPayPrint.loadPaymentRuleInfo - No active BankAccountDoc for C_BankAccount_ID=" + + m_C_BankAccount_ID + " AND PaymentRule=" + PaymentRule); + ADialog.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() + { + String PaymentRule = ((ValueNamePair)fPaymentRule.getSelectedItem()).getValue(); + log.info(PaymentRule); + if (!getChecks(PaymentRule)) + return; + + // Get File Info + JFileChooser fc = new JFileChooser(); + fc.setDialogTitle(Msg.getMsg(Env.getCtx(), "Export")); + fc.setFileSelectionMode(JFileChooser.FILES_ONLY); + fc.setMultiSelectionEnabled(false); + fc.setSelectedFile(new java.io.File("paymentExport.txt")); + if (fc.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) + return; + + // Create File + int no = MPaySelectionCheck.exportToFile(m_checks, fc.getSelectedFile()); + ADialog.info(m_WindowNo, this, "Saved", + fc.getSelectedFile().getAbsolutePath() + "\n" + + Msg.getMsg(Env.getCtx(), "NoOfLines") + "=" + no); if (ADialog.ask(m_WindowNo, this, "VPayPrintSuccess?")) { - int lastDocumentNo = MPaySelectionCheck.confirmPrint (m_checks, m_batch); + // int lastDocumentNo = + MPaySelectionCheck.confirmPrint (m_checks, m_batch); // document No not updated } dispose(); - } // cmd_export - - /** - * Create EFT payment - */ - private void cmd_EFT() - { - String PaymentRule = ((ValueNamePair)fPaymentRule.getSelectedItem()).getValue(); - log.info(PaymentRule); + } // cmd_export + + /** + * Create EFT payment + */ + private void cmd_EFT() + { + String PaymentRule = ((ValueNamePair)fPaymentRule.getSelectedItem()).getValue(); + log.info(PaymentRule); + if (!getChecks(PaymentRule)) + return; + dispose(); + } // cmd_EFT + + /** + * Print Checks and/or Remittance + */ + private void cmd_print() + { + String PaymentRule = ((ValueNamePair)fPaymentRule.getSelectedItem()).getValue(); + log.info(PaymentRule); if (!getChecks(PaymentRule)) return; - dispose(); - } // cmd_EFT - - /** - * Print Checks and/or Remittance - */ - private void cmd_print() - { - String PaymentRule = ((ValueNamePair)fPaymentRule.getSelectedItem()).getValue(); - log.info(PaymentRule); - if (!getChecks(PaymentRule)) - return; - this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 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(), directPrint); - if (!somethingPrinted && ok) - somethingPrinted = true; - } - - // Confirm Print and Update BankAccountDoc - if (somethingPrinted && ADialog.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 (ADialog.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(), directPrint); - } - } // remittance - - this.setCursor(Cursor.getDefaultCursor()); - dispose(); - } // 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) - { - ADialog.error(m_WindowNo, this, "VPayPrintNoRecords", - "(" + Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID") + "=0)"); - return false; - } - - // get data - int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).getKey(); - int startDocumentNo = ((Number)fDocumentNo.getValue()).intValue(); - - log.config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo); + 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(), directPrint); + if (!somethingPrinted && ok) + somethingPrinted = true; + } + + // Confirm Print and Update BankAccountDoc + if (somethingPrinted && ADialog.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 (ADialog.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(), directPrint); + } + } // remittance + + this.setCursor(Cursor.getDefaultCursor()); + dispose(); + } // 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) + { + ADialog.error(m_WindowNo, this, "VPayPrintNoRecords", + "(" + Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID") + "=0)"); + return false; + } + + // get data + int C_PaySelection_ID = ((KeyNamePair)fPaySelect.getSelectedItem()).getKey(); + int startDocumentNo = ((Number)fDocumentNo.getValue()).intValue(); + + log.config("C_PaySelection_ID=" + C_PaySelection_ID + ", PaymentRule=" + PaymentRule + ", DocumentNo=" + startDocumentNo); // this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - // get Checks + // get Slecetions m_checks = MPaySelectionCheck.get(C_PaySelection_ID, PaymentRule, startDocumentNo, null); this.setCursor(Cursor.getDefaultCursor()); - // - if (m_checks == null || m_checks.length == 0) - { - ADialog.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 - -} // PayPrint + // + if (m_checks == null || m_checks.length == 0) + { + ADialog.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 + +} // PayPrint diff --git a/client/src/org/compiere/apps/form/VPaySelect.java b/client/src/org/compiere/apps/form/VPaySelect.java index 7752955ef4..74951901da 100644 --- a/client/src/org/compiere/apps/form/VPaySelect.java +++ b/client/src/org/compiere/apps/form/VPaySelect.java @@ -1,674 +1,689 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.apps.form; - -import java.awt.*; -import java.awt.event.*; -import java.math.*; -import java.sql.*; -import java.text.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; -import javax.swing.event.*; -import org.compiere.apps.*; -import org.compiere.grid.ed.*; -import org.compiere.minigrid.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.process.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Create Manual Payments From (AP) Invoices or (AR) Credit Memos. - * Allows user to select Invoices for payment. - * When Processed, PaySelection is created - * and optionally posted/generated and printed - * - * @author Jorg Janke - * @version $Id: VPaySelect.java,v 1.3 2006/07/30 00:51:28 jjanke Exp $ - */ -public class VPaySelect extends CPanel - implements FormPanel, ActionListener, TableModelListener, ASyncProcess -{ - /** @todo withholding */ - - /** - * Initialize Panel - * @param WindowNo window - * @param frame frame - */ - public void init (int WindowNo, FormFrame frame) - { - log.info(""); - m_WindowNo = WindowNo; - m_frame = frame; - try - { - jbInit(); - dynInit(); - frame.getContentPane().add(commandPanel, BorderLayout.SOUTH); - frame.getContentPane().add(mainPanel, BorderLayout.CENTER); - } - catch(Exception e) - { - log.log(Level.SEVERE, "", e); - } - } // init - - /** Window No */ - private int m_WindowNo = 0; - /** FormFrame */ - private FormFrame m_frame; - - /** Format */ - private DecimalFormat m_format = DisplayType.getNumberFormat(DisplayType.Amount); - /** Bank Balance */ - private BigDecimal m_bankBalance = new BigDecimal(0.0); - /** SQL for Query */ - private String m_sql; - /** Number of selected rows */ - private int m_noSelected = 0; - /** Client ID */ - private int m_AD_Client_ID = 0; - /**/ - private boolean m_isLocked = false; - /** Payment Selection */ - private MPaySelection m_ps = null; - /** Logger */ - private static CLogger log = CLogger.getCLogger(VPaySelect.class); - - // - private CPanel mainPanel = new CPanel(); - private BorderLayout mainLayout = new BorderLayout(); - private CPanel parameterPanel = new CPanel(); - private CLabel labelBankAccount = new CLabel(); - private VComboBox fieldBankAccount = new VComboBox(); - private GridBagLayout parameterLayout = new GridBagLayout(); - private CLabel labelBankBalance = new CLabel(); - private CLabel labelCurrency = new CLabel(); - private CLabel labelBalance = new CLabel(); - private VCheckBox onlyDue = new VCheckBox(); - private CLabel labelBPartner = new CLabel(); - private VComboBox fieldBPartner = new VComboBox(); - private JLabel dataStatus = new JLabel(); - private JScrollPane dataPane = new JScrollPane(); - private MiniTable miniTable = new MiniTable(); - private CPanel commandPanel = new CPanel(); - private JButton bCancel = ConfirmPanel.createCancelButton(true); - private JButton bGenerate = ConfirmPanel.createProcessButton(true); - private FlowLayout commandLayout = new FlowLayout(); - private JButton bRefresh = ConfirmPanel.createRefreshButton(true); - private CLabel labelPayDate = new CLabel(); - private VDate fieldPayDate = new VDate(); - private CLabel labelPaymentRule = new CLabel(); - private VComboBox fieldPaymentRule = new VComboBox(); - - /** - * Static Init - * @throws Exception - */ - private void jbInit() throws Exception - { - CompiereColor.setBackground(this); - // - mainPanel.setLayout(mainLayout); - parameterPanel.setLayout(parameterLayout); - // - labelBankAccount.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); - fieldBankAccount.addActionListener(this); - labelBPartner.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID")); - fieldBPartner.addActionListener(this); - bRefresh.addActionListener(this); - labelPayDate.setText(Msg.translate(Env.getCtx(), "PayDate")); - labelPaymentRule.setText(Msg.translate(Env.getCtx(), "PaymentRule")); - // - labelBankBalance.setText(Msg.translate(Env.getCtx(), "CurrentBalance")); - labelBalance.setText("0"); - onlyDue.setText(Msg.getMsg(Env.getCtx(), "OnlyDue")); - dataStatus.setText(" "); - // - bGenerate.addActionListener(this); - bCancel.addActionListener(this); - // - mainPanel.add(parameterPanel, BorderLayout.NORTH); - parameterPanel.add(labelBankAccount, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(fieldBankAccount, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(labelBankBalance, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(labelCurrency, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0)); - parameterPanel.add(labelBalance, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(labelBPartner, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(fieldBPartner, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(bRefresh, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(labelPayDate, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(fieldPayDate, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(labelPaymentRule, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(fieldPaymentRule, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - parameterPanel.add(onlyDue, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - mainPanel.add(dataStatus, BorderLayout.SOUTH); - mainPanel.add(dataPane, BorderLayout.CENTER); - dataPane.getViewport().add(miniTable, null); - // - commandPanel.setLayout(commandLayout); - commandLayout.setAlignment(FlowLayout.RIGHT); - commandLayout.setHgap(10); - commandPanel.add(bCancel, null); - commandPanel.add(bGenerate, null); - } // jbInit - - /** - * Dynamic Init. - * - Load Bank Info - * - Load BPartner - * - Init Table - */ - private void dynInit() - { - Properties ctx = Env.getCtx(); - - // Bank Account Info - 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); - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - boolean transfers = false; - BankInfo bi = new BankInfo (rs.getInt(1), rs.getInt(3), - rs.getString(2), rs.getString(4), - rs.getBigDecimal(5), transfers); - fieldBankAccount.addItem(bi); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - if (fieldBankAccount.getItemCount() == 0) - ADialog.error(m_WindowNo, this, "VPaySelectNoBank"); - else - fieldBankAccount.setSelectedIndex(0); - - // Optional BusinessPartner with unpaid AP Invoices - KeyNamePair pp = new KeyNamePair(0, ""); - fieldBPartner.addItem(pp); - 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' 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)); - fieldBPartner.addItem(pp); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - fieldBPartner.setSelectedIndex(0); - - /** prepare MiniTable - * - SELECT i.C_Invoice_ID, i.DateInvoiced+p.NetDays AS DateDue, - bp.Name, i.DocumentNo, c.ISO_Code, i.GrandTotal, - paymentTermDiscount(i.GrandTotal, i.C_PaymentTerm_ID, i.DateInvoiced, SysDate) AS Discount, - SysDate-paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced) AS DiscountDate, - i.GrandTotal-paymentTermDiscount(i.GrandTotal,i.C_PaymentTerm_ID,i.DateInvoiced,SysDate) AS DueAmount, - currencyConvert(i.GrandTotal-paymentTermDiscount(i.GrandTotal,i.C_PaymentTerm_ID,i.DateInvoiced,SysDate,null), - i.C_Currency_ID,xx100,SysDate) AS PayAmt - FROM C_Invoice i, C_BPartner bp, C_Currency c, C_PaymentTerm p - WHERE i.IsSOTrx='N' - AND i.C_BPartner_ID=bp.C_BPartner_ID - AND i.C_Currency_ID=c.C_Currency_ID - AND i.C_PaymentTerm_ID=p.C_PaymentTerm_ID - AND i.DocStatus IN ('CO','CL') - ORDER BY 2,3 - */ - - m_sql = miniTable.prepareTable(new ColumnInfo[] { - // 0..4 - new ColumnInfo(" ", "i.C_Invoice_ID", IDColumn.class, false, false, null), - new ColumnInfo(Msg.translate(ctx, "DateDue"), "i.DateInvoiced+p.NetDays AS DateDue", Timestamp.class, true, true, null), - new ColumnInfo(Msg.translate(ctx, "C_BPartner_ID"), "bp.Name", KeyNamePair.class, true, false, "i.C_BPartner_ID"), - new ColumnInfo(Msg.translate(ctx, "DocumentNo"), "i.DocumentNo", String.class), - new ColumnInfo(Msg.translate(ctx, "C_Currency_ID"), "c.ISO_Code", KeyNamePair.class, true, false, "i.C_Currency_ID"), - // 5..9 - new ColumnInfo(Msg.translate(ctx, "GrandTotal"), "i.GrandTotal", BigDecimal.class), - new ColumnInfo(Msg.translate(ctx, "DiscountAmt"), "paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?)", BigDecimal.class), - new ColumnInfo(Msg.getMsg(ctx, "DiscountDate"), "SysDate-paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced,SysDate)", Timestamp.class), - 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), - 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) - }, - // FROM - "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)", - // WHERE - "i.IsSOTrx='N' AND IsPaid='N'" - // Different Payment Selection - + " 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=?", // additional where & order in loadTableInfo() - true, "i"); - // - miniTable.getModel().addTableModelListener(this); - // - fieldPayDate.setMandatory(true); - fieldPayDate.setValue(new Timestamp(System.currentTimeMillis())); - // - m_AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); - } // dynInit - - /** - * Load Bank Info - Load Info from Bank Account and valid Documents (PaymentRule) - */ - private void loadBankInfo() - { - BankInfo bi = (BankInfo)fieldBankAccount.getSelectedItem(); - if (bi == null) - return; - labelCurrency.setText(bi.Currency); - labelBalance.setText(m_format.format(bi.Balance)); - m_bankBalance = bi.Balance; - - // PaymentRule - fieldPaymentRule.removeAllItems(); - int AD_Reference_ID = 195; // MLookupInfo.getAD_Reference_ID("All_Payment Rule"); - 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, bi.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 - fieldPaymentRule.addItem(vp); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - fieldPaymentRule.setSelectedIndex(0); - - } // loadBankInfo - - /** - * Query and create TableInfo - */ - private void loadTableInfo() - { - log.config(""); - // not yet initialized - if (m_sql == null) - return; - - String sql = m_sql; - // Parameters - Timestamp payDate = (Timestamp)fieldPayDate.getValue(); - miniTable.setColorCompare(payDate); - log.config("PayDate=" + payDate); - BankInfo bi = (BankInfo)fieldBankAccount.getSelectedItem(); - // - if (onlyDue.isSelected()) - sql += " AND i.DateInvoiced+p.NetDays <= ?"; - // - KeyNamePair pp = (KeyNamePair)fieldBPartner.getSelectedItem(); - 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); - - // Get Open Invoices - try - { - int index = 1; - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setTimestamp(index++, payDate); // DiscountAmt - pstmt.setInt(index++, bi.C_Currency_ID); // DueAmt - pstmt.setTimestamp(index++, payDate); - pstmt.setTimestamp(index++, payDate); // PayAmt - pstmt.setInt(index++, bi.C_Currency_ID); - pstmt.setTimestamp(index++, payDate); - pstmt.setInt(index++, m_AD_Client_ID); // - if (onlyDue.isSelected()) - pstmt.setTimestamp(index++, payDate); - if (C_BPartner_ID != 0) - pstmt.setInt(index++, C_BPartner_ID); - // - ResultSet rs = pstmt.executeQuery(); - miniTable.loadTable(rs); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - calculateSelection(); - } // loadTableInfo - - /** - * Dispose - */ - public void dispose() - { - if (m_frame != null) - m_frame.dispose(); - m_frame = null; - } // dispose - - - /************************************************************************** - * ActionListener - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - // Update Bank Info - if (e.getSource() == fieldBankAccount) - loadBankInfo(); - - // Generate PaySelection - else if (e.getSource() == bGenerate) - { - generatePaySelect(); - dispose(); - } - - else if (e.getSource() == bCancel) - dispose(); - - // Update Open Invoices - else if (e.getSource() == fieldBPartner || e.getSource() == bRefresh) - loadTableInfo(); - - } // actionPerformed - - /** - * Table Model Listener - * @param e event - */ - public void tableChanged(TableModelEvent e) - { - if (e.getColumn() == 0) - calculateSelection(); - } // valueChanged - - /** - * Calculate selected rows. - * - add up selected rows - */ - public void calculateSelection() - { - m_noSelected = 0; - BigDecimal invoiceAmt = new BigDecimal(0.0); - - int rows = miniTable.getRowCount(); - for (int i = 0; i < rows; i++) - { - IDColumn id = (IDColumn)miniTable.getModel().getValueAt(i, 0); - if (id.isSelected()) - { - BigDecimal amt = (BigDecimal)miniTable.getModel().getValueAt(i, 9); - invoiceAmt = invoiceAmt.add(amt); - m_noSelected++; - } - } - - // Information - BigDecimal remaining = m_bankBalance.subtract(invoiceAmt); - StringBuffer info = new StringBuffer(); - info.append(m_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)); - dataStatus.setText(info.toString()); - // - bGenerate.setEnabled(m_noSelected != 0); - } // calculateSelection - - /** - * Generate PaySelection - */ - private void generatePaySelect() - { - log.info(""); - // String trxName Trx.createTrxName("PaySelect"); - // Trx trx = Trx.get(trxName, true); trx needs to be committed too - String trxName = null; - Trx trx = null; - // - miniTable.stopEditor(true); - if (miniTable.getRowCount() == 0) - return; - miniTable.setRowSelectionInterval(0,0); - calculateSelection(); - if (m_noSelected == 0) - return; - - String PaymentRule = ((ValueNamePair)fieldPaymentRule.getSelectedItem()).getValue(); - - // Create Header - m_ps = new MPaySelection(Env.getCtx(), 0, trxName); - m_ps.setName (Msg.getMsg(Env.getCtx(), "VPaySelect") + " - " + fieldPayDate.getTimestamp()); - m_ps.setPayDate (fieldPayDate.getTimestamp()); - BankInfo bi = (BankInfo)fieldBankAccount.getSelectedItem(); - m_ps.setC_BankAccount_ID(bi.C_BankAccount_ID); - m_ps.setIsApproved(true); - if (!m_ps.save()) - { - ADialog.error(m_WindowNo, this, "SaveError", Msg.translate(Env.getCtx(), "C_PaySelection_ID")); - m_ps = null; - return; - } - log.config(m_ps.toString()); - - // Create Lines - int rows = miniTable.getRowCount(); - int line = 0; - for (int i = 0; i < rows; i++) - { - IDColumn id = (IDColumn)miniTable.getModel().getValueAt(i, 0); - if (id.isSelected()) - { - line += 10; - MPaySelectionLine psl = new MPaySelectionLine (m_ps, line, PaymentRule); - int C_Invoice_ID = id.getRecord_ID().intValue(); - BigDecimal OpenAmt = (BigDecimal)miniTable.getModel().getValueAt(i, 8); - BigDecimal PayAmt = (BigDecimal)miniTable.getModel().getValueAt(i, 9); - boolean isSOTrx = false; - // - psl.setInvoice(C_Invoice_ID, isSOTrx, - OpenAmt, PayAmt, OpenAmt.subtract(PayAmt)); - if (!psl.save(trxName)) - { - ADialog.error(m_WindowNo, this, "SaveError", Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID")); - return; - } - log.fine("C_Invoice_ID=" + C_Invoice_ID + ", PayAmt=" + PayAmt); - } - } // for all rows in table - - - // Ask to Post it - if (!ADialog.ask(m_WindowNo, this, "VPaySelectGenerate?", "(" + m_ps.getName() + ")")) - return; - - // Prepare Process PaySelectionCreateCheck - ProcessInfo pi = new ProcessInfo (m_frame.getTitle(), 155, - MPaySelection.Table_ID, m_ps.getC_PaySelection_ID()); - pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx())); - pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx())); - - // Execute Process - ProcessCtl.process(this, m_WindowNo, pi, trx); - // ProcessCtl worker = new ProcessCtl(this, pi, trx); - // worker.start(); // complete tasks in unlockUI - } // generatePaySelect - - /** - * Lock User Interface - * Called from the Worker before processing - * @param pi process info - */ - public void lockUI (ProcessInfo pi) - { - this.setEnabled(false); - m_isLocked = true; - } // lockUI - - /** - * Unlock User Interface. - * Called from the Worker when processing is done - * @param pi process info - */ - public void unlockUI (ProcessInfo pi) - { - // this.setEnabled(true); - // m_isLocked = false; - // Ask to Print it // Window is disposed - if (!ADialog.ask(0, this, "VPaySelectPrint?", "(" + pi.getSummary() + ")")) - return; - - // Start PayPrint - int AD_Form_ID = 106; // Payment Print/Export - FormFrame ff = new FormFrame(); - ff.openForm (AD_Form_ID); - // Set Parameter - if (m_ps != null) - { - VPayPrint pp = (VPayPrint)ff.getFormPanel(); - pp.setPaySelection(m_ps.getC_PaySelection_ID()); - } - // - ff.pack(); - this.setVisible(false); - AEnv.addToWindowManager(ff); - AEnv.showCenterScreen(ff); - this.dispose(); - } // unlockUI - - /** - * Is the UI locked (Internal method) - * @return true, if UI is locked - */ - public boolean isUILocked() - { - return m_isLocked; - } // isLoacked - - /** - * Method to be executed async. - * Called from the ASyncProcess worker - * @param pi process info - */ - public void executeASync (ProcessInfo pi) - { - log.config("-"); - } // executeASync - - - /************************************************************************** - * Bank Account Info - */ - 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; - } - } // BankInfo - -} // VPaySelect +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.apps.form; + +import java.awt.*; +import java.awt.event.*; +import java.math.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; +import javax.swing.event.*; +import org.compiere.apps.*; +import org.compiere.grid.ed.*; +import org.compiere.minigrid.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.process.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Create Manual Payments From (AP) Invoices or (AR) Credit Memos. + * Allows user to select Invoices for payment. + * When Processed, PaySelection is created + * and optionally posted/generated and printed + * + * @author Jorg Janke + * @version $Id: VPaySelect.java,v 1.3 2006/07/30 00:51:28 jjanke Exp $ + */ +public class VPaySelect extends CPanel + implements FormPanel, ActionListener, TableModelListener, ASyncProcess +{ + /** @todo withholding */ + + /** + * Initialize Panel + * @param WindowNo window + * @param frame frame + */ + public void init (int WindowNo, FormFrame frame) + { + log.info(""); + m_WindowNo = WindowNo; + m_frame = frame; + try + { + jbInit(); + dynInit(); + frame.getContentPane().add(commandPanel, BorderLayout.SOUTH); + frame.getContentPane().add(mainPanel, BorderLayout.CENTER); + } + catch(Exception e) + { + log.log(Level.SEVERE, "", e); + } + } // init + + /** Window No */ + private int m_WindowNo = 0; + /** FormFrame */ + private FormFrame m_frame; + + /** Format */ + private DecimalFormat m_format = DisplayType.getNumberFormat(DisplayType.Amount); + /** Bank Balance */ + private BigDecimal m_bankBalance = new BigDecimal(0.0); + /** SQL for Query */ + private String m_sql; + /** Number of selected rows */ + private int m_noSelected = 0; + /** Client ID */ + private int m_AD_Client_ID = 0; + /**/ + private boolean m_isLocked = false; + /** Payment Selection */ + private MPaySelection m_ps = null; + /** Logger */ + private static CLogger log = CLogger.getCLogger(VPaySelect.class); + + // + private CPanel mainPanel = new CPanel(); + private BorderLayout mainLayout = new BorderLayout(); + private CPanel parameterPanel = new CPanel(); + private CLabel labelBankAccount = new CLabel(); + private VComboBox fieldBankAccount = new VComboBox(); + private GridBagLayout parameterLayout = new GridBagLayout(); + private CLabel labelBankBalance = new CLabel(); + private CLabel labelCurrency = new CLabel(); + private CLabel labelBalance = new CLabel(); + private VCheckBox onlyDue = new VCheckBox(); + private CLabel labelBPartner = new CLabel(); + private VComboBox fieldBPartner = new VComboBox(); + private JLabel dataStatus = new JLabel(); + private JScrollPane dataPane = new JScrollPane(); + private MiniTable miniTable = new MiniTable(); + private CPanel commandPanel = new CPanel(); + private JButton bCancel = ConfirmPanel.createCancelButton(true); + private JButton bGenerate = ConfirmPanel.createProcessButton(true); + private FlowLayout commandLayout = new FlowLayout(); + private JButton bRefresh = ConfirmPanel.createRefreshButton(true); + private CLabel labelPayDate = new CLabel(); + private VDate fieldPayDate = new VDate(); + private CLabel labelPaymentRule = new CLabel(); + private VComboBox fieldPaymentRule = new VComboBox(); + + /** + * Static Init + * @throws Exception + */ + private void jbInit() throws Exception + { + CompiereColor.setBackground(this); + // + mainPanel.setLayout(mainLayout); + parameterPanel.setLayout(parameterLayout); + // + labelBankAccount.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); + fieldBankAccount.addActionListener(this); + labelBPartner.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID")); + fieldBPartner.addActionListener(this); + bRefresh.addActionListener(this); + labelPayDate.setText(Msg.translate(Env.getCtx(), "PayDate")); + labelPaymentRule.setText(Msg.translate(Env.getCtx(), "PaymentRule")); + fieldPaymentRule.addActionListener(this); + // + labelBankBalance.setText(Msg.translate(Env.getCtx(), "CurrentBalance")); + labelBalance.setText("0"); + onlyDue.setText(Msg.getMsg(Env.getCtx(), "OnlyDue")); + dataStatus.setText(" "); + // + bGenerate.addActionListener(this); + bCancel.addActionListener(this); + // + mainPanel.add(parameterPanel, BorderLayout.NORTH); + parameterPanel.add(labelBankAccount, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(fieldBankAccount, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(labelBankBalance, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(labelCurrency, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0)); + parameterPanel.add(labelBalance, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(labelBPartner, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(fieldBPartner, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(bRefresh, new GridBagConstraints(4, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(labelPayDate, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(fieldPayDate, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(labelPaymentRule, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(fieldPaymentRule, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + parameterPanel.add(onlyDue, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + mainPanel.add(dataStatus, BorderLayout.SOUTH); + mainPanel.add(dataPane, BorderLayout.CENTER); + dataPane.getViewport().add(miniTable, null); + // + commandPanel.setLayout(commandLayout); + commandLayout.setAlignment(FlowLayout.RIGHT); + commandLayout.setHgap(10); + commandPanel.add(bCancel, null); + commandPanel.add(bGenerate, null); + } // jbInit + + /** + * Dynamic Init. + * - Load Bank Info + * - Load BPartner + * - Init Table + */ + private void dynInit() + { + Properties ctx = Env.getCtx(); + + // Bank Account Info + 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); + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + boolean transfers = false; + BankInfo bi = new BankInfo (rs.getInt(1), rs.getInt(3), + rs.getString(2), rs.getString(4), + rs.getBigDecimal(5), transfers); + fieldBankAccount.addItem(bi); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + if (fieldBankAccount.getItemCount() == 0) + ADialog.error(m_WindowNo, this, "VPaySelectNoBank"); + else + fieldBankAccount.setSelectedIndex(0); + + // Optional BusinessPartner with unpaid AP Invoices + KeyNamePair pp = new KeyNamePair(0, ""); + fieldBPartner.addItem(pp); + 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" + // X_C_Order.PAYMENTRULE_DirectDebit + + " 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)); + fieldBPartner.addItem(pp); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + fieldBPartner.setSelectedIndex(0); + + /** prepare MiniTable + * + SELECT i.C_Invoice_ID, i.DateInvoiced+p.NetDays AS DateDue, + bp.Name, i.DocumentNo, c.ISO_Code, i.GrandTotal, + paymentTermDiscount(i.GrandTotal, i.C_PaymentTerm_ID, i.DateInvoiced, SysDate) AS Discount, + SysDate-paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced) AS DiscountDate, + i.GrandTotal-paymentTermDiscount(i.GrandTotal,i.C_PaymentTerm_ID,i.DateInvoiced,SysDate) AS DueAmount, + currencyConvert(i.GrandTotal-paymentTermDiscount(i.GrandTotal,i.C_PaymentTerm_ID,i.DateInvoiced,SysDate,null), + i.C_Currency_ID,xx100,SysDate) AS PayAmt + FROM C_Invoice i, C_BPartner bp, C_Currency c, C_PaymentTerm p + WHERE i.IsSOTrx='N' + AND i.C_BPartner_ID=bp.C_BPartner_ID + AND i.C_Currency_ID=c.C_Currency_ID + AND i.C_PaymentTerm_ID=p.C_PaymentTerm_ID + AND i.DocStatus IN ('CO','CL') + ORDER BY 2,3 + */ + + m_sql = miniTable.prepareTable(new ColumnInfo[] { + // 0..4 + new ColumnInfo(" ", "i.C_Invoice_ID", IDColumn.class, false, false, null), + new ColumnInfo(Msg.translate(ctx, "DueDate"), "i.DateInvoiced+p.NetDays AS DateDue", Timestamp.class, true, true, null), + new ColumnInfo(Msg.translate(ctx, "C_BPartner_ID"), "bp.Name", KeyNamePair.class, true, false, "i.C_BPartner_ID"), + new ColumnInfo(Msg.translate(ctx, "DocumentNo"), "i.DocumentNo", String.class), + new ColumnInfo(Msg.translate(ctx, "C_Currency_ID"), "c.ISO_Code", KeyNamePair.class, true, false, "i.C_Currency_ID"), + // 5..9 + new ColumnInfo(Msg.translate(ctx, "GrandTotal"), "i.GrandTotal", BigDecimal.class), + new ColumnInfo(Msg.translate(ctx, "DiscountAmt"), "paymentTermDiscount(i.GrandTotal,i.C_Currency_ID,i.C_PaymentTerm_ID,i.DateInvoiced, ?)", BigDecimal.class), + new ColumnInfo(Msg.getMsg(ctx, "DiscountDate"), "SysDate-paymentTermDueDays(i.C_PaymentTerm_ID,i.DateInvoiced,SysDate)", Timestamp.class), + 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), + 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) + }, + // FROM + "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)", + // WHERE + "i.IsSOTrx=? AND IsPaid='N'" + // Different Payment Selection + + " 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=?", // additional where & order in loadTableInfo() + true, "i"); + // + miniTable.getModel().addTableModelListener(this); + // + fieldPayDate.setMandatory(true); + fieldPayDate.setValue(new Timestamp(System.currentTimeMillis())); + // + m_AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + } // dynInit + + /** + * Load Bank Info - Load Info from Bank Account and valid Documents (PaymentRule) + */ + private void loadBankInfo() + { + BankInfo bi = (BankInfo)fieldBankAccount.getSelectedItem(); + if (bi == null) + return; + labelCurrency.setText(bi.Currency); + labelBalance.setText(m_format.format(bi.Balance)); + m_bankBalance = bi.Balance; + + // PaymentRule + fieldPaymentRule.removeAllItems(); + int AD_Reference_ID = 195; // MLookupInfo.getAD_Reference_ID("All_Payment Rule"); + 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, bi.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 + fieldPaymentRule.addItem(vp); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + fieldPaymentRule.setSelectedIndex(0); + + } // loadBankInfo + + /** + * Query and create TableInfo + */ + private void loadTableInfo() + { + log.config(""); + // not yet initialized + if (m_sql == null) + return; + + String sql = m_sql; + // Parameters + Timestamp payDate = (Timestamp)fieldPayDate.getValue(); + miniTable.setColorCompare(payDate); + log.config("PayDate=" + payDate); + BankInfo bi = (BankInfo)fieldBankAccount.getSelectedItem(); + // + String isSOTrx = "N"; + ValueNamePair vp = (ValueNamePair)fieldPaymentRule.getSelectedItem(); + if (vp != null && X_C_Order.PAYMENTRULE_DirectDebit.equals(vp.getValue())) + { + isSOTrx = "Y"; + sql += " AND i.PaymentRule='" + X_C_Order.PAYMENTRULE_DirectDebit + "'"; + } + // + if (onlyDue.isSelected()) + sql += " AND i.DateInvoiced+p.NetDays <= ?"; + // + KeyNamePair pp = (KeyNamePair)fieldBPartner.getSelectedItem(); + 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); + + // Get Open Invoices + try + { + int index = 1; + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setTimestamp(index++, payDate); // DiscountAmt + pstmt.setInt(index++, bi.C_Currency_ID); // DueAmt + pstmt.setTimestamp(index++, payDate); + pstmt.setTimestamp(index++, payDate); // PayAmt + pstmt.setInt(index++, bi.C_Currency_ID); + pstmt.setTimestamp(index++, payDate); + pstmt.setString(index++, isSOTrx); // IsSOTrx + pstmt.setInt(index++, m_AD_Client_ID); // Client + if (onlyDue.isSelected()) + pstmt.setTimestamp(index++, payDate); + if (C_BPartner_ID != 0) + pstmt.setInt(index++, C_BPartner_ID); + // + ResultSet rs = pstmt.executeQuery(); + miniTable.loadTable(rs); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + calculateSelection(); + } // loadTableInfo + + /** + * Dispose + */ + public void dispose() + { + if (m_frame != null) + m_frame.dispose(); + m_frame = null; + } // dispose + + + /************************************************************************** + * ActionListener + * @param e event + */ + public void actionPerformed (ActionEvent e) + { + // Update Bank Info + if (e.getSource() == fieldBankAccount) + loadBankInfo(); + + // Generate PaySelection + else if (e.getSource() == bGenerate) + { + generatePaySelect(); + dispose(); + } + + else if (e.getSource() == bCancel) + dispose(); + + // Update Open Invoices + else if (e.getSource() == fieldBPartner || e.getSource() == bRefresh) + loadTableInfo(); + + } // actionPerformed + + /** + * Table Model Listener + * @param e event + */ + public void tableChanged(TableModelEvent e) + { + if (e.getColumn() == 0) + calculateSelection(); + } // valueChanged + + /** + * Calculate selected rows. + * - add up selected rows + */ + public void calculateSelection() + { + m_noSelected = 0; + BigDecimal invoiceAmt = new BigDecimal(0.0); + + int rows = miniTable.getRowCount(); + for (int i = 0; i < rows; i++) + { + IDColumn id = (IDColumn)miniTable.getModel().getValueAt(i, 0); + if (id.isSelected()) + { + BigDecimal amt = (BigDecimal)miniTable.getModel().getValueAt(i, 9); + invoiceAmt = invoiceAmt.add(amt); + m_noSelected++; + } + } + + // Information + BigDecimal remaining = m_bankBalance.subtract(invoiceAmt); + StringBuffer info = new StringBuffer(); + info.append(m_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)); + dataStatus.setText(info.toString()); + // + bGenerate.setEnabled(m_noSelected != 0); + } // calculateSelection + + /** + * Generate PaySelection + */ + private void generatePaySelect() + { + log.info(""); + // String trxName Trx.createTrxName("PaySelect"); + // Trx trx = Trx.get(trxName, true); trx needs to be committed too + String trxName = null; + Trx trx = null; + // + miniTable.stopEditor(true); + if (miniTable.getRowCount() == 0) + return; + miniTable.setRowSelectionInterval(0,0); + calculateSelection(); + if (m_noSelected == 0) + return; + + String PaymentRule = ((ValueNamePair)fieldPaymentRule.getSelectedItem()).getValue(); + + // Create Header + m_ps = new MPaySelection(Env.getCtx(), 0, trxName); + m_ps.setName (Msg.getMsg(Env.getCtx(), "VPaySelect") + + " - " + ((ValueNamePair)fieldPaymentRule.getSelectedItem()).getName() + + " - " + fieldPayDate.getTimestamp()); + m_ps.setPayDate (fieldPayDate.getTimestamp()); + BankInfo bi = (BankInfo)fieldBankAccount.getSelectedItem(); + m_ps.setC_BankAccount_ID(bi.C_BankAccount_ID); + m_ps.setIsApproved(true); + if (!m_ps.save()) + { + ADialog.error(m_WindowNo, this, "SaveError", Msg.translate(Env.getCtx(), "C_PaySelection_ID")); + m_ps = null; + return; + } + log.config(m_ps.toString()); + + // Create Lines + int rows = miniTable.getRowCount(); + int line = 0; + for (int i = 0; i < rows; i++) + { + IDColumn id = (IDColumn)miniTable.getModel().getValueAt(i, 0); + if (id.isSelected()) + { + line += 10; + MPaySelectionLine psl = new MPaySelectionLine (m_ps, line, PaymentRule); + int C_Invoice_ID = id.getRecord_ID().intValue(); + BigDecimal OpenAmt = (BigDecimal)miniTable.getModel().getValueAt(i, 8); + BigDecimal PayAmt = (BigDecimal)miniTable.getModel().getValueAt(i, 9); + boolean isSOTrx = false; + // + psl.setInvoice(C_Invoice_ID, isSOTrx, + OpenAmt, PayAmt, OpenAmt.subtract(PayAmt)); + if (!psl.save(trxName)) + { + ADialog.error(m_WindowNo, this, "SaveError", Msg.translate(Env.getCtx(), "C_PaySelectionLine_ID")); + return; + } + log.fine("C_Invoice_ID=" + C_Invoice_ID + ", PayAmt=" + PayAmt); + } + } // for all rows in table + + + // Ask to Post it + if (!ADialog.ask(m_WindowNo, this, "VPaySelectGenerate?", "(" + m_ps.getName() + ")")) + return; + + // Prepare Process + int AD_Proces_ID = 155; // C_PaySelection_CreatePayment + ProcessInfo pi = new ProcessInfo (m_frame.getTitle(), AD_Proces_ID, + X_C_PaySelection.Table_ID, m_ps.getC_PaySelection_ID()); + pi.setAD_User_ID (Env.getAD_User_ID(Env.getCtx())); + pi.setAD_Client_ID(Env.getAD_Client_ID(Env.getCtx())); + + // Execute Process + ProcessCtl.process(this, m_WindowNo, pi, trx); + // ProcessCtl worker = new ProcessCtl(this, pi, trx); + // worker.start(); // complete tasks in unlockUI + } // generatePaySelect + + /** + * Lock User Interface + * Called from the Worker before processing + * @param pi process info + */ + public void lockUI (ProcessInfo pi) + { + this.setEnabled(false); + m_isLocked = true; + } // lockUI + + /** + * Unlock User Interface. + * Called from the Worker when processing is done + * @param pi process info + */ + public void unlockUI (ProcessInfo pi) + { + // this.setEnabled(true); + // m_isLocked = false; + // Ask to Print it // Window is disposed + if (!ADialog.ask(0, this, "VPaySelectPrint?", "(" + pi.getSummary() + ")")) + return; + + // Start PayPrint + int AD_Form_ID = 106; // Payment Print/Export + FormFrame ff = new FormFrame(); + ff.openForm (AD_Form_ID); + // Set Parameter + if (m_ps != null) + { + VPayPrint pp = (VPayPrint)ff.getFormPanel(); + pp.setPaySelection(m_ps.getC_PaySelection_ID()); + } + // + ff.pack(); + this.setVisible(false); + AEnv.showCenterScreen(ff); + this.dispose(); + } // unlockUI + + /** + * Is the UI locked (Internal method) + * @return true, if UI is locked + */ + public boolean isUILocked() + { + return m_isLocked; + } // isLoacked + + /** + * Method to be executed async. + * Called from the ASyncProcess worker + * @param pi process info + */ + public void executeASync (ProcessInfo pi) + { + log.config("-"); + } // executeASync + + + /************************************************************************** + * Bank Account Info + */ + 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; + } + } // BankInfo + +} // VPaySelect diff --git a/client/src/org/compiere/apps/form/VTrxMaterial.java b/client/src/org/compiere/apps/form/VTrxMaterial.java index 97d3bcb85c..7497684ac3 100644 --- a/client/src/org/compiere/apps/form/VTrxMaterial.java +++ b/client/src/org/compiere/apps/form/VTrxMaterial.java @@ -403,7 +403,6 @@ public class VTrxMaterial extends CPanel setCursor(Cursor.getDefaultCursor()); return; } - AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; setCursor(Cursor.getDefaultCursor()); diff --git a/client/src/org/compiere/apps/search/Info.java b/client/src/org/compiere/apps/search/Info.java index dc343f6e69..01e5c52377 100644 --- a/client/src/org/compiere/apps/search/Info.java +++ b/client/src/org/compiere/apps/search/Info.java @@ -686,7 +686,6 @@ public abstract class Info extends CDialog final AWindow frame = new AWindow(); if (!frame.initWindow(AD_Window_ID, zoomQuery)) return; - AEnv.addToWindowManager(frame); // Modal Window causes UI lock if (isModal()) { diff --git a/client/src/org/compiere/apps/wf/WFActivity.java b/client/src/org/compiere/apps/wf/WFActivity.java index 460805a2af..ce280e0fe2 100644 --- a/client/src/org/compiere/apps/wf/WFActivity.java +++ b/client/src/org/compiere/apps/wf/WFActivity.java @@ -509,7 +509,6 @@ public class WFActivity extends CPanel AWindow frame = new AWindow(); if (!frame.initWindow(AD_Window_ID, query)) return; - AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; } @@ -519,7 +518,6 @@ public class WFActivity extends CPanel FormFrame ff = new FormFrame(); ff.openForm(AD_Form_ID); ff.pack(); - AEnv.addToWindowManager(ff); AEnv.showCenterScreen(ff); } else if (MWFNode.ACTION_UserWorkbench.equals(node.getAction())) diff --git a/client/src/org/compiere/apps/wf/WFPanel.java b/client/src/org/compiere/apps/wf/WFPanel.java index cd860400ca..e105de7165 100644 --- a/client/src/org/compiere/apps/wf/WFPanel.java +++ b/client/src/org/compiere/apps/wf/WFPanel.java @@ -432,7 +432,6 @@ public class WFPanel extends CPanel AWindow frame = new AWindow(); if (!frame.initWindow (AD_Window_ID, query)) return; - AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); frame = null; } // zoom diff --git a/client/src/org/compiere/grid/VCreateFromStatement.java b/client/src/org/compiere/grid/VCreateFromStatement.java index a302762239..0148ec23f0 100644 --- a/client/src/org/compiere/grid/VCreateFromStatement.java +++ b/client/src/org/compiere/grid/VCreateFromStatement.java @@ -3,255 +3,255 @@ * 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 * - *****************************************************************************/ -package org.compiere.grid; - -import java.beans.*; -import java.math.*; -import java.sql.*; -import java.text.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.table.*; -import org.compiere.apps.*; -import org.compiere.grid.ed.*; -import org.compiere.model.*; -import org.compiere.util.*; - -/** - * Create Transactions for Bank Statements - * - * @author Jorg Janke - * @version $Id: VCreateFromStatement.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class VCreateFromStatement extends VCreateFrom implements VetoableChangeListener -{ - /** - * Protected Constructor - * @param mTab MTab - */ - VCreateFromStatement(GridTab mTab) - { - super (mTab); - log.info(""); - } // VCreateFromStatement - - /** - * 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) - { - ADialog.error(0, this, "SaveErrorRowNotFound"); - return false; - } - - setTitle(Msg.translate(Env.getCtx(), "C_BankStatement_ID") + " .. " + Msg.translate(Env.getCtx(), "CreateFrom")); - parameterStdPanel.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 VLookup ("C_BankAccount_ID", true, false, true, lookup); - bankAccountField.addVetoableChangeListener(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; - } // dynInit - - /** - * Init Details (never called) - * @param C_BPartner_ID BPartner - */ - protected void initBPDetails(int C_BPartner_ID) - { - } // initDetails - - /** - * Change Listener - * @param e event - */ - public void vetoableChange (PropertyChangeEvent e) - { - log.config(e.getPropertyName() + "=" + e.getNewValue()); - - // BankAccount - if (e.getPropertyName() == "C_BankAccount_ID") - { - int C_BankAccount_ID = ((Integer)e.getNewValue()).intValue(); - loadBankAccount(C_BankAccount_ID); - } - tableChanged(null); - } // vetoableChange - - /** - * 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 - 0 - * Date - 1 - * C_Payment_ID - 2 - * C_Currenncy - 3 - * Amt - 4 - */ - Vector> data = new Vector>(); - 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 " + * 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 * + *****************************************************************************/ +package org.compiere.grid; + +import java.beans.*; +import java.math.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.table.*; +import org.compiere.apps.*; +import org.compiere.grid.ed.*; +import org.compiere.model.*; +import org.compiere.util.*; + +/** + * Create Transactions for Bank Statements + * + * @author Jorg Janke + * @version $Id: VCreateFromStatement.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public class VCreateFromStatement extends VCreateFrom implements VetoableChangeListener +{ + /** + * Protected Constructor + * @param mTab MTab + */ + VCreateFromStatement(GridTab mTab) + { + super (mTab); + log.info(""); + } // VCreateFromStatement + + /** + * 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) + { + ADialog.error(0, this, "SaveErrorRowNotFound"); + return false; + } + + setTitle(Msg.translate(Env.getCtx(), "C_BankStatement_ID") + " .. " + Msg.translate(Env.getCtx(), "CreateFrom")); + parameterStdPanel.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 VLookup ("C_BankAccount_ID", true, false, true, lookup); + bankAccountField.addVetoableChangeListener(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; + } // dynInit + + /** + * Init Details (never called) + * @param C_BPartner_ID BPartner + */ + protected void initBPDetails(int C_BPartner_ID) + { + } // initDetails + + /** + * Change Listener + * @param e event + */ + public void vetoableChange (PropertyChangeEvent e) + { + log.config(e.getPropertyName() + "=" + e.getNewValue()); + + // BankAccount + if (e.getPropertyName() == "C_BankAccount_ID") + { + int C_BankAccount_ID = ((Integer)e.getNewValue()).intValue(); + loadBankAccount(C_BankAccount_ID); + } + tableChanged(null); + } // vetoableChange + + /** + * 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 - 0 + * Date - 1 + * C_Payment_ID - 2 + * C_Currenncy - 3 + * Amt - 4 + */ + Vector> data = new Vector>(); + 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)" - + " INNER JOIN C_BPartner bp ON (p.C_BPartner_ID=bp.C_BPartner_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 line = new Vector(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); - } - // Header Info - Vector columnNames = new Vector(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().removeTableModelListener(this); - // Set Model - DefaultTableModel model = new DefaultTableModel(data, columnNames); - model.addTableModelListener(this); - dataTable.setModel(model); - // - dataTable.setColumnClass(0, Boolean.class, false); // 0-Selection - dataTable.setColumnClass(1, Timestamp.class, true); // 1-TrxDate - dataTable.setColumnClass(2, String.class, true); // 2-Payment - dataTable.setColumnClass(3, String.class, true); // 3-Currency - dataTable.setColumnClass(4, BigDecimal.class, true); // 4-Amount - dataTable.setColumnClass(5, BigDecimal.class, true); // 5-ConvAmount - dataTable.setColumnClass(6, String.class, true); // 6-BPartner - // Table UI - dataTable.autoSize(); - } // loadBankAccount - - /** - * List total amount - */ - protected void info() - { - DecimalFormat format = DisplayType.getNumberFormat(DisplayType.Amount); - - TableModel model = dataTable.getModel(); - BigDecimal total = new BigDecimal(0.0); - int rows = model.getRowCount(); - int count = 0; - for (int i = 0; i < rows; i++) - { - if (((Boolean)model.getValueAt(i, 0)).booleanValue()) - { - total = total.add((BigDecimal)model.getValueAt(i, 4)); - count++; - } - } - statusBar.setStatusLine(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(""); - TableModel model = dataTable.getModel(); - int rows = model.getRowCount(); - 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 (((Boolean)model.getValueAt(i, 0)).booleanValue()) - { - Timestamp trxDate = (Timestamp)model.getValueAt(i, 1); // 1-DateTrx - KeyNamePair pp = (KeyNamePair)model.getValueAt(i, 2); // 2-C_Payment_ID - int C_Payment_ID = pp.getKey(); + + "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 line = new Vector(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); + } + // Header Info + Vector columnNames = new Vector(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().removeTableModelListener(this); + // Set Model + DefaultTableModel model = new DefaultTableModel(data, columnNames); + model.addTableModelListener(this); + dataTable.setModel(model); + // + dataTable.setColumnClass(0, Boolean.class, false); // 0-Selection + dataTable.setColumnClass(1, Timestamp.class, true); // 1-TrxDate + dataTable.setColumnClass(2, String.class, true); // 2-Payment + dataTable.setColumnClass(3, String.class, true); // 3-Currency + dataTable.setColumnClass(4, BigDecimal.class, true); // 4-Amount + dataTable.setColumnClass(5, BigDecimal.class, true); // 5-ConvAmount + dataTable.setColumnClass(6, String.class, true); // 6-BPartner + // Table UI + dataTable.autoSize(); + } // loadBankAccount + + /** + * List total amount + */ + protected void info() + { + DecimalFormat format = DisplayType.getNumberFormat(DisplayType.Amount); + + TableModel model = dataTable.getModel(); + BigDecimal total = new BigDecimal(0.0); + int rows = model.getRowCount(); + int count = 0; + for (int i = 0; i < rows; i++) + { + if (((Boolean)model.getValueAt(i, 0)).booleanValue()) + { + total = total.add((BigDecimal)model.getValueAt(i, 4)); + count++; + } + } + statusBar.setStatusLine(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(""); + TableModel model = dataTable.getModel(); + int rows = model.getRowCount(); + 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 (((Boolean)model.getValueAt(i, 0)).booleanValue()) + { + Timestamp trxDate = (Timestamp)model.getValueAt(i, 1); // 1-DateTrx + KeyNamePair pp = (KeyNamePair)model.getValueAt(i, 2); // 2-C_Payment_ID + int C_Payment_ID = pp.getKey(); pp = (KeyNamePair)model.getValueAt(i, 3); // 3-Currency int C_Currency_ID = pp.getKey(); BigDecimal TrxAmt = (BigDecimal)model.getValueAt(i, 4); // 4-PayAmt - BigDecimal StmtAmt = (BigDecimal)model.getValueAt(i, 5);// 5-Conv Amt + // 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 - -} // VCreateFromStatement + // + 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 + +} // VCreateFromStatement diff --git a/client/src/org/compiere/grid/VPayment.java b/client/src/org/compiere/grid/VPayment.java index 3ccd48430b..610f8f02c4 100644 --- a/client/src/org/compiere/grid/VPayment.java +++ b/client/src/org/compiere/grid/VPayment.java @@ -1,1356 +1,1329 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.grid; - -import java.awt.*; -import java.awt.event.*; -import java.math.*; -import java.sql.*; -import java.text.*; -import java.util.*; -import java.util.logging.*; -import javax.swing.*; - -import org.adempiere.plaf.AdempierePLAF; -import org.compiere.apps.*; -import org.compiere.grid.ed.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.process.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Display (and process) Payment Options. - *
- *  Payment Rule
- *  -B- Cash          (Date)          -> Cash Entry
- *  -P- Payment Term  (Term)
- *  -S- Check         (Routing, ..)   -> Payment Entry
- *  -K- CreditCard    (No)            -> Payment Entry
- *  -U- ACH Transfer  (Routing)       -> Payment Entry
- *
- *  When processing:
- *  - If an invoice is a S/K/U, but has no Payment Entry, it is changed to P
- *  - If an invoive is B and has no Cash Entry, it is created
- *  - An invoice is "Open" if it is "P" and no Payment
- *
- *  Entry:
- *  - If not processed, an invoice has no Cash or Payment entry
- *  - The entry is created, during "Online" and when Saving
- *
- *  Changes/Reversals:
- *  - existing Cash Entries are reversed and newly created
- *  - existing Payment Entries are not changed and then "hang there" and need to be allocated
- *  
- * - * @author Jorg Janke - * @version $Id: VPayment.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class VPayment extends CDialog - implements ActionListener -{ - /** - * Constructor - * - * @param WindowNo owning window - * @param mTab owning tab - * @param button button with access information - */ - public VPayment (int WindowNo, GridTab mTab, VButton button) - { - super(Env.getWindow(WindowNo), Msg.getMsg(Env.getCtx(), "Payment"), true); - m_WindowNo = WindowNo; - m_isSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx")); - m_mTab = mTab; - try - { - bDateField = new VDate("DateAcct", false, false, true, DisplayType.Date, "DateAcct"); - jbInit(); - m_initOK = dynInit(button); // Null Pointer if order/invoice not saved yet - } - catch(Exception ex) - { - log.log(Level.SEVERE, "VPayment", ex); - m_initOK = false; - } - // - AEnv.positionCenterWindow(Env.getWindow(WindowNo), this); - } // VPayment - - /** Window */ - private int m_WindowNo = 0; - /** Tab */ - private GridTab m_mTab; - - // Data from Order/Invoice - private String m_DocStatus = null; - /** Start Payment Rule */ - private String m_PaymentRule = ""; - /** Start Payment Term */ - private int m_C_PaymentTerm_ID = 0; - /** Start Acct Date */ - private Timestamp m_DateAcct = null; - /** Start Payment */ - private int m_C_Payment_ID = 0; - private MPayment m_mPayment = null; - private MPayment m_mPaymentOriginal = null; - /** Start CashBook Line */ - private int m_C_CashLine_ID = 0; - private MCashLine m_cashLine = null; - /** Start CreditCard */ - private String m_CCType = ""; - /** Start Bank Account */ - private int m_C_BankAccount_ID = 0; - /** Start CashBook */ - private int m_C_CashBook_ID = 0; - - /** Is SOTrx */ - private boolean m_isSOTrx = true; - - /** Invoice Currency */ - private int m_C_Currency_ID = 0; - private int m_AD_Client_ID = 0; - private int m_AD_Org_ID = 0; - private int m_C_BPartner_ID = 0; - private BigDecimal m_Amount = Env.ZERO; // Payment Amount - // - private boolean m_initOK = false; - /** Only allow changing Rule */ - private boolean m_onlyRule = false; - private DecimalFormat m_Format = DisplayType.getNumberFormat(DisplayType.Amount); - private static Hashtable s_Currencies = null; // EMU Currencies - - private boolean m_needSave = false; - /** Logger */ - private static CLogger log = CLogger.getCLogger(VPayment.class); - - // - private CPanel mainPanel = new CPanel(); - private BorderLayout mainLayout = new BorderLayout(); - private CPanel northPanel = new CPanel(); - private CPanel centerPanel = new CPanel(); - private FlowLayout northLayout = new FlowLayout(); - private CComboBox paymentCombo = new CComboBox(); - private CLabel paymentLabel = new CLabel(); - private CardLayout centerLayout = new CardLayout(); - private CPanel bPanel = new CPanel(); - private CPanel kPanel = new CPanel(); - private GridBagLayout kLayout = new GridBagLayout(); - private CLabel kTypeLabel = new CLabel(); - private CComboBox kTypeCombo = new CComboBox(); - private CLabel kNumnerLabel = new CLabel(); - private CTextField kNumberField = new CTextField(); - private CLabel kExpLabel = new CLabel(); - private CTextField kExpField = new CTextField(); - private CLabel kApprovalLabel = new CLabel(); - private CTextField kApprovalField = new CTextField(); - private CPanel tPanel = new CPanel(); - private CLabel tAccountLabel = new CLabel(); - private CComboBox tAccountCombo = new CComboBox(); - private CPanel sPanel = new CPanel(); - private GridBagLayout sPanelLayout = new GridBagLayout(); - private CLabel sNumberLabel = new CLabel(); - private CTextField sNumberField = new CTextField(); - private CLabel sRoutingLabel = new CLabel(); - private CTextField sRoutingField = new CTextField(); - private CLabel sCurrencyLabel = new CLabel(); - private CComboBox sCurrencyCombo = new CComboBox(); - private CLabel bCurrencyLabel = new CLabel(); - private CComboBox bCurrencyCombo = new CComboBox(); - private CPanel pPanel = new CPanel(); - private CLabel pTermLabel = new CLabel(); - private CComboBox pTermCombo = new CComboBox(); - private GridBagLayout bPanelLayout = new GridBagLayout(); - private CLabel bAmountLabel = new CLabel(); - private CLabel bAmountField = new CLabel(); - private CLabel sAmountLabel = new CLabel(); - private CLabel sAmountField = new CLabel(); - private VDate bDateField; - private CLabel bDateLabel = new CLabel(); - private ConfirmPanel confirmPanel = new ConfirmPanel(true); - private CTextField sCheckField = new CTextField(); - private CLabel sCheckLabel = new CLabel(); - private CButton kOnline = new CButton(); - private CButton sOnline = new CButton(); - private CComboBox sBankAccountCombo = new CComboBox(); - private CLabel sBankAccountLabel = new CLabel(); - private GridBagLayout pPanelLayout = new GridBagLayout(); - private CLabel bCashBookLabel = new CLabel(); - private CComboBox bCashBookCombo = new CComboBox(); - private GridBagLayout tPanelLayout = new GridBagLayout(); - private CButton tOnline = new CButton(); - private CLabel kStatus = new CLabel(); - private CTextField tRoutingField = new CTextField(); - private CTextField tNumberField = new CTextField(); - private CLabel tStatus = new CLabel(); - private CLabel tRoutingText = new CLabel(); - private CLabel tNumberText = new CLabel(); - private CLabel sStatus = new CLabel(); - - /** - * Static Init - * @throws Exception - */ - private void jbInit() throws Exception - { - centerPanel.setBorder(BorderFactory.createRaisedBevelBorder()); - getContentPane().add(mainPanel); - mainPanel.setLayout(mainLayout); - mainPanel.add(centerPanel, BorderLayout.CENTER); - // - northPanel.setLayout(northLayout); - paymentLabel.setText(Msg.translate(Env.getCtx(), "PaymentRule")); - mainPanel.add(northPanel, BorderLayout.NORTH); - northPanel.add(paymentLabel, null); - northPanel.add(paymentCombo, null); - // - centerPanel.setLayout(centerLayout); - // - kPanel.setLayout(kLayout); - kNumberField.setPreferredSize(new Dimension(120, 21)); - kExpField.setPreferredSize(new Dimension(40, 21)); - kApprovalField.setPreferredSize(new Dimension(120, 21)); - kTypeLabel.setText(Msg.translate(Env.getCtx(), "CreditCardType")); - kNumnerLabel.setText(Msg.translate(Env.getCtx(), "CreditCardNumber")); - kExpLabel.setText(Msg.getMsg(Env.getCtx(), "Expires")); - kApprovalLabel.setText(Msg.translate(Env.getCtx(), "VoiceAuthCode")); - kOnline.setText(Msg.getMsg(Env.getCtx(), "Online")); - kOnline.addActionListener(this); - kStatus.setText(" "); - centerPanel.add(kPanel, "kPanel"); - centerLayout.addLayoutComponent(kPanel, "kPanel"); - kPanel.add(kTypeLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - kPanel.add(kTypeCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); - kPanel.add(kNumnerLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - kPanel.add(kNumberField, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(2, 5, 2, 5), 0, 0)); - kPanel.add(kExpLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - kPanel.add(kExpField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); - kPanel.add(kApprovalLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0)); - kPanel.add(kApprovalField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - kPanel.add(kStatus, new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0 - ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - kPanel.add(kOnline, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - // - tPanel.setLayout(tPanelLayout); - tAccountLabel.setText(Msg.translate(Env.getCtx(), "C_BP_BankAccount_ID")); - tRoutingField.setColumns(8); - tNumberField.setColumns(10); - tRoutingText.setText(Msg.translate(Env.getCtx(), "RoutingNo")); - tNumberText.setText(Msg.translate(Env.getCtx(), "AccountNo")); - tOnline.setText(Msg.getMsg(Env.getCtx(), "Online")); - tStatus.setText(" "); - centerPanel.add(tPanel, "tPanel"); - centerLayout.addLayoutComponent(tPanel, "tPanel"); - tPanel.add(tAccountLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0)); - tPanel.add(tAccountCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - tPanel.add(tRoutingField, new GridBagConstraints(1, 1, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0)); - tPanel.add(tNumberField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 0, 5), 0, 0)); - tPanel.add(tStatus, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0 - ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - tPanel.add(tRoutingText, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 0), 0, 0)); - tPanel.add(tNumberText, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 0, 0), 0, 0)); - tPanel.add(tOnline, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - // - sPanel.setLayout(sPanelLayout); - sBankAccountLabel.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); - sAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); - sAmountField.setText(""); - sRoutingLabel.setText(Msg.translate(Env.getCtx(), "RoutingNo")); - sNumberLabel.setText(Msg.translate(Env.getCtx(), "AccountNo")); - sCheckLabel.setText(Msg.translate(Env.getCtx(), "CheckNo")); - sCheckField.setColumns(8); - sCurrencyLabel.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); - sNumberField.setPreferredSize(new Dimension(100, 21)); - sRoutingField.setPreferredSize(new Dimension(70, 21)); - sStatus.setText(" "); - sOnline.setText(Msg.getMsg(Env.getCtx(), "Online")); - centerPanel.add(sPanel, "sPanel"); - centerLayout.addLayoutComponent(sPanel, "sPanel"); - sPanel.add(sCurrencyLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - sPanel.add(sCurrencyCombo, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); - sPanel.add(sRoutingField, new GridBagConstraints(1, 4, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 2, 0), 0, 0)); - sPanel.add(sNumberField, new GridBagConstraints(1, 5, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 2, 0), 0, 0)); - sPanel.add(sCheckField, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0)); - sPanel.add(sRoutingLabel, new GridBagConstraints(0, 3, 1, 2, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 2, 0), 0, 0)); - sPanel.add(sNumberLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - sPanel.add(sCheckLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - sPanel.add(sBankAccountCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0)); - sPanel.add(sBankAccountLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); - sPanel.add(sStatus, new GridBagConstraints(0, 7, 3, 1, 0.0, 0.0 - ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - sPanel.add(sOnline, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0 - ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); - sPanel.add(sAmountField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 5, 5), 0, 0)); - sPanel.add(sAmountLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 5, 0), 0, 0)); - // - pPanel.setLayout(pPanelLayout); - pTermLabel.setText(Msg.translate(Env.getCtx(), "C_PaymentTerm_ID")); - centerPanel.add(pPanel, "pPanel"); - centerLayout.addLayoutComponent(pPanel, "pPanel"); - pPanel.add(pTermLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0)); - pPanel.add(pTermCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); - // - bCashBookLabel.setText(Msg.translate(Env.getCtx(), "C_CashBook_ID")); - bCurrencyLabel.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); - bPanel.setLayout(bPanelLayout); - bAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); - bAmountField.setText(""); - bDateLabel.setText(Msg.translate(Env.getCtx(), "DateAcct")); - centerLayout.addLayoutComponent(bPanel, "bPanel"); - centerPanel.add(bPanel, "bPanel"); - bPanel.add(bCurrencyLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - bPanel.add(bCurrencyCombo, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); - bPanel.add(bDateField, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0)); - bPanel.add(bDateLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); - bPanel.add(bCashBookLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); - bPanel.add(bCashBookCombo, new GridBagConstraints(1, 0, 2, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); - bPanel.add(bAmountLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); - bPanel.add(bAmountField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 - ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0)); - // - mainPanel.add(confirmPanel, BorderLayout.SOUTH); - confirmPanel.addActionListener(this); - } // jbInit - - - /************************************************************************** - * Dynamic Init. - * B (Cash) (Currency) - * K (CreditCard) Type, Number, Exp, Approval - * L (DirectDebit) BPartner_Bank - * P (PaymentTerm) PaymentTerm - * S (Check) (Currency) CheckNo, Routing - * - * Currencies are shown, if member of EMU - * @param button button - * @return true if init OK - * @throws Exception - */ - private boolean dynInit (VButton button) throws Exception - { - m_DocStatus = (String)m_mTab.getValue("DocStatus"); - log.config(m_DocStatus); - - if (m_mTab.getValue("C_BPartner_ID") == null) - { - ADialog.error(0, this, "SaveErrorRowNotFound"); - return false; - } - - // Is the Trx posted? - // String Posted = (String)m_mTab.getValue("Posted"); - // if (Posted != null && Posted.equals("Y")) - // return false; - - // DocStatus - m_DocStatus = (String)m_mTab.getValue("DocStatus"); - if (m_DocStatus == null) - m_DocStatus = ""; - // Is the Trx closed? Reversed / Voided / Cloased - if (m_DocStatus.equals("RE") || m_DocStatus.equals("VO") || m_DocStatus.equals("CL")) - return false; - // Document is not complete - allow to change the Payment Rule only - if (m_DocStatus.equals("CO") || m_DocStatus.equals("WP") ) - m_onlyRule = false; - else - m_onlyRule = true; - // PO only Rule - if (!m_onlyRule // Only order has Warehouse - && !m_isSOTrx && m_mTab.getValue("M_Warehouse_ID") != null) - m_onlyRule = true; - - centerPanel.setVisible(!m_onlyRule); - - - // Amount - m_Amount = (BigDecimal)m_mTab.getValue("GrandTotal"); - if (!m_onlyRule && m_Amount.compareTo(Env.ZERO) == 0) - { - ADialog.error(m_WindowNo, this, "PaymentZero"); - return false; - } - bAmountField.setText(m_Format.format(m_Amount)); - sAmountField.setText(m_Format.format(m_Amount)); - - /** - * Get Data from Grid - */ - m_AD_Client_ID = ((Integer)m_mTab.getValue("AD_Client_ID")).intValue(); - m_AD_Org_ID = ((Integer)m_mTab.getValue("AD_Org_ID")).intValue(); - m_C_BPartner_ID = ((Integer)m_mTab.getValue("C_BPartner_ID")).intValue(); - m_PaymentRule = (String)m_mTab.getValue("PaymentRule"); - m_C_Currency_ID = ((Integer)m_mTab.getValue("C_Currency_ID")).intValue(); - m_DateAcct = (Timestamp)m_mTab.getValue("DateAcct"); - if (m_mTab.getValue("C_PaymentTerm_ID") != null) - m_C_PaymentTerm_ID = ((Integer)m_mTab.getValue("C_PaymentTerm_ID")).intValue(); - // Existing Payment - if (m_mTab.getValue("C_Payment_ID") != null) - { - m_C_Payment_ID = ((Integer)m_mTab.getValue("C_Payment_ID")).intValue(); - if (m_C_Payment_ID != 0) - { - m_mPayment = new MPayment(Env.getCtx(), m_C_Payment_ID, null); - m_mPaymentOriginal = new MPayment(Env.getCtx(), m_C_Payment_ID, null); // full copy - // CreditCard - m_CCType = m_mPayment.getCreditCardType(); - kNumberField.setText(m_mPayment.getCreditCardNumber()); - kExpField.setText(m_mPayment.getCreditCardExp(null)); - kApprovalField.setText(m_mPayment.getVoiceAuthCode()); - kStatus.setText(m_mPayment.getR_PnRef()); - // if approved/paid, don't let it change - kTypeCombo.setReadWrite(!m_mPayment.isApproved()); - kNumberField.setReadWrite(!m_mPayment.isApproved()); - kExpField.setReadWrite(!m_mPayment.isApproved()); - kApprovalField.setReadWrite(!m_mPayment.isApproved()); - kOnline.setReadWrite(!m_mPayment.isApproved()); - // Check - m_C_BankAccount_ID = m_mPayment.getC_BankAccount_ID(); - sRoutingField.setText(m_mPayment.getRoutingNo()); - sNumberField.setText(m_mPayment.getAccountNo()); - sCheckField.setText(m_mPayment.getCheckNo()); - sStatus.setText(m_mPayment.getR_PnRef()); - // Transfer - tRoutingField.setText(m_mPayment.getRoutingNo()); - tNumberField.setText(m_mPayment.getAccountNo()); - tStatus.setText(m_mPayment.getR_PnRef()); - } - } - if (m_mPayment == null) - { - m_mPayment = new MPayment (Env.getCtx (), 0, null); - m_mPayment.setAD_Org_ID(m_AD_Org_ID); - m_mPayment.setAmount (m_C_Currency_ID, m_Amount); - } - - // Existing Cahbook entry - m_cashLine = null; - m_C_CashLine_ID = 0; - if (m_mTab.getValue("C_CashLine_ID") != null) - { - m_C_CashLine_ID = ((Integer)m_mTab.getValue("C_CashLine_ID")).intValue(); - if (m_C_CashLine_ID == 0) - m_cashLine = null; - else - { - m_cashLine = new MCashLine (Env.getCtx(), m_C_CashLine_ID, null); - m_DateAcct = m_cashLine.getStatementDate(); - } - } - - // Accounting Date - bDateField.setValue(m_DateAcct); - - if (s_Currencies == null) - loadCurrencies(); - - // Is the currency an EMU currency? - Integer C_Currency_ID = new Integer(m_C_Currency_ID); - if (s_Currencies.containsKey(C_Currency_ID)) - { - Enumeration en = s_Currencies.keys(); - while (en.hasMoreElements()) - { - Object key = en.nextElement(); - bCurrencyCombo.addItem(s_Currencies.get(key)); - sCurrencyCombo.addItem(s_Currencies.get(key)); - } - sCurrencyCombo.addActionListener(this); - sCurrencyCombo.setSelectedItem(s_Currencies.get(C_Currency_ID)); - bCurrencyCombo.addActionListener(this); - bCurrencyCombo.setSelectedItem(s_Currencies.get(C_Currency_ID)); - } - else // No EMU Currency - { - bCurrencyLabel.setVisible(false); // Cash - bCurrencyCombo.setVisible(false); - sCurrencyLabel.setVisible(false); // Check - sCurrencyCombo.setVisible(false); - } - - /** - * Payment Combo - */ - if (m_PaymentRule == null) - m_PaymentRule = ""; - ValueNamePair vp = null; - HashMap values = button.getValues(); - Object[] a = values.keySet().toArray(); - for (int i = 0; i < a.length; i++) - { - String PaymentRule = (String)a[i]; - ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values.get(a[i])); - paymentCombo.addItem(pp); - if (PaymentRule.toString().equals(m_PaymentRule)) // to select - vp = pp; - } - - // Set PaymentRule - paymentCombo.addActionListener(this); - if (vp != null) - paymentCombo.setSelectedItem(vp); - - /** - * Load Payment Terms - */ - String SQL = MRole.getDefault().addAccessSQL( - "SELECT C_PaymentTerm_ID, Name FROM C_PaymentTerm WHERE IsActive='Y' ORDER BY Name", - "C_PaymentTerm", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - KeyNamePair kp = null; - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - pTermCombo.addItem(pp); - if (key == m_C_PaymentTerm_ID) - kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException ept) - { - log.log(Level.SEVERE, SQL, ept); - } - // Set Selection - if (kp != null) - pTermCombo.setSelectedItem(kp); - - /** - * Load Accounts - */ - SQL = "SELECT a.C_BP_BankAccount_ID, NVL(b.Name, ' ')||a.AccountNo AS Acct " - + "FROM C_BP_BankAccount a,C_Bank b " - + "WHERE C_BPartner_ID=? AND a.IsActive='Y'"; - kp = null; - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - pstmt.setInt(1, m_C_BPartner_ID); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - tAccountCombo.addItem(pp); - // kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException eac) - { - log.log(Level.SEVERE, SQL, eac); - } - // Set Selection - if (kp != null) - tAccountCombo.setSelectedItem(kp); - - /** - * Load Credit Cards - */ - ValueNamePair[] ccs = m_mPayment.getCreditCards(); - vp = null; - for (int i = 0; i < ccs.length; i++) - { - kTypeCombo.addItem(ccs[i]); - if (ccs[i].getValue().equals(m_CCType)) - vp = ccs[i]; - } - // Set Selection - if (vp != null) - kTypeCombo.setSelectedItem(vp); - - /** - * Load Bank Accounts - */ - SQL = MRole.getDefault().addAccessSQL( - "SELECT C_BankAccount_ID, Name || ' ' || AccountNo, IsDefault " - + "FROM C_BankAccount ba" - + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID) " - + "WHERE b.IsActive='Y'", - "ba", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); - kp = null; - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - sBankAccountCombo.addItem(pp); - if (key == m_C_BankAccount_ID) - kp = pp; - if (kp == null && rs.getString(3).equals("Y")) // Default - kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException ept) - { - log.log(Level.SEVERE, SQL, ept); - } - // Set Selection - if (kp != null) - sBankAccountCombo.setSelectedItem(kp); - - - /** - * Load Cash Books - */ - SQL = MRole.getDefault().addAccessSQL( - "SELECT C_CashBook_ID, Name, AD_Org_ID FROM C_CashBook WHERE IsActive='Y'", - "C_CashBook", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); - kp = null; - try - { - PreparedStatement pstmt = DB.prepareStatement(SQL, null); - ResultSet rs = pstmt.executeQuery(); - while (rs.next()) - { - int key = rs.getInt(1); - String name = rs.getString(2); - KeyNamePair pp = new KeyNamePair(key, name); - bCashBookCombo.addItem(pp); - if (key == m_C_CashBook_ID) - kp = pp; - if (kp == null && key == m_AD_Org_ID) // Default Org - kp = pp; - } - rs.close(); - pstmt.close(); - } - catch (SQLException epc) - { - log.log(Level.SEVERE, SQL, epc); - } - // Set Selection - if (kp != null) - { - bCashBookCombo.setSelectedItem(kp); - if (m_C_CashBook_ID == 0) - m_C_CashBook_ID = kp.getKey(); // set to default to avoid 'cashbook changed' message - } - - // - return true; - } // dynInit - - /** - * Init OK to be able to make changes? - * @return true if init OK - */ - public boolean isInitOK() - { - return m_initOK; - } // isInitOK - - - /** - * Fill s_Currencies with EMU currencies - */ - private void loadCurrencies() - { - s_Currencies = new Hashtable(12); // Currenly only 10+1 - String SQL = "SELECT C_Currency_ID, ISO_Code FROM C_Currency " - + "WHERE (IsEMUMember='Y' AND EMUEntryDate " + newPaymentRule); - // We had a CashBook Entry - if (m_PaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) - { - log.fine("Old Cash - " + m_cashLine); - if (m_cashLine != null) - { - MCashLine cl = m_cashLine.createReversal(); - if (cl.save()) - log.config( "CashCancelled"); - else - ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); - } - newC_CashLine_ID = 0; // reset - } - // We had a change in Payment type (e.g. Check to CC) - else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) != -1 && m_mPaymentOriginal != null) - { - log.fine("Old Payment(1) - " + m_mPaymentOriginal); - m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); - boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); - m_mPaymentOriginal.save(); - if (ok) - log.info( "Payment Canecelled - " + m_mPaymentOriginal); - else - ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPaymentOriginal.getDocumentNo()); - m_mPayment.resetNew(); - } - // We had a Payment and something else (e.g. Check to Cash) - else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) == -1) - { - log.fine("Old Payment(2) - " + m_mPaymentOriginal); - if (m_mPaymentOriginal != null) - { - m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); - boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); - m_mPaymentOriginal.save(); - if (ok) // Cancel Payment - { - log.fine("PaymentCancelled " + m_mPayment.getDocumentNo ()); - m_mTab.getTableModel().dataSave(true); - m_mPayment.resetNew(); - m_mPayment.setAmount(m_C_Currency_ID, m_Amount); - } - else - ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPayment.getDocumentNo()); - } - } - } - - // Get Order and optionally Invoice - int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); - int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); - if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) - C_Invoice_ID = getInvoiceID (C_Order_ID); - - // Amount sign negative, if ARC (Credit Memo) or API (AP Invoice) - boolean negateAmt = false; - MInvoice invoice = null; - if (C_Invoice_ID != 0) - { - invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null); - negateAmt = invoice.isCreditMemo(); - } - MOrder order = null; - if (invoice == null && C_Order_ID != 0) - order = new MOrder (Env.getCtx(), C_Order_ID, null); - BigDecimal payAmount = m_Amount; - if (negateAmt) - payAmount = m_Amount.negate(); - // Info - log.config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt); - - /*********************** - * CashBook - */ - if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) - { - log.fine("Cash"); - String description = (String)m_mTab.getValue("DocumentNo"); - - if (C_Invoice_ID == 0 && order == null) - { - log.config("No Invoice!"); - ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); - } - else - { - // Changed Amount - if (m_cashLine != null - && payAmount.compareTo(m_cashLine.getAmount()) != 0) - { - log.config("Changed CashBook Amount"); - m_cashLine.setAmount(payAmount); - if (m_cashLine.save()) - log.config("CashAmt Changed"); - } - // Different Date/CashBook - if (m_cashLine != null - && (newC_CashBook_ID != m_C_CashBook_ID - || !TimeUtil.isSameDay(m_cashLine.getStatementDate(), newDateAcct))) - { - log.config("Changed CashBook/Date: " + m_C_CashBook_ID + "->" + newC_CashBook_ID); - MCashLine reverse = m_cashLine.createReversal(); - if (!reverse.save()) - ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); - m_cashLine = null; - } - - // Create new - if (m_cashLine == null) - { - log.config("New CashBook"); - int C_Currency_ID = 0; - if (invoice != null) - C_Currency_ID = invoice.getC_Currency_ID(); - if (C_Currency_ID == 0 && order != null) - C_Currency_ID = order.getC_Currency_ID(); - MCash cash = null; - if (newC_CashBook_ID != 0) - cash = MCash.get (Env.getCtx(), newC_CashBook_ID, newDateAcct, null); - else // Default - cash = MCash.get (Env.getCtx(), m_AD_Org_ID, newDateAcct, C_Currency_ID, null); - if (cash == null || cash.get_ID() == 0) - ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); - else - { - MCashLine cl = new MCashLine (cash); - if (invoice != null) - cl.setInvoice(invoice); - if (order != null) - { - cl.setOrder(order, null); - m_needSave = true; - } - if (cl.save()) - log.config("CashCreated"); - else - ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); - } - } - } // have invoice - } - /*********************** - * Payments - */ - if ("KTSD".indexOf(newPaymentRule) != -1) - { - log.fine("Payment - " + newPaymentRule); - // Set Amount - m_mPayment.setAmount(m_C_Currency_ID, payAmount); - if (newPaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) - { - m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, newCCType, - kNumberField.getText(), "", kExpField.getText()); - m_mPayment.setPaymentProcessor(); - } - else if (newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit) - || newPaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) - { - m_mPayment.setBankACH(newC_BankAccount_ID, m_isSOTrx, newPaymentRule, - tRoutingField.getText(), tNumberField.getText()); - } - else if (newPaymentRule.equals(MOrder.PAYMENTRULE_Check)) - { - m_mPayment.setBankCheck(newC_BankAccount_ID, m_isSOTrx, sRoutingField.getText(), - sNumberField.getText(), sCheckField.getText()); - } - m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); - m_mPayment.setC_Invoice_ID(C_Invoice_ID); - if (order != null) - { - m_mPayment.setC_Order_ID(C_Order_ID); - m_needSave = true; - } - m_mPayment.setDateTrx(m_DateAcct); - m_mPayment.setDateAcct(m_DateAcct); - m_mPayment.save(); - - // Save/Post - if (MPayment.DOCSTATUS_Drafted.equals(m_mPayment.getDocStatus())) - { - boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); - m_mPayment.save(); - if (ok) - ADialog.info(m_WindowNo, this, "PaymentCreated", m_mPayment.getDocumentNo()); - else - ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); - } - else - log.fine("NotDraft " + m_mPayment); - } - - - /********************** - * Save Values to mTab - */ - log.config("Saving changes"); - // - if (!newPaymentRule.equals(m_PaymentRule)) - m_mTab.setValue("PaymentRule", newPaymentRule); - // - if (!newDateAcct.equals(m_DateAcct)) - m_mTab.setValue("DateAcct", newDateAcct); - // - if (newC_PaymentTerm_ID != m_C_PaymentTerm_ID) - m_mTab.setValue("C_PaymentTerm_ID", new Integer(newC_PaymentTerm_ID)); - // Set Payment - if (m_mPayment.getC_Payment_ID() != m_C_Payment_ID) - { - if (m_mPayment.getC_Payment_ID() == 0) - m_mTab.setValue("C_Payment_ID", null); - else - m_mTab.setValue("C_Payment_ID", new Integer(m_mPayment.getC_Payment_ID())); - } - // Set Cash - if (newC_CashLine_ID != m_C_CashLine_ID) - { - if (newC_CashLine_ID == 0) - m_mTab.setValue("C_CashLine_ID", null); - else - m_mTab.setValue("C_CashLine_ID", new Integer(newC_CashLine_ID)); - } - return true; - } // saveChanges - - /** - * Check Mandatory - * @return true if all mandatory items are OK - */ - private boolean checkMandatory() - { - // log.config( "VPayment.checkMandatory"); - - ValueNamePair vp = (ValueNamePair)paymentCombo.getSelectedItem(); - String PaymentRule = vp.getValue(); - // only Payment Rule - if (m_onlyRule) - return true; - - Timestamp DateAcct = m_DateAcct; - int C_PaymentTerm_ID = m_C_PaymentTerm_ID; - int C_CashBook_ID = m_C_CashBook_ID; - String CCType = m_CCType; - // - int C_BankAccount_ID = 0; - - /*********************** - * Mandatory Data Check - */ - boolean dataOK = true; - // B (Cash) (Currency) - if (PaymentRule.equals(MOrder.PAYMENTRULE_Cash)) - { - KeyNamePair kp = (KeyNamePair)bCashBookCombo.getSelectedItem(); - if (kp != null) - C_CashBook_ID = kp.getKey(); - DateAcct = (Timestamp)bDateField.getValue(); - } - - // K (CreditCard) Type, Number, Exp, Approval - else if (PaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) - { - vp = (ValueNamePair)kTypeCombo.getSelectedItem(); - if (vp != null) - CCType = vp.getValue(); - // - String error = MPaymentValidate.validateCreditCardNumber(kNumberField.getText(), CCType); - if (error.length() != 0) - { - kNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); - if (error.indexOf("?") == -1) - { - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - else // warning - { - if (!ADialog.ask(m_WindowNo, this, error)) - dataOK = false; - } - } - error = MPaymentValidate.validateCreditCardExp(kExpField.getText()); - if(error.length() != 0) - { - kExpField.setBackground(AdempierePLAF.getFieldBackground_Error()); - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - } - - // T (Transfer) BPartner_Bank - else if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit) - || PaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) - { - tAccountCombo.getSelectedItem(); - String error = MPaymentValidate.validateRoutingNo(tRoutingField.getText()); - if (error.length() != 0) - { - tRoutingField.setBackground(AdempierePLAF.getFieldBackground_Error()); - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - error = MPaymentValidate.validateAccountNo(tNumberField.getText()); - if (error.length() != 0) - { - tNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - } - - // P (PaymentTerm) PaymentTerm - else if (PaymentRule.equals(MOrder.PAYMENTRULE_OnCredit)) - { - KeyNamePair kp = (KeyNamePair)pTermCombo.getSelectedItem(); - if (kp != null) - C_PaymentTerm_ID = kp.getKey(); - } - - // S (Check) (Currency) CheckNo, Routing - else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) - { - // sCurrencyCombo.getSelectedItem(); - KeyNamePair kp = (KeyNamePair)sBankAccountCombo.getSelectedItem(); - if (kp != null) - C_BankAccount_ID = kp.getKey(); - String error = MPaymentValidate.validateRoutingNo(sRoutingField.getText()); - if (error.length() != 0) - { - sRoutingField.setBackground(AdempierePLAF.getFieldBackground_Error()); - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - error = MPaymentValidate.validateAccountNo(sNumberField.getText()); - if (error.length() != 0) - { - sNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - error = MPaymentValidate.validateCheckNo(sCheckField.getText()); - if (error.length() != 0) - { - sCheckField.setBackground(AdempierePLAF.getFieldBackground_Error()); - ADialog.error(m_WindowNo, this, error); - dataOK = false; - } - } - else - { - log.log(Level.SEVERE, "Unknown PaymentRule " + PaymentRule); - return false; - } - - // find Bank Account if not qualified yet - if ("KTSD".indexOf(PaymentRule) != -1 && C_BankAccount_ID == 0) - { - String tender = MPayment.TENDERTYPE_CreditCard; - if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit)) - tender = MPayment.TENDERTYPE_DirectDeposit; - else if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) - tender = MPayment.TENDERTYPE_DirectDebit; - else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) - tender = MPayment.TENDERTYPE_Check; - // ACH & Check must have a bank account - if (C_BankAccount_ID == 0 && "TS".indexOf(PaymentRule) != -1) - { - ADialog.error(m_WindowNo, this, "PaymentNoProcessor"); - dataOK = false; - } - } - // - log.config("OK=" + dataOK); - return dataOK; - } // checkMandatory - - /** - * Get Invoice ID for Order - * @param C_Order_ID order - * @return C_Invoice_ID or 0 if not found - */ - private static int getInvoiceID (int C_Order_ID) - { - int retValue = 0; - String sql = "SELECT C_Invoice_ID FROM C_Invoice WHERE C_Order_ID=? " - + "ORDER BY C_Invoice_ID DESC"; // last invoice - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt(1, C_Order_ID); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - retValue = rs.getInt(1); - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - return retValue; - } // getInvoiceID - - - /************************************************************************** - * Process Online (sales only) - if approved - exit - */ - private void processOnline() - { - log.config(""); - if (!checkMandatory()) - return; - - boolean approved = false; - String info = ""; - // - ValueNamePair vp = (ValueNamePair)paymentCombo.getSelectedItem(); - String PaymentRule = vp.getValue(); - - // -- CreditCard - if (PaymentRule.equals(X_C_Order.PAYMENTRULE_CreditCard)) - { - vp = (ValueNamePair)kTypeCombo.getSelectedItem(); - String CCType = vp.getValue(); - - m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, CCType, - kNumberField.getText(), "", kExpField.getText()); - m_mPayment.setAmount(m_C_Currency_ID, m_Amount); - m_mPayment.setPaymentProcessor(); - m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); - // - int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); - if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) - { - int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); - C_Invoice_ID = getInvoiceID (C_Order_ID); - } - m_mPayment.setC_Invoice_ID(C_Invoice_ID); - m_mPayment.setDateTrx(m_DateAcct); - // Set Amount - m_mPayment.setAmount(m_C_Currency_ID, m_Amount); - - approved = m_mPayment.processOnline(); - info = m_mPayment.getR_RespMsg() + " (" + m_mPayment.getR_AuthCode() - + ") ID=" + m_mPayment.getR_PnRef(); - boolean saved = m_mPayment.save(); - - if (approved) - { - boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); - m_mPayment.save(); - if (ok) - ADialog.info(m_WindowNo, this, "PaymentProcessed", info + "\n" + m_mPayment.getDocumentNo()); - else - ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); - saveChanges(); - dispose(); - } - else - { - ADialog.error(m_WindowNo, this, "PaymentNotProcessed", info); - } - } - else - ADialog.error(m_WindowNo, this, "PaymentNoProcessor"); - } // online - - /** - * Need Save record (payment with waiting order) - * @return true if payment with waiting order - */ - public boolean needSave() - { - return m_needSave; - } // needSave - -} // VPayment +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.grid; + +import java.awt.*; +import java.awt.event.*; +import java.math.*; +import java.sql.*; +import java.text.*; +import java.util.*; +import java.util.logging.*; +import javax.swing.*; + +import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.*; +import org.compiere.grid.ed.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.process.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Display (and process) Payment Options. + *
+ *  Payment Rule
+ *  -B- Cash          (Date)          -> Cash Entry
+ *  -P- Payment Term  (Term)
+ *  -S- Check         (Routing, ..)   -> Payment Entry
+ *  -K- CreditCard    (No)            -> Payment Entry
+ *  -U- ACH Transfer  (Routing)       -> Payment Entry
+ *
+ *  When processing:
+ *  - If an invoice is a S/K/U, but has no Payment Entry, it is changed to P
+ *  - If an invoive is B and has no Cash Entry, it is created
+ *  - An invoice is "Open" if it is "P" and no Payment
+ *
+ *  Entry:
+ *  - If not processed, an invoice has no Cash or Payment entry
+ *  - The entry is created, during "Online" and when Saving
+ *
+ *  Changes/Reversals:
+ *  - existing Cash Entries are reversed and newly created
+ *  - existing Payment Entries are not changed and then "hang there" and need to be allocated
+ *  
+ * + * @author Jorg Janke + * @version $Id: VPayment.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public class VPayment extends CDialog + implements ActionListener +{ + /** + * Constructor + * + * @param WindowNo owning window + * @param mTab owning tab + * @param button button with access information + */ + public VPayment (int WindowNo, GridTab mTab, VButton button) + { + super(Env.getWindow(WindowNo), Msg.getMsg(Env.getCtx(), "Payment"), true); + m_WindowNo = WindowNo; + m_isSOTrx = "Y".equals(Env.getContext(Env.getCtx(), WindowNo, "IsSOTrx")); + m_mTab = mTab; + try + { + bDateField = new VDate("DateAcct", false, false, true, DisplayType.Date, "DateAcct"); + jbInit(); + m_initOK = dynInit(button); // Null Pointer if order/invoice not saved yet + } + catch(Exception ex) + { + log.log(Level.SEVERE, "VPayment", ex); + m_initOK = false; + } + // + AEnv.positionCenterWindow(Env.getWindow(WindowNo), this); + } // VPayment + + /** Window */ + private int m_WindowNo = 0; + /** Tab */ + private GridTab m_mTab; + + // Data from Order/Invoice + private String m_DocStatus = null; + /** Start Payment Rule */ + private String m_PaymentRule = ""; + /** Start Payment Term */ + private int m_C_PaymentTerm_ID = 0; + /** Start Acct Date */ + private Timestamp m_DateAcct = null; + /** Start Payment */ + private int m_C_Payment_ID = 0; + private MPayment m_mPayment = null; + private MPayment m_mPaymentOriginal = null; + /** Start CashBook Line */ + private int m_C_CashLine_ID = 0; + private MCashLine m_cashLine = null; + /** Start CreditCard */ + private String m_CCType = ""; + /** Start Bank Account */ + private int m_C_BankAccount_ID = 0; + /** Start CashBook */ + private int m_C_CashBook_ID = 0; + + /** Is SOTrx */ + private boolean m_isSOTrx = true; + + /** Invoice Currency */ + private int m_C_Currency_ID = 0; + private int m_AD_Client_ID = 0; + private int m_AD_Org_ID = 0; + private int m_C_BPartner_ID = 0; + private BigDecimal m_Amount = Env.ZERO; // Payment Amount + // + private boolean m_initOK = false; + /** Only allow changing Rule */ + private boolean m_onlyRule = false; + private DecimalFormat m_Format = DisplayType.getNumberFormat(DisplayType.Amount); + private static Hashtable s_Currencies = null; // EMU Currencies + + private boolean m_needSave = false; + /** Logger */ + private static CLogger log = CLogger.getCLogger(VPayment.class); + + // + private CPanel mainPanel = new CPanel(); + private BorderLayout mainLayout = new BorderLayout(); + private CPanel northPanel = new CPanel(); + private CPanel centerPanel = new CPanel(); + private FlowLayout northLayout = new FlowLayout(); + private CComboBox paymentCombo = new CComboBox(); + private CLabel paymentLabel = new CLabel(); + private CardLayout centerLayout = new CardLayout(); + private CPanel bPanel = new CPanel(); + private CPanel kPanel = new CPanel(); + private GridBagLayout kLayout = new GridBagLayout(); + private CLabel kTypeLabel = new CLabel(); + private CComboBox kTypeCombo = new CComboBox(); + private CLabel kNumnerLabel = new CLabel(); + private CTextField kNumberField = new CTextField(); + private CLabel kExpLabel = new CLabel(); + private CTextField kExpField = new CTextField(); + private CLabel kApprovalLabel = new CLabel(); + private CTextField kApprovalField = new CTextField(); + private CPanel tPanel = new CPanel(); + private CLabel tAccountLabel = new CLabel(); + private CComboBox tAccountCombo = new CComboBox(); + private CPanel sPanel = new CPanel(); + private GridBagLayout sPanelLayout = new GridBagLayout(); + private CLabel sNumberLabel = new CLabel(); + private CTextField sNumberField = new CTextField(); + private CLabel sRoutingLabel = new CLabel(); + private CTextField sRoutingField = new CTextField(); + private CLabel sCurrencyLabel = new CLabel(); + private CComboBox sCurrencyCombo = new CComboBox(); + private CLabel bCurrencyLabel = new CLabel(); + private CComboBox bCurrencyCombo = new CComboBox(); + private CPanel pPanel = new CPanel(); + private CLabel pTermLabel = new CLabel(); + private CComboBox pTermCombo = new CComboBox(); + private GridBagLayout bPanelLayout = new GridBagLayout(); + private CLabel bAmountLabel = new CLabel(); + private CLabel bAmountField = new CLabel(); + private CLabel sAmountLabel = new CLabel(); + private CLabel sAmountField = new CLabel(); + private VDate bDateField; + private CLabel bDateLabel = new CLabel(); + private ConfirmPanel confirmPanel = new ConfirmPanel(true); + private CTextField sCheckField = new CTextField(); + private CLabel sCheckLabel = new CLabel(); + private CButton kOnline = new CButton(); + private CButton sOnline = new CButton(); + private CComboBox sBankAccountCombo = new CComboBox(); + private CLabel sBankAccountLabel = new CLabel(); + private GridBagLayout pPanelLayout = new GridBagLayout(); + private CLabel bCashBookLabel = new CLabel(); + private CComboBox bCashBookCombo = new CComboBox(); + private GridBagLayout tPanelLayout = new GridBagLayout(); + private CLabel kStatus = new CLabel(); + private CLabel tStatus = new CLabel(); + private CLabel sStatus = new CLabel(); + + /** + * Static Init + * @throws Exception + */ + private void jbInit() throws Exception + { + centerPanel.setBorder(BorderFactory.createRaisedBevelBorder()); + getContentPane().add(mainPanel); + mainPanel.setLayout(mainLayout); + mainPanel.add(centerPanel, BorderLayout.CENTER); + // + northPanel.setLayout(northLayout); + paymentLabel.setText(Msg.translate(Env.getCtx(), "PaymentRule")); + mainPanel.add(northPanel, BorderLayout.NORTH); + northPanel.add(paymentLabel, null); + northPanel.add(paymentCombo, null); + // + centerPanel.setLayout(centerLayout); + // CreditCard + kPanel.setLayout(kLayout); + kNumberField.setPreferredSize(new Dimension(120, 21)); + kExpField.setPreferredSize(new Dimension(40, 21)); + kApprovalField.setPreferredSize(new Dimension(120, 21)); + kTypeLabel.setText(Msg.translate(Env.getCtx(), "CreditCardType")); + kNumnerLabel.setText(Msg.translate(Env.getCtx(), "CreditCardNumber")); + kExpLabel.setText(Msg.getMsg(Env.getCtx(), "Expires")); + kApprovalLabel.setText(Msg.translate(Env.getCtx(), "VoiceAuthCode")); + kOnline.setText(Msg.getMsg(Env.getCtx(), "Online")); + kOnline.addActionListener(this); + kStatus.setText(" "); + centerPanel.add(kPanel, "kPanel"); + centerLayout.addLayoutComponent(kPanel, "kPanel"); + kPanel.add(kTypeLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + kPanel.add(kTypeCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); + kPanel.add(kNumnerLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + kPanel.add(kNumberField, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(2, 5, 2, 5), 0, 0)); + kPanel.add(kExpLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + kPanel.add(kExpField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); + kPanel.add(kApprovalLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0)); + kPanel.add(kApprovalField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + kPanel.add(kStatus, new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0 + ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + kPanel.add(kOnline, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + // DircetDebit/Credit + tPanel.setLayout(tPanelLayout); + tAccountLabel.setText(Msg.translate(Env.getCtx(), "C_BP_BankAccount_ID")); + tStatus.setText(" "); + centerPanel.add(tPanel, "tPanel"); + centerLayout.addLayoutComponent(tPanel, "tPanel"); + tPanel.add(tAccountLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0)); + tPanel.add(tAccountCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + tPanel.add(tStatus, new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0 + ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + // + sPanel.setLayout(sPanelLayout); + sBankAccountLabel.setText(Msg.translate(Env.getCtx(), "C_BankAccount_ID")); + sAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); + sAmountField.setText(""); + sRoutingLabel.setText(Msg.translate(Env.getCtx(), "RoutingNo")); + sNumberLabel.setText(Msg.translate(Env.getCtx(), "AccountNo")); + sCheckLabel.setText(Msg.translate(Env.getCtx(), "CheckNo")); + sCheckField.setColumns(8); + sCurrencyLabel.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); + sNumberField.setPreferredSize(new Dimension(100, 21)); + sRoutingField.setPreferredSize(new Dimension(70, 21)); + sStatus.setText(" "); + sOnline.setText(Msg.getMsg(Env.getCtx(), "Online")); + centerPanel.add(sPanel, "sPanel"); + centerLayout.addLayoutComponent(sPanel, "sPanel"); + sPanel.add(sCurrencyLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + sPanel.add(sCurrencyCombo, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); + sPanel.add(sRoutingField, new GridBagConstraints(1, 4, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 2, 0), 0, 0)); + sPanel.add(sNumberField, new GridBagConstraints(1, 5, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 2, 0), 0, 0)); + sPanel.add(sCheckField, new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0)); + sPanel.add(sRoutingLabel, new GridBagConstraints(0, 3, 1, 2, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 2, 0), 0, 0)); + sPanel.add(sNumberLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + sPanel.add(sCheckLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + sPanel.add(sBankAccountCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0)); + sPanel.add(sBankAccountLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); + sPanel.add(sStatus, new GridBagConstraints(0, 7, 3, 1, 0.0, 0.0 + ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + sPanel.add(sOnline, new GridBagConstraints(3, 6, 1, 1, 0.0, 0.0 + ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); + sPanel.add(sAmountField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 5, 5), 0, 0)); + sPanel.add(sAmountLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 5, 0), 0, 0)); + // + pPanel.setLayout(pPanelLayout); + pTermLabel.setText(Msg.translate(Env.getCtx(), "C_PaymentTerm_ID")); + centerPanel.add(pPanel, "pPanel"); + centerLayout.addLayoutComponent(pPanel, "pPanel"); + pPanel.add(pTermLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 5, 2, 0), 0, 0)); + pPanel.add(pTermCombo, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); + // + bCashBookLabel.setText(Msg.translate(Env.getCtx(), "C_CashBook_ID")); + bCurrencyLabel.setText(Msg.translate(Env.getCtx(), "C_Currency_ID")); + bPanel.setLayout(bPanelLayout); + bAmountLabel.setText(Msg.getMsg(Env.getCtx(), "Amount")); + bAmountField.setText(""); + bDateLabel.setText(Msg.translate(Env.getCtx(), "DateAcct")); + centerLayout.addLayoutComponent(bPanel, "bPanel"); + centerPanel.add(bPanel, "bPanel"); + bPanel.add(bCurrencyLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + bPanel.add(bCurrencyCombo, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); + bPanel.add(bDateField, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0)); + bPanel.add(bDateLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); + bPanel.add(bCashBookLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 0, 2, 0), 0, 0)); + bPanel.add(bCashBookCombo, new GridBagConstraints(1, 0, 2, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); + bPanel.add(bAmountLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 0, 2, 0), 0, 0)); + bPanel.add(bAmountField, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0 + ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 2, 5), 0, 0)); + // + mainPanel.add(confirmPanel, BorderLayout.SOUTH); + confirmPanel.addActionListener(this); + } // jbInit + + + /************************************************************************** + * Dynamic Init. + * B (Cash) (Currency) + * K (CreditCard) Type, Number, Exp, Approval + * L (DirectDebit) BPartner_Bank + * P (PaymentTerm) PaymentTerm + * S (Check) (Currency) CheckNo, Routing + * + * Currencies are shown, if member of EMU + * @param button payment type button + * @return true if init OK + * @throws Exception + */ + private boolean dynInit (VButton button) throws Exception + { + m_DocStatus = (String)m_mTab.getValue("DocStatus"); + log.config(m_DocStatus); + + if (m_mTab.getValue("C_BPartner_ID") == null) + { + ADialog.error(0, this, "SaveErrorRowNotFound"); + return false; + } + + // Is the Trx posted? + // String Posted = (String)m_mTab.getValue("Posted"); + // if (Posted != null && Posted.equals("Y")) + // return false; + + // DocStatus + m_DocStatus = (String)m_mTab.getValue("DocStatus"); + if (m_DocStatus == null) + m_DocStatus = ""; + // Is the Trx closed? Reversed / Voided / Cloased + if (m_DocStatus.equals("RE") || m_DocStatus.equals("VO") || m_DocStatus.equals("CL")) + return false; + // Document is not complete - allow to change the Payment Rule only + if (m_DocStatus.equals("CO") || m_DocStatus.equals("WP") ) + m_onlyRule = false; + else + m_onlyRule = true; + // PO only Rule + if (!m_onlyRule // Only order has Warehouse + && !m_isSOTrx && m_mTab.getValue("M_Warehouse_ID") != null) + m_onlyRule = true; + + centerPanel.setVisible(!m_onlyRule); + + + // Amount + m_Amount = (BigDecimal)m_mTab.getValue("GrandTotal"); + if (!m_onlyRule && m_Amount.compareTo(Env.ZERO) == 0) + { + ADialog.error(m_WindowNo, this, "PaymentZero"); + return false; + } + bAmountField.setText(m_Format.format(m_Amount)); + sAmountField.setText(m_Format.format(m_Amount)); + + /** + * Get Data from Grid + */ + m_AD_Client_ID = ((Integer)m_mTab.getValue("AD_Client_ID")).intValue(); + m_AD_Org_ID = ((Integer)m_mTab.getValue("AD_Org_ID")).intValue(); + m_C_BPartner_ID = ((Integer)m_mTab.getValue("C_BPartner_ID")).intValue(); + m_PaymentRule = (String)m_mTab.getValue("PaymentRule"); + m_C_Currency_ID = ((Integer)m_mTab.getValue("C_Currency_ID")).intValue(); + m_DateAcct = (Timestamp)m_mTab.getValue("DateAcct"); + if (m_mTab.getValue("C_PaymentTerm_ID") != null) + m_C_PaymentTerm_ID = ((Integer)m_mTab.getValue("C_PaymentTerm_ID")).intValue(); + // Existing Payment + if (m_mTab.getValue("C_Payment_ID") != null) + { + m_C_Payment_ID = ((Integer)m_mTab.getValue("C_Payment_ID")).intValue(); + if (m_C_Payment_ID != 0) + { + m_mPayment = new MPayment(Env.getCtx(), m_C_Payment_ID, null); + m_mPaymentOriginal = new MPayment(Env.getCtx(), m_C_Payment_ID, null); // full copy + // CreditCard + m_CCType = m_mPayment.getCreditCardType(); + kNumberField.setText(m_mPayment.getCreditCardNumber()); + kExpField.setText(m_mPayment.getCreditCardExp(null)); + kApprovalField.setText(m_mPayment.getVoiceAuthCode()); + kStatus.setText(m_mPayment.getR_PnRef()); + // if approved/paid, don't let it change + kTypeCombo.setReadWrite(!m_mPayment.isApproved()); + kNumberField.setReadWrite(!m_mPayment.isApproved()); + kExpField.setReadWrite(!m_mPayment.isApproved()); + kApprovalField.setReadWrite(!m_mPayment.isApproved()); + kOnline.setReadWrite(!m_mPayment.isApproved()); + // Check + m_C_BankAccount_ID = m_mPayment.getC_BankAccount_ID(); + sRoutingField.setText(m_mPayment.getRoutingNo()); + sNumberField.setText(m_mPayment.getAccountNo()); + sCheckField.setText(m_mPayment.getCheckNo()); + sStatus.setText(m_mPayment.getR_PnRef()); + // Transfer + tStatus.setText(m_mPayment.getR_PnRef()); + } + } + if (m_mPayment == null) + { + m_mPayment = new MPayment (Env.getCtx (), 0, null); + m_mPayment.setAD_Org_ID(m_AD_Org_ID); + m_mPayment.setAmount (m_C_Currency_ID, m_Amount); + } + + // Existing Cahbook entry + m_cashLine = null; + m_C_CashLine_ID = 0; + if (m_mTab.getValue("C_CashLine_ID") != null) + { + m_C_CashLine_ID = ((Integer)m_mTab.getValue("C_CashLine_ID")).intValue(); + if (m_C_CashLine_ID == 0) + m_cashLine = null; + else + { + m_cashLine = new MCashLine (Env.getCtx(), m_C_CashLine_ID, null); + m_DateAcct = m_cashLine.getStatementDate(); + } + } + + // Accounting Date + bDateField.setValue(m_DateAcct); + + if (s_Currencies == null) + loadCurrencies(); + + // Is the currency an EMU currency? + Integer C_Currency_ID = new Integer(m_C_Currency_ID); + if (s_Currencies.containsKey(C_Currency_ID)) + { + Enumeration en = s_Currencies.keys(); + while (en.hasMoreElements()) + { + Object key = en.nextElement(); + bCurrencyCombo.addItem(s_Currencies.get(key)); + sCurrencyCombo.addItem(s_Currencies.get(key)); + } + sCurrencyCombo.addActionListener(this); + sCurrencyCombo.setSelectedItem(s_Currencies.get(C_Currency_ID)); + bCurrencyCombo.addActionListener(this); + bCurrencyCombo.setSelectedItem(s_Currencies.get(C_Currency_ID)); + } + else // No EMU Currency + { + bCurrencyLabel.setVisible(false); // Cash + bCurrencyCombo.setVisible(false); + sCurrencyLabel.setVisible(false); // Check + sCurrencyCombo.setVisible(false); + } + + /** + * Payment Combo + */ + if (m_PaymentRule == null) + m_PaymentRule = ""; + ValueNamePair vp = null; + HashMap values = button.getValues(); + Object[] a = values.keySet().toArray(); + for (int i = 0; i < a.length; i++) + { + String PaymentRule = (String)a[i]; // used for Panel selection + if (X_C_Order.PAYMENTRULE_DirectDebit.equals(PaymentRule) // SO + && !m_isSOTrx) + continue; + else if (X_C_Order.PAYMENTRULE_DirectDeposit.equals(PaymentRule) // PO + && m_isSOTrx) + continue; + ValueNamePair pp = new ValueNamePair(PaymentRule, (String)values.get(a[i])); + paymentCombo.addItem(pp); + if (PaymentRule.toString().equals(m_PaymentRule)) // to select + vp = pp; + } + + // Set PaymentRule + paymentCombo.addActionListener(this); + if (vp != null) + paymentCombo.setSelectedItem(vp); + + /** + * Load Payment Terms + */ + String SQL = MRole.getDefault().addAccessSQL( + "SELECT C_PaymentTerm_ID, Name FROM C_PaymentTerm WHERE IsActive='Y' ORDER BY Name", + "C_PaymentTerm", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); + KeyNamePair kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + pTermCombo.addItem(pp); + if (key == m_C_PaymentTerm_ID) + kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException ept) + { + log.log(Level.SEVERE, SQL, ept); + } + // Set Selection + if (kp != null) + pTermCombo.setSelectedItem(kp); + + /** + * Load Accounts + */ + SQL = "SELECT a.C_BP_BankAccount_ID, NVL(b.Name, ' ')||a.AccountNo AS Acct " + + "FROM C_BP_BankAccount a,C_Bank b " + + "WHERE C_BPartner_ID=? AND a.IsActive='Y'"; + kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + pstmt.setInt(1, m_C_BPartner_ID); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + tAccountCombo.addItem(pp); + // kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException eac) + { + log.log(Level.SEVERE, SQL, eac); + } + // Set Selection + if (kp != null) + tAccountCombo.setSelectedItem(kp); + + /** + * Load Credit Cards + */ + ValueNamePair[] ccs = m_mPayment.getCreditCards(); + vp = null; + for (int i = 0; i < ccs.length; i++) + { + kTypeCombo.addItem(ccs[i]); + if (ccs[i].getValue().equals(m_CCType)) + vp = ccs[i]; + } + // Set Selection + if (vp != null) + kTypeCombo.setSelectedItem(vp); + + /** + * Load Bank Accounts + */ + SQL = MRole.getDefault().addAccessSQL( + "SELECT C_BankAccount_ID, Name || ' ' || AccountNo, IsDefault " + + "FROM C_BankAccount ba" + + " INNER JOIN C_Bank b ON (ba.C_Bank_ID=b.C_Bank_ID) " + + "WHERE b.IsActive='Y'", + "ba", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO); + kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + sBankAccountCombo.addItem(pp); + if (key == m_C_BankAccount_ID) + kp = pp; + if (kp == null && rs.getString(3).equals("Y")) // Default + kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException ept) + { + log.log(Level.SEVERE, SQL, ept); + } + // Set Selection + if (kp != null) + sBankAccountCombo.setSelectedItem(kp); + + + /** + * Load Cash Books + */ + SQL = MRole.getDefault().addAccessSQL( + "SELECT C_CashBook_ID, Name, AD_Org_ID FROM C_CashBook WHERE IsActive='Y'", + "C_CashBook", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO); + kp = null; + try + { + PreparedStatement pstmt = DB.prepareStatement(SQL, null); + ResultSet rs = pstmt.executeQuery(); + while (rs.next()) + { + int key = rs.getInt(1); + String name = rs.getString(2); + KeyNamePair pp = new KeyNamePair(key, name); + bCashBookCombo.addItem(pp); + if (key == m_C_CashBook_ID) + kp = pp; + if (kp == null && key == m_AD_Org_ID) // Default Org + kp = pp; + } + rs.close(); + pstmt.close(); + } + catch (SQLException epc) + { + log.log(Level.SEVERE, SQL, epc); + } + // Set Selection + if (kp != null) + { + bCashBookCombo.setSelectedItem(kp); + if (m_C_CashBook_ID == 0) + m_C_CashBook_ID = kp.getKey(); // set to default to avoid 'cashbook changed' message + } + + // + return true; + } // dynInit + + /** + * Init OK to be able to make changes? + * @return true if init OK + */ + public boolean isInitOK() + { + return m_initOK; + } // isInitOK + + + /** + * Fill s_Currencies with EMU currencies + */ + private void loadCurrencies() + { + s_Currencies = new Hashtable(12); // Currenly only 10+1 + String SQL = "SELECT C_Currency_ID, ISO_Code FROM C_Currency " + + "WHERE (IsEMUMember='Y' AND EMUEntryDate " + newPaymentRule); + // We had a CashBook Entry + if (m_PaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) + { + log.fine("Old Cash - " + m_cashLine); + if (m_cashLine != null) + { + MCashLine cl = m_cashLine.createReversal(); + if (cl.save()) + log.config( "CashCancelled"); + else + ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); + } + newC_CashLine_ID = 0; // reset + } + // We had a change in Payment type (e.g. Check to CC) + else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) != -1 && m_mPaymentOriginal != null) + { + log.fine("Old Payment(1) - " + m_mPaymentOriginal); + m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); + boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); + m_mPaymentOriginal.save(); + if (ok) + log.info( "Payment Canecelled - " + m_mPaymentOriginal); + else + ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPaymentOriginal.getDocumentNo()); + m_mPayment.resetNew(); + } + // We had a Payment and something else (e.g. Check to Cash) + else if ("KTSD".indexOf(m_PaymentRule) != -1 && "KTSD".indexOf(newPaymentRule) == -1) + { + log.fine("Old Payment(2) - " + m_mPaymentOriginal); + if (m_mPaymentOriginal != null) + { + m_mPaymentOriginal.setDocAction(DocAction.ACTION_Reverse_Correct); + boolean ok = m_mPaymentOriginal.processIt(DocAction.ACTION_Reverse_Correct); + m_mPaymentOriginal.save(); + if (ok) // Cancel Payment + { + log.fine("PaymentCancelled " + m_mPayment.getDocumentNo ()); + m_mTab.getTableModel().dataSave(true); + m_mPayment.resetNew(); + m_mPayment.setAmount(m_C_Currency_ID, m_Amount); + } + else + ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCancelled " + m_mPayment.getDocumentNo()); + } + } + } + + // Get Order and optionally Invoice + int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); + int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); + if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) + C_Invoice_ID = getInvoiceID (C_Order_ID); + + // Amount sign negative, if ARC (Credit Memo) or API (AP Invoice) + boolean negateAmt = false; + MInvoice invoice = null; + if (C_Invoice_ID != 0) + { + invoice = new MInvoice (Env.getCtx(), C_Invoice_ID, null); + negateAmt = invoice.isCreditMemo(); + } + MOrder order = null; + if (invoice == null && C_Order_ID != 0) + order = new MOrder (Env.getCtx(), C_Order_ID, null); + BigDecimal payAmount = m_Amount; + if (negateAmt) + payAmount = m_Amount.negate(); + // Info + log.config("C_Order_ID=" + C_Order_ID + ", C_Invoice_ID=" + C_Invoice_ID + ", NegateAmt=" + negateAmt); + + /*********************** + * CashBook + */ + if (newPaymentRule.equals(X_C_Order.PAYMENTRULE_Cash)) + { + log.fine("Cash"); + String description = (String)m_mTab.getValue("DocumentNo"); + + if (C_Invoice_ID == 0 && order == null) + { + log.config("No Invoice!"); + ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); + } + else + { + // Changed Amount + if (m_cashLine != null + && payAmount.compareTo(m_cashLine.getAmount()) != 0) + { + log.config("Changed CashBook Amount"); + m_cashLine.setAmount(payAmount); + if (m_cashLine.save()) + log.config("CashAmt Changed"); + } + // Different Date/CashBook + if (m_cashLine != null + && (newC_CashBook_ID != m_C_CashBook_ID + || !TimeUtil.isSameDay(m_cashLine.getStatementDate(), newDateAcct))) + { + log.config("Changed CashBook/Date: " + m_C_CashBook_ID + "->" + newC_CashBook_ID); + MCashLine reverse = m_cashLine.createReversal(); + if (!reverse.save()) + ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCancelled"); + m_cashLine = null; + } + + // Create new + if (m_cashLine == null) + { + log.config("New CashBook"); + int C_Currency_ID = 0; + if (invoice != null) + C_Currency_ID = invoice.getC_Currency_ID(); + if (C_Currency_ID == 0 && order != null) + C_Currency_ID = order.getC_Currency_ID(); + MCash cash = null; + if (newC_CashBook_ID != 0) + cash = MCash.get (Env.getCtx(), newC_CashBook_ID, newDateAcct, null); + else // Default + cash = MCash.get (Env.getCtx(), m_AD_Org_ID, newDateAcct, C_Currency_ID, null); + if (cash == null || cash.get_ID() == 0) + ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); + else + { + MCashLine cl = new MCashLine (cash); + if (invoice != null) + cl.setInvoice(invoice); + if (order != null) + { + cl.setOrder(order, null); + m_needSave = true; + } + if (cl.save()) + log.config("CashCreated"); + else + ADialog.error(m_WindowNo, this, "PaymentError", "CashNotCreated"); + } + } + } // have invoice + } + /*********************** + * Payments + */ + if ("KS".indexOf(newPaymentRule) != -1) + { + log.fine("Payment - " + newPaymentRule); + // Set Amount + m_mPayment.setAmount(m_C_Currency_ID, payAmount); + if (newPaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) + { + m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, newCCType, + kNumberField.getText(), "", kExpField.getText()); + m_mPayment.setPaymentProcessor(); + } + else if (newPaymentRule.equals(MOrder.PAYMENTRULE_Check)) + { + m_mPayment.setBankCheck(newC_BankAccount_ID, m_isSOTrx, sRoutingField.getText(), + sNumberField.getText(), sCheckField.getText()); + } + m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); + m_mPayment.setC_Invoice_ID(C_Invoice_ID); + if (order != null) + { + m_mPayment.setC_Order_ID(C_Order_ID); + m_needSave = true; + } + m_mPayment.setDateTrx(m_DateAcct); + m_mPayment.setDateAcct(m_DateAcct); + m_mPayment.save(); + + // Save/Post + if (MPayment.DOCSTATUS_Drafted.equals(m_mPayment.getDocStatus())) + { + boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); + m_mPayment.save(); + if (ok) + ADialog.info(m_WindowNo, this, "PaymentCreated", m_mPayment.getDocumentNo()); + else + ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); + } + else + log.fine("NotDraft " + m_mPayment); + } + + + /********************** + * Save Values to mTab + */ + log.config("Saving changes"); + // + if (!newPaymentRule.equals(m_PaymentRule)) + m_mTab.setValue("PaymentRule", newPaymentRule); + // + if (!newDateAcct.equals(m_DateAcct)) + m_mTab.setValue("DateAcct", newDateAcct); + // + if (newC_PaymentTerm_ID != m_C_PaymentTerm_ID) + m_mTab.setValue("C_PaymentTerm_ID", new Integer(newC_PaymentTerm_ID)); + // Set Payment + if (m_mPayment.getC_Payment_ID() != m_C_Payment_ID) + { + if (m_mPayment.getC_Payment_ID() == 0) + m_mTab.setValue("C_Payment_ID", null); + else + m_mTab.setValue("C_Payment_ID", new Integer(m_mPayment.getC_Payment_ID())); + } + // Set Cash + if (newC_CashLine_ID != m_C_CashLine_ID) + { + if (newC_CashLine_ID == 0) + m_mTab.setValue("C_CashLine_ID", null); + else + m_mTab.setValue("C_CashLine_ID", new Integer(newC_CashLine_ID)); + } + return true; + } // saveChanges + + /** + * Check Mandatory + * @return true if all mandatory items are OK + */ + private boolean checkMandatory() + { + // log.config( "VPayment.checkMandatory"); + + ValueNamePair vp = (ValueNamePair)paymentCombo.getSelectedItem(); + String PaymentRule = vp.getValue(); + // only Payment Rule + if (m_onlyRule) + return true; + + Timestamp DateAcct = m_DateAcct; + int C_PaymentTerm_ID = m_C_PaymentTerm_ID; + int C_CashBook_ID = m_C_CashBook_ID; + String CCType = m_CCType; + // + int C_BankAccount_ID = 0; + + /*********************** + * Mandatory Data Check + */ + boolean dataOK = true; + // B (Cash) (Currency) + if (PaymentRule.equals(MOrder.PAYMENTRULE_Cash)) + { + KeyNamePair kp = (KeyNamePair)bCashBookCombo.getSelectedItem(); + if (kp != null) + C_CashBook_ID = kp.getKey(); + DateAcct = (Timestamp)bDateField.getValue(); + } + + // K (CreditCard) Type, Number, Exp, Approval + else if (PaymentRule.equals(MOrder.PAYMENTRULE_CreditCard)) + { + vp = (ValueNamePair)kTypeCombo.getSelectedItem(); + if (vp != null) + CCType = vp.getValue(); + // + String error = MPaymentValidate.validateCreditCardNumber(kNumberField.getText(), CCType); + if (error.length() != 0) + { + kNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); + if (error.indexOf("?") == -1) + { + ADialog.error(m_WindowNo, this, error); + dataOK = false; + } + else // warning + { + if (!ADialog.ask(m_WindowNo, this, error)) + dataOK = false; + } + } + error = MPaymentValidate.validateCreditCardExp(kExpField.getText()); + if(error.length() != 0) + { + kExpField.setBackground(AdempierePLAF.getFieldBackground_Error()); + ADialog.error(m_WindowNo, this, error); + dataOK = false; + } + } + + // T (Transfer) BPartner_Bank + else if (PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDeposit) + || PaymentRule.equals(X_C_Order.PAYMENTRULE_DirectDebit)) + { + KeyNamePair bpba = (KeyNamePair)tAccountCombo.getSelectedItem(); + if (bpba == null) + { + tAccountCombo.setBackground(AdempierePLAF.getFieldBackground_Error()); + ADialog.error(m_WindowNo, this, "PaymentBPBankNotFound"); + dataOK = false; + } + } // Direct + + // P (PaymentTerm) PaymentTerm + else if (PaymentRule.equals(X_C_Order.PAYMENTRULE_OnCredit)) + { + KeyNamePair kp = (KeyNamePair)pTermCombo.getSelectedItem(); + if (kp != null) + C_PaymentTerm_ID = kp.getKey(); + } + + // S (Check) (Currency) CheckNo, Routing + else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) + { + // sCurrencyCombo.getSelectedItem(); + KeyNamePair kp = (KeyNamePair)sBankAccountCombo.getSelectedItem(); + if (kp != null) + C_BankAccount_ID = kp.getKey(); + String error = MPaymentValidate.validateRoutingNo(sRoutingField.getText()); + if (error.length() != 0) + { + sRoutingField.setBackground(AdempierePLAF.getFieldBackground_Error()); + ADialog.error(m_WindowNo, this, error); + dataOK = false; + } + error = MPaymentValidate.validateAccountNo(sNumberField.getText()); + if (error.length() != 0) + { + sNumberField.setBackground(AdempierePLAF.getFieldBackground_Error()); + ADialog.error(m_WindowNo, this, error); + dataOK = false; + } + error = MPaymentValidate.validateCheckNo(sCheckField.getText()); + if (error.length() != 0) + { + sCheckField.setBackground(AdempierePLAF.getFieldBackground_Error()); + ADialog.error(m_WindowNo, this, error); + dataOK = false; + } + } + else + { + log.log(Level.SEVERE, "Unknown PaymentRule " + PaymentRule); + return false; + } + + // find Bank Account if not qualified yet + if ("KTSD".indexOf(PaymentRule) != -1 && C_BankAccount_ID == 0) + { + String tender = MPayment.TENDERTYPE_CreditCard; + if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDeposit)) + tender = MPayment.TENDERTYPE_DirectDeposit; + else if (PaymentRule.equals(MOrder.PAYMENTRULE_DirectDebit)) + tender = MPayment.TENDERTYPE_DirectDebit; + else if (PaymentRule.equals(MOrder.PAYMENTRULE_Check)) + tender = MPayment.TENDERTYPE_Check; + // Check must have a bank account + if (C_BankAccount_ID == 0 && "S".equals(PaymentRule)) + { + ADialog.error(m_WindowNo, this, "PaymentNoProcessor"); + dataOK = false; + } + } + // + log.config("OK=" + dataOK); + return dataOK; + } // checkMandatory + + /** + * Get Invoice ID for Order + * @param C_Order_ID order + * @return C_Invoice_ID or 0 if not found + */ + private static int getInvoiceID (int C_Order_ID) + { + int retValue = 0; + String sql = "SELECT C_Invoice_ID FROM C_Invoice WHERE C_Order_ID=? " + + "ORDER BY C_Invoice_ID DESC"; // last invoice + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt(1, C_Order_ID); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + retValue = rs.getInt(1); + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + return retValue; + } // getInvoiceID + + + /************************************************************************** + * Process Online (sales only) - if approved - exit + */ + private void processOnline() + { + log.config(""); + if (!checkMandatory()) + return; + + boolean approved = false; + String info = ""; + // + ValueNamePair vp = (ValueNamePair)paymentCombo.getSelectedItem(); + String PaymentRule = vp.getValue(); + + // -- CreditCard + if (PaymentRule.equals(X_C_Order.PAYMENTRULE_CreditCard)) + { + vp = (ValueNamePair)kTypeCombo.getSelectedItem(); + String CCType = vp.getValue(); + + m_mPayment.setCreditCard(MPayment.TRXTYPE_Sales, CCType, + kNumberField.getText(), "", kExpField.getText()); + m_mPayment.setAmount(m_C_Currency_ID, m_Amount); + m_mPayment.setPaymentProcessor(); + m_mPayment.setC_BPartner_ID(m_C_BPartner_ID); + // + int C_Invoice_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Invoice_ID"); + if (C_Invoice_ID == 0 && m_DocStatus.equals("CO")) + { + int C_Order_ID = Env.getContextAsInt(Env.getCtx(), m_WindowNo, "C_Order_ID"); + C_Invoice_ID = getInvoiceID (C_Order_ID); + } + m_mPayment.setC_Invoice_ID(C_Invoice_ID); + m_mPayment.setDateTrx(m_DateAcct); + // Set Amount + m_mPayment.setAmount(m_C_Currency_ID, m_Amount); + + approved = m_mPayment.processOnline(); + info = m_mPayment.getR_RespMsg() + " (" + m_mPayment.getR_AuthCode() + + ") ID=" + m_mPayment.getR_PnRef(); + boolean saved = m_mPayment.save(); + + if (approved) + { + boolean ok = m_mPayment.processIt(DocAction.ACTION_Complete); + m_mPayment.save(); + if (ok) + ADialog.info(m_WindowNo, this, "PaymentProcessed", info + "\n" + m_mPayment.getDocumentNo()); + else + ADialog.error(m_WindowNo, this, "PaymentError", "PaymentNotCreated"); + saveChanges(); + dispose(); + } + else + { + ADialog.error(m_WindowNo, this, "PaymentNotProcessed", info); + } + } + else + ADialog.error(m_WindowNo, this, "PaymentNoProcessor"); + } // online + + /** + * Need Save record (payment with waiting order) + * @return true if payment with waiting order + */ + public boolean needSave() + { + return m_needSave; + } // needSave + +} // VPayment diff --git a/client/src/org/compiere/grid/ed/VCellEditor.java b/client/src/org/compiere/grid/ed/VCellEditor.java index 28f01f03fc..2d0313911d 100644 --- a/client/src/org/compiere/grid/ed/VCellEditor.java +++ b/client/src/org/compiere/grid/ed/VCellEditor.java @@ -3,22 +3,22 @@ * 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 * - *****************************************************************************/ -package org.compiere.grid.ed; - -import java.awt.*; -import java.awt.event.*; -import java.beans.*; + * 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 * + *****************************************************************************/ +package org.compiere.grid.ed; + +import java.awt.*; +import java.awt.event.*; +import java.beans.*; import java.util.*; import javax.swing.*; import javax.swing.table.*; @@ -27,104 +27,104 @@ import org.adempiere.plaf.AdempierePLAF; import org.compiere.model.*; import org.compiere.plaf.*; import org.compiere.util.*; - -/** - * Cell Editor. - *
- *		Sequence of events:
- *			isCellEditable
- *			getTableCellEditor
- *			shouldSelectCell
- *			getCellEditorValue
- *  
- * A new Editor is created for editable columns. - * @author Jorg Janke - * @version $Id: VCellEditor.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public final class VCellEditor extends AbstractCellEditor - implements TableCellEditor, VetoableChangeListener, ActionListener -{ - /** - * Constructor for Grid - * @param mField - */ - public VCellEditor (GridField mField) - { - super(); - m_mField = mField; - // Click - } // VCellEditor - - /** The Field */ - private GridField m_mField = null; - /** The Table Editor */ - private VEditor m_editor = null; - /** Table */ - private JTable m_table = null; - /** ClickCount */ - private static int CLICK_TO_START = 2; - /** Logger */ - private static CLogger log = CLogger.getCLogger(VCellEditor.class); - - /** - * Create Editor - */ - private void createEditor() - { - m_editor = VEditorFactory.getEditor(m_mField, true); - m_editor.addVetoableChangeListener(this); - m_editor.addActionListener(this); - } // createEditor - - /** - * Ask the editor if it can start editing using anEvent. - * If editing can be started this method returns true. - * Previously called: MTable.isCellEditable - * @param anEvent event - * @return true if editable - */ - public boolean isCellEditable (EventObject anEvent) - { - if (!m_mField.isEditable (true)) // row data is in context - return false; - log.fine(m_mField.getHeader()); // event may be null if CellEdit - // not enough mouse clicks - if (anEvent instanceof MouseEvent - && ((MouseEvent)anEvent).getClickCount() < CLICK_TO_START) - return false; - - if (m_editor == null) - createEditor(); - return true; - } // isCellEditable - - /** - * Sets an initial value for the editor. This will cause the editor to - * stopEditing and lose any partially edited value if the editor is editing - * when this method is called. - * Returns the component that should be added to the client's Component hierarchy. - * Once installed in the client's hierarchy this component - * will then be able to draw and receive user input. - * - * @param table - * @param value - * @param isSelected - * @param row - * @param col - * @return component - */ - public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int col) - { - log.finest(m_mField.getColumnName() + ": Value=" + value + ", row=" + row + ", col=" + col); - if (row >= 0) - table.setRowSelectionInterval(row,row); // force moving to new row - if (m_editor == null) - createEditor(); - - m_table = table; - - // Set Value - m_editor.setValue(value); + +/** + * Cell Editor. + *
+ *		Sequence of events:
+ *			isCellEditable
+ *			getTableCellEditor
+ *			shouldSelectCell
+ *			getCellEditorValue
+ *  
+ * A new Editor is created for editable columns. + * @author Jorg Janke + * @version $Id: VCellEditor.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public final class VCellEditor extends AbstractCellEditor + implements TableCellEditor, VetoableChangeListener, ActionListener +{ + /** + * Constructor for Grid + * @param mField + */ + public VCellEditor (GridField mField) + { + super(); + m_mField = mField; + // Click + } // VCellEditor + + /** The Field */ + private GridField m_mField = null; + /** The Table Editor */ + private VEditor m_editor = null; + /** Table */ + private JTable m_table = null; + /** ClickCount */ + private static int CLICK_TO_START = 2; + /** Logger */ + private static CLogger log = CLogger.getCLogger(VCellEditor.class); + + /** + * Create Editor + */ + private void createEditor() + { + m_editor = VEditorFactory.getEditor(m_mField, true); + m_editor.addVetoableChangeListener(this); + m_editor.addActionListener(this); + } // createEditor + + /** + * Ask the editor if it can start editing using anEvent. + * If editing can be started this method returns true. + * Previously called: MTable.isCellEditable + * @param anEvent event + * @return true if editable + */ + public boolean isCellEditable (EventObject anEvent) + { + if (!m_mField.isEditable (true)) // row data is in context + return false; + log.fine(m_mField.getHeader()); // event may be null if CellEdit + // not enough mouse clicks + if (anEvent instanceof MouseEvent + && ((MouseEvent)anEvent).getClickCount() < CLICK_TO_START) + return false; + + if (m_editor == null) + createEditor(); + return true; + } // isCellEditable + + /** + * Sets an initial value for the editor. This will cause the editor to + * stopEditing and lose any partially edited value if the editor is editing + * when this method is called. + * Returns the component that should be added to the client's Component hierarchy. + * Once installed in the client's hierarchy this component + * will then be able to draw and receive user input. + * + * @param table + * @param value + * @param isSelected + * @param row + * @param col + * @return component + */ + public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int col) + { + log.finest(m_mField.getColumnName() + ": Value=" + value + ", row=" + row + ", col=" + col); + if (row >= 0) + table.setRowSelectionInterval(row,row); // force moving to new row + if (m_editor == null) + createEditor(); + + m_table = table; + + // Set Value + m_editor.setValue(value); // Set Background/Foreground to "normal" (unselected) colors m_editor.setBackground(m_mField.isError()); @@ -132,84 +132,75 @@ public final class VCellEditor extends AbstractCellEditor // Other UI m_editor.setFont(table.getFont()); - if ( m_editor instanceof VLookup) { - VLookup lookup = (VLookup)m_editor; - if (lookup.getComponents()[0] instanceof JComboBox) { - lookup.setBorder(BorderFactory.createEmptyBorder()); - } else { - lookup.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); - } - } else { - m_editor.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); - } + m_editor.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder")); // return (Component)m_editor; } // getTableCellEditorComponent - - /** - * The editing cell should be selected or not - * @param e event - * @return true (constant) - */ - public boolean shouldSelectCell(EventObject e) - { - log.finest(m_mField.getColumnName()); - return true; - } // shouldSelectCell - - /** - * Returns the value contained in the editor - * @return value - */ - public Object getCellEditorValue() - { - log.finest(m_mField.getColumnName() + ": " + m_editor.getValue()); - return m_editor.getValue(); - } // getCellEditorValue - - /** - * VEditor Change Listener (property name is columnName). - * - indicate change (for String/Text/..)
- * When editing is complete the value is retrieved via getCellEditorValue - * @param e event - */ - public void vetoableChange(PropertyChangeEvent e) - { - if (m_table == null) - return; - log.fine(e.getPropertyName() + "=" + e.getNewValue()); - // - ((GridTable)m_table.getModel()).setChanged(true); - } // vetoableChange - - /** - * Get Actual Editor. - * Called from GridController to add ActionListener to Button - * @return VEditor - */ - public VEditor getEditor() - { - return m_editor; - } // getEditor - - /** - * Action Editor - Stop Editor - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - log.finer(m_mField.getColumnName() + ": Value=" + m_editor.getValue()); -// super.stopCellEditing(); // causes VLookup.Search Text not to work - } // actionPerformed - - /** - * Dispose - */ - public void dispose() - { - m_editor = null; - m_mField = null; - m_table = null; - } // dispose - -} // VCellEditor + + /** + * The editing cell should be selected or not + * @param e event + * @return true (constant) + */ + public boolean shouldSelectCell(EventObject e) + { + log.finest(m_mField.getColumnName()); + return true; + } // shouldSelectCell + + /** + * Returns the value contained in the editor + * @return value + */ + public Object getCellEditorValue() + { + log.finest(m_mField.getColumnName() + ": " + m_editor.getValue()); + return m_editor.getValue(); + } // getCellEditorValue + + /** + * VEditor Change Listener (property name is columnName). + * - indicate change (for String/Text/..)
+ * When editing is complete the value is retrieved via getCellEditorValue + * @param e event + */ + public void vetoableChange(PropertyChangeEvent e) + { + if (m_table == null) + return; + log.fine(e.getPropertyName() + "=" + e.getNewValue()); + // + ((GridTable)m_table.getModel()).setChanged(true); + } // vetoableChange + + /** + * Get Actual Editor. + * Called from GridController to add ActionListener to Button + * @return VEditor + */ + public VEditor getEditor() + { + return m_editor; + } // getEditor + + /** + * Action Editor - Stop Editor + * @param e event + */ + public void actionPerformed (ActionEvent e) + { + log.finer(m_mField.getColumnName() + ": Value=" + m_editor.getValue()); +// super.stopCellEditing(); // causes VLookup.Search Text not to work + } // actionPerformed + + /** + * Dispose + */ + public void dispose() + { + m_editor = null; + m_mField = null; + m_table = null; + } // dispose + +} // VCellEditor diff --git a/client/src/org/compiere/grid/ed/VCellRenderer.java b/client/src/org/compiere/grid/ed/VCellRenderer.java index 4f8b09e176..df5b2fafbf 100644 --- a/client/src/org/compiere/grid/ed/VCellRenderer.java +++ b/client/src/org/compiere/grid/ed/VCellRenderer.java @@ -1,250 +1,249 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.grid.ed; - -import java.awt.*; -import java.text.*; -import javax.swing.*; -import javax.swing.table.*; - -import org.adempiere.plaf.AdempierePLAF; -import org.compiere.apps.graph.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import java.util.logging.*; -import org.compiere.util.*; - -import sun.security.krb5.internal.*; - -/** - * Table Cell Renderer based on DisplayType - * - * @author Jorg Janke - * @version $Id: VCellRenderer.java,v 1.4 2006/07/30 00:51:27 jjanke Exp $ - */ -public final class VCellRenderer extends DefaultTableCellRenderer -{ - /** - * Constructor for Grid - * @param mField field model - */ - public VCellRenderer(GridField mField) - { - this (mField.getDisplayType()); - m_columnName = mField.getColumnName(); - this.setName(m_columnName); - m_lookup = mField.getLookup(); - m_password = mField.isEncryptedField(); - } // VCellRenderer - - /** - * Constructor for MiniGrid - * @param displayType Display Type - */ - public VCellRenderer (int displayType) - { - super(); - m_displayType = displayType; - // Number - if (DisplayType.isNumeric(m_displayType)) - { - m_numberFormat = DisplayType.getNumberFormat(m_displayType); - setHorizontalAlignment(JLabel.RIGHT); - } - // Date - else if (DisplayType.isDate(m_displayType)) - m_dateFormat = DisplayType.getDateFormat(m_displayType); - // - else if (m_displayType == DisplayType.YesNo) - { - m_check = new JCheckBox(); - m_check.setMargin(new Insets(0,0,0,0)); - m_check.setHorizontalAlignment(JLabel.CENTER); - m_check.setOpaque(true); - } - } // VCellRenderer - - private int m_displayType; - private String m_columnName = null; - private Lookup m_lookup = null; - private boolean m_password = false; - // - private SimpleDateFormat m_dateFormat = null; - private DecimalFormat m_numberFormat = null; - private JCheckBox m_check = null; - /** Logger */ - private static CLogger log = CLogger.getCLogger(VCellRenderer.class); - - /** - * Get TableCell RendererComponent. - * @param table table - * @param value value - * @param isSelected selected - * @param hasFocus focus - * @param row row - * @param col col - * @return component - */ - public Component getTableCellRendererComponent (JTable table, Object value, - boolean isSelected, boolean hasFocus, int row, int col) - { - // log.finest(m_columnName - // + ": Value=" + (value == null ? "null" : value.toString()) - // + ", Row=" + row + ", Col=" + col); - - Component c = null; - if (m_displayType == DisplayType.YesNo) - c = m_check; - else - { // returns JLabel - c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); - //c.setFont(AdempierePLAF.getFont_Field()); - c.setFont(table.getFont()); - } - - // Background & Foreground - Color bg = AdempierePLAF.getFieldBackground_Normal(); - Color fg = AdempierePLAF.getTextColor_Normal(); - // Inactive Background - boolean ro = !table.isCellEditable(row, col); - if (ro) - bg = AdempierePLAF.getFieldBackground_Inactive(); - - // Foreground - int cCode = 0; - // Grid - if (table instanceof org.compiere.grid.VTable) - cCode = ((org.compiere.grid.VTable)table).getColorCode (row); - // MiniGrid - else if (table instanceof org.compiere.minigrid.MiniTable) - cCode = ((org.compiere.minigrid.MiniTable)table).getColorCode (row); - // - if (cCode == 0) - ; // Black - else if (cCode < 0) - fg = AdempierePLAF.getTextColor_Issue(); // Red - else - fg = AdempierePLAF.getTextColor_OK(); // Blue - - // Highlighted row - if (isSelected) - { - // Windows is white on blue - bg = table.getSelectionBackground(); - fg = table.getSelectionForeground(); - if (hasFocus) - bg = GraphUtil.brighter(bg, .9); - } - - // Set Color - c.setBackground(bg); - c.setForeground(fg); - // - // log.fine( "r=" + row + " c=" + col, // + " - " + c.getClass().getName(), - // "sel=" + isSelected + ", focus=" + hasFocus + ", edit=" + table.isCellEditable(row, col)); - // Log.trace(7, "BG=" + (bg.equals(Color.white) ? "white" : bg.toString()), "FG=" + (fg.equals(Color.black) ? "black" : fg.toString())); - - // Format it - setValue(value); - return c; - } // getTableCellRendererComponent - - - /** - * Format Display Value. - * Default is JLabel - * @param value (key)value - */ - protected void setValue (Object value) - { - String retValue = null; - try - { - // Checkbox - if (m_displayType == DisplayType.YesNo) - { - if (value instanceof Boolean) - m_check.setSelected(((Boolean)value).booleanValue()); - else - m_check.setSelected("Y".equals(value)); - return; - } - else if (value == null) - ; - // Number - else if (DisplayType.isNumeric(m_displayType)) - retValue = m_numberFormat.format(value); - // Date - else if (DisplayType.isDate(m_displayType)) - retValue = m_dateFormat.format(value); - // Row ID - else if (m_displayType == DisplayType.RowID) - retValue = ""; - // Lookup - else if (m_lookup != null && (DisplayType.isLookup(m_displayType) - || m_displayType == DisplayType.Location - || m_displayType == DisplayType.Account - || m_displayType == DisplayType.Locator - || m_displayType == DisplayType.PAttribute )) - retValue = m_lookup.getDisplay(value); - // Button - else if (m_displayType == DisplayType.Button) - { - if ("Record_ID".equals(m_columnName)) - retValue = "#" + value + "#"; - else - retValue = null; - } - // Password (fixed string) - else if (m_password) - retValue = "**********"; - // other (String ...) - else - { - super.setValue(value); - return; - } - } - catch (Exception e) - { - log.log(Level.SEVERE, "(" + value + ") " + value.getClass().getName() , e); - retValue = value.toString(); - } - super.setValue(retValue); - } // setValue - - /** - * to String - * @return String representation - */ - public String toString() - { - return "VCellRenderer[" + m_columnName - + ",DisplayType=" + m_displayType + " - " + m_lookup + "]"; - } // toString - - /** - * Dispose - */ - public void dispose() - { - if (m_lookup != null) - m_lookup.dispose(); - m_lookup = null; - } // dispose - -} // VCellRenderer +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.grid.ed; + +import java.awt.*; +import java.text.*; +import javax.swing.*; +import javax.swing.table.*; + +import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.graph.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import java.util.logging.*; +import org.compiere.util.*; + +import sun.security.krb5.internal.*; + +/** + * Table Cell Renderer based on DisplayType + * + * @author Jorg Janke + * @version $Id: VCellRenderer.java,v 1.4 2006/07/30 00:51:27 jjanke Exp $ + */ +public final class VCellRenderer extends DefaultTableCellRenderer +{ + /** + * Constructor for Grid + * @param mField field model + */ + public VCellRenderer(GridField mField) + { + this (mField.getDisplayType()); + m_columnName = mField.getColumnName(); + this.setName(m_columnName); + m_lookup = mField.getLookup(); + m_password = mField.isEncryptedField(); + } // VCellRenderer + + /** + * Constructor for MiniGrid + * @param displayType Display Type + */ + public VCellRenderer (int displayType) + { + super(); + m_displayType = displayType; + // Number + if (DisplayType.isNumeric(m_displayType)) + { + m_numberFormat = DisplayType.getNumberFormat(m_displayType); + setHorizontalAlignment(JLabel.RIGHT); + } + // Date + else if (DisplayType.isDate(m_displayType)) + m_dateFormat = DisplayType.getDateFormat(m_displayType); + // + else if (m_displayType == DisplayType.YesNo) + { + m_check = new JCheckBox(); + m_check.setMargin(new Insets(0,0,0,0)); + m_check.setHorizontalAlignment(JLabel.CENTER); + m_check.setOpaque(true); + } + } // VCellRenderer + + private int m_displayType; + private String m_columnName = null; + private Lookup m_lookup = null; + private boolean m_password = false; + // + private SimpleDateFormat m_dateFormat = null; + private DecimalFormat m_numberFormat = null; + private JCheckBox m_check = null; + /** Logger */ + private static CLogger log = CLogger.getCLogger(VCellRenderer.class); + + /** + * Get TableCell RendererComponent. + * @param table table + * @param value value + * @param isSelected selected + * @param hasFocus focus + * @param row row + * @param col col + * @return component + */ + public Component getTableCellRendererComponent (JTable table, Object value, + boolean isSelected, boolean hasFocus, int row, int col) + { + // log.finest(m_columnName + // + ": Value=" + (value == null ? "null" : value.toString()) + // + ", Row=" + row + ", Col=" + col); + + Component c = null; + if (m_displayType == DisplayType.YesNo) + c = m_check; + else + { // returns JLabel + c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); + c.setFont(AdempierePLAF.getFont_Field()); + } + + // Background & Foreground + Color bg = AdempierePLAF.getFieldBackground_Normal(); + Color fg = AdempierePLAF.getTextColor_Normal(); + // Inactive Background + boolean ro = !table.isCellEditable(row, col); + if (ro) + bg = AdempierePLAF.getFieldBackground_Inactive(); + + // Foreground + int cCode = 0; + // Grid + if (table instanceof org.compiere.grid.VTable) + cCode = ((org.compiere.grid.VTable)table).getColorCode (row); + // MiniGrid + else if (table instanceof org.compiere.minigrid.MiniTable) + cCode = ((org.compiere.minigrid.MiniTable)table).getColorCode (row); + // + if (cCode == 0) + ; // Black + else if (cCode < 0) + fg = AdempierePLAF.getTextColor_Issue(); // Red + else + fg = AdempierePLAF.getTextColor_OK(); // Blue + + // Highlighted row + if (isSelected) + { + // Windows is white on blue + bg = table.getSelectionBackground(); + fg = table.getSelectionForeground(); + if (hasFocus) + bg = GraphUtil.brighter(bg, .9); + } + + // Set Color + c.setBackground(bg); + c.setForeground(fg); + // + // log.fine( "r=" + row + " c=" + col, // + " - " + c.getClass().getName(), + // "sel=" + isSelected + ", focus=" + hasFocus + ", edit=" + table.isCellEditable(row, col)); + // Log.trace(7, "BG=" + (bg.equals(Color.white) ? "white" : bg.toString()), "FG=" + (fg.equals(Color.black) ? "black" : fg.toString())); + + // Format it + setValue(value); + return c; + } // getTableCellRendererComponent + + + /** + * Format Display Value. + * Default is JLabel + * @param value (key)value + */ + protected void setValue (Object value) + { + String retValue = null; + try + { + // Checkbox + if (m_displayType == DisplayType.YesNo) + { + if (value instanceof Boolean) + m_check.setSelected(((Boolean)value).booleanValue()); + else + m_check.setSelected("Y".equals(value)); + return; + } + else if (value == null) + ; + // Number + else if (DisplayType.isNumeric(m_displayType)) + retValue = m_numberFormat.format(value); + // Date + else if (DisplayType.isDate(m_displayType)) + retValue = m_dateFormat.format(value); + // Row ID + else if (m_displayType == DisplayType.RowID) + retValue = ""; + // Lookup + else if (m_lookup != null && (DisplayType.isLookup(m_displayType) + || m_displayType == DisplayType.Location + || m_displayType == DisplayType.Account + || m_displayType == DisplayType.Locator + || m_displayType == DisplayType.PAttribute )) + retValue = m_lookup.getDisplay(value); + // Button + else if (m_displayType == DisplayType.Button) + { + if ("Record_ID".equals(m_columnName)) + retValue = "#" + value + "#"; + else + retValue = null; + } + // Password (fixed string) + else if (m_password) + retValue = "**********"; + // other (String ...) + else + { + super.setValue(value); + return; + } + } + catch (Exception e) + { + log.log(Level.SEVERE, "(" + value + ") " + value.getClass().getName() , e); + retValue = value.toString(); + } + super.setValue(retValue); + } // setValue + + /** + * to String + * @return String representation + */ + public String toString() + { + return "VCellRenderer[" + m_columnName + + ",DisplayType=" + m_displayType + " - " + m_lookup + "]"; + } // toString + + /** + * Dispose + */ + public void dispose() + { + if (m_lookup != null) + m_lookup.dispose(); + m_lookup = null; + } // dispose + +} // VCellRenderer diff --git a/client/src/org/compiere/grid/ed/VColor.java b/client/src/org/compiere/grid/ed/VColor.java index bdceb94894..72d02ef26b 100644 --- a/client/src/org/compiere/grid/ed/VColor.java +++ b/client/src/org/compiere/grid/ed/VColor.java @@ -1,334 +1,334 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.grid.ed; - -import java.awt.*; -import java.awt.event.*; -import java.beans.*; -import java.math.*; -import java.sql.*; -import java.util.logging.*; -import javax.swing.*; - -import org.adempiere.plaf.AdempierePLAF; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Color Editor. - * The editor stores/gets the attributes from the tab. - * - * @author Jorg Janke - * @version $Id: VColor.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ - */ -public class VColor extends CButton - implements VEditor, ActionListener -{ - /** - * Constructor - * @param mTab Tab - * @param mandatory mandatory - * @param isReadOnly read only - */ - public VColor (GridTab mTab, boolean mandatory, boolean isReadOnly) - { - m_mTab = mTab; - setMandatory(mandatory); - setReadWrite(!isReadOnly); - addActionListener(this); - } // VColor - - /** - * Dispose - */ - public void dispose() - { - m_mTab = null; - } // dispose - - private GridTab m_mTab; - private boolean m_mandatory; -// private int m_AD_Color_ID = 0; - private CompiereColor m_cc = null; - private Object m_value; - /** Logger */ - private static CLogger log = CLogger.getCLogger(VColor.class); - - /** - * Set Mandatory - * @param mandatory mandatory - */ - public void setMandatory (boolean mandatory) - { - m_mandatory = mandatory; - } // setMandatory - - /** - * Is Mandatory - * @return true if Mandatory - */ - public boolean isMandatory() - { - return m_mandatory; - } // isMandatory - - /** - * Set Background (nop) - * @param error error - */ - public void setBackground (boolean error) - { - } // setBackground - - /** - * Set Value - * @param value value - */ - public void setValue (Object value) - { - log.config("Value=" + value); - m_value = value; - m_cc = getAdempiereColor(); - - // Display It - setText(getDisplay()); - if (m_cc != null) - setBackgroundColor(m_cc); - else - { - setOpaque(false); - putClientProperty(CompiereLookAndFeel.BACKGROUND, null); - } - repaint(); - } // setValue - - /** - * GetValue - * @return value - */ - public Object getValue() - { - return m_value; - } // getValue - - /** - * Get Displayed Value - * @return String representation - */ - public String getDisplay() - { - if (m_cc == null) - return "-/-"; - return " "; - } // getDisplay - - /** - * Property Change Listener - * @param evt event - */ - public void propertyChange (PropertyChangeEvent evt) - { - // log.config( "VColor.propertyChange", evt); - if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) - { - setValue(evt.getNewValue()); - setBackground(false); - } - } // propertyChange - - /** - * Set Field/WindowNo for ValuePreference - * @param mField field - */ - public void setField (GridField mField) - { - mField.setValueNoFire(false); // fire every time - } // setField - - /*************************************************************************/ - - /** - * Load Color from Tab - * @return true if loaded - * @see org.compiere.model.MColor#getAdempiereColor - */ - private CompiereColor getAdempiereColor() - { - Integer AD_Color_ID = (Integer)m_mTab.getValue("AD_Color_ID"); - log.fine("AD_Color_ID=" + AD_Color_ID); - CompiereColor cc = null; - - // Color Type - String ColorType = (String)m_mTab.getValue("ColorType"); - if (ColorType == null) - { - log.fine("No ColorType"); - return null; - } - // - if (ColorType.equals(CompiereColor.TYPE_FLAT)) - { - cc = new CompiereColor(getColor(true), true); - } - else if (ColorType.equals(CompiereColor.TYPE_GRADIENT)) - { - Integer RepeatDistance = (Integer)m_mTab.getValue("RepeatDistance"); - String StartPoint = (String)m_mTab.getValue("StartPoint"); - int repeatDistance = RepeatDistance == null ? 0 : RepeatDistance.intValue(); - int startPoint = StartPoint == null ? 0 : Integer.parseInt(StartPoint); - cc = new CompiereColor(getColor(true), getColor(false), startPoint, repeatDistance); - } - else if (ColorType.equals(CompiereColor.TYPE_LINES)) - { - BigDecimal LineWidth = (BigDecimal)m_mTab.getValue("LineWidth"); - BigDecimal LineDistance = (BigDecimal)m_mTab.getValue("LineDistance"); - int lineWidth = LineWidth == null ? 0 : LineWidth.intValue(); - int lineDistance = LineDistance == null ? 0 : LineDistance.intValue(); - cc = new CompiereColor(getColor(false), getColor(true), lineWidth, lineDistance); - } - else if (ColorType.equals(CompiereColor.TYPE_TEXTURE)) - { - Integer AD_Image_ID = (Integer)m_mTab.getValue("AD_Image_ID"); - String url = getURL(AD_Image_ID); - if (url == null) - return null; - BigDecimal ImageAlpha = (BigDecimal)m_mTab.getValue("ImageAlpha"); - float compositeAlpha = ImageAlpha == null ? 0.7f : ImageAlpha.floatValue(); - cc = new CompiereColor(url, getColor(true), compositeAlpha); - } - else - return null; - - log.fine("AdempiereColor=" + cc); - return cc; - } // getAdempiereColor - - /** - * Get Color from Tab - * @param primary true if primary false if secondary - * @return Color - */ - private Color getColor (boolean primary) - { - String add = primary ? "" : "_1"; - // is either BD or Int - Integer Red = (Integer)m_mTab.getValue("Red" + add); - Integer Green = (Integer)m_mTab.getValue("Green" + add); - Integer Blue = (Integer)m_mTab.getValue("Blue" + add); - // - int red = Red == null ? 0 : Red.intValue(); - int green = Green == null ? 0 : Green.intValue(); - int blue = Blue == null ? 0 : Blue.intValue(); - // - return new Color (red, green, blue); - } // getColor - - /** - * Get URL from Image - * @param AD_Image_ID image - * @return URL as String or null - */ - private String getURL (Integer AD_Image_ID) - { - if (AD_Image_ID == null || AD_Image_ID.intValue() == 0) - return null; - // - String retValue = null; - String sql = "SELECT ImageURL FROM AD_Image WHERE AD_Image_ID=?"; - try - { - PreparedStatement pstmt = DB.prepareStatement(sql, null); - pstmt.setInt (1, AD_Image_ID.intValue()); - ResultSet rs = pstmt.executeQuery(); - if (rs.next()) - { - retValue = rs.getString(1); - } - rs.close(); - pstmt.close(); - } - catch (SQLException e) - { - log.log(Level.SEVERE, sql, e); - } - return retValue; - } // getURL - - /*************************************************************************/ - - /** - * Action Listener - Open Dialog - * @param e event - */ - public void actionPerformed (ActionEvent e) - { - // Show Dialog - CompiereColor cc = ColorEditor.showDialog((JFrame)Env.getParent(this), m_cc); - if (cc == null) - { - log.info( "VColor.actionPerformed - no color"); - return; - } - setBackgroundColor(cc); // set Button - repaint(); - - // Update Values - m_mTab.setValue("ColorType", cc.getType()); - if (cc.isFlat()) - { - setColor (cc.getFlatColor(), true); - } - else if (cc.isGradient()) - { - setColor (cc.getGradientUpperColor(), true); - setColor (cc.getGradientLowerColor(), false); - m_mTab.setValue("RepeatDistance", new BigDecimal(cc.getGradientRepeatDistance())); - m_mTab.setValue("StartPoint", String.valueOf(cc.getGradientStartPoint())); - } - else if (cc.isLine()) - { - setColor (cc.getLineBackColor(), true); - setColor (cc.getLineColor(), false); - m_mTab.getValue("LineWidth"); - m_mTab.getValue("LineDistance"); - } - else if (cc.isTexture()) - { - setColor (cc.getTextureTaintColor(), true); - // URL url = cc.getTextureURL(); - // m_mTab.setValue("AD_Image_ID"); - m_mTab.setValue("ImageAlpha", new BigDecimal(cc.getTextureCompositeAlpha())); - } - m_cc = cc; - } // actionPerformed - - /** - * Set Color in Tab - * @param c Color - * @param primary true if primary false if secondary - */ - private void setColor (Color c, boolean primary) - { - String add = primary ? "" : "_1"; - m_mTab.setValue("Red" + add, new BigDecimal(c.getRed())); - m_mTab.setValue("Green" + add, new BigDecimal(c.getGreen())); - m_mTab.setValue("Blue" + add, new BigDecimal(c.getBlue())); - } // setColor - -} // VColor +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.grid.ed; + +import java.awt.*; +import java.awt.event.*; +import java.beans.*; +import java.math.*; +import java.sql.*; +import java.util.logging.*; +import javax.swing.*; + +import org.adempiere.plaf.AdempierePLAF; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Color Editor. + * The editor stores/gets the attributes from the tab. + * + * @author Jorg Janke + * @version $Id: VColor.java,v 1.2 2006/07/30 00:51:28 jjanke Exp $ + */ +public class VColor extends CButton + implements VEditor, ActionListener +{ + /** + * Constructor + * @param mTab Tab + * @param mandatory mandatory + * @param isReadOnly read only + */ + public VColor (GridTab mTab, boolean mandatory, boolean isReadOnly) + { + m_mTab = mTab; + setMandatory(mandatory); + setReadWrite(!isReadOnly); + addActionListener(this); + } // VColor + + /** + * Dispose + */ + public void dispose() + { + m_mTab = null; + } // dispose + + private GridTab m_mTab; + private boolean m_mandatory; +// private int m_AD_Color_ID = 0; + private CompiereColor m_cc = null; + private Object m_value; + /** Logger */ + private static CLogger log = CLogger.getCLogger(VColor.class); + + /** + * Set Mandatory + * @param mandatory mandatory + */ + public void setMandatory (boolean mandatory) + { + m_mandatory = mandatory; + } // setMandatory + + /** + * Is Mandatory + * @return true if Mandatory + */ + public boolean isMandatory() + { + return m_mandatory; + } // isMandatory + + /** + * Set Background (nop) + * @param error error + */ + public void setBackground (boolean error) + { + } // setBackground + + /** + * Set Value + * @param value value + */ + public void setValue (Object value) + { + log.config("Value=" + value); + m_value = value; + m_cc = getAdempiereColor(); + + // Display It + setText(getDisplay()); + if (m_cc != null) + setBackgroundColor(m_cc); + else + { + setOpaque(false); + putClientProperty(AdempierePLAF.BACKGROUND, null); + } + repaint(); + } // setValue + + /** + * GetValue + * @return value + */ + public Object getValue() + { + return m_value; + } // getValue + + /** + * Get Displayed Value + * @return String representation + */ + public String getDisplay() + { + if (m_cc == null) + return "-/-"; + return " "; + } // getDisplay + + /** + * Property Change Listener + * @param evt event + */ + public void propertyChange (PropertyChangeEvent evt) + { + // log.config( "VColor.propertyChange", evt); + if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) + { + setValue(evt.getNewValue()); + setBackground(false); + } + } // propertyChange + + /** + * Set Field/WindowNo for ValuePreference + * @param mField field + */ + public void setField (GridField mField) + { + mField.setValueNoFire(false); // fire every time + } // setField + + /*************************************************************************/ + + /** + * Load Color from Tab + * @return true if loaded + * @see org.compiere.model.MColor#getAdempiereColor + */ + private CompiereColor getAdempiereColor() + { + Integer AD_Color_ID = (Integer)m_mTab.getValue("AD_Color_ID"); + log.fine("AD_Color_ID=" + AD_Color_ID); + CompiereColor cc = null; + + // Color Type + String ColorType = (String)m_mTab.getValue("ColorType"); + if (ColorType == null) + { + log.fine("No ColorType"); + return null; + } + // + if (ColorType.equals(CompiereColor.TYPE_FLAT)) + { + cc = new CompiereColor(getColor(true), true); + } + else if (ColorType.equals(CompiereColor.TYPE_GRADIENT)) + { + Integer RepeatDistance = (Integer)m_mTab.getValue("RepeatDistance"); + String StartPoint = (String)m_mTab.getValue("StartPoint"); + int repeatDistance = RepeatDistance == null ? 0 : RepeatDistance.intValue(); + int startPoint = StartPoint == null ? 0 : Integer.parseInt(StartPoint); + cc = new CompiereColor(getColor(true), getColor(false), startPoint, repeatDistance); + } + else if (ColorType.equals(CompiereColor.TYPE_LINES)) + { + BigDecimal LineWidth = (BigDecimal)m_mTab.getValue("LineWidth"); + BigDecimal LineDistance = (BigDecimal)m_mTab.getValue("LineDistance"); + int lineWidth = LineWidth == null ? 0 : LineWidth.intValue(); + int lineDistance = LineDistance == null ? 0 : LineDistance.intValue(); + cc = new CompiereColor(getColor(false), getColor(true), lineWidth, lineDistance); + } + else if (ColorType.equals(CompiereColor.TYPE_TEXTURE)) + { + Integer AD_Image_ID = (Integer)m_mTab.getValue("AD_Image_ID"); + String url = getURL(AD_Image_ID); + if (url == null) + return null; + BigDecimal ImageAlpha = (BigDecimal)m_mTab.getValue("ImageAlpha"); + float compositeAlpha = ImageAlpha == null ? 0.7f : ImageAlpha.floatValue(); + cc = new CompiereColor(url, getColor(true), compositeAlpha); + } + else + return null; + + log.fine("AdempiereColor=" + cc); + return cc; + } // getAdempiereColor + + /** + * Get Color from Tab + * @param primary true if primary false if secondary + * @return Color + */ + private Color getColor (boolean primary) + { + String add = primary ? "" : "_1"; + // is either BD or Int + Integer Red = (Integer)m_mTab.getValue("Red" + add); + Integer Green = (Integer)m_mTab.getValue("Green" + add); + Integer Blue = (Integer)m_mTab.getValue("Blue" + add); + // + int red = Red == null ? 0 : Red.intValue(); + int green = Green == null ? 0 : Green.intValue(); + int blue = Blue == null ? 0 : Blue.intValue(); + // + return new Color (red, green, blue); + } // getColor + + /** + * Get URL from Image + * @param AD_Image_ID image + * @return URL as String or null + */ + private String getURL (Integer AD_Image_ID) + { + if (AD_Image_ID == null || AD_Image_ID.intValue() == 0) + return null; + // + String retValue = null; + String sql = "SELECT ImageURL FROM AD_Image WHERE AD_Image_ID=?"; + try + { + PreparedStatement pstmt = DB.prepareStatement(sql, null); + pstmt.setInt (1, AD_Image_ID.intValue()); + ResultSet rs = pstmt.executeQuery(); + if (rs.next()) + { + retValue = rs.getString(1); + } + rs.close(); + pstmt.close(); + } + catch (SQLException e) + { + log.log(Level.SEVERE, sql, e); + } + return retValue; + } // getURL + + /*************************************************************************/ + + /** + * Action Listener - Open Dialog + * @param e event + */ + public void actionPerformed (ActionEvent e) + { + // Show Dialog + CompiereColor cc = ColorEditor.showDialog((JFrame)Env.getParent(this), m_cc); + if (cc == null) + { + log.info( "VColor.actionPerformed - no color"); + return; + } + setBackgroundColor(cc); // set Button + repaint(); + + // Update Values + m_mTab.setValue("ColorType", cc.getType()); + if (cc.isFlat()) + { + setColor (cc.getFlatColor(), true); + } + else if (cc.isGradient()) + { + setColor (cc.getGradientUpperColor(), true); + setColor (cc.getGradientLowerColor(), false); + m_mTab.setValue("RepeatDistance", new BigDecimal(cc.getGradientRepeatDistance())); + m_mTab.setValue("StartPoint", String.valueOf(cc.getGradientStartPoint())); + } + else if (cc.isLine()) + { + setColor (cc.getLineBackColor(), true); + setColor (cc.getLineColor(), false); + m_mTab.getValue("LineWidth"); + m_mTab.getValue("LineDistance"); + } + else if (cc.isTexture()) + { + setColor (cc.getTextureTaintColor(), true); + // URL url = cc.getTextureURL(); + // m_mTab.setValue("AD_Image_ID"); + m_mTab.setValue("ImageAlpha", new BigDecimal(cc.getTextureCompositeAlpha())); + } + m_cc = cc; + } // actionPerformed + + /** + * Set Color in Tab + * @param c Color + * @param primary true if primary false if secondary + */ + private void setColor (Color c, boolean primary) + { + String add = primary ? "" : "_1"; + m_mTab.setValue("Red" + add, new BigDecimal(c.getRed())); + m_mTab.setValue("Green" + add, new BigDecimal(c.getGreen())); + m_mTab.setValue("Blue" + add, new BigDecimal(c.getBlue())); + } // setColor + +} // VColor diff --git a/client/src/org/compiere/grid/ed/VHeaderRenderer.java b/client/src/org/compiere/grid/ed/VHeaderRenderer.java index 37fa918c2e..0431279dea 100644 --- a/client/src/org/compiere/grid/ed/VHeaderRenderer.java +++ b/client/src/org/compiere/grid/ed/VHeaderRenderer.java @@ -30,13 +30,6 @@ import org.compiere.util.*; */ public final class VHeaderRenderer implements TableCellRenderer { - public VHeaderRenderer() - { - m_button = new CButton(); - m_button.setMargin(new Insets(0,0,0,0)); - m_button.putClientProperty("Plastic.is3D", Boolean.FALSE); - } - /** * Constructor * @param displayType @@ -46,17 +39,16 @@ public final class VHeaderRenderer implements TableCellRenderer super(); // Alignment if (DisplayType.isNumeric(displayType)) - m_alignment = JLabel.RIGHT; + m_button.setHorizontalAlignment(JLabel.RIGHT); else if (displayType == DisplayType.YesNo) - m_alignment = JLabel.CENTER; + m_button.setHorizontalAlignment(JLabel.CENTER); else - m_alignment = JLabel.LEFT; + m_button.setHorizontalAlignment(JLabel.LEFT); + m_button.setMargin(new Insets(0,0,0,0)); } // VHeaderRenderer // for 3D effect in Windows - private CButton m_button; - - private int m_alignment; + private CButton m_button = new CButton(); /** * Get TableCell RendererComponent @@ -73,25 +65,6 @@ public final class VHeaderRenderer implements TableCellRenderer { // Log.trace(this,10, "VHeaderRenderer.getTableCellRendererComponent", value==null ? "null" : value.toString()); // indicator for invisible column - - TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer(); - Component headerComponent = headerRenderer == null ? null : - headerRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - if (headerComponent != null && headerComponent instanceof JComponent) { - if (headerComponent instanceof JLabel ) { - JLabel label = (JLabel)headerComponent; - label.setHorizontalAlignment(m_alignment); - if (value == null) - label.setPreferredSize(new Dimension(0,0)); - else - label.setText(value.toString()); - return label; - } - m_button.setBorder(((JComponent)headerComponent).getBorder()); - } else { - m_button.setBorder(UIManager.getBorder("TableHeader.cellBorder")); - } - if (value == null) { m_button.setPreferredSize(new Dimension(0,0)); diff --git a/client/src/org/compiere/grid/ed/VLocator.java b/client/src/org/compiere/grid/ed/VLocator.java index 09f13242f7..13d6df3a1e 100644 --- a/client/src/org/compiere/grid/ed/VLocator.java +++ b/client/src/org/compiere/grid/ed/VLocator.java @@ -1,542 +1,541 @@ -/****************************************************************************** - * 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 * - *****************************************************************************/ -package org.compiere.grid.ed; - -import java.awt.*; -import java.awt.event.*; -import java.beans.*; -import java.sql.*; -import java.util.logging.*; -import javax.swing.*; - -import org.adempiere.plaf.AdempierePLAF; -import org.compiere.apps.*; -import org.compiere.model.*; -import org.compiere.plaf.*; -import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Warehouse Locator Control - * - * @author Jorg Janke - * @version $Id: VLocator.java,v 1.5 2006/07/30 00:51:27 jjanke Exp $ - */ -public class VLocator extends JComponent - implements VEditor, ActionListener -{ - /** - * IDE Constructor - */ - public VLocator () - { - this("M_Locator_ID", false, false, true, null, 0); - } // VLocator - - /** - * Constructor - * - * @param columnName ColumnName - * @param mandatory mandatory - * @param isReadOnly read only - * @param isUpdateable updateable - * @param mLocator locator (lookup) model - * @param WindowNo window no - */ - public VLocator(String columnName, boolean mandatory, boolean isReadOnly, boolean isUpdateable, - MLocatorLookup mLocator, int WindowNo) - { - super(); - super.setName(columnName); - m_columnName = columnName; - m_mLocator = mLocator; - m_WindowNo = WindowNo; - // - LookAndFeel.installBorder(this, "TextField.border"); - this.setLayout(new BorderLayout()); - // Size - this.setPreferredSize(m_text.getPreferredSize()); // causes r/o to be the same length - int height = m_text.getPreferredSize().height; - - // *** Button & Text *** - m_text.setBorder(null); - m_text.setEditable(true); - m_text.setFocusable(true); - m_text.addMouseListener(new VLocator_mouseAdapter(this)); // popup - m_text.setFont(AdempierePLAF.getFont_Field()); - m_text.setForeground(AdempierePLAF.getTextColor_Normal()); - m_text.addActionListener(this); - this.add(m_text, BorderLayout.CENTER); - - m_button.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Locator10.gif"))); - m_button.setMargin(new Insets(0, 0, 0, 0)); - m_button.setPreferredSize(new Dimension(height, height)); - m_button.addActionListener(this); - this.add(m_button, BorderLayout.EAST); - - // Prefereed Size - this.setPreferredSize(this.getPreferredSize()); // causes r/o to be the same length - - // ReadWrite - if (isReadOnly || !isUpdateable) - setReadWrite (false); - else - setReadWrite (true); - setMandatory (mandatory); - // - mZoom = new CMenuItem(Msg.getMsg(Env.getCtx(), "Zoom"), Env.getImageIcon("Zoom16.gif")); - mZoom.addActionListener(this); - popupMenu.add(mZoom); - mRefresh = new CMenuItem(Msg.getMsg(Env.getCtx(), "Refresh"), Env.getImageIcon("Refresh16.gif")); - mRefresh.addActionListener(this); - popupMenu.add(mRefresh); - } // VLocator - - /** - * Dispose - */ - public void dispose() - { - m_text = null; - m_button = null; - m_mLocator = null; - } // dispose - - private JTextField m_text = new JTextField (VLookup.DISPLAY_LENGTH); - private CButton m_button = new CButton(); - private MLocatorLookup m_mLocator; - private Object m_value; - // - private String m_columnName; - private int m_WindowNo; - /** Logger */ - private static CLogger log = CLogger.getCLogger(VLocator.class); - // Popup - JPopupMenu popupMenu = new JPopupMenu(); - private CMenuItem mZoom; - private CMenuItem mRefresh; - - /** - * Enable/disable - * @param value r/w - */ - public void setReadWrite (boolean value) - { - m_button.setReadWrite(value); - if (m_button.isVisible() != value) - m_button.setVisible(value); - setBackground(false); - } // setReadWrite - - /** - * IsReadWrite - * @return true if ReadWrite - */ - public boolean isReadWrite() - { - return m_button.isReadWrite(); - } // isReadWrite - - /** - * Set Mandatory (and back bolor) - * @param mandatory true if mandatory - */ - public void setMandatory (boolean mandatory) - { - m_button.setMandatory(mandatory); - setBackground(false); - } // setMandatory - - /** - * Is it mandatory - * @return true if mandatory - */ - public boolean isMandatory() - { - return m_button.isMandatory(); - } // isMandatory - - /** - * Set Background - * @param color color - */ - public void setBackground (Color color) - { - if (!color.equals(m_text.getBackground())) - m_text.setBackground(color); - } // setBackground - - /** - * Set Background based on editable / mandatory / error - * @param error if true, set background to error color, otherwise mandatory/editable - */ - public void setBackground (boolean error) - { - if (error) - setBackground(AdempierePLAF.getFieldBackground_Error()); - else if (!isReadWrite()) - setBackground(AdempierePLAF.getFieldBackground_Inactive()); - else if (isMandatory()) - setBackground(AdempierePLAF.getFieldBackground_Mandatory()); - else - setBackground(AdempierePLAF.getFieldBackground_Normal()); - } // setBackground - - /** - * Set Foreground - * @param fg color - */ - public void setForeground(Color fg) - { - m_text.setForeground(fg); - } // setForeground - - /** - * Request Focus - */ - public void requestFocus () - { - m_text.requestFocus (); - } // requestFocus - - /** - * Set Editor to value - * @param value Integer - */ - public void setValue(Object value) - { - setValue (value, false); - } // setValue - - /** - * 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 = value; - m_text.setText(m_mLocator.getDisplay(value)); // loads value - - // Data Binding - try - { - fireVetoableChange(m_columnName, null, value); - } - catch (PropertyVetoException pve) - { - } - } // setValue - - - /** - * Property Change Listener - * @param evt PropertyChangeEvent - */ - public void propertyChange (PropertyChangeEvent evt) - { - if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) - setValue(evt.getNewValue()); - } // propertyChange - - /** - * 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 ((Integer)m_value).intValue(); - return 0; - } // getM_Locator_ID - - /** - * Return Display Value - * @return display value - */ - public String getDisplay() - { - return m_text.getText(); - } // getDisplay - - /** - * ActionListener - * @param e ActionEvent - */ - public void actionPerformed(ActionEvent e) - { - // Refresh - if (e.getSource() == mRefresh) - { - m_mLocator.refresh(); - return; - } - - // Zoom to M_Warehouse - if (e.getSource() == mZoom) - { - actionZoom(); - return; - } - - // 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 (e.getSource() == m_text - && actionText(only_Warehouse_ID, only_Product_ID)) - return; - - // Button - Start Dialog - int M_Locator_ID = 0; - if (m_value instanceof Integer) - M_Locator_ID = ((Integer)m_value).intValue(); - // - m_mLocator.setOnly_Warehouse_ID(only_Warehouse_ID); - m_mLocator.setOnly_Product_ID(getOnly_Product_ID()); - VLocatorDialog ld = new VLocatorDialog(Env.getFrame(this), - Msg.translate(Env.getCtx(), m_columnName), - m_mLocator, M_Locator_ID, isMandatory(), only_Warehouse_ID); - // display - ld.setVisible(true); - m_mLocator.setOnly_Warehouse_ID(0); - - // redisplay - if (!ld.isChanged()) - return; - setValue (ld.getValue(), true); - } // actionPerformed - - /** - * 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 = m_text.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 s.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 - - /** - * Action Listener Interface - * @param listener listener - */ - public void addActionListener(ActionListener listener) - { - m_text.addActionListener(listener); - } // addActionListener - - - /** - * Action - Zoom - */ - private void actionZoom() - { - int AD_Window_ID = 139; // hardcoded - log.info(""); - // - setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - AWindow frame = new AWindow(); - if (!frame.initWindow(AD_Window_ID, null)) - return; - AEnv.addToWindowManager(frame); - AEnv.showCenterScreen(frame); - frame = null; - setCursor(Cursor.getDefaultCursor()); - } // actionZoom - - /** - * 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 - -} // VLocator - -/*****************************************************************************/ - -/** - * Mouse Listener for Popup Menu - */ -final class VLocator_mouseAdapter extends java.awt.event.MouseAdapter -{ - /** - * Constructor - * @param adaptee VLocator - */ - VLocator_mouseAdapter(VLocator adaptee) - { - m_adaptee = adaptee; - } // VLookup_mouseAdapter - - /** Adaptee */ - private VLocator m_adaptee; - - /** - * Mouse Listener - * @param e MouseEvent - */ - public void mouseClicked(MouseEvent e) - { - // popup menu - if (SwingUtilities.isRightMouseButton(e)) - m_adaptee.popupMenu.show((Component)e.getSource(), e.getX(), e.getY()); - } // mouse Clicked - -} // VLocator_mouseAdapter +/****************************************************************************** + * 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 * + *****************************************************************************/ +package org.compiere.grid.ed; + +import java.awt.*; +import java.awt.event.*; +import java.beans.*; +import java.sql.*; +import java.util.logging.*; +import javax.swing.*; + +import org.adempiere.plaf.AdempierePLAF; +import org.compiere.apps.*; +import org.compiere.model.*; +import org.compiere.plaf.*; +import org.compiere.swing.*; +import org.compiere.util.*; + +/** + * Warehouse Locator Control + * + * @author Jorg Janke + * @version $Id: VLocator.java,v 1.5 2006/07/30 00:51:27 jjanke Exp $ + */ +public class VLocator extends JComponent + implements VEditor, ActionListener +{ + /** + * IDE Constructor + */ + public VLocator () + { + this("M_Locator_ID", false, false, true, null, 0); + } // VLocator + + /** + * Constructor + * + * @param columnName ColumnName + * @param mandatory mandatory + * @param isReadOnly read only + * @param isUpdateable updateable + * @param mLocator locator (lookup) model + * @param WindowNo window no + */ + public VLocator(String columnName, boolean mandatory, boolean isReadOnly, boolean isUpdateable, + MLocatorLookup mLocator, int WindowNo) + { + super(); + super.setName(columnName); + m_columnName = columnName; + m_mLocator = mLocator; + m_WindowNo = WindowNo; + // + LookAndFeel.installBorder(this, "TextField.border"); + this.setLayout(new BorderLayout()); + // Size + this.setPreferredSize(m_text.getPreferredSize()); // causes r/o to be the same length + int height = m_text.getPreferredSize().height; + + // *** Button & Text *** + m_text.setBorder(null); + m_text.setEditable(true); + m_text.setFocusable(true); + m_text.addMouseListener(new VLocator_mouseAdapter(this)); // popup + m_text.setFont(AdempierePLAF.getFont_Field()); + m_text.setForeground(AdempierePLAF.getTextColor_Normal()); + m_text.addActionListener(this); + this.add(m_text, BorderLayout.CENTER); + + m_button.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Locator10.gif"))); + m_button.setMargin(new Insets(0, 0, 0, 0)); + m_button.setPreferredSize(new Dimension(height, height)); + m_button.addActionListener(this); + this.add(m_button, BorderLayout.EAST); + + // Prefereed Size + this.setPreferredSize(this.getPreferredSize()); // causes r/o to be the same length + + // ReadWrite + if (isReadOnly || !isUpdateable) + setReadWrite (false); + else + setReadWrite (true); + setMandatory (mandatory); + // + mZoom = new CMenuItem(Msg.getMsg(Env.getCtx(), "Zoom"), Env.getImageIcon("Zoom16.gif")); + mZoom.addActionListener(this); + popupMenu.add(mZoom); + mRefresh = new CMenuItem(Msg.getMsg(Env.getCtx(), "Refresh"), Env.getImageIcon("Refresh16.gif")); + mRefresh.addActionListener(this); + popupMenu.add(mRefresh); + } // VLocator + + /** + * Dispose + */ + public void dispose() + { + m_text = null; + m_button = null; + m_mLocator = null; + } // dispose + + private JTextField m_text = new JTextField (VLookup.DISPLAY_LENGTH); + private CButton m_button = new CButton(); + private MLocatorLookup m_mLocator; + private Object m_value; + // + private String m_columnName; + private int m_WindowNo; + /** Logger */ + private static CLogger log = CLogger.getCLogger(VLocator.class); + // Popup + JPopupMenu popupMenu = new JPopupMenu(); + private CMenuItem mZoom; + private CMenuItem mRefresh; + + /** + * Enable/disable + * @param value r/w + */ + public void setReadWrite (boolean value) + { + m_button.setReadWrite(value); + if (m_button.isVisible() != value) + m_button.setVisible(value); + setBackground(false); + } // setReadWrite + + /** + * IsReadWrite + * @return true if ReadWrite + */ + public boolean isReadWrite() + { + return m_button.isReadWrite(); + } // isReadWrite + + /** + * Set Mandatory (and back bolor) + * @param mandatory true if mandatory + */ + public void setMandatory (boolean mandatory) + { + m_button.setMandatory(mandatory); + setBackground(false); + } // setMandatory + + /** + * Is it mandatory + * @return true if mandatory + */ + public boolean isMandatory() + { + return m_button.isMandatory(); + } // isMandatory + + /** + * Set Background + * @param color color + */ + public void setBackground (Color color) + { + if (!color.equals(m_text.getBackground())) + m_text.setBackground(color); + } // setBackground + + /** + * Set Background based on editable / mandatory / error + * @param error if true, set background to error color, otherwise mandatory/editable + */ + public void setBackground (boolean error) + { + if (error) + setBackground(AdempierePLAF.getFieldBackground_Error()); + else if (!isReadWrite()) + setBackground(AdempierePLAF.getFieldBackground_Inactive()); + else if (isMandatory()) + setBackground(AdempierePLAF.getFieldBackground_Mandatory()); + else + setBackground(AdempierePLAF.getFieldBackground_Normal()); + } // setBackground + + /** + * Set Foreground + * @param fg color + */ + public void setForeground(Color fg) + { + m_text.setForeground(fg); + } // setForeground + + /** + * Request Focus + */ + public void requestFocus () + { + m_text.requestFocus (); + } // requestFocus + + /** + * Set Editor to value + * @param value Integer + */ + public void setValue(Object value) + { + setValue (value, false); + } // setValue + + /** + * 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 = value; + m_text.setText(m_mLocator.getDisplay(value)); // loads value + + // Data Binding + try + { + fireVetoableChange(m_columnName, null, value); + } + catch (PropertyVetoException pve) + { + } + } // setValue + + + /** + * Property Change Listener + * @param evt PropertyChangeEvent + */ + public void propertyChange (PropertyChangeEvent evt) + { + if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) + setValue(evt.getNewValue()); + } // propertyChange + + /** + * 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 ((Integer)m_value).intValue(); + return 0; + } // getM_Locator_ID + + /** + * Return Display Value + * @return display value + */ + public String getDisplay() + { + return m_text.getText(); + } // getDisplay + + /** + * ActionListener + * @param e ActionEvent + */ + public void actionPerformed(ActionEvent e) + { + // Refresh + if (e.getSource() == mRefresh) + { + m_mLocator.refresh(); + return; + } + + // Zoom to M_Warehouse + if (e.getSource() == mZoom) + { + actionZoom(); + return; + } + + // 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 (e.getSource() == m_text + && actionText(only_Warehouse_ID, only_Product_ID)) + return; + + // Button - Start Dialog + int M_Locator_ID = 0; + if (m_value instanceof Integer) + M_Locator_ID = ((Integer)m_value).intValue(); + // + m_mLocator.setOnly_Warehouse_ID(only_Warehouse_ID); + m_mLocator.setOnly_Product_ID(getOnly_Product_ID()); + VLocatorDialog ld = new VLocatorDialog(Env.getFrame(this), + Msg.translate(Env.getCtx(), m_columnName), + m_mLocator, M_Locator_ID, isMandatory(), only_Warehouse_ID); + // display + ld.setVisible(true); + m_mLocator.setOnly_Warehouse_ID(0); + + // redisplay + if (!ld.isChanged()) + return; + setValue (ld.getValue(), true); + } // actionPerformed + + /** + * 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 = m_text.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 + + /** + * Action Listener Interface + * @param listener listener + */ + public void addActionListener(ActionListener listener) + { + m_text.addActionListener(listener); + } // addActionListener + + + /** + * Action - Zoom + */ + private void actionZoom() + { + int AD_Window_ID = 139; // hardcoded + log.info(""); + // + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + AWindow frame = new AWindow(); + if (!frame.initWindow(AD_Window_ID, null)) + return; + AEnv.showCenterScreen(frame); + frame = null; + setCursor(Cursor.getDefaultCursor()); + } // actionZoom + + /** + * 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 + +} // VLocator + +/*****************************************************************************/ + +/** + * Mouse Listener for Popup Menu + */ +final class VLocator_mouseAdapter extends java.awt.event.MouseAdapter +{ + /** + * Constructor + * @param adaptee VLocator + */ + VLocator_mouseAdapter(VLocator adaptee) + { + m_adaptee = adaptee; + } // VLookup_mouseAdapter + + /** Adaptee */ + private VLocator m_adaptee; + + /** + * Mouse Listener + * @param e MouseEvent + */ + public void mouseClicked(MouseEvent e) + { + // popup menu + if (SwingUtilities.isRightMouseButton(e)) + m_adaptee.popupMenu.show((Component)e.getSource(), e.getX(), e.getY()); + } // mouse Clicked + +} // VLocator_mouseAdapter diff --git a/client/src/org/compiere/grid/ed/VLookup.java b/client/src/org/compiere/grid/ed/VLookup.java index de5c67f2f9..21bc237044 100644 --- a/client/src/org/compiere/grid/ed/VLookup.java +++ b/client/src/org/compiere/grid/ed/VLookup.java @@ -1134,7 +1134,6 @@ public class VLookup extends JComponent } else { - AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame); } // async window - not able to get feedback diff --git a/client/src/org/compiere/grid/ed/VString.java b/client/src/org/compiere/grid/ed/VString.java index f45f949d62..6434f767ae 100644 --- a/client/src/org/compiere/grid/ed/VString.java +++ b/client/src/org/compiere/grid/ed/VString.java @@ -3,20 +3,20 @@ * 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 * - *****************************************************************************/ -package org.compiere.grid.ed; - -import java.awt.*; + * 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 * + *****************************************************************************/ +package org.compiere.grid.ed; + +import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; @@ -25,68 +25,68 @@ import org.adempiere.plaf.AdempierePLAF; import org.compiere.model.*; import org.compiere.plaf.*; import org.compiere.swing.*; -import org.compiere.util.*; - -/** - * Data Binding: - * VEditors call fireVetoableChange(m_columnName, null, getText()); - * GridController (for Single-Row) and VCellExitor (for Multi-Row) - * listen to Vetoable Change Listener (vetoableChange) - * then set the value for that column in the current row in the table - * - * @author Jorg Janke - * @version $Id: VString.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ - */ -public final class VString extends CTextField - implements VEditor, ActionListener, FocusListener -{ - /** Max Display Length - 60 */ - public static final int MAXDISPLAY_LENGTH = org.compiere.model.GridField.MAXDISPLAY_LENGTH; - - /** - * IDE Bean Constructor for 30 character updateable field - */ - public VString() - { - this("String", false, false, true, 30, 30, "", null); - } // VString - - /** - * Detail Constructor - * @param columnName column name - * @param mandatory mandatory - * @param isReadOnly read only - * @param isUpdateable updateable - * @param displayLength display length - * @param fieldLength field length - * @param VFormat format - * @param ObscureType obscure type - */ - public VString (String columnName, boolean mandatory, boolean isReadOnly, boolean isUpdateable, - int displayLength, int fieldLength, String VFormat, String ObscureType) - { - super(displayLength>MAXDISPLAY_LENGTH ? MAXDISPLAY_LENGTH : displayLength); - super.setName(columnName); - m_columnName = columnName; - if (VFormat == null) - VFormat = ""; - m_VFormat = VFormat; - m_fieldLength = fieldLength; - if (m_VFormat.length() != 0 || m_fieldLength != 0) - setDocument(new MDocString(m_VFormat, m_fieldLength, this)); - if (m_VFormat.length() != 0) - setCaret(new VOvrCaret()); - // - setMandatory(mandatory); - if (ObscureType != null && ObscureType.length() > 0) - { - m_obscure = new Obscure ("", ObscureType); - m_stdFont = getFont(); - m_obscureFont = new Font("SansSerif", Font.ITALIC, m_stdFont.getSize()); - addFocusListener(this); - } - - // Editable +import org.compiere.util.*; + +/** + * Data Binding: + * VEditors call fireVetoableChange(m_columnName, null, getText()); + * GridController (for Single-Row) and VCellExitor (for Multi-Row) + * listen to Vetoable Change Listener (vetoableChange) + * then set the value for that column in the current row in the table + * + * @author Jorg Janke + * @version $Id: VString.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $ + */ +public final class VString extends CTextField + implements VEditor, ActionListener, FocusListener +{ + /** Max Display Length - 60 */ + public static final int MAXDISPLAY_LENGTH = org.compiere.model.GridField.MAXDISPLAY_LENGTH; + + /** + * IDE Bean Constructor for 30 character updateable field + */ + public VString() + { + this("String", false, false, true, 30, 30, "", null); + } // VString + + /** + * Detail Constructor + * @param columnName column name + * @param mandatory mandatory + * @param isReadOnly read only + * @param isUpdateable updateable + * @param displayLength display length + * @param fieldLength field length + * @param VFormat format + * @param ObscureType obscure type + */ + public VString (String columnName, boolean mandatory, boolean isReadOnly, boolean isUpdateable, + int displayLength, int fieldLength, String VFormat, String ObscureType) + { + super(displayLength>MAXDISPLAY_LENGTH ? MAXDISPLAY_LENGTH : displayLength); + super.setName(columnName); + m_columnName = columnName; + if (VFormat == null) + VFormat = ""; + m_VFormat = VFormat; + m_fieldLength = fieldLength; + if (m_VFormat.length() != 0 || m_fieldLength != 0) + setDocument(new MDocString(m_VFormat, m_fieldLength, this)); + if (m_VFormat.length() != 0) + setCaret(new VOvrCaret()); + // + setMandatory(mandatory); + if (ObscureType != null && ObscureType.length() > 0) + { + m_obscure = new Obscure ("", ObscureType); + m_stdFont = getFont(); + m_obscureFont = new Font("SansSerif", Font.ITALIC, m_stdFont.getSize()); + addFocusListener(this); + } + + // Editable if (isReadOnly || !isUpdateable) { setEditable(false); @@ -94,12 +94,12 @@ public final class VString extends CTextField } this.addKeyListener(this); - this.addActionListener(this); - // Popup for Editor - if (fieldLength > displayLength) - { - addMouseListener(new VString_mouseAdapter(this)); - mEditor = new CMenuItem (Msg.getMsg(Env.getCtx(), "Editor"), Env.getImageIcon("Editor16.gif")); + this.addActionListener(this); + // Popup for Editor + if (fieldLength > displayLength) + { + addMouseListener(new VString_mouseAdapter(this)); + mEditor = new CMenuItem (Msg.getMsg(Env.getCtx(), "Editor"), Env.getImageIcon("Editor16.gif")); mEditor.addActionListener(this); popupMenu.add(mEditor); } @@ -108,171 +108,171 @@ public final class VString extends CTextField } // VString /** - * Dispose - */ - public void dispose() - { - m_mField = null; - } // dispose - - /** Popup Menu */ - JPopupMenu popupMenu = new JPopupMenu(); - /** Editor Menu Item */ - private CMenuItem mEditor; - /** Grid Field */ - private GridField m_mField = null; - /** Column Name */ - private String m_columnName; - private String m_oldText; - private String m_initialText; - private String m_VFormat; - /** Field Length */ - private int m_fieldLength; - /** Obcure Setting */ - private Obscure m_obscure = null; - private Font m_stdFont = null; - private Font m_obscureFont = null; - /** Setting new value */ - private volatile boolean m_setting = false; - /** Field in focus */ - private volatile boolean m_infocus = false; - - /** Logger */ - private static CLogger log = CLogger.getCLogger (VString.class); - - /** - * Set Editor to value - * @param value value - */ - public void setValue(Object value) - { - // log.config( "VString.setValue", value); - if (value == null) - m_oldText = ""; - else - m_oldText = value.toString(); - // only set when not updated here - if (m_setting) - return; - setText (m_oldText); - m_initialText = m_oldText; - // If R/O left justify - if (!isEditable() || !isEnabled()) - setCaretPosition(0); - } // setValue - - /** - * Property Change Listener - * @param evt event - */ - public void propertyChange (PropertyChangeEvent evt) - { - if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) - setValue(evt.getNewValue()); - } // propertyChange - - /** - * Return Editor value - * @return value - */ - public Object getValue() - { - return getText(); - } // getValue - - /** - * Return Display Value - * @return value - */ - public String getDisplay() - { - return super.getText(); // optionally obscured - } // getDisplay - - - /** - * Key Released. - * if Escape Restore old Text - * @param e event - */ - public void keyReleased(KeyEvent e) - { - log.finest("Key=" + e.getKeyCode() + " - " + e.getKeyChar() - + " -> " + getText()); - // ESC - if (e.getKeyCode() == KeyEvent.VK_ESCAPE) - setText(m_initialText); - m_setting = true; - try - { - String clear = getText(); - if (clear.length() > m_fieldLength) - clear = clear.substring(0, m_fieldLength); - fireVetoableChange (m_columnName, m_oldText, clear); - } - catch (PropertyVetoException pve) - { - } - m_setting = false; - } // keyReleased - - /** - * Data Binding to MTable (via GridController) - Enter pressed - * @param e event - */ - public void actionPerformed(ActionEvent e) - { - if (e.getActionCommand().equals(ValuePreference.NAME)) - { - if (MRole.getDefault().isShowPreference()) - ValuePreference.start (m_mField, getValue()); - return; - } - - // Invoke Editor - if (e.getSource() == mEditor) - { - String s = Editor.startEditor(this, Msg.translate(Env.getCtx(), m_columnName), - getText(), isEditable(), m_fieldLength); - setText(s); - } - // Data Binding - try - { - fireVetoableChange(m_columnName, m_oldText, getText()); - } - catch (PropertyVetoException pve) - { - } - } // actionPerformed - - /** - * Set Field/WindowNo for ValuePreference - * @param mField field - */ - public void setField (GridField mField) - { - m_mField = mField; - if (m_mField != null - && MRole.getDefault().isShowPreference()) - ValuePreference.addMenu (this, popupMenu); - } // setField - - - /** - * Set Text (optionally obscured) - * @param text text - */ - public void setText (String text) - { - if (m_obscure != null && !m_infocus) - { - super.setFont(m_obscureFont); - super.setText (m_obscure.getObscuredValue(text)); - super.setForeground(Color.gray); - } - else - { + * Dispose + */ + public void dispose() + { + m_mField = null; + } // dispose + + /** Popup Menu */ + JPopupMenu popupMenu = new JPopupMenu(); + /** Editor Menu Item */ + private CMenuItem mEditor; + /** Grid Field */ + private GridField m_mField = null; + /** Column Name */ + private String m_columnName; + private String m_oldText; + private String m_initialText; + private String m_VFormat; + /** Field Length */ + private int m_fieldLength; + /** Obcure Setting */ + private Obscure m_obscure = null; + private Font m_stdFont = null; + private Font m_obscureFont = null; + /** Setting new value */ + private volatile boolean m_setting = false; + /** Field in focus */ + private volatile boolean m_infocus = false; + + /** Logger */ + private static CLogger log = CLogger.getCLogger (VString.class); + + /** + * Set Editor to value + * @param value value + */ + public void setValue(Object value) + { + // log.config( "VString.setValue", value); + if (value == null) + m_oldText = ""; + else + m_oldText = value.toString(); + // only set when not updated here + if (m_setting) + return; + setText (m_oldText); + m_initialText = m_oldText; + // If R/O left justify + if (!isEditable() || !isEnabled()) + setCaretPosition(0); + } // setValue + + /** + * Property Change Listener + * @param evt event + */ + public void propertyChange (PropertyChangeEvent evt) + { + if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY)) + setValue(evt.getNewValue()); + } // propertyChange + + /** + * Return Editor value + * @return value + */ + public Object getValue() + { + return getText(); + } // getValue + + /** + * Return Display Value + * @return value + */ + public String getDisplay() + { + return super.getText(); // optionally obscured + } // getDisplay + + + /** + * Key Released. + * if Escape Restore old Text + * @param e event + */ + public void keyReleased(KeyEvent e) + { + log.finest("Key=" + e.getKeyCode() + " - " + e.getKeyChar() + + " -> " + getText()); + // ESC + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) + setText(m_initialText); + m_setting = true; + try + { + String clear = getText(); + if (clear.length() > m_fieldLength) + clear = clear.substring(0, m_fieldLength); + fireVetoableChange (m_columnName, m_oldText, clear); + } + catch (PropertyVetoException pve) + { + } + m_setting = false; + } // keyReleased + + /** + * Data Binding to MTable (via GridController) - Enter pressed + * @param e event + */ + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals(ValuePreference.NAME)) + { + if (MRole.getDefault().isShowPreference()) + ValuePreference.start (m_mField, getValue()); + return; + } + + // Invoke Editor + if (e.getSource() == mEditor) + { + String s = Editor.startEditor(this, Msg.translate(Env.getCtx(), m_columnName), + getText(), isEditable(), m_fieldLength); + setText(s); + } + // Data Binding + try + { + fireVetoableChange(m_columnName, m_oldText, getText()); + } + catch (PropertyVetoException pve) + { + } + } // actionPerformed + + /** + * Set Field/WindowNo for ValuePreference + * @param mField field + */ + public void setField (GridField mField) + { + m_mField = mField; + if (m_mField != null + && MRole.getDefault().isShowPreference()) + ValuePreference.addMenu (this, popupMenu); + } // setField + + + /** + * Set Text (optionally obscured) + * @param text text + */ + public void setText (String text) + { + if (m_obscure != null && !m_infocus) + { + super.setFont(m_obscureFont); + super.setText (m_obscure.getObscuredValue(text)); + super.setForeground(Color.gray); + } + else + { if (m_stdFont != null) { super.setFont(m_stdFont); @@ -280,81 +280,74 @@ public final class VString extends CTextField } super.setText (text); } - } // setText - - - /** - * Get Text (clear) - * @return text - */ - public String getText () - { - String text = super.getText(); - if (m_obscure != null && text != null && text.length() > 0) - { - if (text.equals(m_obscure.getObscuredValue())) - text = m_obscure.getClearValue(); - } - return text; - } // getText - - /** - * Focus Gained. - * Enabled with Obscure - * @param e event - */ - public void focusGained (FocusEvent e) - { - m_infocus = true; - setText(getText()); // clear - } // focusGained - - /** - * Focus Lost - * Enabled with Obscure - * @param e event - */ - public void focusLost (FocusEvent e) - { + } // setText + + + /** + * Get Text (clear) + * @return text + */ + public String getText () + { + String text = super.getText(); + if (m_obscure != null && text != null && text.length() > 0) + { + if (text.equals(m_obscure.getObscuredValue())) + text = m_obscure.getClearValue(); + } + return text; + } // getText + + /** + * Focus Gained. + * Enabled with Obscure + * @param e event + */ + public void focusGained (FocusEvent e) + { + m_infocus = true; + setText(getText()); // clear + } // focusGained + + /** + * Focus Lost + * Enabled with Obscure + * @param e event + */ + public void focusLost (FocusEvent e) + { m_infocus = false; setText(getText()); // obscure } // focus Lost - - @Override - public void setFont(Font f) { - super.setFont(f); - m_stdFont = f; - m_obscureFont = new Font("SansSerif", Font.ITALIC, m_stdFont.getSize()); - } } // VString - -/****************************************************************************** - * Mouse Listener - */ -final class VString_mouseAdapter extends MouseAdapter -{ - /** - * Constructor - * @param adaptee adaptee - */ - VString_mouseAdapter(VString adaptee) - { - m_adaptee = adaptee; - } // VString_mouseAdapter - - private VString m_adaptee; - - /** - * Mouse Listener - * @param e event - */ - public void mouseClicked(MouseEvent e) - { - // popup menu - if (SwingUtilities.isRightMouseButton(e)) - m_adaptee.popupMenu.show((Component)e.getSource(), e.getX(), e.getY()); - } // mouseClicked - -} // VText_mouseAdapter + +/****************************************************************************** + * Mouse Listener + */ +final class VString_mouseAdapter extends MouseAdapter +{ + /** + * Constructor + * @param adaptee adaptee + */ + VString_mouseAdapter(VString adaptee) + { + m_adaptee = adaptee; + } // VString_mouseAdapter + + private VString m_adaptee; + + /** + * Mouse Listener + * @param e event + */ + public void mouseClicked(MouseEvent e) + { + // popup menu + if (SwingUtilities.isRightMouseButton(e)) + m_adaptee.popupMenu.show((Component)e.getSource(), e.getX(), e.getY()); + } // mouseClicked + +} // VText_mouseAdapter diff --git a/client/src/org/compiere/print/ReportCtl.java b/client/src/org/compiere/print/ReportCtl.java index 40adef9e82..0aba5d4bae 100644 --- a/client/src/org/compiere/print/ReportCtl.java +++ b/client/src/org/compiere/print/ReportCtl.java @@ -3,17 +3,17 @@ * 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 * - *****************************************************************************/ + * 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 * + *****************************************************************************/ package org.compiere.print; import java.util.logging.*; @@ -23,180 +23,174 @@ import javax.swing.JFrame; import org.compiere.apps.*; import org.compiere.model.*; import org.compiere.process.*; -import org.compiere.util.*; - -/** - * Report Controller. - * - * @author Jorg Janke - * @version $Id: ReportCtl.java,v 1.3 2006/10/08 07:05:08 comdivision Exp $ - */ -public class ReportCtl -{ - /** - * Constructor - prevent instance - */ - private ReportCtl() - { - } // ReportCtrl - - /** Static Logger */ - private static CLogger s_log = CLogger.getCLogger (ReportCtl.class); - - /** - * Create Report. - * Called from ProcessCtl. - * - Check special reports first, if not, create standard Report - * - * @param pi process info - * @param IsDirectPrint if true, prints directly - otherwise View - * @return true if created - */ - static public boolean start (ProcessInfo pi, boolean IsDirectPrint) - { - s_log.info("start - " + pi); - - /** - * Order Print - */ - if (pi.getAD_Process_ID() == 110) // C_Order - return startDocumentPrint(ReportEngine.ORDER, pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 116) // C_Invoice - return startDocumentPrint(ReportEngine.INVOICE, pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 117) // M_InOut - return startDocumentPrint(ReportEngine.SHIPMENT, pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 217) // C_Project - return startDocumentPrint(ReportEngine.PROJECT, pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 276) // C_RfQResponse - return startDocumentPrint(ReportEngine.RFQ, pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 313) // C_Payment - return startCheckPrint(pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 290) // Movement Submission by VHARCQ - return startDocumentPrint(ReportEngine.MOVEMENT, pi.getRecord_ID(), IsDirectPrint); - /** - else if (pi.AD_Process_ID == 9999999) // PaySelection - return startDocumentPrint(CHECK, pi, IsDirectPrint); - else if (pi.AD_Process_ID == 9999999) // PaySelection - return startDocumentPrint(REMITTANCE, pi, IsDirectPrint); - **/ - else if (pi.getAD_Process_ID() == 159) // Dunning - return startDocumentPrint(ReportEngine.DUNNING, pi.getRecord_ID(), IsDirectPrint); - else if (pi.getAD_Process_ID() == 202 // Financial Report - || pi.getAD_Process_ID() == 204) // Financial Statement - return startFinReport (pi); - /******************** - * Standard Report - *******************/ - return startStandardReport (pi, IsDirectPrint); - } // create - - - /************************************************************************** - * Start Standard Report. - * - Get Table Info & submit - * @param pi Process Info - * @param IsDirectPrint if true, prints directly - otherwise View - * @return true if OK - */ - static public boolean startStandardReport (ProcessInfo pi, boolean IsDirectPrint) - { - ReportEngine re = ReportEngine.get(Env.getCtx(), pi); - if (re == null) - { - pi.setSummary("No ReportEngine"); - return false; - } - if (IsDirectPrint) - { +import org.compiere.util.*; + +/** + * Report Controller. + * + * @author Jorg Janke + * @version $Id: ReportCtl.java,v 1.3 2006/10/08 07:05:08 comdivision Exp $ + */ +public class ReportCtl +{ + /** + * Constructor - prevent instance + */ + private ReportCtl() + { + } // ReportCtrl + + /** Static Logger */ + private static CLogger s_log = CLogger.getCLogger (ReportCtl.class); + + /** + * Create Report. + * Called from ProcessCtl. + * - Check special reports first, if not, create standard Report + * + * @param pi process info + * @param IsDirectPrint if true, prints directly - otherwise View + * @return true if created + */ + static public boolean start (ProcessInfo pi, boolean IsDirectPrint) + { + s_log.info("start - " + pi); + + /** + * Order Print + */ + if (pi.getAD_Process_ID() == 110) // C_Order + return startDocumentPrint(ReportEngine.ORDER, pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 116) // C_Invoice + return startDocumentPrint(ReportEngine.INVOICE, pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 117) // M_InOut + return startDocumentPrint(ReportEngine.SHIPMENT, pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 217) // C_Project + return startDocumentPrint(ReportEngine.PROJECT, pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 276) // C_RfQResponse + return startDocumentPrint(ReportEngine.RFQ, pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 313) // C_Payment + return startCheckPrint(pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 290) // Movement Submission by VHARCQ + return startDocumentPrint(ReportEngine.MOVEMENT, pi.getRecord_ID(), IsDirectPrint); + /** + else if (pi.AD_Process_ID == 9999999) // PaySelection + return startDocumentPrint(CHECK, pi, IsDirectPrint); + else if (pi.AD_Process_ID == 9999999) // PaySelection + return startDocumentPrint(REMITTANCE, pi, IsDirectPrint); + **/ + else if (pi.getAD_Process_ID() == 159) // Dunning + return startDocumentPrint(ReportEngine.DUNNING, pi.getRecord_ID(), IsDirectPrint); + else if (pi.getAD_Process_ID() == 202 // Financial Report + || pi.getAD_Process_ID() == 204) // Financial Statement + return startFinReport (pi); + /******************** + * Standard Report + *******************/ + return startStandardReport (pi, IsDirectPrint); + } // create + + + /************************************************************************** + * Start Standard Report. + * - Get Table Info & submit + * @param pi Process Info + * @param IsDirectPrint if true, prints directly - otherwise View + * @return true if OK + */ + static public boolean startStandardReport (ProcessInfo pi, boolean IsDirectPrint) + { + ReportEngine re = ReportEngine.get(Env.getCtx(), pi); + if (re == null) + { + pi.setSummary("No ReportEngine"); + return false; + } + if (IsDirectPrint) + { re.print(); } else - preview(re); + new Viewer(re); return true; } // startStandardReport - /** - * Start Financial Report. - * @param pi Process Info - * @return true if OK - */ - static public boolean startFinReport (ProcessInfo pi) - { - int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); - - // Create Query from Parameters - String TableName = pi.getAD_Process_ID() == 202 ? "T_Report" : "T_ReportStatement"; - MQuery query = MQuery.get (Env.getCtx(), pi.getAD_PInstance_ID(), TableName); - - // Get PrintFormat - MPrintFormat format = (MPrintFormat)pi.getTransientObject(); - if (format == null) - format = (MPrintFormat)pi.getSerializableObject(); - if (format == null) - { - s_log.log(Level.SEVERE, "startFinReport - No PrintFormat"); - return false; - } + /** + * Start Financial Report. + * @param pi Process Info + * @return true if OK + */ + static public boolean startFinReport (ProcessInfo pi) + { + int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx()); + + // Create Query from Parameters + String TableName = pi.getAD_Process_ID() == 202 ? "T_Report" : "T_ReportStatement"; + MQuery query = MQuery.get (Env.getCtx(), pi.getAD_PInstance_ID(), TableName); + + // Get PrintFormat + MPrintFormat format = (MPrintFormat)pi.getTransientObject(); + if (format == null) + format = (MPrintFormat)pi.getSerializableObject(); + if (format == null) + { + s_log.log(Level.SEVERE, "startFinReport - No PrintFormat"); + return false; + } PrintInfo info = new PrintInfo(pi); ReportEngine re = new ReportEngine(Env.getCtx(), format, query, info); - preview(re); + new Viewer(re); return true; } // startFinReport - - /** - * Start Document Print for Type. - * Called also directly from ProcessDialog, VInOutGen, VInvoiceGen, VPayPrint - * @param type document type in ReportEngine - * @param Record_ID id - * @param IsDirectPrint if true, prints directly - otherwise View - * @return true if success - */ - public static boolean startDocumentPrint (int type, int Record_ID, boolean IsDirectPrint) - { - ReportEngine re = ReportEngine.get (Env.getCtx(), type, Record_ID); - if (re == null) - { - ADialog.error(0, null, "NoDocPrintFormat"); - return false; - } - if (IsDirectPrint) - { - re.print (); + + /** + * Start Document Print for Type. + * Called also directly from ProcessDialog, VInOutGen, VInvoiceGen, VPayPrint + * @param type document type in ReportEngine + * @param Record_ID id + * @param IsDirectPrint if true, prints directly - otherwise View + * @return true if success + */ + public static boolean startDocumentPrint (int type, int Record_ID, boolean IsDirectPrint) + { + ReportEngine re = ReportEngine.get (Env.getCtx(), type, Record_ID); + if (re == null) + { + ADialog.error(0, null, "NoDocPrintFormat"); + return false; + } + if (IsDirectPrint) + { + re.print (); ReportEngine.printConfirm (type, Record_ID); } else - preview(re); + new Viewer(re); return true; } // StartDocumentPrint - /** - * Start Check Print. - * Find/Create - * @param C_Payment_ID Payment - * @param IsDirectPrint if true, prints directly - otherwise View - * @return true if success - */ - public static boolean startCheckPrint (int C_Payment_ID, boolean IsDirectPrint) - { - int C_PaySelectionCheck_ID = 0; - MPaySelectionCheck psc = MPaySelectionCheck.getOfPayment(Env.getCtx(), C_Payment_ID, null); - if (psc != null) - C_PaySelectionCheck_ID = psc.getC_PaySelectionCheck_ID(); - else - { - psc = MPaySelectionCheck.createForPayment(Env.getCtx(), C_Payment_ID, null); - if (psc != null) - C_PaySelectionCheck_ID = psc.getC_PaySelectionCheck_ID(); - } + /** + * Start Check Print. + * Find/Create + * @param C_Payment_ID Payment + * @param IsDirectPrint if true, prints directly - otherwise View + * @return true if success + */ + public static boolean startCheckPrint (int C_Payment_ID, boolean IsDirectPrint) + { + int C_PaySelectionCheck_ID = 0; + MPaySelectionCheck psc = MPaySelectionCheck.getOfPayment(Env.getCtx(), C_Payment_ID, null); + if (psc != null) + C_PaySelectionCheck_ID = psc.getC_PaySelectionCheck_ID(); + else + { + psc = MPaySelectionCheck.createForPayment(Env.getCtx(), C_Payment_ID, null); + if (psc != null) + C_PaySelectionCheck_ID = psc.getC_PaySelectionCheck_ID(); + } return startDocumentPrint (ReportEngine.CHECK, C_PaySelectionCheck_ID, IsDirectPrint); } // startCheckPrint - private static void preview(ReportEngine re) { - Viewer viewer = new Viewer(re); - JFrame top = Env.getWindow(0); - if (top instanceof AMenu) - ((AMenu)top).getWindowManager().add(viewer); - } } // ReportCtl