OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
149 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.finance.accounting.ui;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.ui.DeviseCellEditor;
18
import org.openconcerto.erp.core.common.ui.MultiLineTableCellEditor;
19
import org.openconcerto.erp.core.common.ui.RowValuesMultiLineEditTable;
20
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
21
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm;
22
import org.openconcerto.erp.preferences.DefaultNXProps;
23
import org.openconcerto.sql.Configuration;
174 ilm 24
import org.openconcerto.sql.TM;
149 ilm 25
import org.openconcerto.sql.element.SQLElement;
26
import org.openconcerto.sql.model.SQLRow;
27
import org.openconcerto.sql.model.SQLRowAccessor;
28
import org.openconcerto.sql.model.SQLRowValues;
29
import org.openconcerto.sql.model.SQLTable;
30
import org.openconcerto.sql.model.Where;
31
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
32
import org.openconcerto.sql.view.list.AutoCompletionManager;
33
import org.openconcerto.sql.view.list.RowValuesTable;
34
import org.openconcerto.sql.view.list.RowValuesTableControlPanel;
35
import org.openconcerto.sql.view.list.RowValuesTableModel;
36
import org.openconcerto.sql.view.list.SQLTableElement;
37
import org.openconcerto.sql.view.list.ValidStateChecker;
38
import org.openconcerto.ui.DefaultGridBagConstraints;
174 ilm 39
import org.openconcerto.ui.JComponentUtils;
149 ilm 40
import org.openconcerto.ui.RangedIntegerTableCellEditor;
41
import org.openconcerto.utils.DecimalUtils;
42
import org.openconcerto.utils.GestionDevise;
43
import org.openconcerto.utils.Tuple2;
44
import org.openconcerto.utils.checks.ValidState;
45
 
46
import java.awt.GridBagConstraints;
47
import java.awt.GridBagLayout;
48
import java.awt.event.ActionEvent;
174 ilm 49
import java.awt.event.ActionListener;
177 ilm 50
import java.awt.event.KeyAdapter;
149 ilm 51
import java.awt.event.KeyEvent;
52
import java.awt.event.KeyListener;
53
import java.awt.event.MouseEvent;
54
import java.awt.event.MouseListener;
55
import java.beans.PropertyChangeEvent;
56
import java.beans.PropertyChangeListener;
57
import java.math.BigDecimal;
58
import java.math.RoundingMode;
59
import java.sql.SQLException;
174 ilm 60
import java.util.Arrays;
149 ilm 61
import java.util.Calendar;
62
import java.util.Collection;
63
import java.util.Date;
64
import java.util.List;
65
import java.util.Vector;
66
 
67
import javax.swing.AbstractAction;
68
import javax.swing.BorderFactory;
174 ilm 69
import javax.swing.JButton;
149 ilm 70
import javax.swing.JCheckBox;
71
import javax.swing.JLabel;
72
import javax.swing.JOptionPane;
73
import javax.swing.JPanel;
74
import javax.swing.JPopupMenu;
75
import javax.swing.JScrollPane;
156 ilm 76
import javax.swing.JTextField;
149 ilm 77
import javax.swing.SwingConstants;
78
import javax.swing.SwingUtilities;
79
import javax.swing.ToolTipManager;
80
import javax.swing.event.CellEditorListener;
81
import javax.swing.event.ChangeEvent;
82
import javax.swing.event.TableModelEvent;
83
import javax.swing.event.TableModelListener;
84
 
85
public class SaisieJournalItemTable extends JPanel implements MouseListener {
86
 
87
    private final RowValuesTable table;
88
    private final SQLTableElement debit;
89
    private final SQLTableElement credit;
90
    private JLabel labelTotalDebit;
91
    private JLabel labelTotalCredit;
92
    private JLabel labelTotalSolde;
93
    private final SQLTableElement tableElementNumeroCompte;
94
    private final CompteRowValuesRenderer numeroCompteRenderer = new CompteRowValuesRenderer();
95
    private final DeviseKmRowValuesRenderer deviseRenderer = new DeviseKmRowValuesRenderer();
96
    final RangedIntegerTableCellEditor rangedIntegerTableCellEditor = new RangedIntegerTableCellEditor(1, 31);
97
    private final RowValuesTableControlPanel controlPanel;
98
 
99
    private SaisieJournalPanel panel;
100
    private final JCheckBox boxAutoInsert;
101
    private boolean hideAnalytique = false;
102
 
156 ilm 103
    public SaisieJournalItemTable(final SQLRowValues defaultRowVals, JCheckBox boxAutoInsert, final JTextField textField) {
149 ilm 104
        setLayout(new GridBagLayout());
105
        this.boxAutoInsert = boxAutoInsert;
106
        final GridBagConstraints c = new DefaultGridBagConstraints();
107
        c.weightx = 1;
108
 
109
        final SQLElement elt = Configuration.getInstance().getDirectory().getElement("SAISIE_KM_ELEMENT");
110
 
111
        // TODO Obligation de choisir un compte correct
177 ilm 112
        final List<SQLTableElement> list = new Vector<>();
149 ilm 113
        final SQLTable tableElement = elt.getTable();
177 ilm 114
        final SQLTableElement tableElementJour = new SQLTableElement(tableElement.getField("JOUR"), Integer.class, this.rangedIntegerTableCellEditor) {
149 ilm 115
            @Override
116
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
117
 
118
                return super.isCellEditable(vals, rowIndex, columnIndex) && rowIndex == 0;
119
            }
120
 
121
            @Override
122
            protected Object getDefaultNullValue() {
123
                return 1;
124
            }
125
 
126
        };
127
 
128
        list.add(tableElementJour);
129
 
130
        this.tableElementNumeroCompte = new SQLTableElement(tableElement.getField("NUMERO"));
131
        list.add(this.tableElementNumeroCompte);
132
 
133
        final SQLTableElement tableElementNomCompte = new SQLTableElement(tableElement.getField("NOM"));
134
        list.add(tableElementNomCompte);
135
 
136
        final SQLTableElement tableElementNomPiece = new SQLTableElement(tableElement.getField("NOM_PIECE"));
137
        list.add(tableElementNomPiece);
138
 
139
        final SQLTableElement tableElementNomEcriture = new SQLTableElement(tableElement.getField("NOM_ECRITURE"));
140
        list.add(tableElementNomEcriture);
141
 
142
        //
143
        DeviseCellEditor deviseDebitEditor = new DeviseCellEditor();
144
        DeviseCellEditor deviseCreditEditor = new DeviseCellEditor();
145
        this.debit = new SQLTableElement(tableElement.getField("DEBIT"), Long.class, deviseDebitEditor);
146
        list.add(this.debit);
147
        this.credit = new SQLTableElement(tableElement.getField("CREDIT"), Long.class, deviseCreditEditor);
148
        list.add(this.credit);
149
        this.hideAnalytique = DefaultNXProps.getInstance().getBooleanValue("HideAnalytique");
150
        if (!this.hideAnalytique) {
151
            final AnalytiqueItemTable analytiqueAssocTable = new AnalytiqueItemTable(true, new AbstractAction() {
152
 
153
                @Override
154
                public void actionPerformed(ActionEvent e) {
156 ilm 155
                    montantValid(defaultRowVals, true, textField);
149 ilm 156
                }
157
            });
158
            final MultiLineTableCellEditor multiLineTableCellEditor = new MultiLineTableCellEditor((RowValuesMultiLineEditTable) analytiqueAssocTable.getTable(), analytiqueAssocTable);
159
 
160
            SQLTableElement eltPourcentAnalytique = new SQLTableElement(tableElement.getField("ANALYTIQUE"), String.class, multiLineTableCellEditor) {
177 ilm 161
                @Override
149 ilm 162
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
163
                    return vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"));
164
                };
165
            };
166
            list.add(eltPourcentAnalytique);
167
        }
168
 
169
        final RowValuesTableModel model = new RowValuesTableModel(elt, list, tableElement.getField("NUMERO"), false, defaultRowVals) {
170
            @Override
171
            public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
172
                super.setValueAt(aValue, rowIndex, columnIndex);
173
 
174
                final int debitIndex = getColumnIndexForElement(SaisieJournalItemTable.this.debit);
175
                final int creditIndex = getColumnIndexForElement(SaisieJournalItemTable.this.credit);
176
 
177 ilm 177
                if (debitIndex == columnIndex && ((Number) aValue).longValue() != 0 && ((Number) getValueAt(rowIndex, creditIndex)).longValue() != 0) {
149 ilm 178
                    setValueAt(Long.valueOf(0), rowIndex, creditIndex);
179
                } else {
177 ilm 180
                    if (creditIndex == columnIndex && ((Number) aValue).longValue() != 0 && ((Number) getValueAt(rowIndex, debitIndex)).longValue() != 0) {
149 ilm 181
                        setValueAt(Long.valueOf(0), rowIndex, debitIndex);
182
                    }
183
                }
184
            }
185
        };
186
 
187
        this.table = new RowValuesTable(model, null);
188
        ToolTipManager.sharedInstance().unregisterComponent(this.table);
189
        ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
190
 
177 ilm 191
        tableElementNomEcriture.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() {
149 ilm 192
 
193
            @Override
194
            public void editingStopped(ChangeEvent e) {
195
                e.getSource();
177 ilm 196
                int row = SaisieJournalItemTable.this.table.getSelectedRow();
149 ilm 197
                int col = 4;
177 ilm 198
                if (SaisieJournalItemTable.this.table.getValueAt(row, col) != null) {
199
                    defaultRowVals.put("NOM_ECRITURE", SaisieJournalItemTable.this.table.getValueAt(row, col));
149 ilm 200
                }
177 ilm 201
 
149 ilm 202
            }
203
 
204
            @Override
205
            public void editingCanceled(ChangeEvent e) {
177 ilm 206
                //
149 ilm 207
 
208
            }
209
        });
177 ilm 210
        tableElementNomPiece.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() {
149 ilm 211
 
212
            @Override
213
            public void editingStopped(ChangeEvent e) {
214
                e.getSource();
177 ilm 215
                int row = SaisieJournalItemTable.this.table.getSelectedRow();
149 ilm 216
                int col = 3;
177 ilm 217
                if (SaisieJournalItemTable.this.table.getValueAt(row, col) != null) {
218
                    defaultRowVals.put("NOM_PIECE", SaisieJournalItemTable.this.table.getValueAt(row, col));
149 ilm 219
                }
177 ilm 220
 
149 ilm 221
            }
222
 
223
            @Override
224
            public void editingCanceled(ChangeEvent e) {
177 ilm 225
                //
149 ilm 226
 
227
            }
228
        });
229
 
177 ilm 230
        tableElementJour.getTableCellEditor(this.table).addCellEditorListener(new CellEditorListener() {
149 ilm 231
 
232
            @Override
233
            public void editingStopped(ChangeEvent e) {
177 ilm 234
                final Object valueAt = SaisieJournalItemTable.this.table.getValueAt(0, 0);
149 ilm 235
                defaultRowVals.put("JOUR", valueAt);
177 ilm 236
                if (SaisieJournalItemTable.this.table.getRowCount() > 1) {
237
                    for (int i = 1; i < SaisieJournalItemTable.this.table.getRowCount(); i++) {
238
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(valueAt, i, "JOUR");
149 ilm 239
                    }
240
                }
241
            }
242
 
243
            @Override
244
            public void editingCanceled(ChangeEvent e) {
177 ilm 245
                //
149 ilm 246
            }
247
        });
248
 
177 ilm 249
        final KeyListener keyListenerContrepartie = new KeyAdapter() {
149 ilm 250
 
251
            @Override
252
            public void keyPressed(KeyEvent e) {
253
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
156 ilm 254
                    montantValid(defaultRowVals, false, textField);
149 ilm 255
                }
256
            }
257
        };
258
        deviseCreditEditor.addKeyListener(keyListenerContrepartie);
259
        deviseDebitEditor.addKeyListener(keyListenerContrepartie);
260
 
261
        // Autocompletion
262
        final AutoCompletionManager m = new AutoCompletionManager(this.tableElementNumeroCompte,
263
                ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NUMERO"), this.table, this.table.getRowValuesTableModel(),
264
                ITextWithCompletion.MODE_STARTWITH, true, false, new ValidStateChecker() {
265
 
266
                    ComptePCESQLElement elt = Configuration.getInstance().getDirectory().getElement(ComptePCESQLElement.class);
267
 
268
                    @Override
269
                    public ValidState getValidState(Object o) {
270
                        if (o != null) {
177 ilm 271
                            return this.elt.getCompteNumeroValidState(o.toString());
149 ilm 272
                        }
273
                        return super.getValidState(o);
274
                    }
275
                });
276
        m.fill("NOM", "NOM");
277
        m.setFillWithField("NUMERO");
278
        final Where w = new Where(elt.getTable().getTable("COMPTE_PCE").getField("OBSOLETE"), "=", Boolean.FALSE);
279
        m.setWhere(w);
280
 
281
        // FIXME erreur fill numero
282
        final AutoCompletionManager m2 = new AutoCompletionManager(tableElementNomCompte, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NOM"),
283
                this.table, this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true);
284
        m2.fill("NUMERO", "NUMERO");
285
        m2.setFillWithField("NOM");
286
        m2.setWhere(w);
287
 
177 ilm 288
        JButton buttonClone = new JButton(TM.tr(Configuration.getInstance().getLocale(), "duplicateLine"));
174 ilm 289
        buttonClone.addActionListener(new ActionListener() {
290
            public void actionPerformed(ActionEvent event) {
177 ilm 291
                cloneLine(SaisieJournalItemTable.this.table.getSelectedRow());
174 ilm 292
            }
293
        });
294
        buttonClone.setEnabled(false);
295
        c.gridx++;
296
        JComponentUtils.setMinimumWidth(buttonClone, 95);
149 ilm 297
 
174 ilm 298
        this.controlPanel = new RowValuesTableControlPanel(this.table, Arrays.asList(buttonClone));
299
        this.controlPanel.setVisibleButtonClone(false);
300
        this.controlPanel.setButtonAjouterEnabled(false);
301
        this.add(this.controlPanel, c);
302
 
149 ilm 303
        c.gridy++;
304
        c.fill = GridBagConstraints.BOTH;
305
        c.weightx = 1;
306
        c.weighty = 1;
307
        this.add(new JScrollPane(this.table), c);
308
 
309
        this.tableElementNumeroCompte.setRenderer(this.numeroCompteRenderer);
310
        this.debit.setRenderer(this.deviseRenderer);
311
        this.credit.setRenderer(this.deviseRenderer);
312
 
313
        this.table.addMouseListener(this);
314
        this.table.getModel().addTableModelListener(new TableModelListener() {
315
 
316
            @Override
317
            public void tableChanged(TableModelEvent e) {
318
                // Sélectionne automatiquement la ligne ajoutée
319
                if (e.getType() == TableModelEvent.INSERT) {
177 ilm 320
                    if (SaisieJournalItemTable.this.table.getRowCount() == 1) {
149 ilm 321
                        editCellAt(e.getFirstRow(), 0);
322
                    } else {
323
                        editCellAt(e.getFirstRow(), 1);
324
                    }
325
                }
326
                refreshTotal();
327
            }
328
        });
329
 
330
        // Initialisation du panel des Totaux
331
        this.labelTotalCredit = new JLabel("0.00", SwingConstants.RIGHT);
332
        this.labelTotalDebit = new JLabel("0.00", SwingConstants.RIGHT);
333
        this.labelTotalSolde = new JLabel("0.00", SwingConstants.RIGHT);
334
        JPanel panelTotal = new JPanel();
335
        panelTotal.setLayout(new GridBagLayout());
336
        panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux"));
337
        final GridBagConstraints cc = new DefaultGridBagConstraints();
338
        cc.anchor = GridBagConstraints.EAST;
339
 
340
        // Total Debit
341
        cc.fill = GridBagConstraints.NONE;
342
        panelTotal.add(new JLabel("Débit"), cc);
343
        cc.fill = GridBagConstraints.HORIZONTAL;
344
        cc.gridx++;
345
        cc.weightx = 1;
346
 
347
        panelTotal.add(this.labelTotalDebit, cc);
348
 
349
        // Total Credit
350
        cc.gridy++;
351
        cc.gridx = 0;
352
        cc.weightx = 0;
353
        cc.fill = GridBagConstraints.NONE;
354
        panelTotal.add(new JLabel("Crédit"), cc);
355
        cc.weightx = 1;
356
        cc.gridx++;
357
        cc.fill = GridBagConstraints.HORIZONTAL;
358
        panelTotal.add(this.labelTotalCredit, cc);
359
 
360
        // Total Credit
361
        cc.gridy++;
362
        cc.gridx = 0;
363
        cc.weightx = 0;
364
        cc.fill = GridBagConstraints.NONE;
365
        panelTotal.add(new JLabel("Solde"), cc);
366
        cc.weightx = 1;
367
        cc.gridx++;
368
        cc.fill = GridBagConstraints.HORIZONTAL;
369
        panelTotal.add(this.labelTotalSolde, cc);
370
 
371
        c.gridy++;
372
        c.fill = GridBagConstraints.NONE;
373
        c.anchor = GridBagConstraints.EAST;
374
        c.weightx = 1;
375
        c.weighty = 0;
376
        this.add(panelTotal, c);
377
    }
378
 
379
    public void setPanel(final SaisieJournalPanel panel) {
380
        this.panel = panel;
381
 
382
        final PropertyChangeListener lActiveAddButton = new PropertyChangeListener() {
383
            @Override
384
            public void propertyChange(PropertyChangeEvent evt) {
177 ilm 385
                SaisieJournalItemTable.this.controlPanel.setButtonAjouterEnabled(!panel.getBoxJournal().isEmpty() && !panel.getBoxMois().isEmpty());
149 ilm 386
            }
387
        };
388
        panel.getBoxJournal().addModelListener("wantedID", lActiveAddButton);
389
        panel.getBoxMois().addModelListener("wantedID", lActiveAddButton);
390
 
391
        final PropertyChangeListener l = new PropertyChangeListener() {
392
 
393
            @Override
394
            public void propertyChange(PropertyChangeEvent evt) {
395
                if (!SaisieJournalItemTable.this.panel.boxMois.isEmpty()) {
396
                    final SQLRow selectedRow = SaisieJournalItemTable.this.panel.boxMois.getSelectedRow();
397
                    if (selectedRow != null && !selectedRow.isUndefined()) {
398
                        Calendar c = Calendar.getInstance();
399
                        c.set(Calendar.DAY_OF_MONTH, 1);
400
                        c.set(Calendar.YEAR, (Integer) SaisieJournalItemTable.this.panel.spin.getValue());
401
                        c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
177 ilm 402
                        SaisieJournalItemTable.this.rangedIntegerTableCellEditor.setMax(c.getActualMaximum(Calendar.DAY_OF_MONTH));
149 ilm 403
                    }
404
                }
405
            }
406
 
407
        };
408
        panel.boxMois.addModelListener("wantedID", l);
409
 
410
    }
411
 
412
    public void refreshTotal() {
413
 
414
        long totalD = 0L;
415
        long totalC = 0L;
416
 
177 ilm 417
        for (int i = 0; i < this.table.getRowCount(); i++) {
418
            Number c = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("DEBIT"));
419
            Number d = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("CREDIT"));
149 ilm 420
            if (c != null) {
177 ilm 421
                totalC += c.longValue();
149 ilm 422
            }
423
            if (d != null) {
177 ilm 424
                totalD += d.longValue();
149 ilm 425
            }
426
 
427
        }
428
        this.labelTotalCredit.setText(GestionDevise.currencyToString(totalC));
429
        this.labelTotalDebit.setText(GestionDevise.currencyToString(totalD));
430
        this.labelTotalSolde.setText(GestionDevise.currencyToString(totalD - totalC));
431
 
432
    }
433
 
434
    public boolean isSaisieValid() {
435
        // Check if partie double
436
 
437
        long totalD = 0L;
438
        long totalC = 0L;
439
        boolean cptOK = true;
440
        String lib = null;
177 ilm 441
        for (int i = 0; i < this.table.getRowCount(); i++) {
442
            Number c = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("DEBIT"));
443
            Number d = (Number) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("CREDIT"));
149 ilm 444
            if (c != null) {
177 ilm 445
                totalC += c.longValue();
149 ilm 446
            }
447
            if (d != null) {
177 ilm 448
                totalD += d.longValue();
149 ilm 449
            }
450
            if (lib == null) {
177 ilm 451
                lib = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NOM"));
149 ilm 452
            }
177 ilm 453
            String cptNUmber = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NUMERO"));
149 ilm 454
            cptOK = cptOK && cptNUmber != null && ComptePCESQLElement.isExist(cptNUmber);
455
        }
456
        return totalD + totalC != 0 && totalD == totalC && cptOK;
457
    }
458
 
459
    private Tuple2<Date, String> getDateAndLabelFromSaisie() {
460
        int day = 1;
461
        String lib = null;
462
 
177 ilm 463
        for (int i = 0; i < this.table.getRowCount(); i++) {
464
            day = (Integer) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("JOUR"));
149 ilm 465
            if (lib == null) {
177 ilm 466
                lib = (String) this.table.getRowValuesTableModel().getValueAt(i, this.table.getRowValuesTableModel().getColumnForField("NOM"));
149 ilm 467
            }
468
        }
469
        // Create saisieKM
470
        Calendar c = Calendar.getInstance();
471
        c.set(Calendar.YEAR, SaisieJournalItemTable.this.panel.getSelectedYear());
472
        c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
473
        c.set(Calendar.DAY_OF_MONTH, day);
474
        return Tuple2.create(c.getTime(), lib);
475
    }
476
 
156 ilm 477
    public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique, final JTextField textPiece) {
149 ilm 478
        final SQLRowValues vals = SaisieJournalItemTable.this.table.getSelectedRowValues();
479
        final int selectedRow = SaisieJournalItemTable.this.table.getSelectedRow();
480
        SwingUtilities.invokeLater(new Runnable() {
481
            public void run() {
482
 
177 ilm 483
                if (SaisieJournalItemTable.this.boxAutoInsert.isSelected() && isSaisieValid()) {
149 ilm 484
                    if (SaisieJournalItemTable.this.panel.getSelectedJournal() == SQLRow.NONEXISTANT_ID || SaisieJournalItemTable.this.panel.getSelectedMonth() == -1) {
485
                        JOptionPane.showMessageDialog(SaisieJournalItemTable.this.panel, "Impossible de créer la saisie si aucun journal ou aucun mois n'est sélectionné!");
486
                    } else {
156 ilm 487
                        createSaisie(defaultRowVals, textPiece);
149 ilm 488
                    }
489
                } else {
177 ilm 490
                    if (!fromAnalytique && !SaisieJournalItemTable.this.hideAnalytique && vals.getString("NUMERO") != null
491
                            && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"))) {
149 ilm 492
 
493
                        // Update montant
494
                        Collection<SQLRowValues> rowsLinked = vals.getReferentRows(vals.getTable().getTable("ASSOCIATION_ANALYTIQUE"));
495
                        long montant = vals.getLong("DEBIT") - vals.getLong("CREDIT");
496
                        for (SQLRowValues sqlRowValues : rowsLinked) {
497
                            sqlRowValues.put("MONTANT", sqlRowValues.getBigDecimal("POURCENT").movePointLeft(2).multiply(new BigDecimal(montant), DecimalUtils.HIGH_PRECISION)
498
                                    .setScale(0, RoundingMode.HALF_UP).longValue());
499
                        }
500
 
177 ilm 501
                        editCellAt(selectedRow, SaisieJournalItemTable.this.table.getRowValuesTableModel().getColumnForField("ANALYTIQUE"));
149 ilm 502
                    } else {
503
 
504
                        long l = getContrepartie();
505
                        SQLRowValues rowVals = new SQLRowValues(defaultRowVals);
506
                        if (l > 0) {
507
                            rowVals.put("DEBIT", 0L);
508
                            rowVals.put("CREDIT", l);
509
                        } else {
510
                            rowVals.put("DEBIT", -l);
511
                            rowVals.put("CREDIT", 0L);
512
                        }
513
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().addRow(rowVals);
514
                    }
515
                }
516
 
517
            }
518
        });
519
 
520
    }
521
 
156 ilm 522
    public synchronized void createSaisie(final SQLRowValues defaultRowVals, JTextField pieceText) {
149 ilm 523
 
524
        Tuple2<Date, String> t = getDateAndLabelFromSaisie();
525
        final Date d = t.get0();
156 ilm 526
        String pieceLabel = pieceText.getText();
527
        final String lib = pieceLabel == null || pieceLabel.trim().length() == 0 ? t.get1() : pieceLabel;
149 ilm 528
 
529
        // Create saisieKM
530
        SQLRowValues rowVAlsKM = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
531
 
532
        rowVAlsKM.put("DATE", d);
533
        rowVAlsKM.put("NOM", lib);
534
        rowVAlsKM.put("ID_JOURNAL", SaisieJournalItemTable.this.panel.getSelectedJournal());
535
        int id;
536
        try {
537
            id = rowVAlsKM.insert().getID();
538
 
177 ilm 539
            this.table.updateField("ID_SAISIE_KM", id);
540
            this.table.clear();
149 ilm 541
            GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id);
156 ilm 542
            int idMvt = gen.genereMouvement();
149 ilm 543
 
156 ilm 544
            // maj de l'id du mouvement correspondant
545
            SQLRowValues rowValsKMMvt = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
177 ilm 546
            rowValsKMMvt.put("ID_MOUVEMENT", Integer.valueOf(idMvt));
156 ilm 547
            rowValsKMMvt.update(id);
548
 
149 ilm 549
            defaultRowVals.put("NOM_PIECE", "");
550
            defaultRowVals.put("NOM_ECRITURE", "");
177 ilm 551
            this.table.getRowValuesTableModel().addNewRow();
156 ilm 552
            pieceText.setText("");
149 ilm 553
        } catch (SQLException e) {
554
            e.printStackTrace();
555
        }
556
 
557
    }
558
 
559
    public void updateField(final String field, final int id) {
560
        this.table.updateField(field, id);
561
    }
562
 
563
    public void insertFrom(final String field, final int id) {
564
        this.table.insertFrom(field, id);
565
    }
566
 
567
    public void insertFrom(final SQLRowAccessor row) {
568
        this.table.insertFrom(row);
569
    }
570
 
571
    public RowValuesTableModel getModel() {
572
        return this.table.getRowValuesTableModel();
573
    }
574
 
575
    public SQLTableElement getCreditElement() {
576
        return this.credit;
577
    }
578
 
579
    public SQLTableElement getDebitElement() {
580
        return this.debit;
581
    }
582
 
583
    public SQLTableElement getNumeroCompteElement() {
584
        return this.tableElementNumeroCompte;
585
    }
586
 
587
    public void setCreateAutoActive(final boolean b) {
588
        this.numeroCompteRenderer.setCreateActive(b);
589
        this.table.revalidate();
590
        this.table.repaint();
591
    }
592
 
593
    public void setRowDeviseValidAt(final boolean b, final int index) {
594
        this.deviseRenderer.setValid(b, index);
595
 
596
    }
597
 
598
    public void editCellAt(final int row, final int column) {
599
        assert SwingUtilities.isEventDispatchThread();
600
        this.table.setColumnSelectionInterval(column, column);
601
        this.table.setRowSelectionInterval(row, row);
602
        this.table.editCellAt(row, column);
603
    }
604
 
605
    private long getContrepartie() {
606
        assert SwingUtilities.isEventDispatchThread();
607
        long totalCred = 0;
608
        long totalDeb = 0;
609
        final RowValuesTableModel model = this.table.getRowValuesTableModel();
610
        final int creditIndex = model.getColumnIndexForElement(getCreditElement());
611
        final int debitIndex = model.getColumnIndexForElement(getDebitElement());
612
        for (int i = 0; i < this.table.getRowCount(); i++) {
613
            if (model.isRowValid(i)) {
177 ilm 614
                final Number fTc = (Number) model.getValueAt(i, creditIndex);
149 ilm 615
                if (fTc != null) {
616
                    totalCred += fTc.longValue();
617
                }
177 ilm 618
                final Number fTd = (Number) model.getValueAt(i, debitIndex);
149 ilm 619
                if (fTd != null) {
620
                    totalDeb += fTd.longValue();
621
                }
622
            }
623
        }
624
        return totalDeb - totalCred;
625
    }
626
 
627
    private long getSoldeRow(final int index) {
628
        assert SwingUtilities.isEventDispatchThread();
629
        if (index >= 0 && index < this.table.getRowCount()) {
630
            final SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(index);
631
            return rowVals.getLong("DEBIT") - rowVals.getLong("CREDIT");
632
        } else {
633
            return 0;
634
        }
635
    }
636
 
637
    public void fillEmptyEntryLabel(String previousText, String text) {
638
        assert SwingUtilities.isEventDispatchThread();
639
        if (text == null)
640
            return;
177 ilm 641
        RowValuesTableModel model = this.table.getRowValuesTableModel();
149 ilm 642
        int size = model.getRowCount();
643
        for (int i = 0; i < size; i++) {
644
            SQLRowValues r = model.getRowValuesAt(i);
645
            if (r.getString("NOM_ECRITURE") == null || r.getString("NOM_ECRITURE").trim().isEmpty() || r.getString("NOM_ECRITURE").trim().equals(previousText)) {
646
                r.put("NOM_ECRITURE", text);
647
            }
648
        }
649
        model.fireTableDataChanged();
650
    }
651
 
177 ilm 652
    @Override
149 ilm 653
    public void mousePressed(final MouseEvent e) {
654
        final int rowSel = this.table.getSelectedRow();
655
        if (e.getButton() == MouseEvent.BUTTON3 && rowSel >= 0 && rowSel < this.table.getRowCount()) {
656
            final JPopupMenu menuDroit = new JPopupMenu();
657
 
658
            menuDroit.add(new AbstractAction("Contrepartie") {
659
                public void actionPerformed(final ActionEvent ev) {
660
 
661
                    long l = getContrepartie();
662
                    if (SaisieJournalItemTable.this.table.getRowValuesTableModel().isRowValid(rowSel)) {
663
                        l += getSoldeRow(rowSel);
664
                    }
665
 
666
                    if (l > 0) {
667
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "DEBIT");
668
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(l, rowSel, "CREDIT");
669
                    } else {
670
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "CREDIT");
671
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(-l, rowSel, "DEBIT");
672
                    }
673
                }
674
            });
675
            menuDroit.pack();
676
            menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
677
            menuDroit.setVisible(true);
678
        }
679
    }
680
 
177 ilm 681
    @Override
149 ilm 682
    public void mouseReleased(final MouseEvent e) {
177 ilm 683
        // Nothing
149 ilm 684
    }
685
 
177 ilm 686
    @Override
149 ilm 687
    public void mouseClicked(final MouseEvent e) {
177 ilm 688
        // Nothing
149 ilm 689
    }
690
 
177 ilm 691
    @Override
149 ilm 692
    public void mouseEntered(final MouseEvent e) {
177 ilm 693
        // Nothing
149 ilm 694
    }
695
 
177 ilm 696
    @Override
149 ilm 697
    public void mouseExited(final MouseEvent e) {
177 ilm 698
        // Nothing
149 ilm 699
    }
700
 
174 ilm 701
    private void cloneLine(int row) {
702
        if (row < 0) {
703
            return;
704
        }
705
        SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(row);
706
 
707
        SQLRowValues rowValsBis = rowVals.deepCopy();
708
        rowValsBis.clearPrimaryKeys();
709
        rowValsBis.put(rowValsBis.getTable().getOrderField().getName(), null);
710
 
711
        this.table.getRowValuesTableModel().getSQLElement().clearPrivateFields(rowValsBis);
712
        rowValsBis.putEmptyLink("ID_ECRITURE");
713
        for (String elt : this.table.getClearCloneTableElement()) {
714
            if (rowValsBis.getTable().getFieldsName().contains(elt)) {
715
                rowValsBis.putEmptyLink(elt);
716
            }
717
        }
718
 
719
        this.table.getRowValuesTableModel().addRow(rowValsBis);
720
    }
149 ilm 721
}