OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | 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.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.ui.DeviseCellEditor;
import org.openconcerto.erp.core.common.ui.MultiLineTableCellEditor;
import org.openconcerto.erp.core.common.ui.RowValuesMultiLineEditTable;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.TM;
import org.openconcerto.sql.element.SQLElement;
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.model.Where;
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
import org.openconcerto.sql.view.list.AutoCompletionManager;
import org.openconcerto.sql.view.list.RowValuesTable;
import org.openconcerto.sql.view.list.RowValuesTableControlPanel;
import org.openconcerto.sql.view.list.RowValuesTableModel;
import org.openconcerto.sql.view.list.SQLTableElement;
import org.openconcerto.sql.view.list.ValidStateChecker;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.JComponentUtils;
import org.openconcerto.ui.RangedIntegerTableCellEditor;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.GestionDevise;
import org.openconcerto.utils.Tuple2;
import org.openconcerto.utils.checks.ValidState;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

public class SaisieJournalItemTable extends JPanel implements MouseListener {

    private final RowValuesTable table;
    private final SQLTableElement debit;
    private final SQLTableElement credit;
    private JLabel labelTotalDebit;
    private JLabel labelTotalCredit;
    private JLabel labelTotalSolde;
    private final SQLTableElement tableElementNumeroCompte;
    private final CompteRowValuesRenderer numeroCompteRenderer = new CompteRowValuesRenderer();
    private final DeviseKmRowValuesRenderer deviseRenderer = new DeviseKmRowValuesRenderer();
    final RangedIntegerTableCellEditor rangedIntegerTableCellEditor = new RangedIntegerTableCellEditor(1, 31);
    private final RowValuesTableControlPanel controlPanel;

    private SaisieJournalPanel panel;
    private final JCheckBox boxAutoInsert;
    private boolean hideAnalytique = false;

    public SaisieJournalItemTable(final SQLRowValues defaultRowVals, JCheckBox boxAutoInsert, final JTextField textField) {
        setLayout(new GridBagLayout());
        this.boxAutoInsert = boxAutoInsert;
        final GridBagConstraints c = new DefaultGridBagConstraints();
        c.weightx = 1;

        final SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_KM_ELEMENT");

        // TODO Obligation de choisir un compte correct
        final List<SQLTableElement> list = new Vector<>();
        final SQLTable tableElement = elt.getTable();
        final SQLTableElement tableElementJour = new SQLTableElement(tableElement.getField("JOUR"), Integer.class, this.rangedIntegerTableCellEditor) {
            @Override
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {

                return super.isCellEditable(vals, rowIndex, columnIndex) && rowIndex == 0;
            }

            @Override
            protected Object getDefaultNullValue() {
                return 1;
            }

        };

        list.add(tableElementJour);

        this.tableElementNumeroCompte = new SQLTableElement(tableElement.getField("NUMERO"));
        list.add(this.tableElementNumeroCompte);

        final SQLTableElement tableElementNomCompte = new SQLTableElement(tableElement.getField("NOM"));
        list.add(tableElementNomCompte);

        final SQLTableElement tableElementNomPiece = new SQLTableElement(tableElement.getField("NOM_PIECE"));
        list.add(tableElementNomPiece);

        final SQLTableElement tableElementNomEcriture = new SQLTableElement(tableElement.getField("NOM_ECRITURE"));
        list.add(tableElementNomEcriture);

        //
        DeviseCellEditor deviseDebitEditor = new DeviseCellEditor();
        DeviseCellEditor deviseCreditEditor = new DeviseCellEditor();
        this.debit = new SQLTableElement(tableElement.getField("DEBIT"), Long.class, deviseDebitEditor);
        list.add(this.debit);
        this.credit = new SQLTableElement(tableElement.getField("CREDIT"), Long.class, deviseCreditEditor);
        list.add(this.credit);
        this.hideAnalytique = DefaultNXProps.getInstance().getBooleanValue("HideAnalytique");
        if (!this.hideAnalytique) {
            final AnalytiqueItemTable analytiqueAssocTable = new AnalytiqueItemTable(true, new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    montantValid(defaultRowVals, true, textField);
                }
            });
            final MultiLineTableCellEditor multiLineTableCellEditor = new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable);

            SQLTableElement eltPourcentAnalytique = new SQLTableElement(tableElement.getField("ANALYTIQUE"), String.class, multiLineTableCellEditor) {
                @Override
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
                    return vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"));
                };
            };
            list.add(eltPourcentAnalytique);
        }

        final RowValuesTableModel model = new RowValuesTableModel(elt, list, tableElement.getField("NUMERO"), false, defaultRowVals) {
            @Override
            public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
                super.setValueAt(aValue, rowIndex, columnIndex);

                final int debitIndex = getColumnIndexForElement(SaisieJournalItemTable.this.debit);
                final int creditIndex = getColumnIndexForElement(SaisieJournalItemTable.this.credit);

                if (debitIndex == columnIndex && ((Number) aValue).longValue() != 0 && ((Number) getValueAt(rowIndex, creditIndex)).longValue() != 0) {
                    setValueAt(Long.valueOf(0), rowIndex, creditIndex);
                } else {
                    if (creditIndex == columnIndex && ((Number) aValue).longValue() != 0 && ((Number) getValueAt(rowIndex, debitIndex)).longValue() != 0) {
                        setValueAt(Long.valueOf(0), rowIndex, debitIndex);
                    }
                }
            }
        };

        this.table = new RowValuesTable(model, null);
        ToolTipManager.sharedInstance().unregisterComponent(this.table);
        ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());

        tableElementNomEcriture.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() {

            @Override
            public void editingStopped(ChangeEvent e) {
                e.getSource();
                int row = SaisieJournalItemTable.this.table.getSelectedRow();
                int col = 4;
                if (SaisieJournalItemTable.this.table.getValueAt(row, col) != null) {
                    defaultRowVals.put("NOM_ECRITURE", SaisieJournalItemTable.this.table.getValueAt(row, col));
                }

            }

            @Override
            public void editingCanceled(ChangeEvent e) {
                //

            }
        });
        tableElementNomPiece.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() {

            @Override
            public void editingStopped(ChangeEvent e) {
                e.getSource();
                int row = SaisieJournalItemTable.this.table.getSelectedRow();
                int col = 3;
                if (SaisieJournalItemTable.this.table.getValueAt(row, col) != null) {
                    defaultRowVals.put("NOM_PIECE", SaisieJournalItemTable.this.table.getValueAt(row, col));
                }

            }

            @Override
            public void editingCanceled(ChangeEvent e) {
                //

            }
        });

        tableElementJour.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() {

            @Override
            public void editingStopped(ChangeEvent e) {
                final Object valueAt = SaisieJournalItemTable.this.table.getValueAt(0, 0);
                defaultRowVals.put("JOUR", valueAt);
                if (SaisieJournalItemTable.this.table.getRowCount() > 1) {
                    for (int i = 1; i < SaisieJournalItemTable.this.table.getRowCount(); i++) {
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(valueAt, i, "JOUR");
                    }
                }
            }

            @Override
            public void editingCanceled(ChangeEvent e) {
                //
            }
        });

        final KeyListener keyListenerContrepartie = new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    montantValid(defaultRowVals, false, textField);
                }
            }
        };
        deviseCreditEditor.addKeyListener(keyListenerContrepartie);
        deviseDebitEditor.addKeyListener(keyListenerContrepartie);

        // Autocompletion
        final AutoCompletionManager m = new AutoCompletionManager(this.tableElementNumeroCompte,
                ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NUMERO"), this.table, this.table.getRowValuesTableModel(),
                ITextWithCompletion.MODE_STARTWITH, true, false, new ValidStateChecker() {

                    ComptePCESQLElement elt = Configuration.getInstance().getDirectory().getElement(ComptePCESQLElement.class);

                    @Override
                    public ValidState getValidState(Object o) {
                        if (o != null) {
                            return this.elt.getCompteNumeroValidState(o.toString());
                        }
                        return super.getValidState(o);
                    }
                });
        m.fill("NOM", "NOM");
        m.setFillWithField("NUMERO");
        final Where w = new Where(elt.getTable().getTable("COMPTE_PCE").getField("OBSOLETE"), "=", Boolean.FALSE);
        m.setWhere(w);

        // FIXME erreur fill numero
        final AutoCompletionManager m2 = new AutoCompletionManager(tableElementNomCompte, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NOM"),
                this.table, this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true);
        m2.fill("NUMERO", "NUMERO");
        m2.setFillWithField("NOM");
        m2.setWhere(w);

        JButton buttonClone = new JButton(TM.tr(Configuration.getInstance().getLocale(), "duplicateLine"));
        buttonClone.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                cloneLine(SaisieJournalItemTable.this.table.getSelectedRow());
            }
        });
        buttonClone.setEnabled(false);
        c.gridx++;
        JComponentUtils.setMinimumWidth(buttonClone, 95);

        this.controlPanel = new RowValuesTableControlPanel(this.table, Arrays.asList(buttonClone));
        this.controlPanel.setVisibleButtonClone(false);
        this.controlPanel.setButtonAjouterEnabled(false);
        this.add(this.controlPanel, c);

        c.gridy++;
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1;
        c.weighty = 1;
        this.add(new JScrollPane(this.table), c);

        this.tableElementNumeroCompte.setRenderer(this.numeroCompteRenderer);
        this.debit.setRenderer(this.deviseRenderer);
        this.credit.setRenderer(this.deviseRenderer);

        this.table.addMouseListener(this);
        this.table.getModel().addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                // Sélectionne automatiquement la ligne ajoutée
                if (e.getType() == TableModelEvent.INSERT) {
                    if (SaisieJournalItemTable.this.table.getRowCount() == 1) {
                        editCellAt(e.getFirstRow(), 0);
                    } else {
                        editCellAt(e.getFirstRow(), 1);
                    }
                }
                refreshTotal();
            }
        });

        // Initialisation du panel des Totaux
        this.labelTotalCredit = new JLabel("0.00", SwingConstants.RIGHT);
        this.labelTotalDebit = new JLabel("0.00", SwingConstants.RIGHT);
        this.labelTotalSolde = new JLabel("0.00", SwingConstants.RIGHT);
        JPanel panelTotal = new JPanel();
        panelTotal.setLayout(new GridBagLayout());
        panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux"));
        final GridBagConstraints cc = new DefaultGridBagConstraints();
        cc.anchor = GridBagConstraints.EAST;

        // Total Debit
        cc.fill = GridBagConstraints.NONE;
        panelTotal.add(new JLabel("Débit"), cc);
        cc.fill = GridBagConstraints.HORIZONTAL;
        cc.gridx++;
        cc.weightx = 1;

        panelTotal.add(this.labelTotalDebit, cc);

        // Total Credit
        cc.gridy++;
        cc.gridx = 0;
        cc.weightx = 0;
        cc.fill = GridBagConstraints.NONE;
        panelTotal.add(new JLabel("Crédit"), cc);
        cc.weightx = 1;
        cc.gridx++;
        cc.fill = GridBagConstraints.HORIZONTAL;
        panelTotal.add(this.labelTotalCredit, cc);

        // Total Credit
        cc.gridy++;
        cc.gridx = 0;
        cc.weightx = 0;
        cc.fill = GridBagConstraints.NONE;
        panelTotal.add(new JLabel("Solde"), cc);
        cc.weightx = 1;
        cc.gridx++;
        cc.fill = GridBagConstraints.HORIZONTAL;
        panelTotal.add(this.labelTotalSolde, cc);

        c.gridy++;
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.EAST;
        c.weightx = 1;
        c.weighty = 0;
        this.add(panelTotal, c);
    }

    public void setPanel(final SaisieJournalPanel panel) {
        this.panel = panel;

        final PropertyChangeListener lActiveAddButton = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                SaisieJournalItemTable.this.controlPanel.setButtonAjouterEnabled(!panel.getBoxJournal().isEmpty() && !panel.getBoxMois().isEmpty());
            }
        };
        panel.getBoxJournal().addModelListener("wantedID", lActiveAddButton);
        panel.getBoxMois().addModelListener("wantedID", lActiveAddButton);

        final PropertyChangeListener l = new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (!SaisieJournalItemTable.this.panel.boxMois.isEmpty()) {
                    final SQLRow selectedRow = SaisieJournalItemTable.this.panel.boxMois.getSelectedRow();
                    if (selectedRow != null && !selectedRow.isUndefined()) {
                        Calendar c = Calendar.getInstance();
                        c.set(Calendar.DAY_OF_MONTH, 1);
                        c.set(Calendar.YEAR, (Integer) SaisieJournalItemTable.this.panel.spin.getValue());
                        c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
                        SaisieJournalItemTable.this.rangedIntegerTableCellEditor.setMax(c.getActualMaximum(Calendar.DAY_OF_MONTH));
                    }
                }
            }

        };
        panel.boxMois.addModelListener("wantedID", l);

    }

    public void refreshTotal() {

        long totalD = 0L;
        long totalC = 0L;

        for (int i = 0; i < this.table.getRowCount(); i++) {
            Number c = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("DEBIT"));
            Number d = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("CREDIT"));
            if (c != null) {
                totalC += c.longValue();
            }
            if (d != null) {
                totalD += d.longValue();
            }

        }
        this.labelTotalCredit.setText(GestionDevise.currencyToString(totalC));
        this.labelTotalDebit.setText(GestionDevise.currencyToString(totalD));
        this.labelTotalSolde.setText(GestionDevise.currencyToString(totalD - totalC));

    }

    public boolean isSaisieValid() {
        // Check if partie double

        long totalD = 0L;
        long totalC = 0L;
        boolean cptOK = true;
        String lib = null;
        for (int i = 0; i < this.table.getRowCount(); i++) {
            Number c = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("DEBIT"));
            Number d = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("CREDIT"));
            if (c != null) {
                totalC += c.longValue();
            }
            if (d != null) {
                totalD += d.longValue();
            }
            if (lib == null) {
                lib = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NOM"));
            }
            String cptNUmber = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NUMERO"));
            cptOK = cptOK && cptNUmber != null && ComptePCESQLElement.isExist(cptNUmber);
        }
        return totalD + totalC != 0 && totalD == totalC && cptOK;
    }

    private Tuple2<Date, String> getDateAndLabelFromSaisie() {
        int day = 1;
        String lib = null;

        for (int i = 0; i < this.table.getRowCount(); i++) {
            day = (Integer) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("JOUR"));
            if (lib == null) {
                lib = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NOM"));
            }
        }
        // Create saisieKM
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, SaisieJournalItemTable.this.panel.getSelectedYear());
        c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
        c.set(Calendar.DAY_OF_MONTH, day);
        return Tuple2.create(c.getTime(), lib);
    }

    public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique, final JTextField textPiece) {
        final SQLRowValues vals = SaisieJournalItemTable.this.table.getSelectedRowValues();
        final int selectedRow = SaisieJournalItemTable.this.table.getSelectedRow();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                if (SaisieJournalItemTable.this.boxAutoInsert.isSelected() && isSaisieValid()) {
                    if (SaisieJournalItemTable.this.panel.getSelectedJournal() == SQLRow.NONEXISTANT_ID || SaisieJournalItemTable.this.panel.getSelectedMonth() == -1) {
                        JOptionPane.showMessageDialog(SaisieJournalItemTable.this.panel, "Impossible de créer la saisie si aucun journal ou aucun mois n'est sélectionné!");
                    } else {
                        createSaisie(defaultRowVals, textPiece);
                    }
                } else {
                    if (!fromAnalytique && !SaisieJournalItemTable.this.hideAnalytique && vals.getString("NUMERO") != null
                            && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"))) {

                        // Update montant
                        Collection<SQLRowValues> rowsLinked = vals.getReferentRows(vals.getTable().getTable("ASSOCIATION_ANALYTIQUE"));
                        long montant = vals.getLong("DEBIT") - vals.getLong("CREDIT");
                        for (SQLRowValues sqlRowValues : rowsLinked) {
                            sqlRowValues.put("MONTANT", sqlRowValues.getBigDecimal("POURCENT").movePointLeft(2).multiply(new BigDecimal(montant), DecimalUtils.HIGH_PRECISION)
                                    .setScale(0, RoundingMode.HALF_UP).longValue());
                        }

                        editCellAt(selectedRow, SaisieJournalItemTable.this.table.getRowValuesTableModel().getColumnForField("ANALYTIQUE"));
                    } else {

                        long l = getContrepartie();
                        SQLRowValues rowVals = new SQLRowValues(defaultRowVals);
                        if (l > 0) {
                            rowVals.put("DEBIT", 0L);
                            rowVals.put("CREDIT", l);
                        } else {
                            rowVals.put("DEBIT", -l);
                            rowVals.put("CREDIT", 0L);
                        }
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().addRow(rowVals);
                    }
                }

            }
        });

    }

    public synchronized void createSaisie(final SQLRowValues defaultRowVals, JTextField pieceText) {

        Tuple2<Date, String> t = getDateAndLabelFromSaisie();
        final Date d = t.get0();
        String pieceLabel = pieceText.getText();
        final String lib = pieceLabel == null || pieceLabel.trim().length() == 0 ? t.get1() : pieceLabel;

        // Create saisieKM
        SQLRowValues rowVAlsKM = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));

        rowVAlsKM.put("DATE", d);
        rowVAlsKM.put("NOM", lib);
        rowVAlsKM.put("ID_JOURNAL", SaisieJournalItemTable.this.panel.getSelectedJournal());
        int id;
        try {
            id = rowVAlsKM.insert().getID();

            this.table.updateField("ID_SAISIE_KM", id);
            this.table.clear();
            GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id);
            int idMvt = gen.genereMouvement();

            // maj de l'id du mouvement correspondant
            SQLRowValues rowValsKMMvt = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
            rowValsKMMvt.put("ID_MOUVEMENT", Integer.valueOf(idMvt));
            rowValsKMMvt.update(id);

            defaultRowVals.put("NOM_PIECE", "");
            defaultRowVals.put("NOM_ECRITURE", "");
            this.table.getRowValuesTableModel().addNewRow();
            pieceText.setText("");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void updateField(final String field, final int id) {
        this.table.updateField(field, id);
    }

    public void insertFrom(final String field, final int id) {
        this.table.insertFrom(field, id);
    }

    public void insertFrom(final SQLRowAccessor row) {
        this.table.insertFrom(row);
    }

    public RowValuesTableModel getModel() {
        return this.table.getRowValuesTableModel();
    }

    public SQLTableElement getCreditElement() {
        return this.credit;
    }

    public SQLTableElement getDebitElement() {
        return this.debit;
    }

    public SQLTableElement getNumeroCompteElement() {
        return this.tableElementNumeroCompte;
    }

    public void setCreateAutoActive(final boolean b) {
        this.numeroCompteRenderer.setCreateActive(b);
        this.table.revalidate();
        this.table.repaint();
    }

    public void setRowDeviseValidAt(final boolean b, final int index) {
        this.deviseRenderer.setValid(b, index);

    }

    public void editCellAt(final int row, final int column) {
        assert SwingUtilities.isEventDispatchThread();
        this.table.setColumnSelectionInterval(column, column);
        this.table.setRowSelectionInterval(row, row);
        this.table.editCellAt(row, column);
    }

    private long getContrepartie() {
        assert SwingUtilities.isEventDispatchThread();
        long totalCred = 0;
        long totalDeb = 0;
        final RowValuesTableModel model = this.table.getRowValuesTableModel();
        final int creditIndex = model.getColumnIndexForElement(getCreditElement());
        final int debitIndex = model.getColumnIndexForElement(getDebitElement());
        for (int i = 0; i < this.table.getRowCount(); i++) {
            if (model.isRowValid(i)) {
                final Number fTc = (Number) model.getValueAt(i, creditIndex);
                if (fTc != null) {
                    totalCred += fTc.longValue();
                }
                final Number fTd = (Number) model.getValueAt(i, debitIndex);
                if (fTd != null) {
                    totalDeb += fTd.longValue();
                }
            }
        }
        return totalDeb - totalCred;
    }

    private long getSoldeRow(final int index) {
        assert SwingUtilities.isEventDispatchThread();
        if (index >= 0 && index < this.table.getRowCount()) {
            final SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(index);
            return rowVals.getLong("DEBIT") - rowVals.getLong("CREDIT");
        } else {
            return 0;
        }
    }

    public void fillEmptyEntryLabel(String previousText, String text) {
        assert SwingUtilities.isEventDispatchThread();
        if (text == null)
            return;
        RowValuesTableModel model = this.table.getRowValuesTableModel();
        int size = model.getRowCount();
        for (int i = 0; i < size; i++) {
            SQLRowValues r = model.getRowValuesAt(i);
            if (r.getString("NOM_ECRITURE") == null || r.getString("NOM_ECRITURE").trim().isEmpty() || r.getString("NOM_ECRITURE").trim().equals(previousText)) {
                r.put("NOM_ECRITURE", text);
            }
        }
        model.fireTableDataChanged();
    }

    @Override
    public void mousePressed(final MouseEvent e) {
        final int rowSel = this.table.getSelectedRow();
        if (e.getButton() == MouseEvent.BUTTON3 && rowSel >= 0 && rowSel < this.table.getRowCount()) {
            final JPopupMenu menuDroit = new JPopupMenu();

            menuDroit.add(new AbstractAction("Contrepartie") {
                public void actionPerformed(final ActionEvent ev) {

                    long l = getContrepartie();
                    if (SaisieJournalItemTable.this.table.getRowValuesTableModel().isRowValid(rowSel)) {
                        l += getSoldeRow(rowSel);
                    }

                    if (l > 0) {
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "DEBIT");
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(l, rowSel, "CREDIT");
                    } else {
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "CREDIT");
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(-l, rowSel, "DEBIT");
                    }
                }
            });
            menuDroit.pack();
            menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
            menuDroit.setVisible(true);
        }
    }

    @Override
    public void mouseReleased(final MouseEvent e) {
        // Nothing
    }

    @Override
    public void mouseClicked(final MouseEvent e) {
        // Nothing
    }

    @Override
    public void mouseEntered(final MouseEvent e) {
        // Nothing
    }

    @Override
    public void mouseExited(final MouseEvent e) {
        // Nothing
    }

    private void cloneLine(int row) {
        if (row < 0) {
            return;
        }
        SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(row);

        SQLRowValues rowValsBis = rowVals.deepCopy();
        rowValsBis.clearPrimaryKeys();
        rowValsBis.put(rowValsBis.getTable().getOrderField().getName(), null);

        this.table.getRowValuesTableModel().getSQLElement().clearPrivateFields(rowValsBis);
        rowValsBis.putEmptyLink("ID_ECRITURE");
        for (String elt : this.table.getClearCloneTableElement()) {
            if (rowValsBis.getTable().getFieldsName().contains(elt)) {
                rowValsBis.putEmptyLink(elt);
            }
        }

        this.table.getRowValuesTableModel().addRow(rowValsBis);
    }
}