OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 182 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 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.shipment.action;

import org.openconcerto.erp.action.CreateListFrameAbstractAction;
import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
import org.openconcerto.erp.core.common.ui.IListFilterDatePanel;
import org.openconcerto.erp.core.common.ui.IListTotalPanel;
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonSQLElement;
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLField;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.view.ListeAddPanel;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.table.PercentTableCellRenderer;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingWorker;

public class ListeDesBonsDeLivraisonAction extends CreateListFrameAbstractAction<BonDeLivraisonSQLElement, JFrame> {

    public ListeDesBonsDeLivraisonAction(final ComptaPropsConfiguration conf) {
        super(conf, BonDeLivraisonSQLElement.class);
    }

    @Override
    protected JFrame instantiateFrame() {
        final JFrame frame = new JFrame(String.valueOf(getValue(NAME)));
        RowAction toInvoiceAction = new RowAction(new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                transfertFactureClient(IListe.get(e).getSelectedRows());
            }
        }, false, "sales.shipment.create.invoice") {
            @Override
            public boolean enabledFor(List<SQLRowValues> selection) {

                if (!selection.isEmpty()) {
                    for (SQLRowValues sqlRowValues : selection) {
                        if (sqlRowValues.getBoolean("VERROU_FACTURATION")) {
                            return false;
                        }
                    }
                    return true;
                }
                return false;

            }
        };
        // Tabs
        final JTabbedPane tabs = new JTabbedPane();
        tabs.addTab(getConf().getERP_TM().translate("sales.shipment.allShipments"), createAllDeliveryPanel(toInvoiceAction));
        tabs.addTab(getConf().getERP_TM().translate("sales.shipment.nonInvoicedShipments"), createDeliveryWithoutInvoicePanel(toInvoiceAction));
        tabs.addTab(getConf().getERP_TM().translate("sales.shipment.invoicedShipments"), createDeliveryWithInvoicePanel());
        frame.setContentPane(tabs);

        return frame;
    }

    private ListeAddPanel getPanel(final BonDeLivraisonSQLElement eltCmd, final SQLTableModelSourceOnline tableSource, final List<RowAction> allowedActions, String variant) {
        final ListeAddPanel panel = new ListeAddPanel(eltCmd, new IListe(tableSource), variant);

        final List<SQLField> fields = new ArrayList<SQLField>(2);
        fields.add(eltCmd.getTable().getField("TOTAL_HT"));
        final IListTotalPanel totalPanel = new IListTotalPanel(panel.getListe(), fields, getConf().getERP_TM().translate("sales.shipment.listTotal"));

        final GridBagConstraints c = new DefaultGridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        c.anchor = GridBagConstraints.EAST;
        c.weightx = 1;
        c.gridy = 4;

        // Date panel
        final IListFilterDatePanel datePanel = new IListFilterDatePanel(panel.getListe(), eltCmd.getTable().getField("DATE"), IListFilterDatePanel.getDefaultMap());

        panel.getListe().addIListeActions(new MouseSheetXmlListeListener(eltCmd, BonLivraisonXmlSheet.class) {
            @Override
            public List<RowAction> addToMenu() {
                return allowedActions;
            }
        }.getRowActions());

        panel.getListe().addIListeAction(eltCmd.getCloneAction());

        datePanel.setFilterOnDefault();

        final JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new GridBagLayout());
        bottomPanel.setOpaque(false);
        final GridBagConstraints c2 = new DefaultGridBagConstraints();
        c2.fill = GridBagConstraints.NONE;
        c2.weightx = 1;
        bottomPanel.add(datePanel, c2);

        c2.gridx++;
        c2.weightx = 0;
        c2.anchor = GridBagConstraints.EAST;
        bottomPanel.add(totalPanel, c2);

        panel.add(bottomPanel, c);
        return panel;
    }

    JPanel createAllDeliveryPanel(final RowAction toInvoiceAction) {
        final BonDeLivraisonSQLElement eltCmd = getElem();
        final SQLTableModelSourceOnline tableSource = eltCmd.getTableSource(true);
        final List<RowAction> allowedActions = new ArrayList<RowAction>();
        allowedActions.add(toInvoiceAction);
        BaseSQLTableModelColumn colAvancement = new BaseSQLTableModelColumn(eltCmd.getDirectory().getTranslator().getDescFor(eltCmd.getTable(), "invoiceProgress").getTitleLabel(), BigDecimal.class) {

            @Override
            protected Object show_(SQLRowAccessor r) {

                return getAvancement(r);
            }

            @Override
            public Set<FieldPath> getPaths() {
                final Path p = new PathBuilder(eltCmd.getTable()).addTable("TR_BON_DE_LIVRAISON").addTable("SAISIE_VENTE_FACTURE").build();
                return CollectionUtils.createSet(new FieldPath(p, "T_HT"));
            }
        };
        tableSource.getColumns().add(colAvancement);
        colAvancement.setRenderer(new PercentTableCellRenderer());
        final ListeAddPanel panel = getPanel(eltCmd, tableSource, allowedActions, "alldelivery");
        return panel;
    }

    private BigDecimal getAvancement(SQLRowAccessor r) {
        Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("TR_BON_DE_LIVRAISON"));
        long totalFact = 0;
        long total = r.getLong("TOTAL_HT");
        boolean hasFact = false;
        for (SQLRowAccessor row : rows) {
            if (!row.isForeignEmpty("ID_SAISIE_VENTE_FACTURE")) {
                SQLRowAccessor rowFact = row.getForeign("ID_SAISIE_VENTE_FACTURE");
                Long l = rowFact.getLong("T_HT");
                totalFact += l;
                hasFact = true;
            }
        }
        if (total > 0) {
            return new BigDecimal(totalFact).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
        } else if (hasFact) {
            return BigDecimal.ONE.movePointRight(2);
        } else {
            return BigDecimal.ZERO;
        }
    }

    JPanel createDeliveryWithInvoicePanel() {
        final BonDeLivraisonSQLElement eltCmd = getElem();
        final SQLTableModelSourceOnline tableSource = eltCmd.getTableSource(true);
        final List<RowAction> allowedActions = new ArrayList<RowAction>();

        // Filter on transfered
        final SQLInjector injector = SQLInjector.getInjector(eltCmd.getTable(), eltCmd.getTable().getTable("SAISIE_VENTE_FACTURE"));
        injector.setOnlyTransfered(tableSource);

        final ListeAddPanel panel = getPanel(eltCmd, tableSource, allowedActions, "invoiced");
        return panel;
    }

    JPanel createDeliveryWithoutInvoicePanel(RowAction toInvoiceAction) {
        final BonDeLivraisonSQLElement eltCmd = getElem();
        final SQLTableModelSourceOnline tableSource = eltCmd.getTableSource(true);
        final List<RowAction> allowedActions = new ArrayList<RowAction>();
        allowedActions.add(toInvoiceAction);

        // Filter on not transfered
        final SQLInjector injector = SQLInjector.getInjector(eltCmd.getTable(), eltCmd.getTable().getTable("SAISIE_VENTE_FACTURE"));
        injector.setOnlyNotTransfered(tableSource);

        final ListeAddPanel panel = getPanel(eltCmd, tableSource, allowedActions, "waiting");
        return panel;
    }

    /**
     * Transfert en Facture
     * 
     * @param row
     */
    private void transfertFactureClient(List<SQLRowValues> selectedRows) {
        SwingWorker<Boolean, Object> worker = new SwingWorker<Boolean, Object>() {
            @Override
            protected Boolean doInBackground() throws Exception {

                boolean b = TransfertBaseSQLComponent.isAlreadyAllTransfert(selectedRows, getConf().getRootSociete().getTable("BON_DE_LIVRAISON"),
                        getConf().getRootSociete().getTable("SAISIE_VENTE_FACTURE"), "TOTAL_HT", "T_HT");

                if (b) {
                    String label = "Attention ";
                    if (selectedRows.size() > 1) {
                        label += " les bons de livraisons  ont déjà été transféré!";
                    } else {
                        label += "le bon de livraison a déjà été transféré!";
                    }
                    label += "\n Voulez vous continuer?";

                    int ans = JOptionPane.showConfirmDialog(null, label, "Transfert Bon de livraison", JOptionPane.YES_NO_OPTION);
                    if (ans == JOptionPane.NO_OPTION) {
                        return Boolean.FALSE;
                    }
                }

                return Boolean.TRUE;

            }

            @Override
            protected void done() {
                try {
                    Boolean b = get();
                    if (b) {
                        List<SQLRowValues> selRows = new ArrayList<>();
                        for (SQLRowValues r : selectedRows) {
                            selRows.add(r.createEmptyUpdateRow());
                        }
                        TransfertBaseSQLComponent.openTransfertFrame(selectedRows, "SAISIE_VENTE_FACTURE");

                    }
                } catch (Exception e) {
                    ExceptionHandler.handle("Erreur lors du transfert des bons de livraisons!", e);
                }
            }
        };
        worker.execute();

    }
}