OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.core.sales.product.action;

import org.openconcerto.erp.core.common.ui.NumericTextField;
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
import org.openconcerto.erp.core.supplychain.stock.element.ComposedItemStockUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem.TypeStockMouvement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JDate;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.text.SimpleDocumentListener;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;

import org.apache.commons.dbutils.ResultSetHandler;

public class TransfertStockPanel extends JPanel {

    private final String mvtStockTableQuoted;
    private static String defaultLabel = "Transfert de stock";

    public TransfertStockPanel(Configuration instance) {
        super(new GridBagLayout());

        final JButton buttonUpdate = new JButton("Mettre à jour");

        final SQLTable mvtStockTable = instance.getRoot().findTable("MOUVEMENT_STOCK");
        this.mvtStockTableQuoted = mvtStockTable.getSQLName().quote();

        final SQLElement articleElt = instance.getDirectory().getElement("ARTICLE");
        final SQLRequestComboBox comboArticle = new SQLRequestComboBox();
        comboArticle.uiInit(articleElt.createComboRequest());

        final SQLElement stockElt = instance.getDirectory().getElement("DEPOT_STOCK");
        final SQLRequestComboBox comboStockDepart = new SQLRequestComboBox();
        comboStockDepart.uiInit(stockElt.createComboRequest());

        final SQLRequestComboBox comboStockArrive = new SQLRequestComboBox();
        comboStockArrive.uiInit(stockElt.createComboRequest());

        JLabel qteReel = new JLabel("Quantité", SwingConstants.RIGHT);
        final NumericTextField fieldReel = new NumericTextField();

        fieldReel.getDocument().addDocumentListener(new SimpleDocumentListener() {

            @Override
            public void update(DocumentEvent e) {
                buttonUpdate.setEnabled(
                        fieldReel.getText().trim().length() > 0 && comboArticle.getSelectedRow() != null && comboStockArrive.getSelectedRow() != null && comboStockDepart.getSelectedRow() != null);
            }
        });

        comboArticle.addModelListener("wantedID", new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                buttonUpdate.setEnabled(
                        fieldReel.getText().trim().length() > 0 && comboArticle.getSelectedRow() != null && comboStockArrive.getSelectedRow() != null && comboStockDepart.getSelectedRow() != null);
            }
        });

        comboStockArrive.addModelListener("wantedID", new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                buttonUpdate.setEnabled(
                        fieldReel.getText().trim().length() > 0 && comboArticle.getSelectedRow() != null && comboStockArrive.getSelectedRow() != null && comboStockDepart.getSelectedRow() != null);
            }
        });

        comboStockDepart.addModelListener("wantedID", new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                buttonUpdate.setEnabled(
                        fieldReel.getText().trim().length() > 0 && comboArticle.getSelectedRow() != null && comboStockArrive.getSelectedRow() != null && comboStockDepart.getSelectedRow() != null);
            }
        });

        GridBagConstraints c = new DefaultGridBagConstraints();

        this.add(new JLabel("Intitulé"), c);
        final JTextField label = new JTextField();
        c.gridx++;
        c.gridwidth = 2;
        c.weightx = 1;
        this.add(label, c);
        label.setText(defaultLabel);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 1;
        c.weightx = 0;
        this.add(new JLabel("Date", SwingConstants.RIGHT), c);
        final JDate date = new JDate(true);
        c.gridx++;
        c.weightx = 0;
        this.add(date, c);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 2;
        c.weightx = 0;
        this.add(new JLabel("Article", SwingConstants.RIGHT), c);
        c.gridx += 2;
        c.gridwidth = 1;
        c.weightx = 1;
        this.add(comboArticle, c);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 2;
        c.weightx = 0;
        this.add(new JLabel("Départ", SwingConstants.RIGHT), c);
        c.gridx += 2;
        c.gridwidth = 1;
        c.weightx = 1;
        this.add(comboStockDepart, c);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 2;
        c.weightx = 0;
        this.add(new JLabel("Arrivée", SwingConstants.RIGHT), c);
        c.gridx += 2;
        c.gridwidth = 1;
        c.weightx = 1;
        this.add(comboStockArrive, c);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 2;
        c.weightx = 0;
        this.add(qteReel, c);
        c.gridx += 2;
        c.gridwidth = 1;
        c.weightx = 1;
        this.add(fieldReel, c);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 2;
        c.weightx = 0;
        this.add(qteReel, c);
        c.gridx += 2;
        c.gridwidth = 1;
        c.weightx = 1;
        this.add(fieldReel, c);

        c.gridy++;
        c.gridx = 0;
        JButton buttonCancel = new JButton("Annuler");
        JPanel pButton = new JPanel();
        pButton.add(buttonCancel);
        pButton.add(buttonUpdate);
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.anchor = GridBagConstraints.EAST;
        c.weightx = 0;
        c.fill = GridBagConstraints.NONE;
        this.add(pButton, c);
        buttonCancel.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ((JFrame) SwingUtilities.getRoot(TransfertStockPanel.this)).dispose();
            }
        });
        buttonUpdate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                buttonUpdate.setEnabled(false);
                defaultLabel = label.getText();
                BigDecimal qteReel = fieldReel.getValue();

                List<String> multipleRequestsHundred = new ArrayList<String>(100);
                boolean usePrice = mvtStockTable.contains("PRICE");
                List<StockItem> stockItems = new ArrayList<StockItem>();
                final Date dateValue = date.getValue();

                final SQLRow selectedRowArticle = comboArticle.getSelectedRow();

                {
                    // DEPART
                    final SQLRow selectedRowDepotDepart = comboStockDepart.getSelectedRow();
                    final SQLRowAccessor rowStockDepart = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotDepart);
                    StockItem item = new StockItem(selectedRowArticle, rowStockDepart);
                    if (!item.isStockInit()) {
                        SQLRowValues rowVals = new SQLRowValues(mvtStockTable.getTable("STOCK"));
                        rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
                        rowVals.put("ID_DEPOT_STOCK", selectedRowDepotDepart.getID());
                        try {
                            rowVals.commit();
                        } catch (SQLException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        selectedRowArticle.fetchValues();
                        item = new StockItem(selectedRowArticle, rowStockDepart);
                    }
                    stockItems.add(item);
                    double diff = -qteReel.doubleValue();
                    item.updateQty(diff, TypeStockMouvement.REEL);
                    multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, label.getText(), true, usePrice));

                    item.updateQty(diff, TypeStockMouvement.THEORIQUE);
                    multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, label.getText(), false, usePrice));

                    multipleRequestsHundred.add(item.getUpdateRequest());
                }
                // ARRIVEE
                {
                    final SQLRow selectedRowDepotArrivee = comboStockArrive.getSelectedRow();
                    final SQLRowAccessor rowStockArrivee = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotArrivee);

                    StockItem item = new StockItem(selectedRowArticle, rowStockArrivee);
                    if (!item.isStockInit()) {
                        SQLRowValues rowVals = new SQLRowValues(mvtStockTable.getTable("STOCK"));
                        rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
                        rowVals.put("ID_DEPOT_STOCK", selectedRowDepotArrivee.getID());
                        try {
                            rowVals.commit();
                        } catch (SQLException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        selectedRowArticle.fetchValues();
                        item = new StockItem(selectedRowArticle, rowStockArrivee);
                    }
                    stockItems.add(item);
                    double diff = qteReel.doubleValue();
                    item.updateQty(diff, TypeStockMouvement.REEL);
                    multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, label.getText(), true, usePrice));

                    item.updateQty(diff, TypeStockMouvement.THEORIQUE);
                    multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, label.getText(), false, usePrice));

                    multipleRequestsHundred.add(item.getUpdateRequest());
                }

                try {

                    final int size = multipleRequestsHundred.size();
                    List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(size);
                    for (int i = 0; i < size; i++) {
                        handlers.add(null);
                    }
                    SQLUtils.executeMultiple(instance.getRoot().getDBSystemRoot(), multipleRequestsHundred, handlers);

                } catch (SQLException e1) {
                    ExceptionHandler.handle("Stock update error", e1);
                }

                final DBRoot root = mvtStockTable.getDBRoot();
                if (root.contains("ARTICLE_ELEMENT")) {
                    // List<StockItem> stockItems = new ArrayList<StockItem>();
                    // for (SQLRowAccessor sqlRowAccessor2 : stocks) {
                    // final SQLRow asRow = sqlRowAccessor2.asRow();
                    // asRow.fetchValues();
                    // stockItems.add(new StockItem(asRow));
                    // }
                    // Mise à jour des stocks des nomenclatures
                    ComposedItemStockUpdater comp = new ComposedItemStockUpdater(root, stockItems);
                    try {
                        comp.update();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }

                // liste.getModel().updateAll();
                ((JFrame) SwingUtilities.getRoot(TransfertStockPanel.this)).dispose();
            }
        });
    }

    private String getMvtRequest(Date time, BigDecimal prc, double qteFinal, StockItem item, String label, boolean reel, boolean usePrice) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"NOM\",\"REEL\",\"ORDRE\"";

        if (usePrice && prc != null) {
            mvtStockQuery += ",\"PRICE\"";
        }

        mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + item.getArticle().getID() + "," + item.stock.getID() + ",'" + label + "'," + reel
                + ", (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
        if (usePrice && prc != null) {
            mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
        }
        mvtStockQuery += ")";
        return mvtStockQuery;
    }
}