OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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.finance.accounting.ui;

import org.openconcerto.erp.config.Gestion;
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.SQLDataSource;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.JDate;
import org.openconcerto.ui.JLabelBold;
import org.openconcerto.utils.TableSorter;
import org.openconcerto.utils.Tuple2;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class PropoLettrage {

    private SQLElement eltEcr;
    private Date dateKm;

    public PropoLettrage(SQLElement eltEcr) {
        this.eltEcr = eltEcr;
    }

    public void transfert(SQLRow rowKM) {
        List<SQLRow> rowItems = rowKM.getReferentRows(rowKM.getTable().getTable("SAISIE_KM_ELEMENT").getField("ID_SAISIE_KM"));

        this.dateKm = rowKM.getDate("DATE").getTime();

        Set<Tuple2<String, String>> cpts = new HashSet();
        for (SQLRow sqlRow : rowItems) {
            final String cptNumero = sqlRow.getString("NUMERO");
            if (cptNumero.startsWith("40") || cptNumero.startsWith("41")) {
                cpts.add(Tuple2.create(cptNumero, sqlRow.getString("NOM")));
            }
        }
        if (!cpts.isEmpty()) {

            for (Tuple2<String, String> cpt : cpts) {

                SQLRowValues rowValsEcr = new SQLRowValues(this.eltEcr.getTable());
                rowValsEcr.putNulls("DEBIT", "CREDIT", "ID", "COMPTE_NOM", "COMPTE_NUMERO", "NOM", "NOM_PIECE", "DATE");
                rowValsEcr.putRowValues("ID_MOUVEMENT").putNulls("NUMERO").putRowValues("ID_PIECE").putNulls("NOM");
                List<SQLRowValues> resultEcrNonLettrees = SQLRowValuesListFetcher.create(rowValsEcr).fetch(new Where(this.eltEcr.getTable().getField("COMPTE_NUMERO"), "=", cpt.get0())
                        .and(new Where(this.eltEcr.getTable().getField("LETTRAGE"), "=", "").or(new Where(this.eltEcr.getTable().getField("LETTRAGE"), "=", (Object) null))));
                showPreview(resultEcrNonLettrees, cpt);
            }
        }
    }

    private void showPreview(final List<SQLRowValues> rows, Tuple2<String, String> compte) {
        if (rows.isEmpty() || rows.size() == 1) {
            return;
        }
        JPanel panelPreview = new JPanel(new GridBagLayout());
        GridBagConstraints c = new DefaultGridBagConstraints();
        final PropoLettrageTableModel propoModel = new PropoLettrageTableModel(this.eltEcr, rows);
        final TableSorter s = new TableSorter(propoModel);
        final JTable table = new JTable(s);
        s.setTableHeader(table.getTableHeader());
        final int columnCount = table.getColumnCount();
        for (int col = 0; col < columnCount; col++) {

            table.getColumnModel().getColumn(col).setCellRenderer(new PropoLettrageRenderer());
        }

        c.gridwidth = GridBagConstraints.REMAINDER;

        panelPreview.add(new JLabelBold("Ecritures non lettrées du compte " + compte.get0() + " " + compte.get1()), c);
        c.gridx = 0;
        c.gridy++;
        c.fill = GridBagConstraints.BOTH;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.weightx = 1;
        c.weighty = 1;
        panelPreview.add(new JScrollPane(table), c);

        c.gridy++;
        c.gridx = 0;
        c.gridwidth = 1;
        c.weighty = 0;
        c.weightx = 0;
        c.fill = GridBagConstraints.HORIZONTAL;
        panelPreview.add(new JLabel("Lettrer les écritures sélectionnées à la date du "), c);
        final JDate date = new JDate();
        date.setValue(this.dateKm);
        c.gridx++;
        panelPreview.add(date);

        JDialog diag = new JDialog();
        diag.setModal(true);
        diag.setContentPane(panelPreview);
        diag.setTitle("Lettrage " + compte.get0() + " " + compte.get1());

        c.gridy++;
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.EAST;
        c.weightx = 1;
        c.weighty = 0;
        c.gridwidth = 1;
        final JButton valid = new JButton(new AbstractAction("Lettrer") {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    SQLUtils.executeAtomic(eltEcr.getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, Exception>() {
                        @Override
                        public Object handle(SQLDataSource ds) throws SQLException, Exception {
                            String codeLettre = NumerotationAutoSQLElement.getNextCodeLettrage();
                            int[] selectedRows = table.getSelectedRows();
                            int[] modelRows = new int[selectedRows.length];
                            int nb = 0;
                            for (int i : selectedRows) {
                                modelRows[nb] = s.modelIndex(i);
                                nb++;
                            }

                            final Date dateLettrage = date.getValue() == null ? new Date() : date.getValue();
                            for (int index : modelRows) {

                                SQLRowValues rowValsEcr = propoModel.getRowValuesAt(index).createEmptyUpdateRow();
                                // Lettrage
                                // On lettre ou relettre la ligne avec le code saisi
                                if (codeLettre.length() > 0) {

                                    rowValsEcr.put("LETTRAGE", codeLettre);
                                    rowValsEcr.put("DATE_LETTRAGE", dateLettrage);

                                    rowValsEcr.update();

                                }

                            }
                            // Mise à jour du code de lettrage
                            SQLElement elt = Configuration.getInstance().getDirectory().getElement("NUMEROTATION_AUTO");
                            SQLRowValues rowVals = elt.getTable().getRow(2).createEmptyUpdateRow();
                            rowVals.put("CODE_LETTRAGE", codeLettre);

                            rowVals.update();

                            return null;
                        }
                    });
                } catch (Exception e1) {
                    org.openconcerto.utils.ExceptionHandler.handle("Erreur lors du lettrage", e1);
                }
                diag.dispose();
            }
        });
        panelPreview.add(valid, c);
        valid.setEnabled(false);
        c.weightx = 0;
        c.gridx++;
        JButton fermer = new JButton(new AbstractAction("Fermer") {

            @Override
            public void actionPerformed(ActionEvent e) {
                diag.dispose();
            }
        });

        panelPreview.add(fermer, c);

        table.addMouseListener(new MouseAdapter() {

            public void mouseReleased(MouseEvent e) {
                int[] selectedRows = table.getSelectedRows();
                int[] modelRows = new int[selectedRows.length];
                int nb = 0;
                for (int i : selectedRows) {
                    modelRows[nb] = s.modelIndex(i);
                    nb++;
                }
                valid.setEnabled(propoModel.isSelectionEqual(modelRows));
            }
        });

        table.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {

                int[] selectedRows = table.getSelectedRows();
                int[] modelRows = new int[selectedRows.length];
                int nb = 0;
                for (int i : selectedRows) {
                    modelRows[nb] = s.modelIndex(i);
                    nb++;
                }

                valid.setEnabled(propoModel.isSelectionEqual(modelRows));

            }
        });
        diag.pack();
        diag.setIconImage(new ImageIcon(Gestion.class.getResource("frameicon.png")).getImage());
        diag.setLocationRelativeTo(null);
        FrameUtil.show(diag);
    }

}