Remove Libero of trunk

This commit is contained in:
vpj-cd 2009-02-09 15:29:50 +00:00
parent 182222c5d2
commit 82cc03ca50
39 changed files with 0 additions and 13706 deletions

View File

@ -1,441 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JEditorPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import org.compiere.apps.form.FormFrame;
import org.compiere.grid.ed.VLookup;
import org.compiere.model.MColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MProduct;
import org.compiere.model.PO;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.form.action.PopupAction;
import org.eevolution.form.action.ZoomMenuAction;
import org.eevolution.form.bom.BOMTreeFactory;
import org.eevolution.form.bom.BOMTreeModel;
import org.eevolution.form.bom.action.ChangeASIAction;
import org.eevolution.form.bom.action.CreateRfQAction;
import org.eevolution.form.bom.action.DeleteBOMAction;
import org.eevolution.form.bom.action.MergeBOMAction;
import org.eevolution.model.MPPOrder;
import org.eevolution.model.reasoner.StorageReasoner;
import org.eevolution.model.wrapper.BOMLineWrapper;
import org.eevolution.model.wrapper.BOMWrapper;
import org.eevolution.tools.swing.SwingTool;
import org.eevolution.tools.worker.SingleWorker;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class CAbstractBOMTree extends CAbstractForm implements PropertyChangeListener {
class TreeHandler extends MouseInputAdapter implements TreeSelectionListener, KeyListener {
public void mouseClicked(MouseEvent e) {
if(model.getTree().getPathForLocation(e.getX(), e.getY()) == null) {
return;
}
SwingTool.setCursorsFromChild(e.getComponent(), true);
final MouseEvent evt = e;
worker = new SingleWorker() {
protected Object doIt() {
handleTreeEvent(evt);
return null;
}
};
worker.start();
}
public void mouseMoved(MouseEvent e) {
//m_tree.setToolTipText(msg.getToolTipText(e));
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == 38 || e.getKeyCode() == 40) {
TreePath path = model.getTree().getSelectionModel().getSelectionPath();
String text = model.getBOMMessenger().getToolTipText(path);
if(text != null) {
nodeDescription.setText(text);
}
}
}
public void keyTyped(KeyEvent e) {
}
public void valueChanged(TreeSelectionEvent event) {
}
}
private void handleTreeEvent(MouseEvent e) {
String text = model.getBOMMessenger().getToolTipText(e);
if(text != null) {
nodeDescription.setText(text);
}
if(e.getButton() == MouseEvent.BUTTON3) {
model.getTree().setSelectionPath(model.getTree().getPathForLocation(e.getX(), e.getY()));
DefaultMutableTreeNode node = (DefaultMutableTreeNode)model.getTree().getSelectionPath().getLastPathComponent();
if(node.getUserObject() instanceof BOMLineWrapper) {
popupBOMLine.show(e.getComponent(), e.getX(), e.getY());
}
else if(node.getUserObject() instanceof BOMWrapper) {
popupBOM.show(e.getComponent(), e.getX(), e.getY());
}
else if(node.getUserObject() instanceof MProduct) {
popupRoot.show(e.getComponent(), e.getX(), e.getY());
}
else if(node.getUserObject() instanceof MPPOrder) {
popupRoot.show(e.getComponent(), e.getX(), e.getY());
}
}
SwingTool.setCursorsFromChild(e.getComponent(), false);
}
public CAbstractBOMTree () {
super();
}
private SingleWorker worker;
private BOMTreeModel model;
private CPanel northPanel;
private VLookup lookup;
private JSplitPane contentPane;
private CPanel southPanel;
private JEditorPane nodeDescription;
protected JPopupMenu popupRoot;
protected JPopupMenu popupBOM;
protected JPopupMenu popupBOMLine;
protected StorageReasoner reasoner;
protected abstract String type();
protected String idColumn() {
return type()+"_ID";
}
public void init (int WindowNo, FormFrame frame) {
super.init(WindowNo, frame);
reasoner = new StorageReasoner();
try {
preInit();
jbInit ();
getWindow().getContentPane().add(this, BorderLayout.CENTER);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void preInit() {
northPanel = new CPanel ();
southPanel = new CPanel();
contentPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
nodeDescription = new JEditorPane("text/html", "");
nodeDescription.setOpaque(false);
nodeDescription.setEditable(false);
String columnName = null;
int columnId = -1;
if(BOMWrapper.BOM_TYPE_PRODUCT.equals(type())) {
columnName = MProduct.Table_Name+"_ID";
columnId = MColumn.getColumn_ID(MProduct.Table_Name,columnName);
}
else if(BOMWrapper.BOM_TYPE_ORDER.equals(type())) {
columnName = MPPOrder.Table_Name+"_ID";
columnId = MColumn.getColumn_ID(MPPOrder.Table_Name,columnName);
}
MLookup lm = MLookupFactory.get(Env.getCtx(), getWindowNo(), 0, columnId, DisplayType.Search);
lookup = new VLookup (columnName, false, false, true, lm) {
public void setValue(Object obj) {
super.setValue(obj);
dispatchPropertyChange();
};
};
}
private void jbInit () {
CLabel label = null;
if(BOMWrapper.BOM_TYPE_PRODUCT.equals(type())) {
label = new CLabel(Msg.translate(Env.getCtx(), MProduct.Table_Name+"_ID"));
}
else if(BOMWrapper.BOM_TYPE_ORDER.equals(type())) {
label = new CLabel(Msg.translate(Env.getCtx(), MPPOrder.Table_Name+"_ID"));
}
label.setLabelFor(lookup);
northPanel.setLayout (new FlowLayout(FlowLayout.LEFT));
northPanel.add (label, null);
northPanel.add (lookup, null);
southPanel.setLayout(new BorderLayout());
JScrollPane sp = new JScrollPane(nodeDescription);
sp.setBorder(null);
contentPane.add(sp, JSplitPane.RIGHT);
this.setLayout (new BorderLayout());
this.setPreferredSize(new Dimension(1000, 600));
this.add (northPanel, BorderLayout.NORTH);
this.add (contentPane, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
}
public void dispose() {
super.dispose();
if(worker != null) {
worker.stop();
}
worker = null;
if(lookup != null) {
lookup.dispose();
}
lookup = null;
northPanel = null;
contentPane = null;
southPanel = null;
nodeDescription = null;
popupRoot = null;
popupBOM = null;
popupBOMLine = null;
reasoner = null;
}
private void handleActionEvent() {
Integer value = (Integer)lookup.getValue();
if (value == null || value.intValue() == 0) {
return;
}
else {
nodeDescription.setText("");
}
int poID = value.intValue();
PO po = null;
if(BOMWrapper.BOM_TYPE_PRODUCT.equals(type())) {
po = new MProduct(Env.getCtx(), poID, MProduct.Table_Name);
}
else if(BOMWrapper.BOM_TYPE_ORDER.equals(type())) {
po = new MPPOrder(Env.getCtx(), poID, null);
}
model = BOMTreeFactory.get(type(), po, reasoner);
configureTree();
contentPane.add (new JScrollPane(model.getTree()), JSplitPane.LEFT);
contentPane.setDividerLocation(0.25d);
}
protected void configureTree() {
model.getTree().addPropertyChangeListener(this);
TreeHandler th = new TreeHandler();
model.getTree().addMouseMotionListener(th);
model.getTree().addMouseListener(th);
model.getTree().addKeyListener(th);
model.getTree().addTreeSelectionListener(th);
popupRoot = new JPopupMenu();
popupBOM = new JPopupMenu();
popupBOMLine = new JPopupMenu();
try {
configurePopup(popupRoot, model.getTree(), MProduct.class);
configurePopup(popupBOM, model.getTree(), BOMWrapper.class);
configurePopup(popupBOMLine, model.getTree(), BOMLineWrapper.class);
}
catch(Exception e) {
e.printStackTrace();
}
}
protected void configurePopup(JPopupMenu popup, JTree tree, Class clazz) throws Exception {
PopupAction action = null;
// Context menu items for manufacturing order or product
if(MPPOrder.class.equals(clazz) || MProduct.class.equals(clazz)) {
action = new ZoomMenuAction(tree);
popup.add(action);
}
// Context menu items for BOM header
else if(BOMWrapper.class.equals(clazz)) {
// Delete, merge and zoom action only for product BOM type available
if(BOMWrapper.BOM_TYPE_PRODUCT.equals(type())) {
action = new ZoomMenuAction(tree);
popup.add(action);
action = new MergeBOMAction(tree);
action.addPropertyChangeListener(this);
popup.add(action);
action = new DeleteBOMAction(tree);
action.addPropertyChangeListener(this);
popup.add(action);
}
// CreateRFQ action only for order BOM type available
if(BOMWrapper.BOM_TYPE_ORDER.equals(type())) {
action = new CreateRfQAction(tree, getWindow());
action.addPropertyChangeListener(this);
popup.add(action);
}
}
// Context menu items for BOM line
else if(BOMLineWrapper.class.equals(clazz)) {
// Delete action only for product BOM type available
if(BOMWrapper.BOM_TYPE_PRODUCT.equals(type())) {
action = new DeleteBOMAction(tree);
action.addPropertyChangeListener(this);
popup.add(action);
}
action = new ChangeASIAction(tree, getWindow());
action.addPropertyChangeListener(this);
popup.add(action);
}
}
protected void dispatchPropertyChange() {
PropertyChangeEvent evt = new PropertyChangeEvent(lookup, ChangeASIAction.COMMAND, null, null);
propertyChange(evt);
}
public void propertyChange(PropertyChangeEvent e) {
if(
MergeBOMAction.COMMAND.equals(e.getPropertyName())
|| ChangeASIAction.COMMAND.equals(e.getPropertyName())
|| DeleteBOMAction.COMMAND.equals(e.getPropertyName())
) {
SwingTool.setCursorsFromParent(getWindow(), true);
SingleWorker worker = new SingleWorker() {
protected Object doIt() {
handleActionEvent();
SwingTool.setCursorsFromParent(getWindow(), false);
return null;
}
};
runWorker(worker);
}
}
protected void runWorker(SingleWorker worker) {
this.worker = worker;
this.worker.start();
}
}

View File

@ -1,73 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.swing.CPanel;
import org.compiere.util.Env;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class CAbstractForm extends CPanel implements FormPanel {
// Later it may inherit some functionallity. Therefore its included any longer.
class FrameHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
// Disposing isn't necessary here, because its handled by the form frame itself.
//dispose();
}
}
private FormFrame frame;
private FrameHandler handler;
public CAbstractForm() {
handler = new FrameHandler();
}
public void init (int WindowNo, FormFrame frame) {
this.frame = frame;
frame.addWindowListener(handler);
}
public void dispose() {
handler = null;
}
public int getWindowNo() {
return Env.getWindowNo(frame);
}
public FormFrame getWindow() {
return frame;
}
}

View File

@ -1,441 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Properties;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.MouseInputAdapter;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.form.FormFrame;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VLookup;
import org.compiere.model.MColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MResource;
import org.compiere.model.MUOM;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.form.action.PopupAction;
import org.eevolution.form.action.ZoomMenuAction;
import org.eevolution.form.crp.CRPDatasetFactory;
import org.eevolution.form.crp.CRPModel;
import org.eevolution.model.MPPOrderNode;
import org.eevolution.tools.swing.SwingTool;
import org.eevolution.tools.worker.SingleWorker;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.TextAnchor;
/**
* Capacity Requirement Planning Form
*
* AD_FORM:
* INSERT INTO ad_form VALUES (1000020, 0, 0, 'Y', CURRENT_TIMESTAMP, 0, CURRENT_TIMESTAMP, 100, 'Resource Load View', NULL, NULL, '3', 'org.compiere.mfg.form.CCRP', 'U', 'N', NULL);
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class CCRP extends CAbstractForm {
class ActionHandler implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getActionCommand().equals(ConfirmPanel.A_OK)) {
SwingTool.setCursorsFromParent(getWindow(), true);
final ActionEvent evt = e;
worker = new SingleWorker() {
protected Object doIt() {
handleActionEvent(evt);
return null;
}
};
worker.start();
}
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL)) {
dispose();
}
}
}
class TreeHandler extends MouseInputAdapter implements TreeSelectionListener {
public void mouseClicked(MouseEvent e) {
if(model.getTree().getPathForLocation(e.getX(), e.getY()) == null) {
return;
}
SwingTool.setCursorsFromChild(e.getComponent(), true);
final MouseEvent evt = e;
worker = new SingleWorker() {
protected Object doIt() {
handleTreeEvent(evt);
return null;
}
};
worker.start();
}
public void mouseMoved(MouseEvent e) {
//m_tree.setToolTipText(msg.getToolTipText(e));
}
public void valueChanged(TreeSelectionEvent event) {
}
}
class FrameHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
dispose();
}
}
class LabelGenerator extends StandardCategoryItemLabelGenerator
{
public String generateItemLabel(CategoryDataset categorydataset, int i, int j) {
return categorydataset.getRowKey(i).toString();
}
}
private VLookup resource;
private VDate dateFrom;
private VDate dateTo;
private ChartPanel chartPanel;
private JSplitPane contentPanel;
private SingleWorker worker;
protected CRPModel model;
protected JPopupMenu popup;
public CCRP() {
super();
}
public void init (int WindowNo, FormFrame frame) {
super.init(WindowNo, frame);
fillPicks();
jbInit();
}
private void jbInit() {
dateFrom = new VDate("DateFrom", true, false, true, DisplayType.Date, "DateFrom");
dateTo = new VDate("DateTo", true, false, true, DisplayType.Date, "DateTo");
CPanel northPanel = new CPanel();
northPanel.setLayout(new java.awt.GridBagLayout());
northPanel.add(
new CLabel(Msg.translate(Env.getCtx(), "S_Resource_ID")),
new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)
);
northPanel.add(
resource,
new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)
);
northPanel.add(
new CLabel(Msg.translate(Env.getCtx(), "DateFrom")),
new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)
);
northPanel.add(
dateFrom,
new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)
);
northPanel.add(
new CLabel(Msg.translate(Env.getCtx(), "DateTo")),
new GridBagConstraints(4, 1, 1, 1, 0.0, 0.0,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)
);
northPanel.add(
dateTo,
new GridBagConstraints(5, 1, 1, 1, 0.0, 0.0,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)
);
ConfirmPanel confirmPanel = new ConfirmPanel(true);
confirmPanel.addActionListener(new ActionHandler());
contentPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
contentPanel.setPreferredSize(new Dimension(800, 600));
getWindow().getContentPane().add(northPanel, BorderLayout.NORTH);
getWindow().getContentPane().add(contentPanel, BorderLayout.CENTER);
getWindow().getContentPane().add(confirmPanel, BorderLayout.SOUTH);
}
private void fillPicks() {
Properties ctx = Env.getCtx();
// Hardcoded Column ID - Manufacturing Resource ID
MLookup resourceL = MLookupFactory.get (ctx, getWindowNo(), 0, MColumn.getColumn_ID(MResource.Table_Name,"S_Resource_ID"), DisplayType.TableDir);
resource = new VLookup ("S_Resource_ID", false, false, true, resourceL);
}
protected JPopupMenu createPopup(JTree tree) {
JPopupMenu pm = new JPopupMenu();
PopupAction action = null;
try {
action = new ZoomMenuAction(tree);
pm.add(action);
}
catch(Exception e) {
e.printStackTrace();
}
return pm;
}
private void handleTreeEvent(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON3) {
model.getTree().setSelectionPath(model.getTree().getPathForLocation(e.getX(), e.getY()));
DefaultMutableTreeNode node = (DefaultMutableTreeNode)model.getTree().getSelectionPath().getLastPathComponent();
if(!(node.getUserObject() instanceof Date) && !(node.getUserObject() instanceof MPPOrderNode)) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
SwingTool.setCursorsFromChild(e.getComponent(), false);
}
private void handleActionEvent(ActionEvent e) {
Timestamp df = getDateFrom();
Timestamp dt = getDateTo();
MResource r = getResource();
if (df != null && dt != null && r != null) {
model = CRPDatasetFactory.get(df, dt, r);
JFreeChart jfreechart = createChart(model.getDataset(), getChartTitle(), getSourceUOM());
chartPanel = new ChartPanel(jfreechart, false);
contentPanel.setLeftComponent(chartPanel);
JTree tree = model.getTree();
tree.addMouseListener(new TreeHandler());
contentPanel.setRightComponent(new JScrollPane(tree));
popup = createPopup(tree);
contentPanel.setVisible(true);
contentPanel.validate();
contentPanel.repaint();
}
SwingTool.setCursorsFromParent(getWindow(), false);
}
private String getChartTitle() {
MResource r = getResource();
String title = r.getName() != null ? r.getName() : "";
title = title + " " + r.getDescription() != null ? r.getDescription() : "";
return title;
}
public Timestamp getDateFrom() {
Timestamp t = null;
if(dateFrom.getValue() != null) {
t = (Timestamp)dateFrom.getValue();
}
return t;
}
public Timestamp getDateTo() {
Timestamp t = null;
if(dateTo.getValue() != null) {
t = (Timestamp)dateTo.getValue();
}
return t;
}
public MUOM getSourceUOM() {
MResource r = getResource();
int uom_id = r.getResourceType().getC_UOM_ID();
return (uom_id > 0) ? MUOM.get(Env.getCtx(),uom_id) : null;
}
public MResource getResource() {
MResource r = null;
if(resource.getValue() != null) {
r = MResource.get(Env.getCtx(), ((Integer)resource.getValue()).intValue());
}
return r;
}
public MUOM getTargetUOM() {
MUOM u = null;
if(resource.getValue() != null) {
u = MUOM.get(Env.getCtx(), ((Integer)resource.getValue()).intValue());
}
return u;
}
private JFreeChart createChart(CategoryDataset dataset, String title, MUOM uom) {
JFreeChart chart = ChartFactory.createBarChart3D(
title ,
Msg.translate(Env.getCtx(), "Day"), // X-Axis label
Msg.translate(Env.getCtx(), (uom == null) ? "" : uom.getName()), // Y-Axis label
dataset, // Dataset
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
chart.setBackgroundPaint(Color.WHITE);
chart.setAntiAlias(true);
chart.setBorderVisible(true);
CategoryPlot plot = chart.getCategoryPlot();
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.GRAY);
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.GRAY);
BarRenderer3D barrenderer = (BarRenderer3D)plot.getRenderer();
barrenderer.setDrawBarOutline(false);
barrenderer.setBaseItemLabelGenerator(new LabelGenerator());
//barrenderer.setBaseLabelGenerator(new LabelGenerator());
barrenderer.setBaseItemLabelsVisible(true);
barrenderer.setSeriesPaint(0, new Color(10, 80, 150, 128));
barrenderer.setSeriesPaint(1, new Color(180, 60, 50, 128));
ItemLabelPosition itemlabelposition = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.TOP_CENTER);
barrenderer.setPositiveItemLabelPosition(itemlabelposition);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(
CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
);
return chart;
}
public void dispose() {
super.dispose();
if(resource != null) {
resource.dispose();
}
resource = null;
if(dateFrom != null) {
dateFrom.dispose();
}
dateFrom = null;
if(dateTo != null) {
dateTo.dispose();
}
dateTo = null;
if(worker != null) {
worker.stop();
}
worker = null;
chartPanel = null;
contentPanel = null;
popup = null;
}
}

View File

@ -1,41 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import org.eevolution.model.wrapper.BOMWrapper;
/**
* Order BOM Tree is based on PPOrderBOM.
*
* AD_FORM:
* INSERT INTO ad_form VALUES (1000024, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, 'Order BOM Tree', NULL, NULL, '3', 'org.compiere.mfg.form.COrderBOMTree', 'U', 'N', NULL);
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class COrderBOMTree extends CAbstractBOMTree {
public COrderBOMTree() {
super();
}
protected String type() {
return BOMWrapper.BOM_TYPE_ORDER;
}
}

View File

@ -1,42 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import org.eevolution.model.wrapper.BOMWrapper;
/**
* Product BOM Tree is based on PPProductBOM.
*
* AD_FORM:
* INSERT INTO ad_form VALUES (1000023, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, 'Product BOM Tree', NULL, NULL, '3', 'org.compiere.mfg.form.CProductBOMTree', 'U', 'N', NULL);
*
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class CProductBOMTree extends CAbstractBOMTree {
public CProductBOMTree() {
super();
}
protected String type() {
return BOMWrapper.BOM_TYPE_PRODUCT;
}
}

View File

@ -1,730 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Hashtable;
import java.util.Properties;
import java.util.logging.Level;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VLookup;
import org.compiere.model.MColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MProduct;
import org.compiere.model.MResource;
import org.compiere.model.MResourceType;
import org.compiere.model.MUOM;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.form.crp.CRPDatasetFactory;
import org.eevolution.form.crp.CRPModel;
import org.eevolution.model.MPPMRP;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class VCRP extends CPanel
implements FormPanel, ActionListener
{
// begin vpj
private static CLogger log = CLogger.getCLogger(VCRP.class);
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info( "VCRP.init");
m_WindowNo = WindowNo;
m_frame = frame;
try
{
fillPicks();
jbInit();
/*dynInit();*/
frame.getContentPane().add(northPanel, BorderLayout.NORTH);
frame.getContentPane().add(centerPanel, BorderLayout.CENTER);
frame.getContentPane().add(confirmPanel, BorderLayout.SOUTH);
frame.pack();
//frame.m_maximize=true;
//frame.setMaximize(true);
}
catch(Exception e)
{
log.log(Level.SEVERE, "VCRP.init", e);
}
} // init
private CPanel northPanel = new CPanel();
private CPanel centerPanel = new CPanel();
private BorderLayout centerLayout = new BorderLayout();
private ConfirmPanel confirmPanel = new ConfirmPanel(true);
private Hashtable hash = new Hashtable();
private VLookup resource = null;
private CLabel resourceLabel = new CLabel();
private VDate dateFrom = new VDate("DateFrom", true, false, true, DisplayType.Date, "DateFrom");
private CLabel dateFromLabel = new CLabel();
private int AD_Client_ID = Integer.parseInt(Env.getContext(Env.getCtx(), "#AD_Client_ID"));
//private DefaultCategoryDataset dataset = new DefaultCategoryDataset();
//private JFreeChart chart;
private ChartPanel chartPanel = new ChartPanel(createChart(new DefaultCategoryDataset(), "", null));
protected CRPModel model;
//private CPanel chart = new CPanel();
private void jbInit() throws Exception
{
northPanel.setLayout(new java.awt.GridBagLayout());
resourceLabel.setText(Msg.translate(Env.getCtx(), "S_Resource_ID"));
northPanel.add(resourceLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
northPanel.add(resource , new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
dateFromLabel.setText(Msg.translate(Env.getCtx(), "DateFrom"));
northPanel.add(dateFromLabel, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
northPanel.add(dateFrom, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
chartPanel.setPreferredSize(new Dimension(750, 550));
centerPanel.add(chartPanel, BorderLayout.CENTER);
confirmPanel.addActionListener(this);
}
/**
* Fill Picks
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
Properties ctx = Env.getCtx();
//createChart(dataset);
MLookup resourceL = MLookupFactory.get (ctx, m_WindowNo, 0, MColumn.getColumn_ID(MProduct.Table_Name,"S_Resource_ID"), DisplayType.TableDir);
resource = new VLookup ("S_Resource_ID", false, false, true, resourceL);
} // fillPicks
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
Timestamp date = (Timestamp) dateFrom.getValue();
int S_Resource_ID = ((Integer)resource.getValue()).intValue();
System.out.println("ConfirmPanel.A_OK");
System.out.println("date" + date + " S_Resource_ID " + S_Resource_ID);
if (date != null && S_Resource_ID != 0)
{
System.out.println("Call createDataset(date,S_Resource_ID)");
MResource r = MResource.get(Env.getCtx(), S_Resource_ID);
// Ge<EFBFBD>ndert Anfang 04.08.2005
int uom_id = r.getResourceType().getC_UOM_ID();
MUOM uom = MUOM.get(Env.getCtx(),uom_id);
CategoryDataset dataset = null;
if(uom.isHour()) {
System.out.println("\n ->is Hour<- \n");
dataset = createDataset(date,r);
}
else {
System.out.println("\n ->is not Hour<- \n");
dataset = createWeightDataset(date,r);
}
// Ge<EFBFBD>ndert Ende 04.08.2005
//CategoryDataset dataset = createDataset();
System.out.println("dataset.getRowCount:" +dataset.getRowCount());
String title = r.getName() != null ? r.getName() : "";
title = title + " " + r.getDescription() != null ? r.getDescription() : "";
JFreeChart jfreechart = createChart(dataset, title, uom);
centerPanel.removeAll();
chartPanel = new ChartPanel(jfreechart, false);
centerPanel.add(chartPanel, BorderLayout.CENTER);
centerPanel.setVisible(true);
m_frame.pack();
}
}
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
}
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
private JFreeChart createChart(CategoryDataset dataset , String title, MUOM uom)
{
JFreeChart chart = ChartFactory.createBarChart3D(title," "," ",dataset,PlotOrientation.VERTICAL,true,true,false);
//Hinzugef<EFBFBD>gt Begin 05.08.2005
if(uom == null || uom.isHour())
{
chart = ChartFactory.createBarChart3D
( title ,
Msg.translate(Env.getCtx(), "Days"), // X-Axis label
Msg.translate(Env.getCtx(), "Hours"), // Y-Axis label
dataset, // Dataset
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
// set the background color for the chart...
//chart.setBackgroundPaint(Color.white);
}
//Ge<EFBFBD>ndert 05.08.2005 Anfang
else
{
chart = ChartFactory.createBarChart3D
( title ,
Msg.translate(Env.getCtx(), "Days"), // X-Axis label
Msg.translate(Env.getCtx(), "Kilo"), // Y-Axis label
dataset, // Dataset
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
//chart.setBackgroundPaint(Color.white);
}
//Ge<EFBFBD>ndert 05.08.2005 Ende
/*
// get a reference to the plot for further customisation...
CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDomainGridlinePaint(Color.white);
plot.setDomainGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.white);
// set the range axis to display integers only...
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// disable bar outlines...
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
// set up gradient paints for series...
GradientPaint gp0 = new GradientPaint(
0.0f, 0.0f, Color.blue,
0.0f, 0.0f, new Color(0, 0, 64)
);
GradientPaint gp1 = new GradientPaint(
0.0f, 0.0f, Color.green,
0.0f, 0.0f, new Color(0, 64, 0)
);
GradientPaint gp2 = new GradientPaint(
0.0f, 0.0f, Color.red,
0.0f, 0.0f, new Color(64, 0, 0)
);
renderer.setSeriesPaint(0, gp0);
renderer.setSeriesPaint(1, gp1);
renderer.setSeriesPaint(2, gp2);
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(
CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
);*/
// OPTIONAL CUSTOMISATION COMPLETED.
return chart;
}
// Added at 05.08.2005
// Begin
public CategoryDataset createWeightDataset(Timestamp start, MResource r) {
GregorianCalendar gc1 = new GregorianCalendar();
gc1.setTimeInMillis(start.getTime());
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
String namecapacity = Msg.translate(Env.getCtx(), "Capacity");
String nameload = Msg.translate(Env.getCtx(), "Load");
String namesummary = Msg.translate(Env.getCtx(), "Summary");
String namepossiblecapacity = "Possible Capacity";
MResourceType t = MResourceType.get(Env.getCtx(),r.getS_ResourceType_ID());
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
double currentweight = DB.getSQLValue(null, "Select SUM( (mo.qtyordered-mo.qtydelivered)*(Select mp.weight From m_product mp Where mo.m_product_id=mp.m_product_id ) )From PP_order mo Where ad_client_id=?", r.getAD_Client_ID());
double dailyCapacity = r.getDailyCapacity().doubleValue();
double utilization = r.getPercentUtilization().doubleValue();
double summary = 0;
int day = 0;
while(day < 32) {
day++;
switch(gc1.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
if (t.isOnSunday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
case Calendar.MONDAY:
if (t.isOnMonday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
case Calendar.TUESDAY:
if (t.isOnTuesday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
case Calendar.WEDNESDAY:
if (t.isOnWednesday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
case Calendar.THURSDAY:
if (t.isOnThursday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
case Calendar.FRIDAY:
if (t.isOnFriday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
case Calendar.SATURDAY:
if (t.isOnSaturday()) {
currentweight -= (dailyCapacity*utilization)/100;
summary += ((dailyCapacity*utilization)/100);
dataset.addValue(dailyCapacity ,namepossiblecapacity, new Integer(day));
dataset.addValue((dailyCapacity*utilization)/100, namecapacity, new Integer(day) );
}
else {
dataset.addValue(0,namepossiblecapacity, new Integer(day) );
dataset.addValue(0, namecapacity, new Integer(day) );
}
break;
}
dataset.addValue(currentweight, nameload, new Integer(day));
dataset.addValue(summary, namesummary, new Integer(day) );
gc1.add(Calendar.DATE, 1);
}
return dataset;
}
// End
public CategoryDataset createDataset(Timestamp start ,MResource r)
{
//System.out.println("Create new data set");
GregorianCalendar gc1 = new GregorianCalendar();
gc1.setTimeInMillis(start.getTime());
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
Timestamp date = start;
String namecapacity = Msg.translate(Env.getCtx(), "Capacity");
System.out.println("\n Namecapacity :"+namecapacity);
String nameload = Msg.translate(Env.getCtx(), "Load");
System.out.println("\n Nameload :"+nameload);
String namesummary = Msg.translate(Env.getCtx(), "Summary");
System.out.println("\n Namesummary :"+namesummary);
MResourceType t = MResourceType.get(Env.getCtx(),r.getS_ResourceType_ID());
System.out.println("\n Resourcetype "+t);
int days = 1;
long hours = 0;
if (t.isTimeSlot())
hours = MPPMRP.getHoursAvailable(t.getTimeSlotStart(),t.getTimeSlotEnd());
else
hours = 24;
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
// Long Hours = new Long(hours);
int C_UOM_ID = DB.getSQLValue(null,"SELECT C_UOM_ID FROM M_Product WHERE S_Resource_ID = ? " , r.getS_Resource_ID());
MUOM uom = MUOM.get(Env.getCtx(),C_UOM_ID);
System.out.println("\n uom1 "+uom+"\n");
//System.out.println("um.isHour()"+ uom.isHour() );
if (!uom.isHour())
{
System.out.println("\n uom2 "+uom+"\n");
return dataset;
}
System.out.println("\n Dataset "+dataset+"\n");
long summary = 0;
while(days < 32)
{
//System.out.println("Day Number" + days);
String day = new String(new Integer (date.getDate()).toString());
System.out.println("r.getS_Resource_ID()" + r.getS_Resource_ID());
System.out.println("Date:" + date);
long HoursLoad = getLoad(r,date).longValue();
Long Hours = new Long(hours);
System.out.println("Summary "+ summary);
System.out.println("Hours Load "+ HoursLoad);
switch(gc1.get(Calendar.DAY_OF_WEEK))
{
case Calendar.SUNDAY:
days ++;
if (t.isOnSunday())
{ //System.out.println("si Sunday");
//Msg.translate(Env.getCtx(), "OnSunday");
dataset.addValue(hours, namecapacity, day );
dataset.addValue(HoursLoad ,nameload, day );
dataset.addValue(summary, namesummary, day );
summary = summary + Hours.intValue() - (HoursLoad); //+ (Hours.intValue() - ((seconds / 3600)));
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{ //System.out.println("no Sunday");
//String day = Msg.translate(Env.getCtx(), "OnSunday") ;
dataset.addValue(0, namecapacity, day );
dataset.addValue(HoursLoad , nameload, day);
dataset.addValue(summary, namesummary, day );
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
case Calendar.MONDAY:
days ++;
if (t.isOnMonday())
{ //System.out.println("si Monday");
//String day = Msg.translate(Env.getCtx(), "OnMonday") ;
dataset.addValue(hours, namecapacity, day );
dataset.addValue(HoursLoad , nameload, day );
dataset.addValue(summary, namesummary, day);
summary = summary + Hours.intValue() - (HoursLoad );
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{
//System.out.println("no Monday");
//String day = Msg.translate(Env.getCtx(), "OnMonday") ;
dataset.addValue(0, namecapacity, day );
dataset.addValue(HoursLoad, nameload, day );
dataset.addValue(summary, namesummary, day );
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
case Calendar.TUESDAY:
days ++;
if (t.isOnTuesday())
{ //System.out.println("si TuesDay");
//String day = Msg.translate(Env.getCtx(), "OnTuesday");
dataset.addValue(hours, namecapacity, day );
dataset.addValue(HoursLoad, nameload, day );
dataset.addValue(summary, namesummary, day );
summary = summary + Hours.intValue() - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{
//System.out.println("no TuesDay");
//String day = Msg.translate(Env.getCtx(), "OnTuesday");
dataset.addValue(0, namecapacity, day );
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
case Calendar.WEDNESDAY:
days ++;
if (t.isOnWednesday())
{
//String day = Msg.translate(Env.getCtx(), "OnWednesday");
dataset.addValue(hours, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary + Hours.intValue() - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{
//String day = Msg.translate(Env.getCtx(), "OnWednesday");
dataset.addValue(0, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
case Calendar.THURSDAY:
days ++;
if (t.isOnThursday())
{
//String day = Msg.translate(Env.getCtx(), "OnThursday");
dataset.addValue(hours, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary + Hours.intValue() - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{
//String day = Msg.translate(Env.getCtx(), "OnThursday");
dataset.addValue(0, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
case Calendar.FRIDAY:
days ++;
if (t.isOnFriday())
{
//String day = Msg.translate(Env.getCtx(), "OnFriday");
dataset.addValue(hours, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary + Hours.intValue() - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{
//String day = Msg.translate(Env.getCtx(), "OnFriday");
dataset.addValue(0, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
case Calendar.SATURDAY:
days ++;
if (t.isOnSaturday())
{
//String day = Msg.translate(Env.getCtx(), "OnSaturday");
dataset.addValue(hours, namecapacity, day);
dataset.addValue(HoursLoad,nameload, day);
dataset.addValue(summary,namesummary, day);
summary = summary + Hours.intValue() - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
else
{
//String day = Msg.translate(Env.getCtx(), "OnSaturday");
dataset.addValue(0, namecapacity, day);
dataset.addValue(HoursLoad, nameload, day);
dataset.addValue(summary, namesummary, day);
summary = summary - (HoursLoad);
gc1.add(Calendar.DATE, 1);
date = new Timestamp(gc1.getTimeInMillis());
break;
}
}
}
return dataset;
}
private BigDecimal getLoad(MResource r, Timestamp start)
{
model = CRPDatasetFactory.get(start, start, r);
return model.calculateLoad(start, r, null);
}
}

View File

@ -1,734 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Contributor(s): Oscar Gomez & Victor Perez www.e-evolution.com *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.logging.Level;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VComboBox;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VNumber;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MRole;
import org.compiere.model.MTable;
import org.compiere.model.X_AD_Ref_List;
import org.compiere.plaf.CompiereColor;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTextField;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.eevolution.model.MHRConcept;
import org.eevolution.model.MHRMovement;
import org.eevolution.model.MHRProcess;
import org.eevolution.model.X_HR_Period;
/**
* 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 Oscar Gomez
* @version $Id: VHRIncidence.java
*/
public class VHRActionNotice extends CPanel
implements FormPanel,VetoableChangeListener, ActionListener
{
/** @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;
jbInit();
dynInit();
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.setSize(1000, 400);
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
/** Format */
private DecimalFormat aformat = DisplayType.getNumberFormat(DisplayType.Amount);
private DecimalFormat qformat = DisplayType.getNumberFormat(DisplayType.Quantity);
//Language language = Language.getLoginLanguage();// Base Language
/** Client ID */
private int m_AD_Client_ID = 0;
private int HR_Process_ID = 0;
private int C_BPartner_ID = 0;
private int HR_Concept_ID = 0;
private int HR_Period_ID = 0;
private int HR_Payroll_ID = 0;
private int sHR_Movement_ID = 0; // // initial not exist record in Movement to actual date
private Timestamp dateStart = null;
private Timestamp dateEnd = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VHRActionNotice.class);
//
private CPanel mainPanel = new CPanel();
private BorderLayout mainLayout = new BorderLayout();
private CPanel parameterPanel = new CPanel();
private CLabel labelProcess = new CLabel();
private VComboBox fieldProcess; // = new VComboBox();
private CLabel labelEmployee = new CLabel();
private VComboBox fieldEmployee = new VComboBox();
private CLabel labelColumnType = new CLabel();
private CTextField fieldColumnType = new CTextField(18);
private CLabel labelConcept = new CLabel();
private VComboBox fieldConcept = new VComboBox();
private JLabel labelValue = new JLabel();
private VNumber fieldQty = new VNumber();
private VNumber fieldAmount = new VNumber();
private VDate fieldDate = new VDate();
private CTextField fieldText = new CTextField(22);
private VNumber fieldRuleE = new VNumber();
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 bOk = ConfirmPanel.createOKButton(true);
private CLabel labelValidFrom = new CLabel();
private VDate fieldValidFrom = new VDate();
private CLabel labelDescription = new CLabel();
private CTextField fieldDescription = new CTextField(22);
private GridBagLayout parameterLayout = new GridBagLayout();
/**
* Static Init
* @throws Exception
*/
private void jbInit()
{
CompiereColor.setBackground(this);
mainPanel.setLayout(mainLayout);
///mainPanel.setSize(500, 500);
mainPanel.setPreferredSize(new Dimension(1000, 400));
parameterPanel.setLayout(parameterLayout);
// Process
labelProcess.setText(Msg.translate(Env.getCtx(), "Process"));
fieldProcess = new VComboBox(getProcess());
fieldProcess.setMandatory(true);
fieldProcess.addActionListener(this);
// Employee
labelEmployee.setText(Msg.translate(Env.getCtx(), "Employee"));
fieldEmployee.setReadWrite(false);
fieldEmployee.setMandatory(true);
fieldEmployee.addActionListener(this);
fieldEmployee.addVetoableChangeListener(this);
// Concept
labelConcept.setText(Msg.translate(Env.getCtx(), "Concept"));
getConceptValid();
fieldConcept.setReadWrite(false);
fieldConcept.setMandatory(true);
fieldConcept.addActionListener(this);
// ValidFrom
labelValidFrom.setText(Msg.translate(Env.getCtx(), "Date"));
fieldValidFrom.setReadWrite(false);
fieldValidFrom.setMandatory(true);
fieldValidFrom.addVetoableChangeListener(this);
// Description
labelDescription.setText(Msg.translate(Env.getCtx(), "Description"));
fieldDescription.setValue("");
fieldDescription.setReadWrite(false);
// ColumnType
labelColumnType.setText(Msg.getMsg(Env.getCtx(), "ColumnType"));
fieldColumnType.setReadWrite(false);
// Qty-Amount-Date-Text-RuleEngine
fieldQty.setReadWrite(false);
fieldQty.setDisplayType(DisplayType.Quantity);
fieldQty.setVisible(true);
fieldAmount.setDisplayType(DisplayType.Amount);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
//
bOk.addActionListener(this);
//
mainPanel.add(parameterPanel, BorderLayout.NORTH);
// Process
parameterPanel.add(labelProcess, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldProcess, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
// Employee
parameterPanel.add(labelEmployee, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldEmployee, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
// ValidFrom
parameterPanel.add(labelValidFrom, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldValidFrom, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
// Concepto
parameterPanel.add(labelConcept, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldConcept, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// ColumnType
parameterPanel.add(labelColumnType, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldColumnType, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Qty-Amount-Date-Text-RuleEngine
parameterPanel.add(labelValue, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldQty, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldAmount, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldDate, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldText, new GridBagConstraints(3, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Description
parameterPanel.add(labelDescription, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
parameterPanel.add(fieldDescription, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Refresh
parameterPanel.add(bOk, new GridBagConstraints(3, 3, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
// Agree
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);
} // jbInit
/**
* Dynamic Init.
* - Load Bank Info
* - Load BPartner
* - Init Table
*/
private void dynInit()
{
miniTable.addColumn("HR_Movement_ID"); // 0
miniTable.addColumn("AD_Org_ID"); // 1
miniTable.addColumn("HR_Concept_ID"); // 2
miniTable.addColumn("ValidFrom"); // 3
miniTable.addColumn("ColumnType"); // 4
miniTable.addColumn("Qty"); // 5
miniTable.addColumn("Amount"); // 6
miniTable.addColumn("ServiceDate"); // 7
miniTable.addColumn("Text"); // 8
miniTable.addColumn("AD_Rule_ID"); // 9
miniTable.addColumn("Description"); // 10
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "HR_Concept_ID"));
miniTable.setColumnClass(3, Timestamp.class, true, Msg.translate(Env.getCtx(), "ValidFrom"));
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "ColumnType"));
miniTable.setColumnClass(5, BigDecimal.class, true, Msg.translate(Env.getCtx(), "Qty"));
miniTable.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "Amount"));
miniTable.setColumnClass(7, Timestamp.class, true, Msg.translate(Env.getCtx(), "ServiceDate"));
miniTable.setColumnClass(8, String.class, true, Msg.translate(Env.getCtx(), "Text"));
miniTable.setColumnClass(9, String.class, true, Msg.translate(Env.getCtx(), "AD_Rule_ID"));
miniTable.setColumnClass(10, String.class, true, Msg.translate(Env.getCtx(), "Description"));
//
miniTable.autoSize();
} // dynInit
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**************************************************************************
* vetoableChange
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e) throws PropertyVetoException
{
fieldConcept.setReadWrite(true);
log.fine("Event"+ e);
log.fine("Event Source "+ e.getSource());
log.fine("Event Property "+ e.getPropertyName());
//if (e.getPropertyName().equals("AD_Org_ID"))
if ( e.getSource().equals(fieldProcess) ) { // Process
KeyNamePair pp = (KeyNamePair)fieldProcess.getSelectedItem();
if (pp != null){
HR_Process_ID = pp.getKey();
MHRProcess process = new MHRProcess(Env.getCtx(),HR_Process_ID,null);
dateStart= new X_HR_Period(Env.getCtx(),process.getHR_Period_ID(),null).getStartDate();
dateEnd = new X_HR_Period(Env.getCtx(),process.getHR_Period_ID(),null).getEndDate();
HR_Period_ID = process.getHR_Period_ID();
HR_Payroll_ID = process.getHR_Payroll_ID();
getEmployeeValid(new MHRProcess(Env.getCtx(),HR_Process_ID,null));
fieldEmployee.setReadWrite(true);
}
}
else if ( e.getSource().equals(fieldEmployee) ){ // Employee
KeyNamePair pp = (KeyNamePair)fieldEmployee.getSelectedItem();
int C_BPartner_ID = 0;
if ( pp != null )
C_BPartner_ID = pp.getKey();
if ( C_BPartner_ID > 0){
fieldValidFrom.setValue(dateEnd);
fieldValidFrom.setReadWrite(true);
getConceptValid();
fieldConcept.setReadWrite(true);
executeQuery();
}
}
else if ( e.getSource().equals(fieldConcept) ) { // Concept
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = 0;
if (pp != null)
HR_Concept_ID = pp.getKey();
if ( HR_Concept_ID > 0 ){
MHRConcept concept = new MHRConcept (Env.getCtx(),HR_Concept_ID,null);
// Name To Type Column
fieldColumnType.setValue(DB.getSQLValueString(null, getSQL_ColumnType("?"), concept.getColumnType() ));
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
//
if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity)){ // Concept Type
fieldQty.setVisible(true);
fieldQty.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount)){
fieldQty.setVisible(false);
fieldAmount.setVisible(true);
fieldAmount.setReadWrite(true);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date)){
fieldQty.setVisible(false);
fieldAmount.setVisible(false);
fieldDate.setVisible(true);
fieldDate.setReadWrite(true);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text)){
fieldText.setVisible(true);
fieldText.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldRuleE.setVisible(false);
}
fieldDescription.setReadWrite(true);
}
} // Concept
Integer HR_Period_ID = new MHRProcess(Env.getCtx(),(Integer)fieldProcess.getValue(),null).getHR_Period_ID();
String date = DB.TO_DATE((Timestamp)fieldValidFrom.getValue());
int existRange = DB.getSQLValue("HR_Period","SELECT * FROM HR_Period WHERE " +date+
" >= StartDate AND "+date+ " <= EndDate AND HR_Period_ID = "+HR_Period_ID);
// Exist of Range Payroll
if ( existRange < 0){
fieldConcept.setReadWrite(false);
return;
}
if (fieldConcept != null)
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
} // actionPerformed
/**************************************************************************
* Action Listener
* @param e event
*/
public void actionPerformed(ActionEvent e)
{
log.fine("Event "+ e);
log.fine("Event Source "+ e.getSource());
if ( e.getSource().equals(fieldProcess) ) { // Process
KeyNamePair pp = (KeyNamePair)fieldProcess.getSelectedItem();
if (pp != null){
HR_Process_ID = pp.getKey();
MHRProcess process = new MHRProcess(Env.getCtx(),HR_Process_ID,null);
dateStart= new X_HR_Period(Env.getCtx(),process.getHR_Period_ID(),null).getStartDate();
dateEnd = new X_HR_Period(Env.getCtx(),process.getHR_Period_ID(),null).getEndDate();
HR_Period_ID = process.getHR_Period_ID();
HR_Payroll_ID = process.getHR_Payroll_ID();
getEmployeeValid(new MHRProcess(Env.getCtx(),HR_Process_ID,null));
fieldEmployee.setReadWrite(true);
}
}
else if ( e.getSource().equals(fieldEmployee) ){ // Employee
KeyNamePair pp = (KeyNamePair)fieldEmployee.getSelectedItem();
int C_BPartner_ID = 0;
if ( pp != null )
C_BPartner_ID = pp.getKey();
if ( C_BPartner_ID > 0){
fieldValidFrom.setValue(dateEnd);
fieldValidFrom.setReadWrite(true);
getConceptValid();
fieldConcept.setReadWrite(true);
executeQuery();
}
}
else if ( e.getSource().equals(fieldConcept) ) { // Concept
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = 0;
if (pp != null)
HR_Concept_ID = pp.getKey();
if ( HR_Concept_ID > 0 ) {
MHRConcept concept = new MHRConcept (Env.getCtx(),HR_Concept_ID,null);
// Name To Type Column
fieldColumnType.setValue(DB.getSQLValueString(null, getSQL_ColumnType("?"), concept.getColumnType() ));
sHR_Movement_ID = seekMovement(); // exist movement record to date actual
//
if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity)){ // Concept Type
fieldQty.setVisible(true);
fieldQty.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount)){
fieldQty.setVisible(false);
fieldAmount.setVisible(true);
fieldAmount.setReadWrite(true);
fieldDate.setVisible(false);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date)){
fieldQty.setVisible(false);
fieldAmount.setVisible(false);
fieldDate.setVisible(true);
fieldDate.setReadWrite(true);
fieldText.setVisible(false);
fieldRuleE.setVisible(false);
} else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text)){
fieldText.setVisible(true);
fieldText.setReadWrite(true);
fieldAmount.setVisible(false);
fieldDate.setVisible(false);
fieldRuleE.setVisible(false);
}
fieldDescription.setReadWrite(true);
}
} // Concept
else if (e.getSource().equals(bOk) ){ // Movement SAVE
KeyNamePair pp = (KeyNamePair)fieldConcept.getSelectedItem();
int HR_Concept_ID = pp.getKey();
MHRConcept conceptOK = new MHRConcept(Env.getCtx(),HR_Concept_ID,null);
int mov = sHR_Movement_ID > 0 ? sHR_Movement_ID : 0;
MHRMovement movementOK = new MHRMovement(Env.getCtx(),mov,null);
movementOK.setDescription((String)fieldDescription.getValue().toString());
movementOK.setHR_Process_ID((Integer)fieldProcess.getValue());
movementOK.setC_BPartner_ID((Integer)fieldEmployee.getValue());
movementOK.setHR_Concept_ID((Integer)fieldConcept.getValue());
movementOK.setColumnType(conceptOK.getColumnType());
movementOK.setQty(fieldQty.getValue() != null ? (BigDecimal)fieldQty.getValue() : Env.ZERO);
movementOK.setAmount(fieldAmount.getValue() != null ? (BigDecimal)fieldAmount.getValue() : Env.ZERO );
movementOK.setTextMsg(fieldText.getValue() != null ? "" : (String)fieldText.getValue().toString());
movementOK.setValidFrom((Timestamp)fieldValidFrom.getTimestamp());
movementOK.setValidTo((Timestamp)fieldValidFrom.getTimestamp());
movementOK.save();
executeQuery();
fieldValidFrom.setValue(dateEnd);
fieldColumnType.setValue("");
fieldQty.setValue(Env.ZERO);
fieldAmount.setValue(Env.ZERO);
fieldQty.setReadWrite(false);
fieldAmount.setReadWrite(false);
fieldText.setReadWrite(false);
fieldDescription.setValue("");
fieldDescription.setReadWrite(false);
sHR_Movement_ID = 0; // Initial not exist record in Movement to actual date
}
}
/**
* Query Info
*/
private void executeQuery()
{
StringBuffer sqlQuery = new StringBuffer("SELECT o.Name,hp.Name," // AD_Org_ID, HR_Process_ID -- 1,2
+ " bp.Name,hc.Name,hm.ValidFrom," // HR_Employee_ID,HR_Concept_ID,ValidFrom,ColumnType -- 3,4,5
+ "("+getSQL_ColumnType("hc.ColumnType")+") AS ColumnType," // 6 ColumnType(Reference Name)
+ " hm.Qty,hm.Amount,hm.ServiceDate,hm.TextMsg,er.Name,hm.Description " // Qty,Amount,ServiceDate,Text,AD_Rule_ID,Description -- 7,8,9,10,11,12
+ " FROM HR_Movement hm "
+ " INNER JOIN AD_Org o ON (hm.AD_Org_ID=o.AD_Org_ID)"
+ " INNER JOIN HR_Process hp ON (hm.HR_Process_ID=hp.HR_Process_ID)"
+ " INNER JOIN C_BPartner bp ON (hm.C_BPartner_ID=bp.C_BPartner_ID)"
+ " INNER JOIN HR_Employee e ON (e.C_BPartner_ID=bp.C_BPartner_ID)"
+ " INNER JOIN HR_Concept hc ON (hm.HR_Concept_ID=hc.HR_Concept_ID)"
+ " LEFT OUTER JOIN AD_Rule er ON (hm.AD_Rule_ID=er.AD_Rule_ID)"
+ " WHERE hm.Processed='N' AND hp.HR_Process_ID = " +fieldProcess.getValue()
//+ " AND IsStatic = 'Y' " // Solo aplique Incidencias [add 30Dic2006 para ver Todo]
+ " AND hm.C_BPartner_ID = " + fieldEmployee.getValue()
+ " AND (Qty > 0 OR Amount > 0 OR hm.TextMsg IS NOT NULL OR ServiceDate IS NOT NULL) ");
if (fieldValidFrom.getValue() == null) {
sqlQuery.append(" AND " +DB.TO_DATE(dateStart)+" >= hm.ValidFrom AND "+DB.TO_DATE(dateEnd)+" <= hm.ValidTo ");
}
sqlQuery.append(" ORDER BY hm.AD_Org_ID,hp.HR_Process_ID,bp.Name,hm.ValidFrom,hm.HR_Concept_ID");
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = DB.prepareStatement(sqlQuery.toString(), null);
rs = pstmt.executeQuery();
while (rs.next()) {
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setValueAt(rs.getString(1), row, 1); // AD_Org_ID
miniTable.setValueAt(rs.getString(4), row, 2); // HR_Concept_ID
miniTable.setValueAt(rs.getTimestamp(5), row, 3); // ValidFrom
miniTable.setValueAt(rs.getString(6), row, 4); // ColumnType
miniTable.setValueAt(rs.getObject(7) != null ? rs.getBigDecimal(7) : Env.ZERO, row, 5); // Qty
miniTable.setValueAt(rs.getObject(8) != null ? rs.getBigDecimal(8) : Env.ZERO, row, 6); // Amount
miniTable.setValueAt(rs.getTimestamp(9), row, 7); // ServiceDate
miniTable.setValueAt(rs.getString(10), row, 8); // TextMsg
miniTable.setValueAt(rs.getString(11), row, 9); // AD_Rule_ID
miniTable.setValueAt(rs.getString(12), row, 10); // Description
// prepare next
row++;
}
}
catch (SQLException e) {
log.log(Level.SEVERE, sqlQuery.toString(), e);
}
finally {
DB.close(rs, pstmt);
rs = null; pstmt = null;
}
miniTable.autoSize();
} // executeQuery
/**
* get Process
* parameter: MHRProcess
*/
private KeyNamePair[] getProcess()
{
String sql = MRole.getDefault().addAccessSQL(
"SELECT hrp.HR_Process_ID,hrp.DocumentNo ||'-'|| hrp.Name,hrp.DocumentNo,hrp.Name FROM HR_Process hrp",
"hrp",MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO) + " AND hrp.IsActive = 'Y' ";
sql += " ORDER BY hrp.DocumentNo, hrp.Name";
return DB.getKeyNamePairs(sql, true);
} //getProcess
/**
* get Employee
* to Valid Payroll-Departmant-Employee of Process Actual
* parameter: MHRProcess
*/
private void getEmployeeValid(MHRProcess process)
{
if(process == null)
return;
//fieldEmployee.removeAllItems(); // Limpia antes de Agregar
KeyNamePair pp = new KeyNamePair(0, "");
fieldEmployee.addItem(pp);
String sql = MRole.getDefault().addAccessSQL(
"SELECT bp.C_BPartner_ID,bp.Name FROM HR_Employee hrpe INNER JOIN C_BPartner bp ON(bp.C_BPartner_ID=hrpe.C_BPartner_ID)",
"hrpe",MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO) + " AND hrpe.IsActive = 'Y' ";
if ( process.getHR_Payroll_ID() != 0){
sql += " AND (hrpe.HR_Payroll_ID =" +process.getHR_Payroll_ID()+ " OR hrpe.HR_Payroll_ID is NULL)" ;
/*if ( process.getHR_Department_ID() != 0 );
sql += " AND (hrpe.HR_Department_ID =" +process.getHR_Department_ID()+" OR hrpe.HR_Department_ID is NULL)" ;
if ( process.getHR_Employee_ID() != 0 );
sql += " AND (hrpe.HR_Employee_ID =" + process.getHR_Employee_ID()+" OR hrpe.HR_Employee_ID is NULL)" ;*/
}
sql += " ORDER BY bp.Name ";
try{
PreparedStatement pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
fieldEmployee.addItem(pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e){
log.log(Level.SEVERE, sql, e);
}
fieldEmployee.setSelectedIndex(0);
} //getEmployeeValid
/**
* get Concept
* to Valide Dates of Process
* parameter: MHRProcess
*/
private void getConceptValid()
{
if( fieldProcess == null )
return;
//fieldConcept.removeAllItems(); // Limpia antes de Agregar
KeyNamePair pp = new KeyNamePair(0, "");
fieldConcept.addItem(pp);
String sql = "SELECT hrpc.HR_Concept_ID,hrpc.Name,hrpc.Value "
+ " FROM HR_Concept hrpc "
+ " INNER JOIN HR_Attribute hrpa ON (hrpa.HR_Concept_ID=hrpc.HR_Concept_ID)"
+ " WHERE hrpc.AD_Client_ID = " +Env.getAD_Client_ID(Env.getCtx())
+ " AND hrpc.IsActive = 'Y' AND hrpc.IsRegistered = 'Y' "
+ " AND (hrpa.HR_Payroll_ID = " +HR_Payroll_ID+ "OR hrpa.HR_Payroll_ID IS NULL)";
if (fieldProcess != null){ // Process
; //sql += " AND " +DB.TO_DATE(dateStart)+ " >= hrpa.ValidFrom AND " +DB.TO_DATE(dateEnd)+ "<= hrpa.ValidTo";
/* if (process.getHR_Payroll_ID() != 0) // Process & Payroll
sql = sql + " AND (hrpa.HR_Payroll_ID = " +process.getHR_Payroll_ID()+ " OR hrpa.HR_Payroll_ID is NULL)" ;
if (process.getHR_Department_ID() != 0 ); // Process & Department
sql = sql + " AND (hrpa.HR_Department_ID = " +process.getHR_Department_ID()+" OR hrpa.HR_Department_ID is NULL)" ;
if (process.getHR_Department_ID() != 0 ); // Process & Employee
sql = sql + " AND (hrpa.HR_Employee_ID = " + process.getHR_Employee_ID()+" OR hrpa.HR_Employee_ID is NULL)" ;*/
}
sql = sql +" ORDER BY hrpc.Value";
try {
PreparedStatement pstmt = DB.prepareStatement(sql, null);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
pp = new KeyNamePair(rs.getInt(1), rs.getString(2));
fieldConcept.addItem(pp);
}
rs.close();
pstmt.close();
}
catch (SQLException e){
log.log(Level.SEVERE, sql, e);
}
fieldConcept.setSelectedIndex(0);
} //getConceptValid
/**
* get record Found to Movement Payroll
* parameter:
*/
public int seekMovement()
{
if(fieldConcept.getValue() == null )
return 0;
int HR_Movement_ID = 0;
String date = DB.TO_DATE((Timestamp)fieldValidFrom.getValue());
int Process_ID = 0; KeyNamePair ppp = (KeyNamePair)fieldProcess.getSelectedItem();
int Employee_ID = 0; KeyNamePair ppe = (KeyNamePair)fieldEmployee.getSelectedItem();
int Concept_ID = 0; KeyNamePair ppc = (KeyNamePair)fieldConcept.getSelectedItem();
//
Process_ID = ppp != null ? ppp.getKey(): null;
Employee_ID = ppe != null ? ppe.getKey(): null;
Concept_ID = ppc != null ? ppc.getKey(): null;
MHRConcept concept = new MHRConcept(Env.getCtx(),Concept_ID,null);
//
if ( (Process_ID+Employee_ID+Concept_ID) > 0 ){
HR_Movement_ID = DB.getSQLValue("Movement","SELECT HR_Movement_ID "
+" FROM HR_Movement WHERE HR_Process_ID = "+Process_ID
+" AND C_BPartner_ID =" +Employee_ID+ " AND HR_Concept_ID = "+Concept_ID
+" AND TRUNC(ValidFrom) = TRUNC(" + date +")");
if (HR_Movement_ID > 0){ // exist record in Movement Payroll
sHR_Movement_ID = HR_Movement_ID;
MHRMovement movementFound = new MHRMovement(Env.getCtx(),sHR_Movement_ID,null);
//
fieldDescription.setValue(movementFound.getDescription());
if ( concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Quantity) ) // Quantity
fieldQty.setValue(movementFound.getQty());
else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Amount) ) // Amount
fieldAmount.setValue(movementFound.getAmount());
else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Text) ) // Text
fieldText.setValue(movementFound.getTextMsg());
else if (concept.getColumnType().equals(MHRConcept.COLUMNTYPE_Date) ) // Date
fieldDate.setValue(movementFound.getServiceDate());
}
}
return HR_Movement_ID;
} //seekMovement
/**
* Get SQL Code of ColumnType for given sqlValue
* @param sqlValue
* @return sql select code
*/
private String getSQL_ColumnType(String sqlValue) {
int columnType_Ref_ID = MTable.get(Env.getCtx(), MHRConcept.Table_ID)
.getColumn(MHRConcept.COLUMNNAME_ColumnType)
.getAD_Reference_Value_ID();
String sql;
if (Env.isBaseLanguage(Env.getCtx(), X_AD_Ref_List.Table_Name)) {
sql = "SELECT zz.Name FROM AD_Ref_List zz WHERE zz.AD_Reference_ID="+columnType_Ref_ID;
}
else {
sql = "SELECT zz.Name FROM AD_Ref_List zz, AD_Ref_List_Trl zzt"
+" WHERE zz.AD_Reference_ID="+columnType_Ref_ID
+" AND zzt.AD_Ref_List_ID=zz.AD_Ref_List_ID"
+" AND zzt.AD_Language="+DB.TO_STRING(Env.getAD_Language(Env.getCtx()));
}
sql += " AND zz.Value = "+sqlValue;
return sql;
}
} // VIncidence

View File

@ -1,893 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Contributor(s): Victor Perez www.e-evolution.com *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.adempiere.plaf.AdempierePLAF;
import org.compiere.apps.ADialog;
import org.compiere.apps.ADialogDialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.ProcessCtl;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VComboBox;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MOrder;
import org.compiere.model.MPInstance;
import org.compiere.model.MPInstancePara;
import org.compiere.model.MPrivateAccess;
import org.compiere.model.MRMA;
import org.compiere.plaf.CompiereColor;
import org.compiere.print.ReportCtl;
import org.compiere.print.ReportEngine;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoUtil;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTabbedPane;
import org.compiere.swing.CTextPane;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
/**
* Manual Shipment Selection
*
* @author victor.perez@e-evolution.com
* @version $Id: VInOutInvoiceGen.java
*/
public class VInOutInvoiceGen extends CPanel
implements FormPanel, ActionListener, VetoableChangeListener,
ChangeListener, TableModelListener, ASyncProcess
{
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info("");
m_WindowNo = WindowNo;
m_frame = frame;
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "Y");
try
{
fillPicks();
jbInit();
dynInit();
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
}
catch(Exception ex)
{
log.log(Level.SEVERE, "init", ex);
}
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private boolean m_selectionActive = true;
private Object m_M_Warehouse_ID = null;
private Object m_C_BPartner_ID = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VInOutInvoiceGen.class);
//
private CTabbedPane tabbedPane = new CTabbedPane();
private CPanel selPanel = new CPanel();
private CPanel selNorthPanel = new CPanel();
private BorderLayout selPanelLayout = new BorderLayout();
private CLabel lWarehouse = new CLabel();
private VLookup fWarehouse;
private CLabel lBPartner = new CLabel();
private VLookup fBPartner;
private FlowLayout northPanelLayout = new FlowLayout();
private ConfirmPanel confirmPanelSel = new ConfirmPanel(true);
private ConfirmPanel confirmPanelGen = new ConfirmPanel(false, true, false, false, false, false, true);
private StatusBar statusBar = new StatusBar();
private CPanel genPanel = new CPanel();
private BorderLayout genLayout = new BorderLayout();
private CTextPane info = new CTextPane();
private JScrollPane scrollPane = new JScrollPane();
private MiniTable miniTable = new MiniTable();
private CLabel lDocType = new CLabel();
private VComboBox cmbDocType = new VComboBox();
/** User selection */
private ArrayList<Integer> selection = null;
private StringBuffer iText = new StringBuffer();
/**
* Static Init.
* <pre>
* selPanel (tabbed)
* fOrg, fBPartner
* scrollPane & miniTable
* genPanel
* info
* </pre>
* @throws Exception
*/
void jbInit() throws Exception
{
CompiereColor.setBackground(this);
//
selPanel.setLayout(selPanelLayout);
lWarehouse.setLabelFor(fWarehouse);
lBPartner.setLabelFor(fBPartner);
lBPartner.setText("BPartner");
selNorthPanel.setLayout(northPanelLayout);
northPanelLayout.setAlignment(FlowLayout.LEFT);
tabbedPane.add(selPanel, Msg.getMsg(Env.getCtx(), "Select"));
selPanel.add(selNorthPanel, BorderLayout.NORTH);
selNorthPanel.add(lWarehouse, null);
selNorthPanel.add(fWarehouse, null);
selNorthPanel.add(lBPartner, null);
selNorthPanel.add(fBPartner, null);
selPanel.setName("selPanel");
selPanel.add(confirmPanelSel, BorderLayout.SOUTH);
selPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(miniTable, null);
confirmPanelSel.addActionListener(this);
//
tabbedPane.add(genPanel, Msg.getMsg(Env.getCtx(), "Generate"));
genPanel.setLayout(genLayout);
genPanel.add(info, BorderLayout.CENTER);
genPanel.setEnabled(false);
info.setBackground(AdempierePLAF.getFieldBackground_Inactive());
info.setEditable(false);
genPanel.add(confirmPanelGen, BorderLayout.SOUTH);
confirmPanelGen.addActionListener(this);
lDocType.setLabelFor(cmbDocType);
selNorthPanel.add(lDocType, null);
selNorthPanel.add(cmbDocType, null);
} // jbInit
/**
* Fill Picks.
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
// C_OrderLine.M_Warehouse_ID
MLookup orgL = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 2223, DisplayType.TableDir);
fWarehouse = new VLookup ("M_Warehouse_ID", true, false, true, orgL);
lWarehouse.setText(Msg.translate(Env.getCtx(), "M_Warehouse_ID"));
fWarehouse.addVetoableChangeListener(this);
m_M_Warehouse_ID = fWarehouse.getValue();
// C_Order.C_BPartner_ID
MLookup bpL = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 2762, DisplayType.Search);
fBPartner = new VLookup ("C_BPartner_ID", false, false, true, bpL);
lBPartner.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID"));
fBPartner.addVetoableChangeListener(this);
//Document Type Sales Order/Vendor RMA
lDocType.setText(Msg.translate(Env.getCtx(), "C_DocType_ID"));
cmbDocType.addItem(new KeyNamePair(MOrder.Table_ID, Msg.translate(Env.getCtx(), "Order")));
cmbDocType.addItem(new KeyNamePair(MRMA.Table_ID, Msg.translate(Env.getCtx(), "VendorRMA")));
cmbDocType.addActionListener(this);
} // fillPicks
/**
* Dynamic Init.
* - Create GridController & Panel
* - AD_Column_ID from C_Order
*/
private void dynInit()
{
// create Columns
miniTable.addColumn("C_Order_ID");
miniTable.addColumn("AD_Org_ID");
miniTable.addColumn("C_DocType_ID");
miniTable.addColumn("DocumentNo");
miniTable.addColumn("C_BPartner_ID");
miniTable.addColumn("DateOrdered");
miniTable.addColumn("TotalLines");
//
miniTable.setMultiSelection(true);
miniTable.setRowSelectionAllowed(true);
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "C_DocType_ID"));
miniTable.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "DocumentNo"));
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "C_BPartner_ID"));
miniTable.setColumnClass(5, Timestamp.class, true, Msg.translate(Env.getCtx(), "DateOrdered"));
miniTable.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
//
miniTable.autoSize();
miniTable.getModel().addTableModelListener(this);
// Info
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InOutGenerateSel"));//@@
statusBar.setStatusDB(" ");
// Tabbed Pane Listener
tabbedPane.addChangeListener(this);
} // dynInit
/**
* Get SQL for Orders that needs to be shipped
* @return sql
*/
private String getOrderSQL()
{
// Create SQL
StringBuffer sql = new StringBuffer(
"SELECT C_Order_ID, o.Name, dt.Name, DocumentNo, bp.Name, DateOrdered, TotalLines "
+ "FROM M_InOut_Candidate_v ic, AD_Org o, C_BPartner bp, C_DocType dt "
+ "WHERE ic.AD_Org_ID=o.AD_Org_ID"
+ " AND ic.C_BPartner_ID=bp.C_BPartner_ID"
+ " AND ic.C_DocType_ID=dt.C_DocType_ID"
+ " AND ic.AD_Client_ID=?");
if (m_M_Warehouse_ID != null)
sql.append(" AND ic.M_Warehouse_ID=").append(m_M_Warehouse_ID);
if (m_C_BPartner_ID != null)
sql.append(" AND ic.C_BPartner_ID=").append(m_C_BPartner_ID);
// bug - [ 1713317 ] Generate Shipments (manual) show locked records
/* begin - Exclude locked records; @Trifon */
int AD_User_ID = Env.getContextAsInt(Env.getCtx(), "#AD_User_ID");
String lockedIDs = MPrivateAccess.getLockedRecordWhere(MOrder.Table_ID, AD_User_ID);
if (lockedIDs != null)
{
if (sql.length() > 0)
sql.append(" AND ");
sql.append("C_Order_ID").append(lockedIDs);
}
/* eng - Exclude locked records; @Trifon */
//
sql.append(" ORDER BY o.Name,bp.Name,DateOrdered");
return sql.toString();
}
/**
* Get SQL for Vendor RMA that need to be shipped
* @return sql
*/
private String getRMASql()
{
StringBuffer sql = new StringBuffer();
sql.append("SELECT rma.M_RMA_ID, org.Name, dt.Name, rma.DocumentNo, bp.Name, rma.Created, rma.Amt ");
sql.append("FROM M_RMA rma INNER JOIN AD_Org org ON rma.AD_Org_ID=org.AD_Org_ID ");
sql.append("INNER JOIN C_DocType dt ON rma.C_DocType_ID=dt.C_DocType_ID ");
sql.append("INNER JOIN C_BPartner bp ON rma.C_BPartner_ID=bp.C_BPartner_ID ");
sql.append("INNER JOIN M_InOut io ON rma.InOut_ID=io.M_InOut_ID ");
sql.append("WHERE rma.DocStatus='CO' ");
sql.append("AND dt.DocBaseType = 'POO' ");
sql.append("AND EXISTS (SELECT * FROM M_RMA r INNER JOIN M_RMALine rl ");
sql.append("ON r.M_RMA_ID=rl.M_RMA_ID WHERE r.M_RMA_ID=rma.M_RMA_ID ");
sql.append("AND rl.IsActive='Y' AND rl.M_InOutLine_ID > 0 AND rl.QtyDelivered < rl.Qty) ");
sql.append("AND NOT EXISTS (SELECT * FROM M_InOut oio WHERE oio.M_RMA_ID=rma.M_RMA_ID ");
sql.append("AND oio.DocStatus IN ('IP', 'CO', 'CL')) " );
sql.append("AND rma.AD_Client_ID=?");
if (m_M_Warehouse_ID != null)
sql.append(" AND io.M_Warehouse_ID=").append(m_M_Warehouse_ID);
if (m_C_BPartner_ID != null)
sql.append(" AND bp.C_BPartner_ID=").append(m_C_BPartner_ID);
int AD_User_ID = Env.getContextAsInt(Env.getCtx(), "#AD_User_ID");
String lockedIDs = MPrivateAccess.getLockedRecordWhere(MRMA.Table_ID, AD_User_ID);
if (lockedIDs != null)
{
sql.append(" AND rma.M_RMA_ID").append(lockedIDs);
}
sql.append(" ORDER BY org.Name, bp.Name, rma.Created ");
return sql.toString();
}
/**
* Query Info
*/
private void executeQuery()
{
log.info("");
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
String sql = "";
KeyNamePair docTypeKNPair = (KeyNamePair)cmbDocType.getSelectedItem();
if (docTypeKNPair.getKey() == MRMA.Table_ID)
{
sql = getRMASql();
}
else
{
sql = getOrderSQL();
}
log.fine(sql);
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
//
while (rs.next())
{
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // C_Order_ID
miniTable.setValueAt(rs.getString(2), row, 1); // Org
miniTable.setValueAt(rs.getString(3), row, 2); // DocType
miniTable.setValueAt(rs.getString(4), row, 3); // Doc No
miniTable.setValueAt(rs.getString(5), row, 4); // BPartner
miniTable.setValueAt(rs.getTimestamp(6), row, 5); // DateOrdered
miniTable.setValueAt(rs.getBigDecimal(7), row, 6); // TotalLines
// prepare next
row++;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
//
miniTable.autoSize();
// statusBar.setStatusDB(String.valueOf(miniTable.getRowCount()));
} // executeQuery
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
log.info("Cmd=" + e.getActionCommand());
//
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
return;
}
if (cmbDocType.equals(e.getSource()))
{
executeQuery();
return;
}
//
saveSelection();
if (selection != null
&& selection.size() > 0
&& m_selectionActive // on selection tab
&& m_M_Warehouse_ID != null)
{
generateShipments ();
}
else
dispose();
} // actionPerformed
/**
* Vetoable Change Listener - requery
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e)
{
log.info(e.getPropertyName() + "=" + e.getNewValue());
if (e.getPropertyName().equals("M_Warehouse_ID"))
m_M_Warehouse_ID = e.getNewValue();
if (e.getPropertyName().equals("C_BPartner_ID"))
{
m_C_BPartner_ID = e.getNewValue();
fBPartner.setValue(m_C_BPartner_ID); // display value
}
executeQuery();
} // vetoableChange
/**
* Change Listener (Tab changed)
* @param e event
*/
public void stateChanged (ChangeEvent e)
{
int index = tabbedPane.getSelectedIndex();
m_selectionActive = (index == 0);
} // stateChanged
/**
* Table Model Listener
* @param e event
*/
public void tableChanged(TableModelEvent e)
{
int rowsSelected = 0;
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
if (id != null && id.isSelected())
rowsSelected++;
}
statusBar.setStatusDB(" " + rowsSelected + " ");
} // tableChanged
/**
* Save Selection & return selecion Query or ""
* @return where clause like C_Order_ID IN (...)
*/
private void saveSelection()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
selection = null;
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
// log.fine( "Row=" + i + " - " + id);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return;
log.config("Selected #" + results.size());
selection = results;
} // saveSelection
/**************************************************************************
* Generate Shipments
*/
private void generateShipments ()
{
log.info("M_Warehouse_ID=" + m_M_Warehouse_ID);
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
//String trxName = null;
//Trx trx = null;
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InOutGenerateGen"));
statusBar.setStatusDB(String.valueOf(selection.size()));
// Prepare Process
int AD_Process_ID = 0;
KeyNamePair docTypeKNPair = (KeyNamePair)cmbDocType.getSelectedItem();
if (docTypeKNPair.getKey() == MRMA.Table_ID)
{
AD_Process_ID = 52001; // M_InOut_GenerateRMA - org.adempiere.process.InOutGenerateRMA
}
else
{
AD_Process_ID = 199; // M_InOut_Generate - org.compiere.process.InOutGenerate
}
MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
if (!instance.save())
{
info.setText(Msg.getMsg(Env.getCtx(), "ProcessNoInstance"));
return;
}
//insert selection
StringBuffer insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
int counter = 0;
for(Integer selectedId : selection)
{
counter++;
if (counter > 1)
insert.append(" UNION ");
insert.append("SELECT ");
insert.append(instance.getAD_PInstance_ID());
insert.append(", ");
insert.append(selectedId);
insert.append(" FROM DUAL ");
if (counter == 1000)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
info.setText(msg);
trx.rollback();
return;
}
insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
counter = 0;
}
}
if (counter > 0)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
info.setText(msg);
trx.rollback();
return;
}
}
//call process
ProcessInfo pi = new ProcessInfo ("VInOutGen", AD_Process_ID);
pi.setAD_PInstance_ID (instance.getAD_PInstance_ID());
// Add Parameter - Selection=Y
MPInstancePara ip = new MPInstancePara(instance, 10);
ip.setParameter("Selection","Y");
if (!ip.save())
{
String msg = "No Parameter added"; // not translated
info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
// Add Parameter - M_Warehouse_ID=x
ip = new MPInstancePara(instance, 20);
ip.setParameter("M_Warehouse_ID", Integer.parseInt(m_M_Warehouse_ID.toString()));
if (!ip.save())
{
String msg = "No Parameter added"; // not translated
info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
// Execute Process
ProcessCtl worker = new ProcessCtl(this, Env.getWindowNo(this), pi, trx);
worker.start(); // complete tasks in unlockUI / generateShipments_complete
//
} // generateShipments
/**
* Complete generating shipments.
* Called from Unlock UI
* @param pi process info
*/
private void generateShipments_complete (ProcessInfo pi)
{
// Switch Tabs
tabbedPane.setSelectedIndex(1);
//
ProcessInfoUtil.setLogFromDB(pi);
//StringBuffer iText = new StringBuffer();
iText.append("<b>").append(pi.getSummary())
.append("</b><br>(")
.append(Msg.getMsg(Env.getCtx(), "InOutGenerateInfo"))
// Shipments are generated depending on the Delivery Rule selection in the Order
.append(")<br>")
.append(pi.getLogInfo(true));
info.setText(iText.toString());
// Reset Selection
/*
String sql = "UPDATE C_Order SET IsSelected='N' WHERE " + m_whereClause;
int no = DB.executeUpdate(sql, null);
log.config("Reset=" + no);*/
// Get results
int[] ids = pi.getIDs();
if (ids == null || ids.length == 0)
return;
log.config("PrintItems=" + ids.length);
confirmPanelGen.getOKButton().setEnabled(false);
// OK to print shipments
if (ADialog.ask(m_WindowNo, this, "PrintShipments"))
{
// info.append("\n\n" + Msg.getMsg(Env.getCtx(), "PrintShipments"));
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int retValue = ADialogDialog.A_CANCEL; // see also ProcessDialog.printShipments/Invoices
do
{
// Loop through all items
for (int i = 0; i < ids.length; i++)
{
int M_InOut_ID = ids[i];
ReportCtl.startDocumentPrint(ReportEngine.SHIPMENT, M_InOut_ID, this, Env.getWindowNo(this), true);
}
ADialogDialog d = new ADialogDialog (m_frame,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
setCursor(Cursor.getDefaultCursor());
} // OK to print shipments
//
confirmPanelGen.getOKButton().setEnabled(true);
} // generateShipments_complete
/**************************************************************************
* Generate Invoices
*/
private void generateInvoices ()
{
String trxName = Trx.createTrxName("IVG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
//String trxName = null;
//Trx trx = null;
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InvGenerateGen"));
statusBar.setStatusDB(String.valueOf(selection.size()));
// Prepare Process
int AD_Process_ID = 0;
KeyNamePair docTypeKNPair = (KeyNamePair)cmbDocType.getSelectedItem();
if (docTypeKNPair.getKey() == MRMA.Table_ID)
{
AD_Process_ID = 52002; // C_Invoice_GenerateRMA - org.adempiere.process.InvoiceGenerateRMA
}
else
{
AD_Process_ID = 134; // HARDCODED C_InvoiceCreate
}
MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
if (!instance.save())
{
info.setText(Msg.getMsg(Env.getCtx(), "ProcessNoInstance"));
return;
}
//insert selection
/*Selection exist from shipment*/
StringBuffer insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
int counter = 0;
for(Integer selectedId : selection)
{
counter++;
if (counter > 1)
insert.append(" UNION ");
insert.append("SELECT ");
insert.append(instance.getAD_PInstance_ID());
insert.append(", ");
insert.append(selectedId);
insert.append(" FROM DUAL ");
if (counter == 1000)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
info.setText(msg);
trx.rollback();
return;
}
insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
counter = 0;
}
}
if (counter > 0)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
info.setText(msg);
trx.rollback();
return;
}
}
ProcessInfo pi = new ProcessInfo ("", AD_Process_ID);
pi.setAD_PInstance_ID (instance.getAD_PInstance_ID());
// Add Parameters
MPInstancePara para = new MPInstancePara(instance, 10);
para.setParameter("Selection", "Y");
if (!para.save())
{
String msg = "No Selection Parameter added"; // not translated
info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
para = new MPInstancePara(instance, 20);
para.setParameter("DocAction", "CO");
if (!para.save())
{
String msg = "No DocAction Parameter added"; // not translated
info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
// Execute Process
ProcessCtl worker = new ProcessCtl(this, Env.getWindowNo(this), pi, trx);
worker.start(); // complete tasks in unlockUI / generateInvoice_complete
} // generateInvoices
/**
* Complete generating invoices.
* Called from Unlock UI
* @param pi process info
*/
private void generateInvoice_complete (ProcessInfo pi)
{
// Switch Tabs
tabbedPane.setSelectedIndex(1);
//
ProcessInfoUtil.setLogFromDB(pi);
//StringBuffer iText = new StringBuffer();
iText.append("<b>").append(pi.getSummary())
.append("</b><br>(")
.append(Msg.getMsg(Env.getCtx(), "InvGenerateInfo"))
//Invoices are generated depending on the Invoicing Rule selection in the Order
.append(")<br>")
.append(pi.getLogInfo(true));
info.setText(iText.toString());
// Reset Selection
/*
String sql = "UPDATE C_Order SET IsSelected = 'N' WHERE " + m_whereClause;
int no = DB.executeUpdate(sql, null);
log.config("Reset=" + no);*/
// Get results
int[] ids = pi.getIDs();
if (ids == null || ids.length == 0)
return;
confirmPanelGen.getOKButton().setEnabled(false);
// OK to print invoices
if (ADialog.ask(m_WindowNo, this, "PrintInvoices"))
{
// info.append("\n\n" + Msg.getMsg(Env.getCtx(), "PrintInvoices"));
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int retValue = ADialogDialog.A_CANCEL;
do
{
// Loop through all items
for (int i = 0; i < ids.length; i++)
{
int C_Invoice_ID = ids[i];
ReportCtl.startDocumentPrint(ReportEngine.INVOICE, C_Invoice_ID, this, Env.getWindowNo(this), true);
}
ADialogDialog d = new ADialogDialog (m_frame,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
setCursor(Cursor.getDefaultCursor());
} // OK to print invoices
//
confirmPanelGen.getOKButton().setEnabled(true);
} // generateInvoices_complete
/**************************************************************************
* Lock User Interface.
* Called from the Worker before processing
* @param pi process info
*/
public void lockUI (ProcessInfo pi)
{
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
this.setEnabled(false);
} // lockUI
/**
* Unlock User Interface.
* Called from the Worker when processing is done
* @param pi result of execute ASync call
*/
public void unlockUI (ProcessInfo pi)
{
//
if(pi.getAD_Process_ID() == 199)
{
generateShipments_complete(pi);
generateInvoices ();
}
if(pi.getAD_Process_ID() == 134)
{
generateInvoice_complete(pi);
this.setEnabled(true);
this.setCursor(Cursor.getDefaultCursor());
}
} // unlockUI
/**
* Is the UI locked (Internal method)
* @return true, if UI is locked
*/
public boolean isUILocked()
{
return this.isEnabled();
} // isUILocked
/**
* Method to be executed async.
* Called from the Worker
* @param pi ProcessInfo
*/
public void executeASync (ProcessInfo pi)
{
} // executeASync
} // VInOutGen

File diff suppressed because it is too large Load Diff

View File

@ -1,713 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.adempiere.plaf.AdempierePLAF;
import org.compiere.apps.ADialog;
import org.compiere.apps.ADialogDialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.ProcessCtl;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VComboBox;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MColumn;
import org.compiere.model.MLocator;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MMovement;
import org.compiere.model.MOrder;
import org.compiere.model.MPInstance;
import org.compiere.model.MPInstancePara;
import org.compiere.model.MPrivateAccess;
import org.compiere.model.MProcess;
import org.compiere.model.MQuery;
import org.compiere.model.PrintInfo;
import org.compiere.plaf.CompiereColor;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportEngine;
import org.compiere.print.Viewer;
import org.compiere.process.ProcessInfo;
import org.compiere.process.ProcessInfoUtil;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTabbedPane;
import org.compiere.swing.CTextPane;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
import org.eevolution.model.MDDOrder;
/**
* Create Movement from Distribution Order
*
* @author victor.perez@www.e-evolution.com
* @version $Id: VOrderDistribution,v 1.0
*/
public class VOrderDistribution extends CPanel
implements FormPanel, ActionListener, VetoableChangeListener,
ChangeListener, TableModelListener, ASyncProcess
{
private static final long serialVersionUID = 1L;
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info("");
m_WindowNo = WindowNo;
m_frame = frame;
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "N");
try
{
fillPicks();
jbInit();
dynInit();
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
}
catch(Exception ex)
{
log.log(Level.SEVERE, "init", ex);
}
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private boolean m_selectionActive = true;
private Object m_M_Locator_ID = null;
private Object m_M_LocatorTo_ID = null;
private Object m_C_BPartner_ID = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VOrderDistribution.class);
//
private CTabbedPane tabbedPane = new CTabbedPane();
private CPanel selPanel = new CPanel();
private CPanel selNorthPanel = new CPanel();
private BorderLayout selPanelLayout = new BorderLayout();
private CLabel lOrder = new CLabel();
private VLookup fOrder;
private CLabel lLocator = new CLabel();
private VLookup fLocator;
private CLabel lLocatorTo = new CLabel();
private VLookup fLocatorTo;
private CLabel lBPartner = new CLabel();
private VLookup fBPartner;
private FlowLayout northPanelLayout = new FlowLayout();
private ConfirmPanel confirmPanelSel = new ConfirmPanel(true);
private ConfirmPanel confirmPanelGen = new ConfirmPanel(false, true, false, false, false, false, true);
private StatusBar statusBar = new StatusBar();
private CPanel genPanel = new CPanel();
private BorderLayout genLayout = new BorderLayout();
private CTextPane info = new CTextPane();
private JScrollPane scrollPane = new JScrollPane();
private MiniTable miniTable = new MiniTable();
private CLabel lDocType = new CLabel();
private VComboBox cmbDocType = new VComboBox();
/** User selection */
private ArrayList<Integer> selection = null;
/**
* Static Init.
* <pre>
* selPanel (tabbed)
* fOrg, fBPartner
* scrollPane & miniTable
* genPanel
* info
* </pre>
* @throws Exception
*/
void jbInit() throws Exception
{
CompiereColor.setBackground(this);
//
selPanel.setLayout(selPanelLayout);
lOrder.setLabelFor(fOrder);
lLocator.setLabelFor(fLocator);
lLocatorTo.setLabelFor(fLocatorTo);
lBPartner.setLabelFor(fBPartner);
lBPartner.setText("BPartner");
selNorthPanel.setLayout(northPanelLayout);
northPanelLayout.setAlignment(FlowLayout.LEFT);
tabbedPane.add(selPanel, Msg.getMsg(Env.getCtx(), "Select"));
selPanel.add(selNorthPanel, BorderLayout.NORTH);
selNorthPanel.add(lOrder, null);
selNorthPanel.add(fOrder, null);
selNorthPanel.add(lLocator, null);
selNorthPanel.add(fLocator, null);
selNorthPanel.add(lLocatorTo, null);
selNorthPanel.add(fLocatorTo, null);
//selNorthPanel.add(lWarehouse, null);
//selNorthPanel.add(fWarehouse, null);
selNorthPanel.add(lBPartner, null);
selNorthPanel.add(fBPartner, null);
selPanel.setName("selPanel");
selPanel.add(confirmPanelSel, BorderLayout.SOUTH);
selPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(miniTable, null);
confirmPanelSel.addActionListener(this);
//
tabbedPane.add(genPanel, Msg.getMsg(Env.getCtx(), "Generate"));
genPanel.setLayout(genLayout);
genPanel.add(info, BorderLayout.CENTER);
genPanel.setEnabled(false);
info.setBackground(AdempierePLAF.getFieldBackground_Inactive());
info.setEditable(false);
genPanel.add(confirmPanelGen, BorderLayout.SOUTH);
confirmPanelGen.addActionListener(this);
} // jbInit
/**
* Fill Picks.
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
// Order Distribution
MLookup orderL = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, MColumn.getColumn_ID(MDDOrder.Table_Name, MDDOrder.COLUMNNAME_DD_Order_ID), DisplayType.Search);
fOrder = new VLookup (MDDOrder.COLUMNNAME_DD_Order_ID, true, false, true, orderL);
lOrder.setText(Msg.translate(Env.getCtx(), MDDOrder.COLUMNNAME_DD_Order_ID));
fOrder.addVetoableChangeListener(this);
lOrder.setVisible(false);
fOrder.setVisible(false);
MLookup llocator= MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 53950, DisplayType.TableDir);
fLocator = new VLookup (MLocator.COLUMNNAME_M_Locator_ID, true, false, true, llocator);
lLocator.setText(Msg.translate(Env.getCtx(), "M_Locator_ID"));
fLocator.addVetoableChangeListener(this);
m_M_Locator_ID = fLocator.getValue();
MLookup llocatorto = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 53949, DisplayType.TableDir);
fLocatorTo = new VLookup ("M_LocatorTo_ID", false, false, true, llocatorto);
lLocatorTo.setText(Msg.translate(Env.getCtx(), "M_LocatorTo_ID"));
fLocatorTo.addVetoableChangeListener(this);
m_M_LocatorTo_ID = fLocatorTo.getValue();
// C_Order.C_BPartner_ID
MLookup bpL = MLookupFactory.get (Env.getCtx(), m_WindowNo, 0, 2762, DisplayType.Search);
fBPartner = new VLookup ("C_BPartner_ID", false, false, true, bpL);
lBPartner.setText(Msg.translate(Env.getCtx(), "C_BPartner_ID"));
fBPartner.addVetoableChangeListener(this);
//Document Type Sales Order/Vendor RMA
//lDocType.setText(Msg.translate(Env.getCtx(), "C_DocType_ID"));
//cmbDocType.addItem(new KeyNamePair(MOrder.Table_ID, Msg.translate(Env.getCtx(), "Order")));
//cmbDocType.addItem(new KeyNamePair(MRMA.Table_ID, Msg.translate(Env.getCtx(), "VendorRMA")));
//cmbDocType.addActionListener(this);
} // fillPicks
/**
* Dynamic Init.
* - Create GridController & Panel
* - AD_Column_ID from C_Order
*/
private void dynInit()
{
// create Columns
miniTable.addColumn("C_Order_ID");
miniTable.addColumn("AD_Org_ID");
miniTable.addColumn("C_DocType_ID");
miniTable.addColumn("DocumentNo");
miniTable.addColumn("C_BPartner_ID");
miniTable.addColumn("DateOrdered");
miniTable.addColumn("TotalLines");
//
miniTable.setMultiSelection(true);
miniTable.setRowSelectionAllowed(true);
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, String.class, true, Msg.translate(Env.getCtx(), "AD_Org_ID"));
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "C_DocType_ID"));
miniTable.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "DocumentNo"));
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "C_BPartner_ID"));
miniTable.setColumnClass(5, Timestamp.class, true, Msg.translate(Env.getCtx(), "DateOrdered"));
miniTable.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
//
miniTable.autoSize();
miniTable.getModel().addTableModelListener(this);
// Info
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InOutGenerateSel"));//@@
statusBar.setStatusDB(" ");
// Tabbed Pane Listener
tabbedPane.addChangeListener(this);
} // dynInit
/**
* Get SQL for Orders that needs to be shipped
* @return sql
*/
private String getOrderSQL()
{
// Create SQL
StringBuffer sql = new StringBuffer(
"SELECT DD_Order_ID, o.Name, dt.Name, DocumentNo, bp.Name, DateOrdered "
+ "FROM M_Movement_Candidate_v ic, AD_Org o, C_BPartner bp, C_DocType dt "
+ "WHERE ic.AD_Org_ID=o.AD_Org_ID"
+ " AND ic.C_BPartner_ID=bp.C_BPartner_ID"
+ " AND ic.C_DocType_ID=dt.C_DocType_ID"
+ " AND ic.AD_Client_ID=?");
if(m_M_Locator_ID != null)
sql.append(" AND ic.M_Locator_ID=").append(m_M_Locator_ID);
/*if (m_M_Warehouse_ID != null)
sql.append(" AND ic.M_Warehouse_ID=").append(m_M_Warehouse_ID);*/
if(m_M_LocatorTo_ID != null)
sql.append(" AND ic.M_LocatorTo_ID=").append(m_M_LocatorTo_ID);
if (m_C_BPartner_ID != null)
sql.append(" AND ic.C_BPartner_ID=").append(m_C_BPartner_ID);
// bug - [ 1713317 ] Generate Shipments (manual) show locked records
/* begin - Exclude locked records; @Trifon */
int AD_User_ID = Env.getContextAsInt(Env.getCtx(), "#AD_User_ID");
String lockedIDs = MPrivateAccess.getLockedRecordWhere(MOrder.Table_ID, AD_User_ID);
if (lockedIDs != null)
{
if (sql.length() > 0)
sql.append(" AND ");
sql.append("DD_Order_ID").append(lockedIDs);
}
/* eng - Exclude locked records; @Trifon */
//
sql.append(" ORDER BY o.Name,bp.Name,DateOrdered");
return sql.toString();
}
/**
* Query Info
*/
private void executeQuery()
{
log.info("");
int AD_Client_ID = Env.getAD_Client_ID(Env.getCtx());
String sql = "";
KeyNamePair docTypeKNPair = (KeyNamePair)cmbDocType.getSelectedItem();
sql = getOrderSQL();
log.fine(sql);
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, AD_Client_ID);
ResultSet rs = pstmt.executeQuery();
//
while (rs.next())
{
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // C_Order_ID
miniTable.setValueAt(rs.getString(2), row, 1); // Org
miniTable.setValueAt(rs.getString(3), row, 2); // DocType
miniTable.setValueAt(rs.getString(4), row, 3); // Doc No
miniTable.setValueAt(rs.getString(5), row, 4); // BPartner
miniTable.setValueAt(rs.getTimestamp(6), row, 5); // DateOrdered
//miniTable.setValueAt(rs.getBigDecimal(7), row, 6); // QtyBackOrder
// prepare next
row++;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
//
miniTable.autoSize();
// statusBar.setStatusDB(String.valueOf(miniTable.getRowCount()));
} // executeQuery
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
log.info("Cmd=" + e.getActionCommand());
//
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
return;
}
if (cmbDocType.equals(e.getSource()))
{
executeQuery();
return;
}
//
saveSelection();
if (selection != null
&& selection.size() > 0
&& m_selectionActive // on selection tab
&& m_M_Locator_ID != null)
generateMovements ();
else
dispose();
} // actionPerformed
/**
* Vetoable Change Listener - requery
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e)
{
log.info(e.getPropertyName() + "=" + e.getNewValue());
//if (e.getPropertyName().equals("M_Warehouse_ID"))
//m_M_Warehouse_ID = e.getNewValue();
if (e.getPropertyName().equals("M_Locator_ID"))
m_M_Locator_ID = e.getNewValue();
if (e.getPropertyName().equals("M_LocatorTo_ID"))
m_M_LocatorTo_ID = e.getNewValue();
if (e.getPropertyName().equals("C_BPartner_ID"))
{
m_C_BPartner_ID = e.getNewValue();
fBPartner.setValue(m_C_BPartner_ID); // display value
}
executeQuery();
} // vetoableChange
/**
* Change Listener (Tab changed)
* @param e event
*/
public void stateChanged (ChangeEvent e)
{
int index = tabbedPane.getSelectedIndex();
m_selectionActive = (index == 0);
} // stateChanged
/**
* Table Model Listener
* @param e event
*/
public void tableChanged(TableModelEvent e)
{
int rowsSelected = 0;
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
if (id != null && id.isSelected())
rowsSelected++;
}
statusBar.setStatusDB(" " + rowsSelected + " ");
} // tableChanged
/**
* Save Selection & return selecion Query or ""
* @return where clause like C_Order_ID IN (...)
*/
private void saveSelection()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
selection = null;
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
// log.fine( "Row=" + i + " - " + id);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return;
log.config("Selected #" + results.size());
selection = results;
} // saveSelection
/**************************************************************************
* Generate Shipments
*/
private void generateMovements ()
{
//log.info("M_Warehouse_ID=" + m_M_Warehouse_ID);
log.info("M_Locator_ID=" + m_M_Locator_ID);
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
//String trxName = null;
//Trx trx = null;
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "M_Movement_ID"));
statusBar.setStatusDB(String.valueOf(selection.size()));
// Prepare Process
int AD_Process_ID = MProcess.getProcess_ID("M_Generate Movement", trxName);
KeyNamePair docTypeKNPair = (KeyNamePair)cmbDocType.getSelectedItem();
MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
if (!instance.save())
{
info.setText(Msg.getMsg(Env.getCtx(), "ProcessNoInstance"));
return;
}
//insert selection
StringBuffer insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
int counter = 0;
for(Integer selectedId : selection)
{
counter++;
if (counter > 1)
insert.append(" UNION ");
insert.append("SELECT ");
insert.append(instance.getAD_PInstance_ID());
insert.append(", ");
insert.append(selectedId);
insert.append(" FROM DUAL ");
if (counter == 1000)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Shipments"; // not translated!
log.config(msg);
info.setText(msg);
trx.rollback();
return;
}
insert = new StringBuffer();
insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
counter = 0;
}
}
if (counter > 0)
{
if ( DB.executeUpdate(insert.toString(), trxName) < 0 )
{
String msg = "No Movements"; // not translated!
log.config(msg);
info.setText(msg);
trx.rollback();
return;
}
}
//call process
ProcessInfo pi = new ProcessInfo ("VOrderDistribution", AD_Process_ID);
pi.setAD_PInstance_ID (instance.getAD_PInstance_ID());
// Add Parameter - Selection=Y
MPInstancePara ip = new MPInstancePara(instance, 10);
ip.setParameter("Selection","Y");
if (!ip.save())
{
String msg = "No Parameter added"; // not translated
info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
MLocator locator = MLocator.get(Env.getCtx(), Integer.parseInt(m_M_Locator_ID.toString()));
// Add Parameter - M_Warehouse_ID=x
ip = new MPInstancePara(instance, 20);
ip.setParameter("M_Warehouse_ID", locator.getM_Warehouse_ID());
if (!ip.save())
{
String msg = "No Parameter added"; // not translated
info.setText(msg);
log.log(Level.SEVERE, msg);
return;
}
// Execute Process
ProcessCtl worker = new ProcessCtl(this, Env.getWindowNo(this), pi, trx);
worker.start(); // complete tasks in unlockUI / generateShipments_complete
//
} // generateShipments
/**
* Complete generating shipments.
* Called from Unlock UI
* @param pi process info
*/
private void generateMovements_complete (ProcessInfo pi)
{
// Switch Tabs
tabbedPane.setSelectedIndex(1);
//
ProcessInfoUtil.setLogFromDB(pi);
StringBuffer iText = new StringBuffer();
iText.append("<b>").append(pi.getSummary())
.append("</b><br>(")
.append(Msg.getMsg(Env.getCtx(), "InOutGenerateInfo"))
// Shipments are generated depending on the Delivery Rule selection in the Order
.append(")<br>")
.append(pi.getLogInfo(true));
info.setText(iText.toString());
// Reset Selection
//String sql = "UPDATE DD_Order SET IsSelected='N' WHERE " + m_whereClause;
//int no = DB.executeUpdate(sql, null);
//log.config("Reset=" + no);
// Get results
int[] ids = pi.getIDs();
if (ids == null || ids.length == 0)
return;
log.config("PrintItems=" + ids.length);
confirmPanelGen.getOKButton().setEnabled(false);
// OK to print shipments
if (ADialog.ask(m_WindowNo, this, "PrintShipments"))
{
// info.append("\n\n" + Msg.getMsg(Env.getCtx(), "PrintShipments"));
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int retValue = ADialogDialog.A_CANCEL; // see also ProcessDialog.printShipments/Invoices
do
{
// Loop through all items
for (int i = 0; i < ids.length; i++)
{
int M_Movement_ID = ids[i];
MPrintFormat format = MPrintFormat.get(Env.getCtx(), MPrintFormat.getPrintFormat_ID("Inventory Move Hdr (Example)", MMovement.Table_ID, 0), false);
MQuery query = new MQuery(MMovement.Table_Name);
query.addRestriction(MMovement.COLUMNNAME_M_Movement_ID, MQuery.EQUAL, M_Movement_ID);
// Engine
PrintInfo info = new PrintInfo(MMovement.Table_Name,MMovement.Table_ID, M_Movement_ID);
ReportEngine re = new ReportEngine(Env.getCtx(), format, query, info);
re.print();
new Viewer(re);
}
ADialogDialog d = new ADialogDialog (m_frame,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
setCursor(Cursor.getDefaultCursor());
} // OK to print shipments
//
confirmPanelGen.getOKButton().setEnabled(true);
} // generateShipments_complete
/**************************************************************************
* Lock User Interface.
* Called from the Worker before processing
* @param pi process info
*/
public void lockUI (ProcessInfo pi)
{
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
this.setEnabled(false);
} // lockUI
/**
* Unlock User Interface.
* Called from the Worker when processing is done
* @param pi result of execute ASync call
*/
public void unlockUI (ProcessInfo pi)
{
this.setEnabled(true);
this.setCursor(Cursor.getDefaultCursor());
//
generateMovements_complete(pi);
} // unlockUI
/**
* Is the UI locked (Internal method)
* @return true, if UI is locked
*/
public boolean isUILocked()
{
return this.isEnabled();
} // isUILocked
/**
* Method to be executed async.
* Called from the Worker
* @param pi ProcessInfo
*/
public void executeASync (ProcessInfo pi)
{
} // executeASync
} // VOrderDistribution

View File

@ -1,550 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): victor.perez@e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.plaf.AdempierePLAF;
import org.compiere.apps.ADialog;
import org.compiere.apps.ADialogDialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MMovement;
import org.compiere.model.MMovementLine;
import org.compiere.model.MQuery;
import org.compiere.model.PrintInfo;
import org.compiere.plaf.CompiereColor;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportEngine;
import org.compiere.print.Viewer;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTabbedPane;
import org.compiere.swing.CTextPane;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
import org.eevolution.model.MDDOrder;
import org.eevolution.model.MDDOrderLine;
/**
* Create Movement for Material Receipt from Distribution Order
*
* @author victor.perez@www.e-evolution.com
* @version $Id: VOrderDistributionReceipt,v 1.0
*/
public class VOrderDistributionReceipt extends CPanel
implements FormPanel, ActionListener, VetoableChangeListener,
ChangeListener, TableModelListener
{
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info("");
m_WindowNo = WindowNo;
m_frame = frame;
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "Y");
try
{
fillPicks();
jbInit();
dynInit();
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
}
catch(Exception ex)
{
log.log(Level.SEVERE, "init", ex);
}
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private boolean m_selectionActive = true;
private Object m_DD_Order_ID = null;
private Object m_MovementDate = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VOrderDistributionReceipt.class);
//
private CTabbedPane tabbedPane = new CTabbedPane();
private CPanel selPanel = new CPanel();
private CPanel selNorthPanel = new CPanel();
private BorderLayout selPanelLayout = new BorderLayout();
private CLabel lOrder = new CLabel();
private VLookup fOrder;
private VDate fMovementDate = new VDate("MovementDate", true, false, true, DisplayType.Date, "MovementDate");
private CLabel lMovementDate = new CLabel(Msg.translate(Env.getCtx(),"MovementDate"));
private FlowLayout northPanelLayout = new FlowLayout();
private ConfirmPanel confirmPanelSel = new ConfirmPanel(true);
private ConfirmPanel confirmPanelGen = new ConfirmPanel(false, true, false, false, false, false, true);
private StatusBar statusBar = new StatusBar();
private CPanel genPanel = new CPanel();
private BorderLayout genLayout = new BorderLayout();
private CTextPane info = new CTextPane();
private JScrollPane scrollPane = new JScrollPane();
private MiniTable miniTable = new MiniTable();
/** User selection */
private ArrayList<Integer> selection = null;
/**
* Static Init.
* <pre>
* selPanel (tabbed)
* fOrg, fBPartner
* scrollPane & miniTable
* genPanel
* info
* </pre>
* @throws Exception
*/
void jbInit() throws Exception
{
CompiereColor.setBackground(this);
//
selPanel.setLayout(selPanelLayout);
lOrder.setLabelFor(fOrder);
selNorthPanel.setLayout(northPanelLayout);
northPanelLayout.setAlignment(FlowLayout.LEFT);
tabbedPane.add(selPanel, Msg.getMsg(Env.getCtx(), "Select"));
selPanel.add(selNorthPanel, BorderLayout.NORTH);
selNorthPanel.add(lOrder, null);
selNorthPanel.add(fOrder, null);
selNorthPanel.add(lMovementDate, null);
selNorthPanel.add(fMovementDate, null);
selPanel.setName("selPanel");
selPanel.add(confirmPanelSel, BorderLayout.SOUTH);
selPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(miniTable, null);
confirmPanelSel.addActionListener(this);
//
tabbedPane.add(genPanel, Msg.getMsg(Env.getCtx(), "Generate"));
genPanel.setLayout(genLayout);
genPanel.add(info, BorderLayout.CENTER);
genPanel.setEnabled(false);
info.setBackground(AdempierePLAF.getFieldBackground_Inactive());
info.setEditable(false);
genPanel.add(confirmPanelGen, BorderLayout.SOUTH);
confirmPanelGen.addActionListener(this);
} // jbInit
/**
* Fill Picks.
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
Language language = Language.getLoginLanguage();
MLookup orderL = MLookupFactory.get(Env.getCtx(), m_WindowNo, MColumn.getColumn_ID(MDDOrder.Table_Name,MDDOrder.COLUMNNAME_DD_Order_ID) , DisplayType.Search , language , MDDOrder.COLUMNNAME_DD_Order_ID , 0 , false, "DocStatus='CO'");
fOrder = new VLookup (MDDOrder.COLUMNNAME_DD_Order_ID, true, false, true, orderL);
lOrder.setText(Msg.translate(Env.getCtx(), MDDOrder.COLUMNNAME_DD_Order_ID));
fOrder.addVetoableChangeListener(this);
Timestamp today = new Timestamp (System.currentTimeMillis());
m_MovementDate = today;
fMovementDate.setValue(today);
fMovementDate.addVetoableChangeListener(this);
} // fillPicks
/**
* Dynamic Init.
* - Create GridController & Panel
* - AD_Column_ID from C_Order
*/
private void dynInit()
{
// create Columns
miniTable.addColumn("DD_Order_ID");
miniTable.addColumn("QtyInTransit");
miniTable.addColumn("C_UOM_ID");
miniTable.addColumn("Value");
miniTable.addColumn("M_Product_ID");
miniTable.addColumn("M_WarehouseSource_ID");
//miniTable.addColumn("TotalLines");
//
miniTable.setMultiSelection(true);
miniTable.setRowSelectionAllowed(true);
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, BigDecimal.class, false, Msg.translate(Env.getCtx(), "QtyInTransit")); //Qty
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "C_UOM_ID")); //UM
miniTable.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "M_Product_ID")); // Product
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "Value")); // Line
miniTable.setColumnClass(5, String.class, true, Msg.translate(Env.getCtx(), "WarehouseSource"));
//miniTable.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
//
miniTable.autoSize();
miniTable.getModel().addTableModelListener(this);
// Info
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InOutGenerateSel"));//@@
statusBar.setStatusDB(" ");
// Tabbed Pane Listener
tabbedPane.addChangeListener(this);
} // dynInit
/**
* Get SQL for Orders that needs to be shipped
* @return sql
*/
private String getOrderSQL()
{
// Create SQL
StringBuffer sql = new StringBuffer(
"SELECT ol.DD_OrderLine_ID, ol.QtyInTransit , uom.Name , p.Value ,p.Name , w.Name "
+ "FROM DD_OrderLine ol INNER JOIN DD_Order o ON (o.DD_Order_ID=ol.DD_Order_ID) INNER JOIN M_Product p ON (p.M_Product_ID=ol.M_Product_ID) "
+ " INNER JOIN C_UOM uom ON (uom.C_UOM_ID=ol.C_UOM_ID)"
+ " INNER JOIN M_Locator l ON (l.M_Locator_ID = ol.M_Locator_ID)"
+ " INNER JOIN M_Warehouse w ON (w.M_Warehouse_ID = l.M_Warehouse_ID)"
+ " WHERE o.DocStatus= 'CO' AND ol.QtyInTransit > 0 AND o.DD_Order_ID = ? ");
return sql.toString();
}
/**
* Query Info
*/
private void executeQuery()
{
log.info("");
String sql = "";
if (m_DD_Order_ID == null)
return;
sql = getOrderSQL();
log.fine(sql);
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, Integer.parseInt(m_DD_Order_ID.toString()));
ResultSet rs = pstmt.executeQuery();
//
while (rs.next())
{
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // DD_Order_ID
miniTable.setValueAt(rs.getBigDecimal(2), row, 1); // QtyInTransit
miniTable.setValueAt(rs.getString(3), row, 2); // C_UOM_ID
miniTable.setValueAt(rs.getString(4), row, 4); // Value
miniTable.setValueAt(rs.getString(5), row, 3); // M_Product_ID
miniTable.setValueAt(rs.getString(6), row, 5); // WarehouseSource
//miniTable.setValueAt(rs.getBigDecimal(7), row, 6); // QtyBackOrder
// prepare next
row++;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
//
miniTable.autoSize();
// statusBar.setStatusDB(String.valueOf(miniTable.getRowCount()));
} // executeQuery
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
log.info("Cmd=" + e.getActionCommand());
//
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
return;
}
//
saveSelection();
if (selection != null
&& selection.size() > 0
&& m_selectionActive // on selection tab
&& m_DD_Order_ID != null && m_MovementDate != null)
generateMovements ();
else
dispose();
} // actionPerformed
/**
* Vetoable Change Listener - requery
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e)
{
log.info(e.getPropertyName() + "=" + e.getNewValue());
if (e.getPropertyName().equals("DD_Order_ID"))
m_DD_Order_ID = e.getNewValue();
if(e.getPropertyName().equals("MovementDate"))
m_MovementDate = e.getNewValue();
executeQuery();
} // vetoableChange
/**
* Change Listener (Tab changed)
* @param e event
*/
public void stateChanged (ChangeEvent e)
{
int index = tabbedPane.getSelectedIndex();
m_selectionActive = (index == 0);
} // stateChanged
/**
* Table Model Listener
* @param e event
*/
public void tableChanged(TableModelEvent e)
{
int rowsSelected = 0;
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
if (id != null && id.isSelected())
rowsSelected++;
}
statusBar.setStatusDB(" " + rowsSelected + " ");
} // tableChanged
/**
* Save Selection & return selecion Query or ""
* @return where clause like C_Order_ID IN (...)
*/
private void saveSelection()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
selection = null;
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
// log.fine( "Row=" + i + " - " + id);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return;
log.config("Selected #" + results.size());
selection = results;
} // saveSelection
/**************************************************************************
* Generate Shipments
*/
private void generateMovements ()
{
log.info("DD_Order_ID=" + m_DD_Order_ID);
log.info("MovementDate" + m_MovementDate);
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.translate(Env.getCtx(), "M_Movement_ID"));
statusBar.setStatusDB(String.valueOf(selection.size()));
if (selection.size() <= 0)
return;
Properties m_ctx = Env.getCtx();
Timestamp MovementDate = (Timestamp) m_MovementDate;
MDDOrder order = new MDDOrder(m_ctx , Integer.parseInt(m_DD_Order_ID.toString()), trxName);
MMovement movement = new MMovement(m_ctx , 0 , trxName);
movement.setDD_Order_ID(order.getDD_Order_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setPOReference(order.getPOReference());
movement.setReversal_ID(order.getSalesRep_ID());
movement.setM_Shipper_ID(order.getM_Shipper_ID());
movement.setDescription(order.getDescription());
//movement.setDateReceived(DateReceived);
movement.setC_BPartner_ID(order.getC_BPartner_ID());
movement.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID());
movement.setAD_Org_ID(order.getAD_Org_ID());
movement.setAD_OrgTrx_ID(order.getAD_OrgTrx_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setC_Activity_ID(order.getC_Activity_ID());
movement.setC_Campaign_ID(order.getC_Campaign_ID());
movement.setC_Project_ID(order.getC_Project_ID());
movement.setMovementDate(MovementDate);
movement.setDeliveryRule(order.getDeliveryRule());
movement.setDeliveryViaRule(order.getDeliveryViaRule());
movement.setDocAction(MMovement.ACTION_Prepare);
movement.setDocStatus(MMovement.DOCACTION_Complete);
if (!movement.save())
throw new AdempiereException("Can not save Inventory Move");
for (int i = 0 ; i < selection.size() ; i++ )
{
int DD_OrderLine_ID = selection.get(i);
MDDOrderLine oline = new MDDOrderLine(m_ctx, DD_OrderLine_ID, trxName);
MMovementLine line = new MMovementLine(movement);
line.setM_Product_ID(oline.getM_Product_ID());
BigDecimal QtyDeliver = (BigDecimal) miniTable.getValueAt(i, 1);
if(QtyDeliver == null | QtyDeliver.compareTo(oline.getQtyInTransit()) > 0)
throw new AdempiereException("Error in Qty");
line.setOrderLine(oline, QtyDeliver, true);
line.save();
}
movement.completeIt();
movement.setDocAction(MMovement.ACTION_Complete);
movement.setDocStatus(MMovement.DOCACTION_Close);
movement.save();
trx.commit();
generateMovements_complete(movement);
//
} // generateMovements
/**
* Complete generating movements.
* @param movement
*/
private void generateMovements_complete (MMovement movement)
{
// Switch Tabs
tabbedPane.setSelectedIndex(1);
StringBuffer iText = new StringBuffer();
iText.append("<b>").append("")
.append("</b><br>")
.append(Msg.translate(Env.getCtx(), "DocumentNo") +" : " +movement.getDocumentNo())
// Shipments are generated depending on the Delivery Rule selection in the Order
.append("<br>")
.append("");
info.setText(iText.toString());
confirmPanelGen.getOKButton().setEnabled(false);
// OK to print shipments
if (ADialog.ask(m_WindowNo, this, "PrintShipments"))
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int retValue = ADialogDialog.A_CANCEL; // see also ProcessDialog.printShipments/Invoices
do
{
MPrintFormat format = MPrintFormat.get(Env.getCtx(), MPrintFormat.getPrintFormat_ID("Inventory Move Hdr (Example)", MMovement.Table_ID, 0), false);
MQuery query = new MQuery(MMovement.Table_Name);
query.addRestriction(MMovement.COLUMNNAME_M_Movement_ID, MQuery.EQUAL, movement.getM_Movement_ID());
// Engine
PrintInfo info = new PrintInfo(MMovement.Table_Name,MMovement.Table_ID, movement.getM_Movement_ID());
ReportEngine re = new ReportEngine(Env.getCtx(), format, query, info);
re.print();
new Viewer(re);
ADialogDialog d = new ADialogDialog (m_frame,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
setCursor(Cursor.getDefaultCursor());
} // OK to print shipments
//
confirmPanelGen.getOKButton().setEnabled(true);
} // generateMovement_complete
} // VOrderDistributionReceipt

View File

@ -1,684 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): victor.perez@e-evolution.com www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.logging.Level;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.compiere.apps.ADialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.apps.search.Find;
import org.compiere.apps.search.Info_Column;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.GridField;
import org.compiere.model.MQuery;
import org.compiere.model.MRole;
import org.compiere.model.MTab;
import org.compiere.model.MTable;
import org.compiere.model.MWindow;
import org.compiere.swing.CPanel;
import org.compiere.util.ASyncProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.eevolution.model.MPPOrder;
/**
*
* @author vpj-cd
*/
public class VOrderPlanning extends CPanel
implements FormPanel, ActionListener, VetoableChangeListener, ChangeListener, ListSelectionListener, TableModelListener, ASyncProcess
{
/** Creates new form VOrderPlanning */
public VOrderPlanning() {
initComponents();
}
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
m_WindowNo = WindowNo;
m_frame = frame;
//Log.trace(Log.l1_User, "VOrderReceipIssue.init - WinNo=" + m_WindowNo,
// "AD_Client_ID=" + m_AD_Client_ID + ", AD_Org_ID=" + m_AD_Org_ID);
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "N");
try
{
// UI
fillPicks();
jbInit();
//
dynInit();
m_frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
m_frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
}
catch(Exception e)
{
log.log(Level.SEVERE, "Info", e);
}
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private StatusBar statusBar = new StatusBar();
private int AD_Table_ID = MTable.getTable_ID("PP_Order");
private MTable table = null;
private int AD_Window_ID = MWindow.getWindow_ID("Manufacturing Order");
private int AD_Tab_ID = MTab.getTab_ID(AD_Window_ID, "Order");
/** Master (owning) Window */
protected int p_WindowNo;
/** Table Name */
private String p_tableName = getTableName();
/** Key Column Name */
protected String p_keyColumn;
/** Enable more than one selection */
protected boolean p_multiSelection = true;
/** Initial WHERE Clause */
protected String p_whereClause = "";
/** Table */
protected MiniTable p_table = new MiniTable();
/** Model Index of Key Column */
private int m_keyColumnIndex = -1;
/** Layout of Grid */
protected Info_Column[] p_layout;
/** Main SQL Statement */
private String m_sqlMain;
/** Order By Clause */
private String m_sqlAdd;
protected int row = 0;
/** Loading success indicator */
protected boolean p_loadedOK = false;
/** Worker */
private Worker m_worker = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VOrderPlanning.class);
/** Static Layout */
private CPanel southPanel = new CPanel();
private BorderLayout southLayout = new BorderLayout();
ConfirmPanel confirmPanel = new ConfirmPanel(true, true, true, true, true, true, true);
protected CPanel parameterPanel = new CPanel();
private JScrollPane scrollPane = new JScrollPane();
//
private JPopupMenu popup = new JPopupMenu();
private JMenuItem calcMenu = new JMenuItem();
/** Window Width */
static final int INFO_WIDTH = 800;
// public IDColumn id = new IDColumn(0);
// id.setSelected(true);
/** Array of Column Info */
private Info_Column[] m_layout = {
//new ColumnInfo(" "," ", IDColumn.class, true, true, ""),
new Info_Column(Msg.translate(Env.getCtx(), "Select"), p_tableName +".PP_Order_ID", IDColumn.class),
new Info_Column(Msg.translate(Env.getCtx(), "DocumentNo"), p_tableName + ".DocumentNo", String.class),
new Info_Column(Msg.translate(Env.getCtx(), "Line"), p_tableName + ".Line", Integer.class),
new Info_Column(Msg.translate(Env.getCtx(), "M_Product_ID"), "(SELECT Name FROM M_Product p WHERE p.M_Product_ID=" +p_tableName + ".M_Product_ID)", String.class),
new Info_Column(Msg.translate(Env.getCtx(), "C_UOM_ID"), "(SELECT Name FROM C_UOM u WHERE u.C_UOM_ID=" +p_tableName + ".C_UOM_ID)", String.class),
new Info_Column(Msg.translate(Env.getCtx(), "QtyEntered"), p_tableName+".QtyEntered", BigDecimal.class),
new Info_Column(Msg.translate(Env.getCtx(), "QtyOrdered"), p_tableName+".QtyOrdered", BigDecimal.class),
new Info_Column(Msg.translate(Env.getCtx(), "DateOrdered"), p_tableName+".DateOrdered", Timestamp.class),
new Info_Column(Msg.translate(Env.getCtx(), "DateStartSchedule"), p_tableName+".DateStartSchedule", Timestamp.class),
new Info_Column(Msg.translate(Env.getCtx(), "DateFinishSchedule"), p_tableName+".DateFinishSchedule", Timestamp.class)
//new Info_Column(Msg.translate(Env.getCtx(), "DateOrdered"), "o.DatePromided", Timestamp.class),
//new Info_Column(Msg.translate(Env.getCtx(), "ConvertedAmount"), "C_Base_Convert(o.GrandTotal,o.C_Currency_ID,o.AD_Client_ID,o.DateAcct, o.AD_Org_ID)", BigDecimal.class),
//new Info_Column(Msg.translate(Env.getCtx(), "IsSOTrx"), "o.IsSOTrx", Boolean.class),
//new Info_Column(Msg.translate(Env.getCtx(), "Description"), "o.Description", String.class),
//new Info_Column(Msg.translate(Env.getCtx(), "POReference"), "o.POReference", String.class)
};
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {//GEN-BEGIN:initComponents
mainPanel = new javax.swing.JPanel();
OrderPlanning = new javax.swing.JTabbedPane();
PanelOrder = new javax.swing.JPanel();
PanelFind = new javax.swing.JPanel();
PanelCenter = new javax.swing.JPanel();
PanelBottom = new javax.swing.JPanel();
Results = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout());
mainPanel.setLayout(new java.awt.BorderLayout());
PanelOrder.setLayout(new java.awt.BorderLayout());
PanelOrder.add(PanelFind, java.awt.BorderLayout.NORTH);
PanelOrder.add(PanelCenter, java.awt.BorderLayout.CENTER);
PanelOrder.add(PanelBottom, java.awt.BorderLayout.SOUTH);
OrderPlanning.addTab("Order", PanelOrder);
OrderPlanning.addTab("Results", Results);
mainPanel.add(OrderPlanning, java.awt.BorderLayout.CENTER);
add(mainPanel, java.awt.BorderLayout.CENTER);
}//GEN-END:initComponents
/**
* Static Init
* @throws Exception
*/
protected void jbInit() throws Exception
{
//this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainPanel.setLayout(new java.awt.BorderLayout());
setLayout(new java.awt.BorderLayout());
southPanel.setLayout(southLayout);
southPanel.add(confirmPanel, BorderLayout.CENTER);
southPanel.add(statusBar, BorderLayout.SOUTH);
/*m_frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
m_frame.getContentPane().add(parameterPanel, BorderLayout.NORTH);
m_frame.getContentPane().add(scrollPane, BorderLayout.CENTER);*/
mainPanel.add(southPanel, BorderLayout.SOUTH);
mainPanel.add(parameterPanel, BorderLayout.NORTH);
mainPanel.add(scrollPane, BorderLayout.CENTER);
/*add(southPanel, BorderLayout.SOUTH);
add(parameterPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);*/
scrollPane.getViewport().add(p_table, null);
//
confirmPanel.addActionListener(this);
confirmPanel.getResetButton().setVisible(hasReset());
confirmPanel.getCustomizeButton().setVisible(hasCustomize());
confirmPanel.getHistoryButton().setVisible(hasHistory());
confirmPanel.getZoomButton().setVisible(hasZoom());
//
JButton print = ConfirmPanel.createPrintButton(true);
print.addActionListener(this);
confirmPanel.addButton(print);
//
popup.add(calcMenu);
calcMenu.setText(Msg.getMsg(Env.getCtx(), "Calculator"));
calcMenu.setIcon(new ImageIcon(org.compiere.Adempiere.class.getResource("images/Calculator16.gif")));
calcMenu.addActionListener(this);
//
p_table.getSelectionModel().addListSelectionListener(this);
enableButtons();
} // jbInit
/**
* Dynamic Init.
* Table Layout, Visual, Listener
*/
private void dynInit()
{
}
/**
* Fill Picks
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
//prepareTable (m_layout, getTableName(), " DocStatus='"+MPPOrder.DOCSTATUS_Drafted + "' " +find(), "2" );
prepareTable (m_layout, getTableName(), " DocStatus='"+MPPOrder.DOCSTATUS_Drafted + "' ", "2" );
executeQuery();
}
public void actionPerformed(ActionEvent e)
{
// Confirm Panel
String cmd = e.getActionCommand();
if (cmd.equals(ConfirmPanel.A_OK))
{
m_frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//System.out.println("Row ...ID " + row);
int rows[] = p_table.getSelectedRows();
for (int r = 0 ; r < rows.length ; r ++ )
{
IDColumn id = (IDColumn)p_table.getValueAt(rows[r], 0);
if (id != null)
{
Integer PP_Order_ID = id.getRecord_ID();
MPPOrder order = new MPPOrder(Env.getCtx(), PP_Order_ID.intValue(),null);
order.setDocStatus(order.prepareIt());
order.setDocAction(MPPOrder.DOCACTION_Prepare);
order.save();
}
}
if(rows.length != 0)
{
ADialog.info(m_WindowNo,this,"ProcessOK");
executeQuery();
m_frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
executeQuery();
}
m_frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
if (cmd.equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
dispose();
}
public void dispose() {
if (m_frame != null)
m_frame.dispose();
m_frame = null;
}
public void executeASync(org.compiere.process.ProcessInfo processInfo) {
}
public boolean isUILocked() {
return false;
}
public void lockUI(org.compiere.process.ProcessInfo processInfo) {
}
public void stateChanged(ChangeEvent e) {
}
public void tableChanged(TableModelEvent e) {
}
public void unlockUI(org.compiere.process.ProcessInfo processInfo) {
}
public void valueChanged(ListSelectionEvent e)
{
}
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
}
private String find()
{
//
GridField[] findFields = GridField.createFields(Env.getCtx(),AD_Window_ID, 0, AD_Tab_ID);
Find find = new Find (Env.getFrame(this),AD_Window_ID, this.getName() ,
AD_Tab_ID, AD_Table_ID, getTableName(),
"", findFields, 1);
MQuery query = find.getQuery();
if (query != null )
return query.getWhereClause();
else return "";
}
/*private MField[] getFields()
{
ArrayList list = new ArrayList();
M_Column[] cols = table.getColumns(true);
for (int c = 0 ; c < cols.length ; c++)
{
StringBuffer sql = new StringBuffer("SELECT * FROM AD_Column WHERE AD_Column_ID = " + cols[c].getAD_Column_ID());
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString());
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
MFieldVO vo = MFieldVO.create (Env.getCtx(), m_WindowNo, AD_Tab_ID , AD_Window_ID, true,rs);
MField field = new MField(vo);
//System.out.println("Columna -------:" + field.getColumnName());
list.add(field);
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, "InfoGeneral.initInfoTable 1", e);
}
}
//
MField[] lines = new MField[list.size ()];
list.toArray (lines);
return lines;
}*/
/**
* Reset Parameters
* To be overwritten by concrete classes
*/
void doReset() {}
/**
* Has Reset (false)
* To be overwritten by concrete classes
* @return true if it has reset (default false)
*/
boolean hasReset() {return false;}
/**
* History dialog
* To be overwritten by concrete classes
*/
void showHistory() {}
/**
* Has History (false)
* To be overwritten by concrete classes
* @return true if it has history (default false)
*/
boolean hasHistory() {return false;}
/**
* Customize dialog
* To be overwritten by concrete classes
*/
void customize() {}
/**
* Has Customize (false)
* To be overwritten by concrete classes
* @return true if it has customize (default false)
*/
boolean hasCustomize() {return false;}
/**
* Zoom action
* To be overwritten by concrete classes
*/
void zoom() {}
/**
* Has Zoom (false)
* To be overwritten by concrete classes
* @return true if it has zoom (default false)
*/
boolean hasZoom() {return false;}
/**
* Enable OK, History, Zoom if row selected
*/
void enableButtons ()
{
boolean enable = true;//p_table.getSelectedRow() != -1;
confirmPanel.getOKButton().setEnabled(true);
if (hasHistory())
confirmPanel.getHistoryButton().setEnabled(enable);
if (hasZoom())
confirmPanel.getZoomButton().setEnabled(enable);
} // enableButtons
/**************************************************************************
* Execute Query
*/
void executeQuery()
{
// ignore when running
if (m_worker != null && m_worker.isAlive())
return;
m_worker = new Worker();
m_worker.start();
} // executeQuery
/**************************************************************************
* Prepare Table, Construct SQL (m_m_sqlMain, m_sqlAdd)
* and size Window
* @param layout layout array
* @param from from clause
* @param staticWhere where clause
* @param orderBy order by clause
*/
protected void prepareTable (Info_Column[] layout, String from, String staticWhere, String orderBy)
{
p_layout = layout;
StringBuffer sql = new StringBuffer ("SELECT ");
// add columns & sql
for (int i = 0; i < layout.length; i++)
{
if (i > 0)
sql.append(", ");
sql.append(layout[i].getColSQL());
// adding ID column
if (layout[i].isIDcol())
sql.append(",").append(layout[i].getIDcolSQL());
// add to model
p_table.addColumn(layout[i].getColHeader());
if (layout[i].isColorColumn())
p_table.setColorColumn(i);
if (layout[i].getColClass() == IDColumn.class)
m_keyColumnIndex = i;
}
// set editors (two steps)
for (int i = 0; i < layout.length; i++)
p_table.setColumnClass(i, layout[i].getColClass(), layout[i].isReadOnly(), layout[i].getColHeader());
sql.append( " FROM ").append(from);
//
if (!staticWhere.equals(""))
sql.append(" WHERE ").append(staticWhere);
m_sqlMain = sql.toString();
m_sqlAdd = "";
if (orderBy != null && orderBy.length() > 0)
m_sqlAdd = " ORDER BY " + orderBy;
if (m_keyColumnIndex == -1)
log.log(Level.SEVERE, "Info.prepareTable - No KeyColumn - " + sql);
// Table Selection
p_table.setRowSelectionAllowed(true);
//p_table.addMouseListener(this);
p_table.setMultiSelection(false);
p_table.setEditingColumn(0);
p_table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Window Sizing
parameterPanel.setPreferredSize(new Dimension (INFO_WIDTH, parameterPanel.getPreferredSize().height));
scrollPane.setPreferredSize(new Dimension(INFO_WIDTH, 400));
} // prepareTable
/**
* Get the key of currently selected row
* @return selected key
*/
protected Integer getSelectedRowKey()
{
int row = p_table.getSelectedRow();
if (row != -1 && m_keyColumnIndex != -1)
{
Object data = p_table.getModel().getValueAt(row, m_keyColumnIndex);
if (data instanceof IDColumn)
data = ((IDColumn)data).getRecord_ID();
if (data instanceof Integer)
return (Integer)data;
}
return null;
} // getSelectedRowKey
/**
* Get Table name Synonym
* @return table name
*/
String getTableName()
{
table = new MTable(Env.getCtx(),AD_Table_ID,"AD_Table");
p_tableName = table.getTableName();
return p_tableName;
} // getTableName
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTabbedPane OrderPlanning;
private javax.swing.JPanel PanelBottom;
private javax.swing.JPanel PanelCenter;
private javax.swing.JPanel PanelFind;
private javax.swing.JPanel PanelOrder;
private javax.swing.JPanel Results;
private javax.swing.JPanel mainPanel;
// End of variables declaration//GEN-END:variables
/**
* Worker
*/
class Worker extends Thread
{
/**
* Do Work (load data)
*/
public void run()
{
log.fine("Info.Worker.run");
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
StringBuffer sql = new StringBuffer (m_sqlMain);
String dynWhere = find ();
if (dynWhere.length() > 0)
sql.append(" AND " + dynWhere); // includes first AND
sql.append(m_sqlAdd);
String xSql = Msg.parseTranslation(Env.getCtx(), sql.toString()); // Variables
xSql = MRole.getDefault().addAccessSQL(xSql, getTableName(),
MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);
try
{
PreparedStatement pstmt = DB.prepareStatement(xSql,null);
log.fine("SQL=" + xSql);
ResultSet rs = pstmt.executeQuery();
while (!isInterrupted() & rs.next())
{
int row = p_table.getRowCount();
p_table.setRowCount(row+1);
int colOffset = 1; // columns start with 1
for (int col = 0; col < p_layout.length; col++)
{
Object data = null;
Class<?> c = p_layout[col].getColClass();
int colIndex = col + colOffset;
if (c == IDColumn.class)
{
IDColumn id = new IDColumn(rs.getInt(colIndex));
id.setSelected(true);
data = id;
p_table.setColumnReadOnly(0, false);
}
else if (c == Boolean.class)
data = new Boolean("Y".equals(rs.getString(colIndex)));
else if (c == Timestamp.class)
data = rs.getTimestamp(colIndex);
else if (c == BigDecimal.class)
data = rs.getBigDecimal(colIndex);
else if (c == Double.class)
data = new Double(rs.getDouble(colIndex));
else if (c == Integer.class)
data = new Integer(rs.getInt(colIndex));
else if (c == KeyNamePair.class)
{
String display = rs.getString(colIndex);
int key = rs.getInt(colIndex+1);
data = new KeyNamePair(key, display);
colOffset++;
}
else
data = rs.getString(colIndex);
// store
p_table.setValueAt(data, row, col);
}
}
log.config("Interrupted=" + isInterrupted());
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, xSql, e);
}
p_table.autoSize();
//
setCursor(Cursor.getDefaultCursor());
} // run
} // Worker
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,784 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.logging.Level;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MProduct;
import org.compiere.model.MUOM;
import org.compiere.model.Query;
import org.compiere.swing.CCheckBox;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.util.CLogger;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.eevolution.model.MPPProductBOM;
import org.eevolution.model.MPPProductBOMLine;
/**
* BOM Tree Maintenance
*
* @author Victor Perez,Sergio Ramazzinag
* @version $Id: VTreeMaintenance.java,v 1.1 2004/03/20 04:35:51 jjanke Exp $
*
* 4Layers - MODIFICATIONS --------------------------------------------------------
* 2005/04/12 Various improvements to the standard form (Sergio Ramazzina)
* 4Layers -------------------------------------------------------------------- end
*
* @author Teo Sarca, SC ARHIPAC SERVICE SRL
*/
public class VTreeBOM extends CPanel implements FormPanel, ActionListener,
ListSelectionListener, PropertyChangeListener, VetoableChangeListener,
TreeSelectionListener, TableModelListener
{
private static final long serialVersionUID = 1L;
/**
* Tree Maintenance
*/
public VTreeBOM ()
{
} // VTreeMaintenance
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
/** Active Tree */
private JTree m_tree;
private static CLogger log = CLogger.getCLogger(VTreeBOM.class);
private BorderLayout mainLayout = new BorderLayout ();
private CPanel northPanel = new CPanel ();
private FlowLayout northLayout = new FlowLayout ();
private CLabel labelProduct = new CLabel ();
private VLookup fieldProduct;
//private CButton bAddAll = new CButton (Env.getImageIcon("FastBack24.gif"));
//private CButton bAdd = new CButton (Env.getImageIcon("StepBack24.gif"));
//private CButton bDelete = new CButton (Env.getImageIcon("StepForward24.gif"));
//private CButton bDeleteAll = new CButton (Env.getImageIcon("FastForward24.gif"));
private CCheckBox implosion = new CCheckBox ();
private CLabel treeInfo = new CLabel ();
//
private JSplitPane splitPane = new JSplitPane ();
//private VTreePanel centerTree;
//private JList centerList = new JList ();
private JScrollPane dataPane = new JScrollPane();
private JScrollPane treePane = new JScrollPane();
//private CLabel labelUOM = new CLabel();
//private CTextField fieldUOM = new CTextField(10);
//private CLabel labelDocument = new CLabel();
//private CTextField fieldDocument = new CTextField(10);
//private CLabel labelRevision = new CLabel();
//private CTextField fieldRevision = new CTextField(8);
//private CLabel labelECN = new CLabel();
//private CTextField fieldECN = new CTextField(10);
//private VDate dateFrom = new VDate ("DateFrom", false, false, true, DisplayType.Date, Msg.translate(getCtx(), "DateFrom"));
//private VDate dateTo = new VDate ("DateTo", false, false, true, DisplayType.Date, Msg.translate(getCtx(), "DateTo"));
private CPanel southPanel = new CPanel();
private BorderLayout southLayout = new BorderLayout();
private ConfirmPanel confirmPanel = new ConfirmPanel(true);
protected StatusBar statusBar = new StatusBar();
private MiniTable tableBOM = new MiniTable();
private Vector<Vector<Object>> dataBOM = new Vector<Vector<Object>>();
private Vector<String> columnNames;
//private VDate fieldGuaranteeDate =
//4Layers - Set divider location variable
private final int DIVIDER_LOCATION = 240;
// 4Layers - end
public Properties getCtx() {
return Env.getCtx();
}
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
m_WindowNo = WindowNo;
m_frame = frame;
log.info( "VMerge.init - WinNo=" + m_WindowNo);
try
{
preInit();
jbInit ();
frame.getContentPane().add(this, BorderLayout.CENTER);
// frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
//action_loadBOM();
}
catch (Exception ex)
{
log.log(Level.SEVERE,"VTreeMaintenance.init", ex);
}
} // init
/**
* Fill Tree Combo
*/
private void preInit() throws Exception
{
Properties ctx = getCtx();
Language language = Language.getLoginLanguage(); // Base Language
MLookup m_fieldProduct = MLookupFactory.get(ctx, m_WindowNo,
MColumn.getColumn_ID(MProduct.Table_Name, "M_Product_ID"),
DisplayType.Search, language, MProduct.COLUMNNAME_M_Product_ID, 0, false,
" M_Product.IsSummary = 'N'");
fieldProduct = new VLookup ("M_Product_ID", false, false, true, m_fieldProduct) {
private static final long serialVersionUID = 1L;
public void setValue(Object value) {
super.setValue(value);
action_loadBOM();
}
};
implosion.addActionListener(this);
splitPane.add (dataPane, JSplitPane.RIGHT);
splitPane.add (treePane, JSplitPane.LEFT);
} // preInit
/**
* Static Init.
* <pre>
* mainPanel
* northPanel
* centerPanel
* xMatched
* xPanel
* xMathedTo
* southPanel
* </pre>
* @throws Exception
*/
private void loadTableBOM()
{
// Header Info
columnNames = new Vector<String>(18);
columnNames.add(Msg.translate(getCtx(), "Select")); // 0
columnNames.add(Msg.translate(getCtx(), "IsActive")); // 1
columnNames.add(Msg.translate(getCtx(), "Line")); // 2
columnNames.add(Msg.translate(getCtx(), "ValidFrom")); // 3
columnNames.add(Msg.translate(getCtx(), "ValidTo")); // 4
columnNames.add(Msg.translate(getCtx(), "M_Product_ID")); // 5
columnNames.add(Msg.translate(getCtx(), "C_UOM_ID")); // 6
columnNames.add(Msg.translate(getCtx(), "IsQtyPercentage")); // 7
columnNames.add(Msg.translate(getCtx(), "QtyBatch")); // 8
columnNames.add(Msg.translate(getCtx(), "QtyBOM")); // 9
columnNames.add(Msg.translate(getCtx(), "IsCritical")); // 10
columnNames.add(Msg.translate(getCtx(), "LeadTimeOffset")); // 11
columnNames.add(Msg.translate(getCtx(), "Assay")); // 12
columnNames.add(Msg.translate(getCtx(), "Scrap")); // 13
columnNames.add(Msg.translate(getCtx(), "IssueMethod")); // 14
columnNames.add(Msg.translate(getCtx(), "BackflushGroup")); // 15
columnNames.add(Msg.translate(getCtx(), "Forecast")); // 16
// Remove previous listeners
tableBOM.getModel().removeTableModelListener(this);
// Remove previous listeners
tableBOM.getModel().removeTableModelListener(this);
// Set Model
DefaultTableModel model = new DefaultTableModel(dataBOM, columnNames);
model.addTableModelListener(this);
tableBOM.setModel(model);
tableBOM.setColumnClass( 0, Boolean.class, false); // 0 Select
tableBOM.setColumnClass( 1, Boolean.class, false); // 1 IsActive
tableBOM.setColumnClass( 2, Integer.class,false); // 2 Line
tableBOM.setColumnClass( 3, Timestamp.class,false); // 3 ValidFrom
tableBOM.setColumnClass( 4, Timestamp.class,false); // 4 ValidTo
tableBOM.setColumnClass( 5, KeyNamePair.class,false); // 5 M_Product_ID
tableBOM.setColumnClass( 6, KeyNamePair.class,false); // 6 C_UOM_ID
tableBOM.setColumnClass( 7, Boolean.class,false); // 7 QtyPorcentage
tableBOM.setColumnClass( 8, BigDecimal.class,false); // 8 BatchPercent
tableBOM.setColumnClass( 9, BigDecimal.class,false); // 9 QtyBOM
tableBOM.setColumnClass( 10, Boolean.class,false); // 10 IsCritical
tableBOM.setColumnClass( 11, BigDecimal.class,false); // 11 LTOffSet
tableBOM.setColumnClass( 12, BigDecimal.class,false); // 12 Assay
tableBOM.setColumnClass( 13, Integer.class,false); // 13 Scrap
tableBOM.setColumnClass( 14, String.class,false); // 14 IssueMethod
tableBOM.setColumnClass( 15, String.class,false); // 15 BackflushGroup
tableBOM.setColumnClass( 16, BigDecimal.class,false); // 16 Forecast
tableBOM.autoSize();
//tableBOM.prepareTable(layout, "", "", false, "");
// Visual
//CompiereColor.setBackground (this);
//tableBOM.getSelectionModel().addListSelectionListener(this);
} // dynInit
/**
* Static init
* @throws Exception
*/
private void jbInit ()
{
this.setLayout (mainLayout);
// 4Layers - Set initial window dimension
this.setPreferredSize(new Dimension(640, 480));
//labelUOM.setText (Msg.getElement(getCtx(), "C_UOM_ID"));
//fieldUOM.setEditable(false);
//labelDocument.setText (Msg.translate(getCtx(), "Document"));
//labelRevision.setText (Msg.translate(getCtx(), "Revision"));
//labelECN.setText (Msg.translate(getCtx(), "ECN"));
labelProduct.setText (Msg.getElement(getCtx(), "M_Product_ID"));
//implosion.setEnabled (false);
implosion.setText (Msg.getElement(getCtx(), "Implosion"));
//treeInfo.setText (" ");
//bAdd.setToolTipText("Add to Tree");
//bAddAll.setToolTipText("Add ALL to Tree");
//bDelete.setToolTipText("Delete from Tree");
//bDeleteAll.setToolTipText("Delete ALL from Tree");
//bAdd.addActionListener(this);
//bAddAll.addActionListener(this);
//bDelete.addActionListener(this);
//bDeleteAll.addActionListener(this);
northPanel.setLayout (northLayout);
northLayout.setAlignment (FlowLayout.LEFT);
//
this.add (northPanel, BorderLayout.NORTH);
northPanel.add (labelProduct, null);
northPanel.add (fieldProduct, null);
northPanel.add (implosion, null);
//northPanel.add (cbAllNodes, null);
northPanel.add (treeInfo, null);
//northPanel.add (labelUOM, null);
//northPanel.add (fieldUOM, null);
//northPanel.add (labelDocument, null);
//northPanel.add (fieldDocument, null);
//northPanel.add (labelRevision, null);
//northPanel.add (fieldRevision, null);
//northPanel.add (fieldECN, null);
//northPanel.add (bAddAll, null);
//northPanel.add (bAdd, null);
//northPanel.add (bDelete, null);
//northPanel.add (bDeleteAll, null);
//
this.add(southPanel, BorderLayout.SOUTH);
southPanel.setLayout(southLayout);
confirmPanel.addActionListener(this);
southPanel.add(confirmPanel, BorderLayout.SOUTH);
//southPanel.add(statusBar, BorderLayout.SOUTH);
this.add (splitPane, BorderLayout.CENTER);
// 4Layers - Set divider location
splitPane.setDividerLocation(DIVIDER_LOCATION);
//centerList.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
//centerList.addListSelectionListener(this);
} // jbInit
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
public void vetoableChange (PropertyChangeEvent e)
{
String name = e.getPropertyName();
Object value = e.getNewValue();
log.info( "VAllocation.vetoableChange - " + name + "=" + value);
if (value == null)
return;
// BPartner
if (name.equals("M_Product_ID"))
{
if (fieldProduct != null)
action_loadBOM();
}
} // vetoableChange
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
if (e.getSource() == implosion)
{
action_loadBOM();
}
if (e.getActionCommand().equals(ConfirmPanel.A_OK))
{
action_loadBOM();
}
// 4Layers - Close window when cancel is pressed
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
}
// 4Layers - End
/*else if (e.getSource() == bAddAll)
action_treeAddAll();
else if (e.getSource() == bAdd)
action_treeAdd((ListItem)centerList.getSelectedValue());
else if (e.getSource() == bDelete)
action_treeDelete((ListItem)centerList.getSelectedValue());
else if (e.getSource() == bDeleteAll)
action_treeDeleteAll();*/
//super.actionPerformed(e);
} // actionPerformed
/**
* Action: Fill Tree with all nodes
*/
private void action_loadBOM()
{
int M_Product_ID = getM_Product_ID();
if (M_Product_ID == 0)
return;
MProduct M_Product = MProduct.get(getCtx(), M_Product_ID);
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(productSummary(M_Product, false));
dataBOM.clear();
if (isImplosion())
{
for (MPPProductBOMLine bomline : getBOMLines(M_Product_ID))
{
parent.add(parent(bomline));
}
m_tree = new JTree(parent);
}
else
{
for (MPPProductBOM bom : getBOMs(M_Product_ID, true))
{
parent.add(parent(bom));
}
m_tree = new JTree(parent);
}
m_tree.addTreeSelectionListener(this);
treePane.getViewport().add (m_tree, null);
loadTableBOM();
dataPane.getViewport().add(tableBOM, null);
// 4Layers - Set divider location
splitPane.setDividerLocation(DIVIDER_LOCATION);
// 4Layers - end
} // action_fillTree
public DefaultMutableTreeNode parent(MPPProductBOMLine bomline)
{
//System.out.println("-------------------------Parent:" + bom.getName());
MProduct M_Product = MProduct.get(getCtx(), bomline.getM_Product_ID());
MPPProductBOM bomproduct = new MPPProductBOM(getCtx(), bomline.getPP_Product_BOM_ID(), null);
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(productSummary(M_Product, false));
Vector<Object> line = new Vector<Object>(17);
line.add( new Boolean(false)); // 0 Select
line.add( new Boolean(true)); // 1 IsActive
line.add( new Integer(bomline.getLine())); // 2 Line
line.add( (Timestamp) bomline.getValidFrom()); // 3 ValidDrom
line.add( (Timestamp) bomline.getValidTo()); // 4 ValidTo
KeyNamePair pp = new KeyNamePair(M_Product.getM_Product_ID(),M_Product.getName());
line.add(pp); // 5 M_Product_ID
KeyNamePair uom = new KeyNamePair(bomline.getC_UOM_ID(),"");
line.add(uom); // 6 C_UOM_ID
line.add(new Boolean(bomline.isQtyPercentage())); // 7 IsQtyPorcentage
line.add((BigDecimal) bomline.getQtyBatch()); // 8 BatchPercent
line.add((BigDecimal) ((bomline.getQtyBOM()!=null) ? bomline.getQtyBOM() : new BigDecimal(0))); // 9 QtyBOM
line.add(new Boolean(bomline.isCritical())); // 10 IsCritical
line.add( (Integer) bomline.getLeadTimeOffset()); // 11 LTOffSet
line.add( (BigDecimal) bomline.getAssay()); // 12 Assay
line.add( (BigDecimal) (bomline.getScrap())); // 13 Scrap
line.add( (String) bomline.getIssueMethod()); // 14 IssueMethod
line.add( (String) bomline.getBackflushGroup()); // 15 BackflushGroup
line.add( (BigDecimal) bomline.getForecast()); // 16 Forecast
dataBOM.add(line);
for (MPPProductBOM bom : getBOMs(bomproduct.getM_Product_ID(), false))
{
MProduct component = MProduct.get(getCtx(), bom.getM_Product_ID());
return component(component);
}
return parent;
}
public DefaultMutableTreeNode parent(MPPProductBOM bom)
{
// System.out.println("Parent:" + bom.getName());
// X_M_Product product = new X_M_Product(getCtx(), bom.getM_Product_ID(),"M_Product");
//vparent.setValue(m_product_id);
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(productSummary(bom));
for (MPPProductBOMLine bomline : bom.getLines())
{
MProduct component = MProduct.get(getCtx(), bomline.getM_Product_ID());
//System.out.println("Componente :" + component.getValue() + "[" + component.getName() + "]");
//component(component);
Vector<Object> line = new Vector<Object>(17);
line.add( new Boolean(false)); // 0 Select
line.add( new Boolean(true)); // 1 IsActive
line.add( new Integer(bomline.getLine())); // 2 Line
line.add( (Timestamp) bomline.getValidFrom()); // 3 ValidDrom
line.add( (Timestamp) bomline.getValidTo()); // 4 ValidTo
KeyNamePair pp = new KeyNamePair(component.getM_Product_ID(),component.getName());
line.add(pp); // 5 M_Product_ID
KeyNamePair uom = new KeyNamePair(bomline.getC_UOM_ID(),"");
line.add(uom); // 6 C_UOM_ID
line.add(new Boolean(bomline.isQtyPercentage())); // 7 IsQtyPercentage
line.add((BigDecimal) bomline.getQtyBatch()); // 8 BatchPercent
line.add((BigDecimal) bomline.getQtyBOM()); // 9 QtyBom
line.add(new Boolean(bomline.isCritical())); // 10 IsCritical
line.add( (Integer) bomline.getLeadTimeOffset()); // 11 LTOffSet
line.add( (BigDecimal) bomline.getAssay()); // 12 Assay
line.add( (BigDecimal) (bomline.getScrap())); // 13 Scrap
line.add( (String) bomline.getIssueMethod()); // 14 IssueMethod
line.add( (String) bomline.getBackflushGroup()); // 15 BackflushGroup
line.add( (BigDecimal) bomline.getForecast()); // 16 Forecast
//line.add(this.);
dataBOM.add(line);
parent.add(component(component));
}
return parent;
}
public DefaultMutableTreeNode component(MProduct M_Product)
{
if (isImplosion())
{
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(productSummary(M_Product, false));
for (MPPProductBOMLine bomline : getBOMLines(M_Product.getM_Product_ID()))
{
parent.add(parent(bomline));
}
return parent;
}
else
{
for (MPPProductBOM bom : getBOMs(M_Product.getValue()))
{
return parent(bom);
}
return new DefaultMutableTreeNode(productSummary(M_Product, true));
}
}
public void valueChanged(TreeSelectionEvent event)
{
//currentSelectionField.setText("Current Selection: " + tree.getLastSelectedPathComponent().toString());
}
/**
* List Selection Listener
* @param e event
*/
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting())
return;
} // valueChanged
/**
* VTreePanel Changed
* @param e event
*/
public void propertyChange (PropertyChangeEvent e)
{
//MTreeNode tn = (MTreeNode)e.getNewValue();
//log.info( "VTreeMaintenance.propertyChanged", tn);
//if (tn == null)
// return;
/*ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
if (item.id == tn.getNode_ID())
break;
}
centerList.setSelectedIndex(index);*/
} // propertyChange
/**
* Action: Add Node to Tree
*/
private void action_treeAdd(ListItem item)
{
log.info( "VTreeMaintenance.action_treeAdd " + item);
if (item != null)
{
//centerTree.nodeChanged(true, item.id, item.name,
// item.description, item.isSummary, item.imageIndicator);
/* if (m_tree.isProduct())
{
MTree_NodePR node = new MTree_NodePR (m_tree, item.id);
node.save();
}
else if (m_tree.isBPartner())
{
MTree_NodeBP node = new MTree_NodeBP (m_tree, item.id);
node.save();
}
else if (m_tree.isMenu())
{
MTree_NodeMM node = new MTree_NodeMM (m_tree, item.id);
node.save();
}
else
{
MTree_Node node = new MTree_Node (m_tree, item.id);
node.save();
}*/
}
} // action_treeAdd
/**
* Action: Delete Node from Tree
*/
private void action_treeDelete(ListItem item)
{
log.info( "VTreeMaintenance.action_treeDelete" + item);
if (item != null)
{
//centerTree.nodeChanged(false, item.id, item.name,
// item.description, item.isSummary, item.imageIndicator);
/*if (m_tree.isProduct())
{
MTree_NodePR node = MTree_NodePR.get (m_tree, item.id);
if (node != null)
node.delete();
}
else if (m_tree.isBPartner())
{
MTree_NodeBP node = MTree_NodeBP.get (m_tree, item.id);
if (node != null)
node.delete();
}
else if (m_tree.isMenu())
{
MTree_NodeMM node = MTree_NodeMM.get (m_tree, item.id);
if (node != null)
node.delete();
}
else
{
MTree_Node node = MTree_Node.get (m_tree, item.id);
if (node != null)
node.delete();
}*/
}
} // action_treeDelete
/**
* Action: Add All Nodes to Tree
*/
private void action_treeAddAll()
{
log.info( "VTreeMaintenance.action_treeAddAll");
/*ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeAdd(item);
}*/
} // action_treeAddAll
/**
* Action: Delete All Nodes from Tree
*/
private void action_treeDeleteAll()
{
log.info( "VTreeMaintenance.action_treeDeleteAll");
/*ListModel model = centerList.getModel();
int size = model.getSize();
int index = -1;
for (index = 0; index < size; index++)
{
ListItem item = (ListItem)model.getElementAt(index);
action_treeDelete(item);
}*/
}
public void tableChanged(TableModelEvent e) {
}
// action_treeDeleteAll
/**************************************************************************
* Tree Maintenance List Item
*/
class ListItem
{
public ListItem (int id, String name, String description, boolean isSummary, String imageIndicator)
{
this.id = id;
this.name = name;
this.description = description;
this.isSummary = isSummary;
this.imageIndicator = imageIndicator;
} // ListItem
public int id;
public String name;
public String description;
public boolean isSummary;
public String imageIndicator; // Menu - Action
/**
* To String
* @return String Representation
*/
public String toString ()
{
String retValue = name;
if (description != null && description.length() > 0)
retValue += " (" + description + ")";
return retValue;
} // toString
} // ListItem
private String productSummary(MProduct product, boolean isLeaf) {
MUOM uom = MUOM.get(getCtx(), product.getC_UOM_ID());
String value = product.getValue();
String name = product.get_Translation(MProduct.COLUMNNAME_Name);
//
StringBuffer sb = new StringBuffer(value);
if (name != null && !value.equals(name))
sb.append("_").append(product.getName());
sb.append(" [").append(uom.get_Translation(MUOM.COLUMNNAME_UOMSymbol)).append("]");
//
return sb.toString();
}
private String productSummary(MPPProductBOM bom) {
String value = bom.getValue();
String name = bom.get_Translation(MPPProductBOM.COLUMNNAME_Name);
//
StringBuffer sb = new StringBuffer(value);
if (name != null && !name.equals(value))
sb.append("_").append(name);
//
return sb.toString();
}
private boolean isImplosion() {
return implosion.isSelected();
}
private int getM_Product_ID() {
Integer Product = (Integer)fieldProduct.getValue();
if (Product == null)
return 0;
return Product.intValue();
}
private List<MPPProductBOM> getBOMs(String productValue)
{
int ad_client_id = Env.getAD_Client_ID(getCtx());
String filter = MPPProductBOM.COLUMNNAME_Value+"=? AND AD_Client_ID=?";
return new Query (getCtx(), MPPProductBOM.Table_Name, filter, null)
.setParameters(new Object[]{productValue, ad_client_id})
.list();
}
private List<MPPProductBOM> getBOMs(int M_Product_ID, boolean onlyActiveRecords)
{
String filter = MPPProductBOM.COLUMNNAME_M_Product_ID+"=?"
+(onlyActiveRecords ? " AND IsActive='Y'" : "");
return new Query(getCtx(), MPPProductBOM.Table_Name, filter, null)
.setParameters(new Object[]{M_Product_ID})
.list();
}
private List<MPPProductBOMLine> getBOMLines(int M_Product_ID)
{
String filter = MPPProductBOMLine.COLUMNNAME_M_Product_ID+"=?";
return new Query(getCtx(), MPPProductBOMLine.Table_Name, filter, null)
.setParameters(new Object[]{M_Product_ID})
.list();
}
} // VTreeMaintenance

View File

@ -1,45 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 2008 SC ARHIPAC SERVICE SRL. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*****************************************************************************/
package org.eevolution.form;
import org.compiere.apps.wf.WFPanel;
import org.compiere.util.DB;
import org.compiere.wf.MWorkflow;
/**
* Manufacturing WorkFlow Editor
* @author Teo Sarca, SC ARHIPAC SERVICE SRL
*/
public class WFPanelManufacturing extends WFPanel {
private static final long serialVersionUID = 1L;
private static final String WF_WhereClause = MWorkflow.COLUMNNAME_WorkflowType+" IN ("
+ DB.TO_STRING(MWorkflow.WORKFLOWTYPE_Manufacturing)
+","+DB.TO_STRING(MWorkflow.WORKFLOWTYPE_Quality)
+")";
private static final int WF_Window_ID = 53005; // TODO: HARDCODED (Manufacturing Workflows)
/*
SELECT AD_Window_Id
FROM AD_Window
WHERE Name = 'Manufacturing Workflows'
*/
/**
* Default constructor
*/
public WFPanelManufacturing() {
super(null, WF_WhereClause, WF_Window_ID);
}
}

View File

@ -1,167 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.action;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ResourceBundle;
import javax.swing.JMenuItem;
import org.compiere.model.PO;
import org.eevolution.tools.swing.SwingTool;
import org.eevolution.tools.worker.SingleWorker;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class PopupAction extends JMenuItem implements ActionListener {
protected final ResourceBundle language;
protected PropertyChangeSupport propertyChange;
protected boolean success;
protected boolean ignoreChange;
protected SingleWorker worker;
protected String errorMsg;
protected abstract void doAction(ActionEvent e);
protected abstract String getCommand();
protected abstract String validateAction();
protected boolean successful() {
return success;
}
public String getSuccessMsg() {
return "OK";
}
protected void setError(String msg) {
errorMsg = msg;
success = false;
}
public String getErrorMsg() {
return errorMsg;
}
public PopupAction(String property) {
super();
language = ResourceBundle.getBundle(getClass().getPackage().getName()+".language");
setText(language.getString(property));
setActionCommand(getCommand());
init();
addActionListener(this);
}
protected void init() {
this.success = true;
this.ignoreChange = false;
}
protected void beforeAction() {
init();
String valid = validateAction();
if(valid != null) {
setError(valid);
return;
}
SwingTool.setCursorsFromChild(this, true);
}
protected void afterAction() {
if(!isIgnoreChange()) {
propertyChange.firePropertyChange(getCommand(), false, successful());
}
SwingTool.setCursorsFromChild(this, false);
}
public void actionPerformed(ActionEvent e) {
final ActionEvent evt = e;
worker = new SingleWorker() {
protected Object doIt() {
run(evt);
return null;
};
};
worker.start();
}
protected void run(ActionEvent e) {
beforeAction();
if(getActionCommand() != null && getActionCommand().equals(e.getActionCommand())) {
doAction(e);
}
afterAction();
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
if(propertyChange == null) {
propertyChange = new PropertyChangeSupport(this);
}
propertyChange.addPropertyChangeListener(listener);
}
protected void setIgnoreChange(boolean ignore) {
ignoreChange = ignore;
}
public boolean isIgnoreChange() {
return ignoreChange;
}
protected void savePO(PO po) {
success = po.save(null);
}
protected void deletePO(PO po) {
success = po.delete(true, null);
}
}

View File

@ -1,140 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.action;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import javax.swing.JFrame;
import org.compiere.apps.ADialog;
import org.compiere.apps.ProcessParameter;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.process.ProcessInfoHandler;
import org.eevolution.tools.swing.SwingTool;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class ProcessPopupAction extends PopupAction {
protected JFrame window;
protected ProcessInfoHandler pih;
protected abstract void doProcess();
protected abstract int getProcessID();
public ProcessPopupAction(String property, JFrame window) {
super(property);
this.window = window;
}
protected void beforeAction() {
SwingTool.setCursorsFromParent(window.getContentPane(), true);
super.beforeAction();
pih = new ProcessInfoHandler(getProcessID());
showDialog(pih);
}
protected void doAction(ActionEvent e) {
if(successful()) {
doProcess();
}
}
protected void afterAction() {
super.afterAction();
if(isIgnoreChange()) {
SwingTool.setCursorsFromParent(window, false);
return;
}
if(successful()) {
ADialog.info(Env.getWindowNo(getWindow()), getWindow(), Msg.translate(Env.getCtx(), "Success"), getSuccessMsg());
}
else {
ADialog.error(Env.getWindowNo(getWindow()), getWindow(), Msg.translate(Env.getCtx(), "Error"), getErrorMsg());
}
SwingTool.setCursorsFromParent(window, false);
}
protected int getParameterValueAsInt(String name) {
Object o = pih.getParameterValue(name);
int value = -1;
if(o instanceof Integer) {
value = ((Integer)o).intValue();
}
else if(o instanceof BigDecimal) {
value = ((BigDecimal)o).intValue();
}
else {
value = Integer.parseInt(o.toString());
}
return value;
}
public JFrame getWindow() {
return window;
}
protected Object getParameterValue(String name) {
return pih.getParameterValue(name);
}
protected void showDialog(ProcessInfoHandler pib) {
ProcessParameter para = new ProcessParameter(
Env.getFrame((Container)window), Env.getWindowNo(window), pib.getProcessInfo());
if (para.initDialog()) {
para.setVisible(true);
if (!para.isOK()) {
setError(Msg.translate(Env.getCtx(), "Cancel"));
setIgnoreChange(true);
pib.setProcessError();
return;
}
}
}
}

View File

@ -1,191 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.action;
import java.awt.event.ActionEvent;
import java.lang.reflect.Field;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.apps.AEnv;
import org.compiere.apps.AWindow;
import org.compiere.model.MQuery;
import org.compiere.model.PO;
import org.eevolution.model.wrapper.AbstractPOWrapper;
/**
* Zoom Menu Action
*
* Zooms directly to a static destination window referred from action's properties or to a dynamic destination,
* dependent on action's instantiation w/o or with a target component.
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class ZoomMenuAction extends PopupAction {
public static final String COMMAND = "zoom";
protected Object target;
protected int tableID;
protected String tableName;
/**
* Constructs a new Instance with static zoom target, determined by . The properties are used to determine the
* zoom target.
*/
public ZoomMenuAction(int tableID, String tableName) {
super(COMMAND);
setActionCommand(COMMAND);
this.tableID = tableID;
this.tableName = tableName;
}
/**
* Constructs a new Instance with a overgiven target. E.g. use your JTree as target object. The nodes
* of your tree owns their compiere model objects (PO) as user objects.
* Supported classes are: JTree.
*
* @param target the target object.
* @throws an exception, if the target class isn't supported.
*/
public ZoomMenuAction(Object target) throws Exception {
super(COMMAND);
setActionCommand(COMMAND);
if(target != null && !(target instanceof JTree)) {
throw new Exception("Unsupported target component: "+ target.getClass().getName());
}
this.target = target;
}
protected String getCommand() {
return COMMAND;
}
protected String validateAction() {
return null;
}
protected void doAction(ActionEvent e) {
if(target != null) {
zoom(target);
}
else {
zoom();
}
}
protected boolean successful() {
return true;
}
public Object getTarget() {
return target;
}
private void zoom(Object obj) {
if(obj instanceof JTree) {
JTree tree = (JTree)obj;
Object node = tree.getSelectionPath().getLastPathComponent();
int tableId = 0;
int recordId = 0;
try {
tableId = getTableID((DefaultMutableTreeNode)node);
recordId = getRecordID((DefaultMutableTreeNode)node);
}
catch(Exception e) {
e.printStackTrace();
}
AEnv.zoom(tableId, recordId);
}
}
private int getTableID(DefaultMutableTreeNode tn) throws Exception {
PO po = null;
if(tn.getUserObject() instanceof PO) {
po = (PO)tn.getUserObject();
}
else if(tn.getUserObject() instanceof AbstractPOWrapper) {
po = ((AbstractPOWrapper)tn.getUserObject()).get();
}
else {
return -1;
}
Field f = po.getClass().getField("Table_ID");
return f.getInt(null);
}
private int getRecordID(DefaultMutableTreeNode tn) {
PO po = null;
if(tn.getUserObject() instanceof PO) {
po = (PO)tn.getUserObject();
}
else if(tn.getUserObject() instanceof AbstractPOWrapper) {
po = ((AbstractPOWrapper)tn.getUserObject()).get();
}
return po == null ? -1 : po.get_ID();
}
private void zoom() {
String tablename = tableName;
int tableid = tableID;
MQuery query = new MQuery();
query.setTableName(tablename);
AWindow window = new AWindow();
if (window.initWindow(tableid, query)) {
AEnv.showCenterScreen(window);
}
window = null;
}
}

View File

@ -1 +0,0 @@
zoom=Zoom

View File

@ -1,98 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import org.compiere.model.MProduct;
import org.eevolution.model.MPPOrder;
import org.eevolution.model.wrapper.BOMLineWrapper;
import org.eevolution.model.wrapper.BOMWrapper;
import org.eevolution.msg.HTMLMessenger;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class BOMMessenger extends HTMLMessenger {
protected JTree bomTree;
protected BOMTreeCellRenderer bomTreeCellRenderer;
protected HashMap cache;
public BOMMessenger(JTree bomTree) {
this.bomTree = bomTree;
this.cache = new HashMap();
}
public String getToolTipText(MouseEvent evt){
String tooltip = null;
if(bomTree.getRowForLocation(evt.getX(), evt.getY()) == -1) {
return tooltip;
}
return getToolTipText(bomTree.getPathForLocation(evt.getX(), evt.getY()));
}
public String getToolTipText(TreePath path){
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
String tooltip = (String)cache.get(node);
if(tooltip != null) {
return tooltip;
}
if(node.getUserObject() instanceof MProduct) {
tooltip = getProductInfo((MProduct)node.getUserObject());
}
if(node.getUserObject() instanceof MPPOrder) {
tooltip = getMfcOrderInfo((MPPOrder)node.getUserObject());
}
else if(node.getUserObject() instanceof BOMWrapper) {
tooltip = getBOMInfo((BOMWrapper)node.getUserObject());
}
else if(node.getUserObject() instanceof BOMLineWrapper) {
tooltip = getBOMLineInfo((BOMLineWrapper) node.getUserObject());
}
cache.put(node, tooltip);
return tooltip;
}
public static String getToolTipText(JTree tree, MouseEvent evt) {
BOMMessenger msg = new BOMMessenger(tree);
return msg.getToolTipText(evt);
}
}

View File

@ -1,50 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.util.Env;
import org.eevolution.form.tree.MapTreeCellRenderer;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class BOMTreeCellRenderer extends MapTreeCellRenderer {
public BOMTreeCellRenderer(HashMap map) {
super(map);
}
protected ImageIcon getIcon(Object value) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
ImageIcon icon = null;
if(node.isLeaf()) {
icon = Env.getImageIcon("Product10.gif");
}
return icon;
}
}

View File

@ -1,210 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.util.HashMap;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.model.MProduct;
import org.compiere.model.MResource;
import org.compiere.model.PO;
import org.compiere.util.Env;
import org.eevolution.model.MPPOrder;
import org.eevolution.model.reasoner.StorageReasoner;
import org.eevolution.model.wrapper.BOMLineWrapper;
import org.eevolution.model.wrapper.BOMWrapper;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class BOMTreeFactory implements BOMTreeModel {
protected JTree tree;
protected HashMap mapping;
protected BOMMessenger msg;
private StorageReasoner reasoner;
protected abstract String type();
public static BOMTreeModel get(String bomType, PO po, StorageReasoner reasoner) {
final StorageReasoner r = reasoner;
final String type = bomType;
BOMTreeFactory factory = new BOMTreeFactory() {
protected String type() {
return type;
};
};
factory.buildTree(po, reasoner);
return factory;
}
private StorageReasoner getStorageReasoner() {
return reasoner;
}
protected void buildTree(PO po, StorageReasoner reasoner) {
this.reasoner = reasoner;
tree = new JTree(buildStructure(po, reasoner)) {
public String getToolTipText(MouseEvent event) {
return msg.getToolTipText(event);
};
};
tree.setCellRenderer(new BOMTreeCellRenderer(getNodeMapping()));
msg = new BOMMessenger(tree);
}
protected DefaultMutableTreeNode buildStructure(PO po, StorageReasoner reasoner) {
mapping = new HashMap();
DefaultMutableTreeNode root = new DefaultMutableTreeNode(po);
mapping.put(root, getTreeNodeRepresentation(root));
BOMWrapper bom = null;
String restriction = null;
if(po instanceof MProduct) {
restriction = MProduct.Table_Name+"_ID";
}
else if(po instanceof MPPOrder) {
restriction = MPPOrder.Table_Name+"_ID";
}
int[] ids = reasoner.getPOIDs(BOMWrapper.tableName(type()), "IsActive = 'Y' AND "+restriction+" = " + po.get_ID(), null);
for(int i = 0; i < ids.length; i++) {
bom = new BOMWrapper(Env.getCtx(), ids[i], null, type());
root.add(getNode(bom, null, mapping));
}
return root;
}
protected DefaultMutableTreeNode getNode(BOMWrapper bom, BigDecimal qty, HashMap map) {
MProduct product = new MProduct(Env.getCtx(), bom.getM_Product_ID(),MProduct.Table_Name);
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(bom);;
map.put(parent, getTreeNodeRepresentation(parent));
DefaultMutableTreeNode node = null;
DefaultMutableTreeNode leaf = null;
int[] ids = getStorageReasoner().getPOIDs(BOMLineWrapper.tableName(type()), BOMWrapper.idColumn(type())+" = "+bom.getID(), null);
BOMLineWrapper bomline = null;
MProduct p = null;
for(int i = 0; i < ids.length; i++) {
bomline = new BOMLineWrapper(Env.getCtx(), ids[i], null, type());
bomline.setQtyBOM(qty != null ? qty.multiply(bomline.getQtyBOM()) : bomline.getQtyBOM());
p = new MProduct(Env.getCtx(), bomline.getM_Product_ID(), null);
node = addLeafs(p, qty, map);
leaf = new DefaultMutableTreeNode(bomline);
map.put(leaf, getTreeNodeRepresentation(leaf));
parent.add( (node==null) ? leaf : node);
}
return parent;
}
protected DefaultMutableTreeNode addLeafs(MProduct M_Product, BigDecimal qty, HashMap map) {
int[] ids = getStorageReasoner().getPOIDs(BOMWrapper.tableName(type()), "Value = '"+M_Product.getValue()+"'", null);
BOMWrapper bom = null;
for(int i = 0; i < ids.length; i++) {
bom = new BOMWrapper(Env.getCtx(), ids[i], null, type());
return getNode(bom, qty, map);
}
return null;
}
protected String getTreeNodeRepresentation(DefaultMutableTreeNode node) {
String name = null;
if(node.getUserObject() instanceof MProduct) {
MProduct p = (MProduct)node.getUserObject();
name = p.getName()+" ("+p.getValue()+")";
}
if(node.getUserObject() instanceof MPPOrder) {
MPPOrder o = (MPPOrder)node.getUserObject();
MResource r = MResource.get(Env.getCtx(), o.getS_Resource_ID());
name = o.getDocumentNo()+" ("+r.getName()+")";
}
else if(node.getUserObject() instanceof BOMWrapper) {
BOMWrapper pb = (BOMWrapper)node.getUserObject();
MProduct p = new MProduct(Env.getCtx(), pb.getM_Product_ID(), null);
name = pb.getName();
}
else if(node.getUserObject() instanceof BOMLineWrapper) {
BOMLineWrapper mpbl = (BOMLineWrapper)node.getUserObject();
MProduct p = new MProduct(Env.getCtx(), mpbl.getM_Product_ID(), null);
name = p.getName();
}
return name;
}
public JTree getTree() {
return this.tree;
}
public HashMap getNodeMapping() {
return this.mapping;
}
public BOMMessenger getBOMMessenger() {
return this.msg;
}
}

View File

@ -1,33 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom;
import java.util.HashMap;
import javax.swing.JTree;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public interface BOMTreeModel {
public JTree getTree();
public HashMap getNodeMapping();
public BOMMessenger getBOMMessenger();
}

View File

@ -1,496 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2008 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
//RadioButtonTreeCellRenderer.java
package org.eevolution.form.bom;
import it.cnr.imaa.essi.lablib.gui.checkboxtree.CheckboxTree;
import it.cnr.imaa.essi.lablib.gui.checkboxtree.CheckboxTreeCellRenderer;
import it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingEvent;
import it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingListener;
import it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingModel;
import java.awt.Color;
import java.awt.Component;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Vector;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.compiere.model.MProduct;
import org.compiere.model.MUOM;
import org.compiere.model.Query;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;
import org.eevolution.model.MPPProductBOM;
import org.eevolution.model.MPPProductBOMLine;
public class RadioButtonTreeCellRenderer implements CheckboxTreeCellRenderer {
JRadioButton button = new JRadioButton();
JCheckBox checkBox = new JCheckBox();
JPanel panel = new JPanel();
JLabel label = new JLabel();
//ButtonGroup group = new ButtonGroup();
boolean toggle = false;
private Vector<Vector<Comparable<?>>> dataBOM = new Vector<Vector<Comparable<?>>>();
public DefaultMutableTreeNode root = null;
public HashSet<TreePath> checkedPathsSet = new HashSet<TreePath>();
public HashSet<TreePath> greyedPathsSet = new HashSet<TreePath>();
public HashSet<TreePath> disabledPathsSet = new HashSet<TreePath>();
public HashSet<TreePath> checkBoxPathsSet = new HashSet<TreePath>();
private static CLogger log = CLogger.getCLogger(RadioButtonTreeCellRenderer.class);
public DefaultMutableTreeNode getTreeNodeForNodeUserObject(nodeUserObject m_nodeUserObject) {
log.fine("In getTreeNodeForNodeUserObject");
DefaultMutableTreeNode foundChild = null;
Enumeration<?> children = this.root.breadthFirstEnumeration();
if (children != null) {
while (children.hasMoreElements()) {
DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
if(m_nodeUserObject == (nodeUserObject)child.getUserObject()) {
log.fine("nodeUserObjectFound");
foundChild = child;
}
}
}
return foundChild;
}
public static void printDescendents(TreeNode root) {
log.fine(root.toString());
Enumeration<?> children = root.children();
if (children != null) {
while (children.hasMoreElements()) {
printDescendents((TreeNode) children.nextElement());
}
}
}
/**
* Action: Fill Tree with all nodes
*/
public DefaultMutableTreeNode action_loadBOM(MProduct Product, boolean setRoot)
{
int M_Product_ID = Product.get_ID();
MProduct M_Product = MProduct.get(Env.getCtx(), M_Product_ID);
MUOM UOM = new MUOM(Env.getCtx() , M_Product.getC_UOM_ID(), null);
DefaultMutableTreeNode root = new DefaultMutableTreeNode(new nodeUserObject(Msg.translate(Env.getCtx(), "M_Product_ID") + Msg.translate(Env.getCtx(), "Value") + ": " + M_Product.getValue() + " " + Msg.translate(Env.getCtx(), "Name") + ": " +M_Product.getName() + " " + Msg.translate(Env.getCtx(), "C_UOM_ID") + ": " + UOM.getName(), M_Product, null, null));
if(setRoot) {
this.root = root;
}
dataBOM.clear();
if (false)
{
String whereClause = "M_Product_ID=?";
List<MPPProductBOMLine> bomlines = new Query(Env.getCtx(),MPPProductBOMLine.Table_Name,whereClause, null)
.setParameters(new Object[]{M_Product_ID})
.list();
for (MPPProductBOMLine bomline : bomlines)
{
root.add(parent(bomline));
}
}
else
{
String whereClause = "M_Product_ID=?";
List<MPPProductBOM> boms = new Query(Env.getCtx(),MPPProductBOM.Table_Name,whereClause, null)
.setParameters(new Object[]{M_Product_ID})
.setOnlyActiveRecords(true)
.list();
for (MPPProductBOM bom : boms)
{
DefaultMutableTreeNode child = parent(bom);
root.add(child);
}
}
log.fine("root.getChildCount: " + root.getChildCount());
if(root.getChildCount() > 0) {
root = (DefaultMutableTreeNode)root.getFirstChild();
}
if(setRoot)
this.root = root;
return root;
} // action_fillTree
public DefaultMutableTreeNode parent(MPPProductBOMLine bomline)
{
log.fine("In parent with X_PP_Product_BOMLine");
MProduct M_Product = MProduct.get(Env.getCtx(), bomline.getM_Product_ID());
MUOM UOM = new MUOM(Env.getCtx() , M_Product.getC_UOM_ID(),null);
MPPProductBOM bomproduct = new MPPProductBOM(Env.getCtx(),bomline.getPP_Product_BOM_ID(),null);
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(new nodeUserObject(Msg.translate(Env.getCtx(), "M_Product_ID") + Msg.translate(Env.getCtx(), "key") + ": " + M_Product.getValue() + " " + Msg.translate(Env.getCtx(), "Name") + ": " +M_Product.getName() + " " + Msg.translate(Env.getCtx(), "C_UOM_ID") + ": " + UOM.getName(), M_Product, bomproduct, bomline));
Vector<Comparable<?>> line = new Vector<Comparable<?>>(17);
line.add( new Boolean(false)); // 0 Select
line.add( new Boolean(true)); // 1 IsActive
line.add( new Integer(bomline.getLine())); // 2 Line
line.add( (Timestamp) bomline.getValidFrom()); // 3 ValidDrom
line.add( (Timestamp) bomline.getValidTo()); // 4 ValidTo
KeyNamePair pp = new KeyNamePair(M_Product.getM_Product_ID(),M_Product.getName());
line.add(pp); // 5 M_Product_ID
KeyNamePair uom = new KeyNamePair(bomline.getC_UOM_ID(),"");
line.add(uom); // 6 C_UOM_ID
line.add(new Boolean(bomline.isQtyPercentage())); // 7 IsQtyPorcentage
line.add((BigDecimal) bomline.getQtyBatch()); // 8 BatchPercent
line.add((BigDecimal) ((bomline.getQtyBOM()!=null) ? bomline.getQtyBOM() : new BigDecimal(0))); // 9 QtyBOM
line.add(new Boolean(bomline.isCritical())); // 10 IsCritical
line.add( (Integer) bomline.getLeadTimeOffset()); // 11 LTOffSet
line.add( (BigDecimal) bomline.getAssay()); // 12 Assay
line.add( (BigDecimal) (bomline.getScrap())); // 13 Scrap
line.add( (String) bomline.getIssueMethod()); // 14 IssueMethod
line.add( (String) bomline.getBackflushGroup()); // 15 BackflushGroup
line.add( (BigDecimal) bomline.getForecast()); // 16 Forecast
dataBOM.add(line);
String whereClause = "M_Product_ID=?";
List<MPPProductBOM> boms = new Query(Env.getCtx(),MPPProductBOM.Table_Name,whereClause, null)
.setParameters(new Object[]{bomproduct.getM_Product_ID()})
.setOnlyActiveRecords(true)
.list();
for (MPPProductBOM bom : boms)
{
MProduct component = MProduct.get(Env.getCtx(), bom.getM_Product_ID());
return component(component, bom, bomline);
}
return parent;
}
public DefaultMutableTreeNode parent(MPPProductBOM bom)
{
log.fine("Parent:" + bom.getName());
MProduct product = MProduct.get(Env.getCtx(), bom.getM_Product_ID());
//vparent.setValue(m_product_id);
String data = Msg.translate(Env.getCtx(), "PP_Product_BOM_ID") + " " + Msg.translate(Env.getCtx(), "Value") + ":"+ bom.getValue()+ " " + Msg.translate(Env.getCtx(), "Name") + ": " + bom.getName();
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(new nodeUserObject(data, product, bom, null));
String whereClause = "PP_Product_BOM_ID=?";
List<MPPProductBOMLine> bomlines = new Query(Env.getCtx(),MPPProductBOMLine.Table_Name,whereClause, null)
.setParameters(new Object[]{bom.getPP_Product_BOM_ID()})
.list();
for (MPPProductBOMLine bomline : bomlines)
{
MProduct component = MProduct.get(Env.getCtx(), bomline.getM_Product_ID());
//System.out.println("Componente :" + component.getValue() + "[" + component.getName() + "]");
//component(component);
Vector<Comparable<?>> line = new Vector<Comparable<?>>(17);
line.add( new Boolean(false)); // 0 Select
line.add( new Boolean(true)); // 1 IsActive
line.add( new Integer(bomline.getLine())); // 2 Line
line.add( (Timestamp) bomline.getValidFrom()); // 3 ValidDrom
line.add( (Timestamp) bomline.getValidTo()); // 4 ValidTo
KeyNamePair pp = new KeyNamePair(component.getM_Product_ID(),component.getName());
line.add(pp); // 5 M_Product_ID
KeyNamePair uom = new KeyNamePair(bomline.getC_UOM_ID(),"");
line.add(uom); // 6 C_UOM_ID
line.add(new Boolean(bomline.isQtyPercentage())); // 7 IsQtyPercentage
line.add((BigDecimal) bomline.getQtyBatch()); // 8 BatchPercent
line.add((BigDecimal) bomline.getQtyBOM()); // 9 QtyBom
line.add(new Boolean(bomline.isCritical())); // 10 IsCritical
line.add( (Integer) bomline.getLeadTimeOffset()); // 11 LTOffSet
line.add( (BigDecimal) bomline.getAssay()); // 12 Assay
line.add( (BigDecimal) (bomline.getScrap())); // 13 Scrap
line.add( (String) bomline.getIssueMethod()); // 14 IssueMethod
line.add( (String) bomline.getBackflushGroup()); // 15 BackflushGroup
line.add( (BigDecimal) bomline.getForecast()); // 16 Forecast
//line.add(this.);
dataBOM.add(line);
parent.add(component(component, bom, bomline));
}
return parent;
}
public DefaultMutableTreeNode component(MProduct M_Product, MPPProductBOM bomPassed, MPPProductBOMLine bomlinePassed)
{
MUOM UOM = new MUOM(Env.getCtx() , M_Product.getC_UOM_ID(),null);
String whereClause = "Value=?";
List<MPPProductBOM> boms = new Query(Env.getCtx(),MPPProductBOM.Table_Name,whereClause, null)
.setParameters(new Object[]{M_Product.getValue()})
.setOnlyActiveRecords(true)
.list();
for (MPPProductBOM bom : boms)
{
return parent(bom);
}
return new DefaultMutableTreeNode(new nodeUserObject(Msg.translate(Env.getCtx(), "Value") + ": " + M_Product.getValue() + " " + Msg.translate(Env.getCtx(), "Name") + ": " +M_Product.getName() + " " + Msg.translate(Env.getCtx(), "C_UOM_ID") + ": " + UOM.getName(), M_Product, bomPassed, bomlinePassed));
}
public boolean isOnHotspot(int x, int y) {
return (button.getBounds().contains(x, y));
}
protected TreePath[] getChildrenPath(TreePath path, TreeModel model) {
Object node = path.getLastPathComponent();
int childrenNumber = model.getChildCount(node);
TreePath[] childrenPath = new TreePath[childrenNumber];
for (int childIndex = 0; childIndex < childrenNumber; childIndex++) {
childrenPath[childIndex] = path.pathByAddingChild(model.getChild(node, childIndex));
}
return childrenPath;
}
public TreePath getPath(TreeNode node) {
java.util.List<TreeNode> list = new ArrayList<TreeNode>();
// Add all nodes to list
while (node != null) {
list.add(node);
node = node.getParent();
}
Collections.reverse(list);
// Convert array of nodes to TreePath
return new TreePath(list.toArray());
}
public void printTree(TreePath path, TreeModel model, TreeCheckingModel checkingModel ) {
log.fine("In printTree");
DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
log.fine("Node: " + node);
log.fine("isPathCheckbox: " + checkingModel.isPathCheckBox(getPath(node)));
for (TreePath childPath : getChildrenPath(path, model)) {
printTree(childPath, model, checkingModel);
}
return;
}
public String getComponentTypeUsingBOMParent(int bom_id, int m_product_id) {
String retVal = "";
String sql = "select componenttype from pp_product_bomline where pp_product_bom_id = ? and m_product_id = ?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = DB.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, "test");
pstmt.setInt(1, bom_id);
pstmt.setInt(2, m_product_id);
rs = pstmt.executeQuery();
while (rs.next()) {
retVal = rs.getString(1);
}
rs.close();
pstmt.close();
} catch (SQLException e) {
log.fine("Execption; sql = "+sql+"; e.getMessage() = " +e.getMessage());
}
return retVal;
}
public Component getTreeCellRendererComponent(JTree tree, Object
value, boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
log.fine("row: " + row);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value;
log.fine("treeNode.getLevel: " + treeNode.getLevel());
nodeUserObject m_nodeUserObject = (nodeUserObject)treeNode.getUserObject();
log.fine("m_nodeUserObject.toString: " + m_nodeUserObject.toString());
log.fine("m_nodeUserObject.M_Product.getName: " + m_nodeUserObject.M_Product.getName());
log.fine("value.toString: " + value.toString());
label.setText(value.toString());
TreeCheckingModel checkingModel = ((CheckboxTree)tree).getCheckingModel();
//printTree(new TreePath(tree.getModel().getRoot()), tree.getModel(), checkingModel);
TreePath path = tree.getPathForRow(row);
boolean enabled = checkingModel.isPathEnabled(path);
boolean checked = checkingModel.isPathChecked(path);
// boolean checkBoxed = checkingModel.isPathCheckBox(path);
checked = checkingModel.isPathChecked(path);
// boolean grayed = checkingModel.isPathGreyed(path);
button.setEnabled(true);
button.setSelected(checked);
m_nodeUserObject.isChosen = checked;
log.fine("m_nodeUserObject.isChosen" + m_nodeUserObject.isChosen);
if(m_nodeUserObject.isCheckbox || treeNode.isRoot() ) {
panel.add(checkBox);
panel.remove(button);
log.fine("checked: " + checked);
log.fine("enabled: " + enabled);
checkBox.setEnabled(enabled);
checkBox.setSelected(checked);
if(treeNode.isRoot()) {
checkBox.setSelected(true);
checkBox.setEnabled(false);
m_nodeUserObject.isMandatory = true;
}
if(m_nodeUserObject.isMandatory) {
checkBox.setSelected(true);
checkBox.setEnabled(false);
}
} else {
panel.remove(checkBox);
panel.add(button);
}
panel.add(label);
m_nodeUserObject.isChosen = checked;
log.fine("m_nodeUserObject.isChosen: " + m_nodeUserObject.isChosen);
if( m_nodeUserObject.bom!= null) {
log.fine("m_nodeUserObject.bom not null");
log.fine("m_nodeUserObject.bom product_id: " + m_nodeUserObject.bom.getM_Product_ID());
if( m_nodeUserObject.bomLine == null) {
log.fine("m_nodeUserObject.bomLine is null");
DefaultMutableTreeNode m_treeNode = getTreeNodeForNodeUserObject(m_nodeUserObject);
if(!m_treeNode.isRoot()) {
DefaultMutableTreeNode m_treeNodeParent = (DefaultMutableTreeNode)m_treeNode.getParent();
if(m_treeNodeParent.isRoot()) {
m_nodeUserObject.isMandatory = true;
}
nodeUserObject m_nodeUserObjectParent = (nodeUserObject)m_treeNodeParent.getUserObject();
if(m_nodeUserObjectParent.bom != null) {
log.fine("m_nodeUserObjectParent.bom is not null");
log.fine("m_nodeUserObjectParent.bom.pp_product_bom_id: " + m_nodeUserObjectParent.bom.get_ID());
log.fine("m_nodeUserObject.M_Product.get_ID: " + m_nodeUserObject.M_Product.get_ID());
if(getComponentTypeUsingBOMParent(m_nodeUserObjectParent.bom.get_ID(), m_nodeUserObject.M_Product.get_ID()).equals(MPPProductBOMLine.COMPONENTTYPE_Variant) || getComponentTypeUsingBOMParent(m_nodeUserObjectParent.bom.get_ID(), m_nodeUserObject.M_Product.get_ID()).equals(MPPProductBOMLine.COMPONENTTYPE_Component)) {
log.fine("Type is checkbox");
if(!m_nodeUserObject.isCheckbox) {
m_nodeUserObject.isCheckbox = true;
panel.remove(label);
panel.add(checkBox);
panel.add(label);
panel.remove(button);
if(!m_nodeUserObject.isChosen) {
checkBox.setSelected(false);
m_nodeUserObject.isChosen = false;
} else {
checkBox.setSelected(true);
m_nodeUserObject.isMandatory = true;
m_nodeUserObject.isChosen = true;
}
}
}
} else {
log.fine("Type is checkbox");
if(!m_nodeUserObject.isCheckbox) {
panel.remove(label);
panel.add(checkBox);
panel.add(label);
panel.remove(button);
}
}
}
} else {
log.fine("m_nodeUserObject.bomLine is not null");
log.fine("m_nodeUserObject.M_Product.get_ID: " + m_nodeUserObject.M_Product.get_ID());
log.fine("m_nodeUserObject.bomLine.getM_Product_ID: " + m_nodeUserObject.bomLine.getM_Product_ID());
log.fine("m_nodeUserObject.isCheckbox: " + m_nodeUserObject.isCheckbox);
}
}
panel.setBackground(Color.white);
log.fine("m_nodeUserObject.isChosen: " + m_nodeUserObject.isChosen);
return panel;
}
public static void main(String[] args) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode one = new DefaultMutableTreeNode("one");
DefaultMutableTreeNode two = new DefaultMutableTreeNode("two");
DefaultMutableTreeNode three = new DefaultMutableTreeNode("three");
root.add(one);
root.add(two);
root.add(three);
RadioButtonTreeCellRenderer m_RadioButtonTreeCellRenderer = new RadioButtonTreeCellRenderer();
final CheckboxTree tree = new CheckboxTree(m_RadioButtonTreeCellRenderer.action_loadBOM(null, false));
tree.getCheckingModel().setCheckingMode(it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingModel.CheckingMode.SIMPLE);
tree.getCheckingModel().clearChecking();
tree.setCellRenderer(m_RadioButtonTreeCellRenderer);
tree.addTreeCheckingListener(new TreeCheckingListener() {
public void valueChanged(TreeCheckingEvent e) {
log.fine("Checked paths changed: user clicked on " + (e.getLeadingPath().getLastPathComponent()));
// TreeModel tm = tree.getModel();
// TreePath selected = tree.getSelectionPath();
// TreeCheckingModel checkingModel = ((CheckboxTree)tree).getCheckingModel();
}
});
JFrame frame = new JFrame("RadioButton tree");
frame.add(tree);
tree.expandAll();
frame.pack();
frame.setVisible(true);
}
}

View File

@ -1,152 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom.action;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.apps.search.PAttributeInstance;
import org.compiere.model.MAttributeSetInstance;
import org.compiere.model.MProduct;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.form.action.ProcessPopupAction;
import org.eevolution.model.wrapper.BOMLineWrapper;
/**
* @author Victor Perez, e-Evolution, S.C.
* Change Attribute Set Instance
*
* Allows by tree selection the change of the product's attribute set instance by
* choosing an existing other from a list for this product.
*
* !NOTICE! : Hardcoded process id 1000102 expected.
*
* AD_Process:
* INSERT INTO ad_process VALUES (1000102, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, '10000007', 'Change ASI', NULL, NULL, '3', 'U', NULL, 'N', 'N', NULL, 'com.compiere.form.bom.action.ChangeASIAction', 0, 0, NULL, NULL, NULL, 'N');
*
* AD_Process_Para:
* INSERT INTO ad_process_para VALUES (1000249, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, 'M_Warehouse_ID', NULL, NULL, 1000102, 10, 18, 197, NULL, 'M_Warehouse_ID', 'Y', 0, 'N', 'N', NULL, NULL, NULL, NULL, NULL, 459, 'U');
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class ChangeASIAction extends ProcessPopupAction {
public static final String COMMAND = "changeASI";
// Hard coded process id. Expected process is 'Create RfQ'.
final public static int PROCESS_ID = 1000102;
protected JTree tree;
/**
* Constructs a new Instance.
*/
public ChangeASIAction(JTree tree, JFrame window) {
super(COMMAND, window);
this.tree = tree;
}
protected String getCommand() {
return COMMAND;
}
protected int getProcessID() {
return PROCESS_ID;
}
protected String validateAction() {
String validate = null;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
BOMLineWrapper line = null;
if(!(node.getUserObject() instanceof BOMLineWrapper)) {
validate = "'"+node.getUserObject().getClass().getName()+"' isn't a type of 'BOMLineWrapper'(ClassCastException)";
}
else {
line = (BOMLineWrapper)node.getUserObject();
MProduct p = new MProduct(Env.getCtx(), line.getM_Product_ID(), null);
if(p.getM_AttributeSet_ID() == 0) {
validate = Msg.getMsg(Env.getCtx(), "PAttributeNoAttributeSet");
}
}
return validate;
}
protected void doProcess() {
if(tree != null) {
changeASI((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent());
}
}
private void changeBOMLine(BOMLineWrapper line, MProduct p, MAttributeSetInstance asi) {
//BigDecimal maxLength = messenger.getLength(p, asi);
//BigDecimal neededLength = line.getLength();
//BigDecimal onehundred = new BigDecimal(100);
//line.setQtyBatch(neededLength.divide(maxLength, 2, BigDecimal.ROUND_HALF_UP).multiply(onehundred));
//line.setScrap(onehundred.subtract(line.getQtyBatch()).intValue());
line.setM_AttributeSetInstance_ID(asi.getM_AttributeSetInstance_ID());
savePO(line.get());
}
private void changeASI(DefaultMutableTreeNode node) {
BOMLineWrapper line = (BOMLineWrapper)node.getUserObject();
int selectedASI = selectASIID(line);
if(selectedASI == -1) {
setIgnoreChange(true);
return;
}
MAttributeSetInstance asi = new MAttributeSetInstance(Env.getCtx(), selectedASI, null);
MProduct p = new MProduct(Env.getCtx(), line.getM_Product_ID(), null);
changeBOMLine(line, p, asi);
}
private int selectASIID(BOMLineWrapper line) {
if (line.getM_Product_ID() <= 0)
return -1;
MProduct p = new MProduct(Env.getCtx(), line.getM_Product_ID(), null);
PAttributeInstance pai =
new PAttributeInstance ((JFrame)null, p.getName(), getParameterValueAsInt("M_Warehouse_ID"), 0, line.getM_Product_ID(), 0);
return pai.getM_AttributeSetInstance_ID();
}
}

View File

@ -1,205 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom.action;
import java.math.BigDecimal;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.model.MResource;
import org.compiere.model.MRfQ;
import org.compiere.model.MRfQLine;
import org.compiere.model.MRfQLineQty;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.form.action.ProcessPopupAction;
import org.eevolution.model.MPPOrder;
import org.eevolution.model.reasoner.StorageReasoner;
import org.eevolution.model.wrapper.BOMLineWrapper;
import org.eevolution.model.wrapper.BOMWrapper;
/**
* @author Victor Perez, e-Evolution, S.C. * @author Victor Perez, e-Evolution, S.C.
* Create Request for Quotation
*
* Creates an RfQ with its line/s from a bill of material with its line/s by tree selection.
* Checks the storage quantities of every line's product, dependent on its setted attribute
* set instance.
*
* AD_Process:
* INSERT INTO ad_process VALUES (1000100, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, '10000005', 'Create RfQ', NULL, NULL, '3', 'U', NULL, 'N', 'N', NULL, 'com.compiere.process.CreateBOM', 0, 0, NULL, NULL, NULL, 'N');
*
* AD_Process_Para:
* INSERT INTO ad_process_para VALUES (1000245, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, 'Sales Representative', NULL, NULL, 1000100, 20, 18, 190, NULL, 'SalesRep_ID', 'Y', 0, 'Y', 'N', NULL, NULL, NULL, NULL, NULL, 1063, 'U');
* INSERT INTO ad_process_para VALUES (1000246, 0, 0, 'Y', CURRENT_TIMESTAMP, 100, CURRENT_TIMESTAMP, 100, 'RfQ Topic', NULL, NULL, 1000100, 10, 18, 1000041, NULL, 'C_RFQ_Topic_ID', 'Y', 0, 'Y', 'N', NULL, NULL, NULL, NULL, NULL, 2376, 'U');
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class CreateRfQAction extends ProcessPopupAction {
public static final String COMMAND = "createRfQ";
// Hard coded process id. Expected process is 'Create RfQ'.
final public static int PROCESS_ID = 1000100;
protected JTree tree;
protected StorageReasoner reasoner;
/**
* Constructs a new Instance.
*/
public CreateRfQAction(JTree tree, JFrame window) {
super(COMMAND, window);
setActionCommand(COMMAND);
this.tree = tree;
this.reasoner = new StorageReasoner();
}
protected String getCommand() {
return COMMAND;
}
protected int getProcessID() {
return PROCESS_ID;
}
protected String validateAction() {
return null;
}
protected void doProcess() {
if(tree != null) {
createRfQ((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent());
}
}
private void createRfQ(DefaultMutableTreeNode node) {
BOMWrapper bom = (BOMWrapper)node.getUserObject();
MPPOrder mo = new MPPOrder(Env.getCtx(), bom.getPP_Order_ID(), null);
MResource r = MResource.get(Env.getCtx(), mo.getS_Resource_ID());
Calendar cal = Calendar.getInstance();
MRfQ rfq = new MRfQ(Env.getCtx(), 0, null);
rfq.setName(
Msg.translate(Env.getCtx(), "C_RFQ_ID")
+": "
+mo.getDocumentNo()+"_"+r.getName()
+" ("+bom.getName()+")"
);
rfq.setC_Currency_ID(Env.getContextAsInt(Env.getCtx(), "$C_Currency_ID"));
rfq.setQuoteType(MRfQ.QUOTETYPE_QuoteSelectedLines);
rfq.setDateWorkStart(mo.getDateStartSchedule());
rfq.setDateWorkComplete(mo.getDateFinishSchedule());
// process parameters
rfq.setC_RfQ_Topic_ID(((BigDecimal)getParameterValue("C_RFQ_Topic_ID")).intValue());
rfq.setSalesRep_ID(((BigDecimal)getParameterValue("SalesRep_ID")).intValue());
savePO(rfq);
if(successful()) {
createRfQLines(rfq.get_ID(), node);
}
}
private void createRfQLines(int rfqId, DefaultMutableTreeNode parent) {
DefaultMutableTreeNode node = null;
for(int i = 0; i < parent.getChildCount(); i++) {
node = (DefaultMutableTreeNode)parent.getChildAt(i);
if(node.isLeaf()) {
createRfQLine(rfqId, node);
}
else {
createRfQLines(rfqId, node);
}
if(!successful()) {
break;
}
}
}
private void createRfQLine(int rfqId, DefaultMutableTreeNode node) {
BOMLineWrapper sourceLine = (BOMLineWrapper)node.getUserObject();
BigDecimal qtyReq = reasoner.getSumQtyRequired(sourceLine);
// No requirement qty
if(qtyReq.compareTo(BigDecimal.ZERO) <= 0) {
return;
}
MRfQ rfq = new MRfQ(Env.getCtx(), rfqId, null);
MRfQLine targetLine = new MRfQLine(Env.getCtx(),0,null);
targetLine.setC_RfQ_ID(rfqId);
targetLine.setLine(lineCount(rfqId)+1);
targetLine.setM_AttributeSetInstance_ID(sourceLine.getM_AttributeSetInstance_ID());
targetLine.setM_Product_ID(sourceLine.getM_Product_ID());
targetLine.setDateWorkStart(rfq.getDateWorkStart());
targetLine.setDateWorkComplete(rfq.getDateWorkComplete());
savePO(targetLine);
if(!successful()) {
return;
}
MRfQLineQty lineQty = new MRfQLineQty(Env.getCtx(),0,null);
//lineQty.setQty(reasoner.calculateRequiredProducts(sourceLine));
lineQty.setQty(qtyReq);
lineQty.setC_UOM_ID(sourceLine.getC_UOM_ID());
lineQty.setC_RfQLine_ID(targetLine.get_ID());
lineQty.setIsRfQQty(true);
lineQty.setIsPurchaseQty(true);
savePO(lineQty);
}
private int lineCount(int rfqId) {
MRfQ rfq = new MRfQ(Env.getCtx(), rfqId, null);
return rfq.getLines().length;
}
}

View File

@ -1,94 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom.action;
import java.awt.event.ActionEvent;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.eevolution.form.action.PopupAction;
import org.eevolution.model.wrapper.BOMLineWrapper;
import org.eevolution.model.wrapper.BOMWrapper;
/**
* @author Victor Perez, e-Evolution, S.C.
* Delete Bill of Material / Line
*
* Deletes a bill of material or a single line by tree selection.
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class DeleteBOMAction extends PopupAction {
public static final String COMMAND = "deleteBOM";
protected JTree tree;
/**
* Constructs a new Instance.
*/
public DeleteBOMAction(JTree tree) {
super(COMMAND);
setActionCommand(COMMAND);
this.tree = tree;
}
protected String getCommand() {
return COMMAND;
}
protected String validateAction() {
return null;
}
protected void doAction(ActionEvent e) {
if(tree != null) {
delete((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent());
}
}
private void delete(DefaultMutableTreeNode node) {
if(node.getUserObject() instanceof BOMWrapper) {
BOMWrapper bom = (BOMWrapper)node.getUserObject();
for(int i = 0; i < node.getChildCount(); i++) {
delete((DefaultMutableTreeNode)node.getChildAt(i));
if(!successful()) {
break;
}
}
deletePO(bom.get());
}
else {
BOMLineWrapper line = (BOMLineWrapper)node.getUserObject();
deletePO(line.get());
}
}
}

View File

@ -1,155 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.bom.action;
import java.awt.event.ActionEvent;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.util.Env;
import org.eevolution.form.action.PopupAction;
import org.eevolution.model.MPPProductBOM;
import org.eevolution.model.MPPProductBOMLine;
import org.eevolution.model.wrapper.BOMLineWrapper;
import org.eevolution.model.wrapper.BOMWrapper;
/**
* @author Victor Perez, e-Evolution, S.C.
* Merge Bill of Material
*
* Merges a multi level bill of material to a single level bill of material by tree selection.
*
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class MergeBOMAction extends PopupAction {
public static final String COMMAND = "mergeBOM";
protected JTree tree;
protected boolean actionResult;
/**
* Constructs a new Instance.
*/
public MergeBOMAction(JTree tree) {
super(COMMAND);
setActionCommand(COMMAND);
this.tree = tree;
}
protected String getCommand() {
return COMMAND;
}
protected boolean successful() {
return actionResult;
}
protected String validateAction() {
return null;
}
protected void doAction(ActionEvent e) {
if(tree != null) {
mergeBOMFrom((DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent());
}
}
private void mergeBOMFrom(DefaultMutableTreeNode node) {
BOMWrapper sourceBOM = (BOMWrapper)node.getUserObject();
MPPProductBOM targetBOM = new MPPProductBOM(Env.getCtx(), 0, null);
targetBOM.setBOMType(sourceBOM.getBOMType());
targetBOM.setDescription(sourceBOM.getDescription());
targetBOM.setM_AttributeSetInstance_ID(sourceBOM.getM_AttributeSetInstance_ID());
targetBOM.setM_Product_ID(sourceBOM.getM_Product_ID());
targetBOM.setName(sourceBOM.getName());
targetBOM.setRevision(sourceBOM.getRevision());
targetBOM.setValidFrom(sourceBOM.getValidFrom());
targetBOM.setValidTo(sourceBOM.getValidTo());
targetBOM.setValue(sourceBOM.getValue());
targetBOM.setDocumentNo(sourceBOM.getDocumentNo());
targetBOM.setC_UOM_ID(sourceBOM.getC_UOM_ID());
actionResult = targetBOM.save();
if(successful()) {
mergeInDepth(targetBOM.get_ID(), node);
}
}
private void mergeInDepth(int bomId, DefaultMutableTreeNode parent) {
DefaultMutableTreeNode node = null;
for(int i = 0; i < parent.getChildCount(); i++) {
node = (DefaultMutableTreeNode)parent.getChildAt(i);
if(node.isLeaf()) {
createBOMLine(bomId, node);
}
else {
mergeInDepth(bomId, node);
}
if(!successful()) {
break;
}
}
}
private void createBOMLine(int bomId, DefaultMutableTreeNode node) {
BOMLineWrapper sourceLine = (BOMLineWrapper)node.getUserObject();
MPPProductBOMLine targetLine = new MPPProductBOMLine(Env.getCtx(),0,null);
targetLine.setPP_Product_BOM_ID(bomId);
targetLine.setHelp(sourceLine.getHelp());
targetLine.setM_ChangeNotice_ID(sourceLine.getM_ChangeNotice_ID());
targetLine.setAssay(sourceLine.getAssay());
targetLine.setQtyBatch(sourceLine.getQtyBatch());
targetLine.setQtyBOM(sourceLine.getQtyBOM());
targetLine.setIsQtyPercentage(sourceLine.isQtyPercentage());
targetLine.setComponentType(sourceLine.getComponentType());
targetLine.setC_UOM_ID(sourceLine.getC_UOM_ID());
targetLine.setForecast(sourceLine.getForecast());
targetLine.setIsCritical(sourceLine.isCritical());
targetLine.setIssueMethod(sourceLine.getIssueMethod());
targetLine.setLine(sourceLine.getLine());
targetLine.setLeadTimeOffset(sourceLine.getLeadTimeOffset());
targetLine.setM_AttributeSetInstance_ID(sourceLine.getM_AttributeSetInstance_ID());
targetLine.setM_Product_ID(sourceLine.getM_Product_ID());
targetLine.setScrap(sourceLine.getScrap());
targetLine.setValidFrom(sourceLine.getValidFrom());
targetLine.setValidTo(sourceLine.getValidTo());
actionResult = targetLine.save();
}
}

View File

@ -1,4 +0,0 @@
mergeBOM=Merge
deleteBOM=Delete
changeASI=Change Attributes
createRfQ=Create RfQ

View File

@ -1,4 +0,0 @@
mergeBOM=Zusammenfassen
deleteBOM=Löschen
changeASI=Änderung Merkmalsausprägung
createRfQ=Anfrage nach Angebot erstellen

View File

@ -1,52 +0,0 @@
package org.eevolution.form.bom;
import org.compiere.model.X_M_Product;
import org.eevolution.model.X_PP_Product_BOM;
import org.eevolution.model.X_PP_Product_BOMLine;
public class nodeUserObject {
public X_M_Product M_Product = null;
public String displayString = "";
public X_PP_Product_BOM bom = null;
public X_PP_Product_BOMLine bomLine = null;
public boolean isChosen = false;
public boolean isCheckbox = false;
public boolean isMandatory = false;
public boolean isOptional = false;
public nodeUserObject(String displayString, X_M_Product M_Product, X_PP_Product_BOM bom, X_PP_Product_BOMLine bomLine) {
this.displayString = displayString;
this.M_Product = M_Product;
this.bom = bom;
this.bomLine = bomLine;
System.out.println("bomLine: " + bomLine);
if(bom != null) {
if(bomLine != null) {
System.out.println("bomLine.getComponentType: " + bomLine.getComponentType());
System.out.println("bomLine.COMPONENTTYPE_Component: " + bomLine.COMPONENTTYPE_Component);
if(bomLine.getComponentType().equals(bomLine.COMPONENTTYPE_Component)) {
System.out.println("setting checkbox to true");
isCheckbox = true;
isMandatory = true;
}
if(bomLine.getComponentType().equals(bomLine.COMPONENTTYPE_Variant)) {
System.out.println("setting checkbox to true");
isCheckbox = true;
isOptional = true;
}
}
}
}
public String toString() {
return displayString;
}
}

View File

@ -1,275 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
* Teo Sarca, www.arhipac.ro *
*****************************************************************************/
package org.eevolution.form.crp;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.model.MProduct;
import org.compiere.model.MResource;
import org.compiere.model.MResourceType;
import org.compiere.model.MUOM;
import org.compiere.model.MUOMConversion;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Msg;
import org.eevolution.model.MPPOrder;
import org.eevolution.model.MPPOrderNode;
import org.eevolution.model.MPPOrderWorkflow;
import org.eevolution.model.reasoner.CRPReasoner;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*
* @author Teo Sarca, http://www.arhipac.ro
*/
public abstract class CRPDatasetFactory extends CRPReasoner implements CRPModel
{
protected JTree tree;
protected DefaultCategoryDataset dataset;
/**
* Convert from minutes to base UOM
*/
protected abstract BigDecimal convert(BigDecimal minutes);
public static CRPModel get(Timestamp start, Timestamp end, MResource r)
{
MResourceType t = MResourceType.get(Env.getCtx(), r.getS_ResourceType_ID());
// UOM ID - 'Minutes' is base unit
final MUOM uom1 = MUOM.get(Env.getCtx(), MUOM.getMinute_UOM_ID(Env.getCtx()));
// Target UOM is the resource type's UOM
final MUOM uom2 = MUOM.get(Env.getCtx(), t.getC_UOM_ID());
CRPDatasetFactory factory = new CRPDatasetFactory() {
protected BigDecimal convert(BigDecimal minutes)
{
return MUOMConversion.convert(Env.getCtx(), uom1.get_ID(), uom2.get_ID(), minutes);
}
};
factory.generate(start, end, r);
return factory;
}
private void generate(Timestamp start, Timestamp end, MResource r)
{
if(start == null || end == null || r == null)
{
return ;
}
String labelActCap = Msg.translate(Env.getCtx(), "DailyCapacity");
String labelLoadAct = Msg.translate(Env.getCtx(), "ActualLoad");
DateFormat formatter = DisplayType.getDateFormat(DisplayType.DateTime, Env.getLanguage(Env.getCtx()));
BigDecimal dailyCapacity = getMaxRange(r);
dataset = new DefaultCategoryDataset();
HashMap<DefaultMutableTreeNode, String> names = new HashMap<DefaultMutableTreeNode, String>();
DefaultMutableTreeNode root = new DefaultMutableTreeNode(r);
names.put(root, getTreeNodeRepresentation(null, root, r));
Timestamp dateTime = start;
while(end.after(dateTime))
{
String label = formatter.format(dateTime);
names.putAll(addTreeNodes(dateTime, root, r));
boolean available = isAvailable(r, dateTime);
dataset.addValue(available ? dailyCapacity : BigDecimal.ZERO, labelActCap, label);
dataset.addValue(available ? calculateLoad(dateTime, r, null) : BigDecimal.ZERO, labelLoadAct, label);
dateTime = org.compiere.util.TimeUtil.addDays(dateTime, 1); // TODO: teo_sarca: increment should be more general, not only days
}
tree = new JTree(root);
tree.setCellRenderer(new DiagramTreeCellRenderer(names));
}
public BigDecimal calculateLoad(Timestamp dateTime, MResource r, String docStatus)
{
MResourceType t = MResourceType.get(Env.getCtx(), r.getS_ResourceType_ID());
MUOM uom = MUOM.get(Env.getCtx(), t.getC_UOM_ID());
BigDecimal qtyOpen;
long millis = 0l;
for(MPPOrderNode node : getPPOrderNodes(dateTime, r))
{
if (docStatus != null)
{
MPPOrder o = new MPPOrder(node.getCtx(), node.getPP_Order_ID(), node.get_TrxName());
if(!o.getDocStatus().equals(docStatus))
{
continue;
}
}
millis += calculateMillisForDay(dateTime, node, t);
}
// Pre-converts to minutes, because its the lowest time unit of compiere
BigDecimal scale = new BigDecimal(1000*60);
BigDecimal minutes = new BigDecimal(millis).divide(scale, 2, BigDecimal.ROUND_HALF_UP);
return convert(minutes);
}
/**
* Gets {StartDate, EndDate} times for given dateTime.
* For calculating this, following factors are considered:
* <li> resource type time slot
* <li> node DateStartSchedule and DateEndSchedule
* @param dateTime
* @param node
* @param t resouce type
* @return array of 2 elements, {StartDate, EndDate}
*/
private Timestamp[] getDayBorders(Timestamp dateTime, MPPOrderNode node, MResourceType t)
{
// The theoretical latest time on a day, where the work ends, dependent on
// the resource type's time slot value
Timestamp endDayTime = t.getDayEnd(dateTime);
// Initialize the end time to the present, if the work ends at this day.
// Otherwise the earliest possible start time for a day is set.
endDayTime = (endDayTime.before(node.getDateFinishSchedule())) ? endDayTime : node.getDateFinishSchedule();
// The theoretical earliest time on a day, where the work begins, dependent on
// the resource type's time slot value
Timestamp startDayTime = t.getDayStart(dateTime);
// Initialize the start time to the present, if the work begins at this day.
// Otherwise the latest possible start time for a day is set.
startDayTime = (startDayTime.after(node.getDateStartSchedule())) ? startDayTime : node.getDateStartSchedule();
return new Timestamp[] {startDayTime, endDayTime};
}
private long calculateMillisForDay(Timestamp dateTime, MPPOrderNode node, MResourceType t)
{
Timestamp[] borders = getDayBorders(dateTime, node, t);
return borders[1].getTime() - borders[0].getTime();
}
/**
* Generates following tree:
* <pre>
* (dateTime)
* \-------(root)
* \-------(PP Order)
* \---------(PP Order Node)
* </pre>
* @param dateTime
* @param root
* @param r
* @return
*/
private HashMap<DefaultMutableTreeNode, String> addTreeNodes(Timestamp dateTime, DefaultMutableTreeNode root, MResource r)
{
HashMap<DefaultMutableTreeNode, String> names = new HashMap<DefaultMutableTreeNode, String>();
DefaultMutableTreeNode parent = new DefaultMutableTreeNode(dateTime);
names.put(parent, getTreeNodeRepresentation(null, parent, r));
root.add(parent);
for(MPPOrder order : getPPOrders(dateTime, r))
{
DefaultMutableTreeNode childOrder = new DefaultMutableTreeNode(order);
parent.add(childOrder);
names.put(childOrder, getTreeNodeRepresentation(dateTime, childOrder, r));
for(MPPOrderNode node : getPPOrderNodes(dateTime, r))
{
DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(node);
childOrder.add(childNode);
names.put(childNode, getTreeNodeRepresentation(dateTime, childNode, r));
}
}
return names;
}
private String getTreeNodeRepresentation(Timestamp dateTime, DefaultMutableTreeNode node, MResource r)
{
String name = null;
if(node.getUserObject() instanceof MResource)
{
MResource res = (MResource) node.getUserObject();
name = res.getName();
}
else if(node.getUserObject() instanceof Timestamp)
{
Timestamp d = (Timestamp)node.getUserObject();
SimpleDateFormat df = Env.getLanguage(Env.getCtx()).getDateFormat();
name = df.format(d);
if(!isAvailable(r, d))
{
name = "{"+name+"}";
}
}
else if(node.getUserObject() instanceof MPPOrder)
{
MPPOrder o = (MPPOrder)node.getUserObject();
MProduct p = MProduct.get(Env.getCtx(), o.getM_Product_ID());
name = o.getDocumentNo()+" ("+p.getName()+")";
}
else if(node.getUserObject() instanceof MPPOrderNode)
{
MPPOrderNode on = (MPPOrderNode)node.getUserObject();
MPPOrderWorkflow owf = on.getMPPOrderWorkflow();
MResourceType rt = MResourceType.get(Env.getCtx(), r.getS_ResourceType_ID());
// no function
//Env.getLanguage(Env.getCtx()).getTimeFormat();
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Timestamp[] interval = getDayBorders(dateTime, on, rt);
name = df.format(interval[0])+" - "+df.format(interval[1])+" "+on.getName()+" ("+owf.getName()+")";
}
return name;
}
/**
* @return Daily Capacity * Utilization / 100
*/
private BigDecimal getMaxRange(MResource r)
{
BigDecimal utilizationDec = r.getPercentUtilization().divide(Env.ONEHUNDRED, 2, RoundingMode.HALF_UP);
int precision = 2; // TODO: hardcoded
return r.getDailyCapacity().multiply(utilizationDec).setScale(precision, RoundingMode.HALF_UP);
}
public CategoryDataset getDataset()
{
return dataset;
}
public JTree getTree()
{
return tree;
}
}

View File

@ -1,37 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.crp;
import java.math.BigDecimal;
import java.sql.Timestamp;
import javax.swing.JTree;
import org.compiere.model.MResource;
import org.jfree.data.category.CategoryDataset;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public interface CRPModel
{
public JTree getTree();
public CategoryDataset getDataset();
public BigDecimal calculateLoad(Timestamp dateTime, MResource r, String docStatus);
}

View File

@ -1,97 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.crp;
import java.awt.Component;
import java.awt.Graphics;
import java.util.Date;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import org.compiere.model.MResource;
import org.compiere.util.Env;
import org.eevolution.form.tree.MapTreeCellRenderer;
import org.eevolution.model.MPPOrder;
import org.eevolution.model.MPPOrderNode;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public class DiagramTreeCellRenderer extends MapTreeCellRenderer
{
private static final long serialVersionUID = 1L;
public DiagramTreeCellRenderer(HashMap<?, ?> map)
{
super(map);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
{
Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
String name = (String)getMapping(value);
ImageIcon icon = getIcon(value);
if(isNotAvailable(name))
{
final int x1 = getFontMetrics(getFont()).stringWidth(name) + icon.getIconWidth();
JLabel l = new JLabel(name.substring(1, name.length()-1), icon, JLabel.LEFT) {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
super.paint(g);
int y = getFont().getSize()/2;
g.drawLine(0, y, x1, y);
}
};
l.setFont(getFont());
return l;
}
return c;
}
private boolean isNotAvailable(String value)
{
return value.startsWith("{") && value.endsWith("}");
}
protected ImageIcon getIcon(Object value)
{
ImageIcon icon = null;
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
if(node.getUserObject() instanceof MResource)
{
}
else if(node.getUserObject() instanceof Date)
{
icon = Env.getImageIcon("Calendar10.gif");
}
else if(node.getUserObject() instanceof MPPOrder)
{
}
else if(node.getUserObject() instanceof MPPOrderNode)
{
}
return icon;
}
}

View File

@ -1,125 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.tree;
import java.awt.Component;
import java.util.HashMap;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class CachableTreeCellRenderer extends DefaultTreeCellRenderer {
private boolean virtual;
private HashMap cache;
private CachableTreeCellRenderer complement;
protected abstract void init(Object value);
public CachableTreeCellRenderer() {
this(false);
}
public CachableTreeCellRenderer(boolean virtual) {
super();
this.virtual = virtual;
cache = new HashMap();
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
String name = (String)getFromCache(value);
if(name == null) {
init(value);
name = (String)getFromCache(value);
}
setName(name);
return this;
}
/*
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if(!isVirtual()) {
if(!isInitialized()) {
init(value);
}
return this;
}
else {
CachableTreeCellRenderer r = null;
try {
System.out.println(this.getClass()+" class: "+getClass());
r = (CachableTreeCellRenderer)this.getClass().newInstance();
r.setVirtual(false);
r.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
complement = (CachableTreeCellRenderer)tree.getCellRenderer();
tree.setCellRenderer(r);
}
catch(Exception e) {
e.printStackTrace();
}
return r;
}
}
*/
public boolean isInitialized() {
return !cache.isEmpty();
}
public void addToCache(Object key, Object value) {
cache.put(key, value);
}
public Object getFromCache(Object key) {
return cache.get(key);
}
public boolean isVirtual() {
return virtual;
}
public void setVirtual(boolean on) {
this.virtual = on;
}
}

View File

@ -1,59 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.form.tree;
import java.awt.Component;
import java.util.HashMap;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
/**
* @author Gunther Hoppe, tranSIT GmbH Ilmenau/Germany
* @version 1.0, October 14th 2005
*/
public abstract class MapTreeCellRenderer extends DefaultTreeCellRenderer
{
private HashMap<Object, Object> map;
protected abstract ImageIcon getIcon(Object value);
public MapTreeCellRenderer(HashMap<?, ?> map)
{
this.map = new HashMap<Object, Object>();
this.map.putAll(map);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
{
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
String name = (String)getMapping(value);
setText(name);
ImageIcon icon = getIcon(value);
setIcon(icon);
return this;
}
protected Object getMapping(Object value)
{
return map.get(value);
}
}

View File

@ -1,443 +0,0 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* 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 *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): Victor Perez www.e-evolution.com *
*****************************************************************************/
package org.eevolution.process;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import javax.sql.RowSet;
import org.compiere.model.MQuery;
import org.compiere.model.PrintInfo;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportCtl;
import org.compiere.print.ReportEngine;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Language;
import org.compiere.util.ValueNamePair;
import org.eevolution.model.X_RV_PP_Product_BOMLine;
import org.eevolution.model.X_T_BOMLine;
/**
* Multi-Level BOM & Formula Detail
*
* @author victor.perez@e-evolution.com,Sergio Ramazzina
* @version $Id: PrintBOM.java,v 1.2 2005/04/19 12:54:30 srama Exp $
*
*/
public class PrintBOM extends SvrProcess
{
private static final Properties ctx = Env.getCtx();
private int p_M_Product_ID = 0;
private boolean p_implosion = false;
private int LevelNo = 1;
private int SeqNo = 0;
private String levels = new String("....................");
private int AD_PInstance_ID = 0;
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("M_Product_ID"))
{
p_M_Product_ID = ((BigDecimal) para[i].getParameter()).intValue();
}
else if (name.equals("Implosion"))
{
p_implosion = ((String) para[i].getParameter()).equals("N") ? false : true;
}
else
log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name);
}
} // prepare
/**
* Perform process.
*
* @return Message (clear text)
* @throws Exception
* if not successful
*/
protected String doIt() throws Exception
{
AD_PInstance_ID = getAD_PInstance_ID();
try
{
loadBOM();
print();
}
catch (Exception e)
{
log.log(Level.SEVERE, "PrintBOM", e.toString());
throw new Exception(e.getLocalizedMessage());
}
finally
{
String sql = "DELETE FROM T_BomLine WHERE AD_PInstance_ID = " + AD_PInstance_ID;
DB.executeUpdate(sql, null);
}
return "@OK@";
} // doIt
/**
* Print result generate for this report
*/
void print() throws Exception
{
Language language = Language.getLoginLanguage(); // Base Language
MPrintFormat pf = null;
int pfid = 0;
// get print format for client, else copy system to client
RowSet pfrs = MPrintFormat.getAccessiblePrintFormats(X_RV_PP_Product_BOMLine.Table_ID, -1, null);
pfrs.next();
pfid = pfrs.getInt("AD_PrintFormat_ID");
if(pfrs.getInt("AD_Client_ID") != 0) pf = MPrintFormat.get(getCtx(), pfid, false);
else pf = MPrintFormat.copyToClient(getCtx(), pfid, getAD_Client_ID());
pfrs.close();
if (pf == null) raiseError("Error: ","No Print Format");
pf.setLanguage(language);
pf.setTranslationLanguage(language);
// query
MQuery query = MQuery.get(getCtx(), AD_PInstance_ID, X_RV_PP_Product_BOMLine.Table_Name);
query.addRestriction("AD_PInstance_ID", MQuery.EQUAL, AD_PInstance_ID);
PrintInfo info = new PrintInfo(X_RV_PP_Product_BOMLine.Table_Name,
X_RV_PP_Product_BOMLine.Table_ID, getRecord_ID());
ReportEngine re = new ReportEngine(getCtx(), pf, query, info);
ReportCtl.preview(re);
// wait for report window to be closed as t_bomline
// records are deleted when process ends
while (re.getView().isDisplayable())
{
Env.sleep(1);
}
}
/**
* Action: Fill Tree with all nodes
*/
private void loadBOM() throws Exception
{
int count = 0;
if (p_M_Product_ID == 0)
raiseError("Error: ","Product ID not found");
X_T_BOMLine tboml = new X_T_BOMLine(ctx, 0, null);
tboml.setPP_Product_BOM_ID(0);
tboml.setPP_Product_BOMLine_ID(0);
tboml.setM_Product_ID(p_M_Product_ID);
tboml.setSel_Product_ID(p_M_Product_ID);
tboml.setImplosion(p_implosion);
tboml.setLevelNo(0);
tboml.setLevels("0");
tboml.setSeqNo(0);
tboml.setAD_PInstance_ID(AD_PInstance_ID);
tboml.save();
if (p_implosion)
{
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT PP_Product_BOMLine_ID FROM PP_Product_BOMLine "
+ "WHERE IsActive = 'Y' AND M_Product_ID = ? ";
try
{
stmt = DB.prepareStatement(sql, get_TrxName());
stmt.setInt(1, p_M_Product_ID);
rs = stmt.executeQuery();
while (rs.next())
{
parentImplotion(rs.getInt(1));
++count;
}
if (count == 0)
raiseError("Error: ","Product is not a component");
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage() + sql, e);
throw new Exception("SQLException: "+e.getLocalizedMessage());
}
finally
{
DB.close(rs, stmt);
rs = null;
stmt = null;
}
}
else
{
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT PP_Product_BOM_ID FROM PP_Product_BOM "
+ "WHERE IsActive = 'Y' AND M_Product_ID = ? ";
try
{
stmt = DB.prepareStatement(sql, get_TrxName());
stmt.setInt(1, p_M_Product_ID);
rs = stmt.executeQuery();
while (rs.next())
{
parentExplotion(rs.getInt(1));
++count;
}
if (count == 0)
raiseError("Error: ","Product is not a BOM");
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage() + sql, e);
throw new Exception("SQLException: "+e.getLocalizedMessage());
}
finally
{
DB.close(rs, stmt);
rs = null;
stmt = null;
}
}
}
/**
* Generate an Implotion for this BOM Line
*
* @param PP_Product_BOMLine_ID
* ID BOM Line
*/
public void parentImplotion(int PP_Product_BOMLine_ID) throws Exception
{
int PP_Product_BOM_ID = 0;
int M_Product_ID = 0;
X_T_BOMLine tboml = new X_T_BOMLine(ctx, 0, null);
PP_Product_BOM_ID = DB.getSQLValue(null,
"SELECT PP_Product_BOM_ID FROM PP_Product_BOMLine WHERE PP_Product_BOMLine_ID=?",PP_Product_BOMLine_ID);
if (PP_Product_BOM_ID < 0)
throw new Exception(CLogger.retrieveErrorString("Error: PrintBOM.parentImplotion()"));
M_Product_ID = DB.getSQLValue(null,
"SELECT M_Product_ID FROM PP_Product_BOM WHERE PP_Product_BOM_ID=?", PP_Product_BOM_ID);
if (M_Product_ID < 0)
throw new Exception(CLogger.retrieveErrorString("Error: PrintBOM.parentImplotion()"));
tboml.setPP_Product_BOM_ID(PP_Product_BOM_ID);
tboml.setPP_Product_BOMLine_ID(PP_Product_BOMLine_ID);
tboml.setM_Product_ID(M_Product_ID);
tboml.setLevelNo(LevelNo);
tboml.setSel_Product_ID(p_M_Product_ID);
tboml.setImplosion(p_implosion);
if (LevelNo >= 11)
tboml.setLevels(levels + ">" + LevelNo);
else if (LevelNo >= 1) tboml.setLevels(levels.substring(0, LevelNo) + LevelNo);
tboml.setSeqNo(SeqNo);
tboml.setAD_PInstance_ID(AD_PInstance_ID);
tboml.save();
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT PP_Product_BOM_ID, M_Product_ID FROM PP_Product_BOM "
+ "WHERE IsActive = 'Y' AND M_Product_ID = ? ";
try
{
stmt = DB.prepareStatement(sql, get_TrxName());
stmt.setInt(1, M_Product_ID);
rs = stmt.executeQuery();
while (rs.next())
{
SeqNo += 1;
component(rs.getInt(2));
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage() + sql, e);
throw new Exception("SQLException: "+e.getLocalizedMessage());
}
finally
{
DB.close(rs, stmt);
rs = null;
stmt = null;
}
}
/**
* Generate an Explotion for this BOM
*
* @param PP_Product_BOMLine_ID
* ID BOM Line
*/
public void parentExplotion(int PP_Product_BOM_ID) throws Exception
{
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT PP_Product_BOMLine_ID, M_Product_ID FROM PP_Product_BOMLine boml "
+ "WHERE IsActive = 'Y' AND PP_Product_BOM_ID = ? ORDER BY Line ";
try
{
stmt = DB.prepareStatement(sql, get_TrxName());
stmt.setInt(1, PP_Product_BOM_ID);
rs = stmt.executeQuery();
while (rs.next())
{
SeqNo += 1;
X_T_BOMLine tboml = new X_T_BOMLine(ctx, 0, null);
tboml.setPP_Product_BOM_ID(PP_Product_BOM_ID);
tboml.setPP_Product_BOMLine_ID(rs.getInt(1));
tboml.setM_Product_ID(rs.getInt(2));
tboml.setLevelNo(LevelNo);
tboml.setLevels(levels.substring(0, LevelNo) + LevelNo);
tboml.setSeqNo(SeqNo);
tboml.setAD_PInstance_ID(AD_PInstance_ID);
tboml.setSel_Product_ID(p_M_Product_ID);
tboml.setImplosion(p_implosion);
tboml.save();
component(rs.getInt(2));
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage() + sql, e);
throw new Exception("SQLException: "+e.getLocalizedMessage());
}
finally
{
DB.close(rs, stmt);
rs = null;
stmt = null;
}
}
/**
* Find if this product as component
*
* @param M_Product_ID
* ID Component
*/
public void component(int M_Product_ID) throws Exception
{
if (p_implosion)
{
LevelNo += 1;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT PP_Product_BOMLine_ID FROM PP_Product_BOMLine "
+ "WHERE IsActive = 'Y' AND M_Product_ID = ? ";
try
{
stmt = DB.prepareStatement(sql, get_TrxName());
stmt.setInt(1, M_Product_ID);
rs = stmt.executeQuery();
while (rs.next())
{
parentImplotion(rs.getInt(1));
}
rs.close();
stmt.close();
LevelNo -= 1;
return;
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage() + sql, e);
throw new Exception("SQLException: "+e.getLocalizedMessage());
}
finally
{
DB.close(rs, stmt);
rs = null;
stmt = null;
}
}
else
{
String sql = "SELECT PP_Product_BOM_ID FROM PP_Product_BOM "
+ "WHERE IsActive = 'Y' AND Value = ? ";
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
String Value = DB.getSQLValueString(get_TrxName(),
"SELECT Value FROM M_PRODUCT WHERE M_PRODUCT_ID=?", M_Product_ID);
if (Value == null)
{
throw new Exception(CLogger.retrieveErrorString("Error: PrintBOM.component()"));
}
stmt = DB.prepareStatement(sql, get_TrxName());
stmt.setString(1, Value);
rs = stmt.executeQuery();
boolean level = false;
while (rs.next())
{
if (!level) LevelNo += 1;
level = true;
parentExplotion(rs.getInt(1));
LevelNo -= 1;
}
}
catch (SQLException e)
{
log.log(Level.SEVERE, e.getLocalizedMessage() + sql, e);
throw new Exception("SQLException: "+e.getLocalizedMessage());
}
finally
{
DB.close(rs, stmt);
rs = null;
stmt = null;
}
}
return;
}
private void raiseError(String string, String hint) throws Exception
{
String msg = string;
ValueNamePair pp = CLogger.retrieveError();
if (pp != null) msg = pp.getName() + " - ";
msg += hint;
throw new Exception(msg);
}
}