OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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