OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | 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.TextTableCellEditorWithCompletion;
38
import org.openconcerto.sql.view.list.ValidStateChecker;
39
import org.openconcerto.ui.DefaultGridBagConstraints;
174 ilm 40
import org.openconcerto.ui.JComponentUtils;
149 ilm 41
import org.openconcerto.ui.RangedIntegerTableCellEditor;
42
import org.openconcerto.utils.DecimalUtils;
43
import org.openconcerto.utils.GestionDevise;
44
import org.openconcerto.utils.Tuple2;
45
import org.openconcerto.utils.checks.ValidState;
46
 
47
import java.awt.GridBagConstraints;
48
import java.awt.GridBagLayout;
49
import java.awt.event.ActionEvent;
174 ilm 50
import java.awt.event.ActionListener;
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
112
        final List<SQLTableElement> list = new Vector<SQLTableElement>();
113
        final SQLTable tableElement = elt.getTable();
114
        final SQLTableElement tableElementJour = new SQLTableElement(tableElement.getField("JOUR"), Integer.class, rangedIntegerTableCellEditor) {
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) {
161
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
162
                    return vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"));
163
                };
164
            };
165
            list.add(eltPourcentAnalytique);
166
        }
167
 
168
        final RowValuesTableModel model = new RowValuesTableModel(elt, list, tableElement.getField("NUMERO"), false, defaultRowVals) {
169
            @Override
170
            public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) {
171
                super.setValueAt(aValue, rowIndex, columnIndex);
172
 
173
                final int debitIndex = getColumnIndexForElement(SaisieJournalItemTable.this.debit);
174
                final int creditIndex = getColumnIndexForElement(SaisieJournalItemTable.this.credit);
175
 
176
                // float debitVal = ((Float) model.getValueAt(rowIndex, debitIndex);
177
 
178
                if (debitIndex == columnIndex && ((Long) aValue).longValue() != 0 && ((Long) getValueAt(rowIndex, creditIndex)).longValue() != 0) {
179
                    setValueAt(Long.valueOf(0), rowIndex, creditIndex);
180
                } else {
181
                    if (creditIndex == columnIndex && ((Long) aValue).longValue() != 0 && ((Long) getValueAt(rowIndex, debitIndex)).longValue() != 0) {
182
                        setValueAt(Long.valueOf(0), rowIndex, debitIndex);
183
                    }
184
                }
185
            }
186
        };
187
 
188
        this.table = new RowValuesTable(model, null);
189
        ToolTipManager.sharedInstance().unregisterComponent(this.table);
190
        ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
191
 
192
        tableElementNomEcriture.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() {
193
 
194
            @Override
195
            public void editingStopped(ChangeEvent e) {
196
                e.getSource();
197
                int row = table.getSelectedRow();
198
                int col = 4;
199
                if (table.getValueAt(row, col) != null) {
200
                    defaultRowVals.put("NOM_ECRITURE", table.getValueAt(row, col));
201
                }
202
                // defaultRowVals.put
203
            }
204
 
205
            @Override
206
            public void editingCanceled(ChangeEvent e) {
207
                // TODO Auto-generated method stub
208
 
209
            }
210
        });
211
        tableElementNomPiece.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() {
212
 
213
            @Override
214
            public void editingStopped(ChangeEvent e) {
215
                e.getSource();
216
                int row = table.getSelectedRow();
217
                int col = 3;
218
                if (table.getValueAt(row, col) != null) {
219
                    defaultRowVals.put("NOM_PIECE", table.getValueAt(row, col));
220
                }
221
                // defaultRowVals.put
222
            }
223
 
224
            @Override
225
            public void editingCanceled(ChangeEvent e) {
226
                // TODO Auto-generated method stub
227
 
228
            }
229
        });
230
 
231
        tableElementJour.getTableCellEditor(table).addCellEditorListener(new CellEditorListener() {
232
 
233
            @Override
234
            public void editingStopped(ChangeEvent e) {
235
                final Object valueAt = table.getValueAt(0, 0);
236
                defaultRowVals.put("JOUR", valueAt);
237
                if (table.getRowCount() > 1) {
238
                    for (int i = 1; i < table.getRowCount(); i++) {
239
                        table.getRowValuesTableModel().putValue(valueAt, i, "JOUR");
240
                    }
241
                }
242
            }
243
 
244
            @Override
245
            public void editingCanceled(ChangeEvent e) {
246
                // TODO Auto-generated method stub
247
 
248
            }
249
        });
250
        ;
251
 
252
        final KeyListener keyListenerContrepartie = new KeyListener() {
253
 
254
            @Override
255
            public void keyTyped(KeyEvent e) {
256
 
257
            }
258
 
259
            @Override
260
            public void keyReleased(KeyEvent e) {
261
 
262
            }
263
 
264
            @Override
265
            public void keyPressed(KeyEvent e) {
266
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
156 ilm 267
                    montantValid(defaultRowVals, false, textField);
149 ilm 268
                }
269
            }
270
        };
271
        deviseCreditEditor.addKeyListener(keyListenerContrepartie);
272
        deviseDebitEditor.addKeyListener(keyListenerContrepartie);
273
 
274
        // Autocompletion
275
        final AutoCompletionManager m = new AutoCompletionManager(this.tableElementNumeroCompte,
276
                ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NUMERO"), this.table, this.table.getRowValuesTableModel(),
277
                ITextWithCompletion.MODE_STARTWITH, true, false, new ValidStateChecker() {
278
 
279
                    ComptePCESQLElement elt = Configuration.getInstance().getDirectory().getElement(ComptePCESQLElement.class);
280
 
281
                    @Override
282
                    public ValidState getValidState(Object o) {
283
                        if (o != null) {
284
                            return elt.getCompteNumeroValidState(o.toString());
285
                        }
286
                        return super.getValidState(o);
287
                    }
288
                });
289
        m.fill("NOM", "NOM");
290
        m.setFillWithField("NUMERO");
291
        final Where w = new Where(elt.getTable().getTable("COMPTE_PCE").getField("OBSOLETE"), "=", Boolean.FALSE);
292
        m.setWhere(w);
293
 
294
        // FIXME erreur fill numero
295
        final AutoCompletionManager m2 = new AutoCompletionManager(tableElementNomCompte, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("COMPTE_PCE.NOM"),
296
                this.table, this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true);
297
        m2.fill("NUMERO", "NUMERO");
298
        m2.setFillWithField("NOM");
299
        m2.setWhere(w);
300
 
301
        TextTableCellEditorWithCompletion t = (TextTableCellEditorWithCompletion) this.tableElementNumeroCompte.getTableCellEditor(this.table);
302
 
174 ilm 303
        JButton buttonClone = new JButton(TM.tr("duplicateLine"));
304
        buttonClone.addActionListener(new ActionListener() {
305
            public void actionPerformed(ActionEvent event) {
306
                cloneLine(table.getSelectedRow());
307
            }
308
        });
309
        buttonClone.setEnabled(false);
310
        c.gridx++;
311
        JComponentUtils.setMinimumWidth(buttonClone, 95);
149 ilm 312
 
174 ilm 313
        this.controlPanel = new RowValuesTableControlPanel(this.table, Arrays.asList(buttonClone));
314
        this.controlPanel.setVisibleButtonClone(false);
315
        this.controlPanel.setButtonAjouterEnabled(false);
316
        this.add(this.controlPanel, c);
317
 
149 ilm 318
        c.gridy++;
319
        c.fill = GridBagConstraints.BOTH;
320
        c.weightx = 1;
321
        c.weighty = 1;
322
        this.add(new JScrollPane(this.table), c);
323
 
324
        this.tableElementNumeroCompte.setRenderer(this.numeroCompteRenderer);
325
        this.debit.setRenderer(this.deviseRenderer);
326
        this.credit.setRenderer(this.deviseRenderer);
327
 
328
        this.table.addMouseListener(this);
329
        this.table.getModel().addTableModelListener(new TableModelListener() {
330
 
331
            @Override
332
            public void tableChanged(TableModelEvent e) {
333
                // Sélectionne automatiquement la ligne ajoutée
334
                if (e.getType() == TableModelEvent.INSERT) {
335
                    if (table.getRowCount() == 1) {
336
                        editCellAt(e.getFirstRow(), 0);
337
                    } else {
338
                        editCellAt(e.getFirstRow(), 1);
339
                    }
340
                }
341
                refreshTotal();
342
            }
343
        });
344
 
345
        // Initialisation du panel des Totaux
346
        this.labelTotalCredit = new JLabel("0.00", SwingConstants.RIGHT);
347
        this.labelTotalDebit = new JLabel("0.00", SwingConstants.RIGHT);
348
        this.labelTotalSolde = new JLabel("0.00", SwingConstants.RIGHT);
349
        JPanel panelTotal = new JPanel();
350
        panelTotal.setLayout(new GridBagLayout());
351
        panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux"));
352
        final GridBagConstraints cc = new DefaultGridBagConstraints();
353
        cc.anchor = GridBagConstraints.EAST;
354
 
355
        // Total Debit
356
        cc.fill = GridBagConstraints.NONE;
357
        panelTotal.add(new JLabel("Débit"), cc);
358
        cc.fill = GridBagConstraints.HORIZONTAL;
359
        cc.gridx++;
360
        cc.weightx = 1;
361
 
362
        panelTotal.add(this.labelTotalDebit, cc);
363
 
364
        // Total Credit
365
        cc.gridy++;
366
        cc.gridx = 0;
367
        cc.weightx = 0;
368
        cc.fill = GridBagConstraints.NONE;
369
        panelTotal.add(new JLabel("Crédit"), cc);
370
        cc.weightx = 1;
371
        cc.gridx++;
372
        cc.fill = GridBagConstraints.HORIZONTAL;
373
        panelTotal.add(this.labelTotalCredit, cc);
374
 
375
        // Total Credit
376
        cc.gridy++;
377
        cc.gridx = 0;
378
        cc.weightx = 0;
379
        cc.fill = GridBagConstraints.NONE;
380
        panelTotal.add(new JLabel("Solde"), cc);
381
        cc.weightx = 1;
382
        cc.gridx++;
383
        cc.fill = GridBagConstraints.HORIZONTAL;
384
        panelTotal.add(this.labelTotalSolde, cc);
385
 
386
        c.gridy++;
387
        c.fill = GridBagConstraints.NONE;
388
        c.anchor = GridBagConstraints.EAST;
389
        c.weightx = 1;
390
        c.weighty = 0;
391
        this.add(panelTotal, c);
392
    }
393
 
394
    public void setPanel(final SaisieJournalPanel panel) {
395
        this.panel = panel;
396
 
397
        final PropertyChangeListener lActiveAddButton = new PropertyChangeListener() {
398
            @Override
399
            public void propertyChange(PropertyChangeEvent evt) {
400
                controlPanel.setButtonAjouterEnabled(!panel.getBoxJournal().isEmpty() && !panel.getBoxMois().isEmpty());
401
            }
402
        };
403
        panel.getBoxJournal().addModelListener("wantedID", lActiveAddButton);
404
        panel.getBoxMois().addModelListener("wantedID", lActiveAddButton);
405
 
406
        final PropertyChangeListener l = new PropertyChangeListener() {
407
 
408
            @Override
409
            public void propertyChange(PropertyChangeEvent evt) {
410
                if (!SaisieJournalItemTable.this.panel.boxMois.isEmpty()) {
411
                    final SQLRow selectedRow = SaisieJournalItemTable.this.panel.boxMois.getSelectedRow();
412
                    if (selectedRow != null && !selectedRow.isUndefined()) {
413
                        Calendar c = Calendar.getInstance();
414
                        c.set(Calendar.DAY_OF_MONTH, 1);
415
                        c.set(Calendar.YEAR, (Integer) SaisieJournalItemTable.this.panel.spin.getValue());
416
                        c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
417
                        rangedIntegerTableCellEditor.setMax(c.getActualMaximum(Calendar.DAY_OF_MONTH));
418
                    }
419
                }
420
            }
421
 
422
        };
423
        panel.boxMois.addModelListener("wantedID", l);
424
 
425
    }
426
 
427
    public void refreshTotal() {
428
 
429
        long totalD = 0L;
430
        long totalC = 0L;
431
 
432
        for (int i = 0; i < table.getRowCount(); i++) {
433
            Long c = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("DEBIT"));
434
            Long d = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("CREDIT"));
435
            if (c != null) {
436
                totalC += c;
437
            }
438
            if (d != null) {
439
                totalD += d;
440
            }
441
 
442
        }
443
        this.labelTotalCredit.setText(GestionDevise.currencyToString(totalC));
444
        this.labelTotalDebit.setText(GestionDevise.currencyToString(totalD));
445
        this.labelTotalSolde.setText(GestionDevise.currencyToString(totalD - totalC));
446
 
447
    }
448
 
449
    public boolean isSaisieValid() {
450
        // Check if partie double
451
 
452
        long totalD = 0L;
453
        long totalC = 0L;
454
        boolean cptOK = true;
455
        String lib = null;
456
        for (int i = 0; i < table.getRowCount(); i++) {
457
            Long c = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("DEBIT"));
458
            Long d = (Long) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("CREDIT"));
459
            if (c != null) {
460
                totalC += c;
461
            }
462
            if (d != null) {
463
                totalD += d;
464
            }
465
            if (lib == null) {
466
                lib = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NOM"));
467
            }
468
            String cptNUmber = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NUMERO"));
469
            cptOK = cptOK && cptNUmber != null && ComptePCESQLElement.isExist(cptNUmber);
470
        }
471
        return totalD + totalC != 0 && totalD == totalC && cptOK;
472
    }
473
 
474
    private Tuple2<Date, String> getDateAndLabelFromSaisie() {
475
        int day = 1;
476
        String lib = null;
477
 
478
        for (int i = 0; i < table.getRowCount(); i++) {
479
            day = (Integer) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("JOUR"));
480
            if (lib == null) {
481
                lib = (String) table.getRowValuesTableModel().getValueAt(i, table.getRowValuesTableModel().getColumnForField("NOM"));
482
            }
483
        }
484
        // Create saisieKM
485
        Calendar c = Calendar.getInstance();
486
        c.set(Calendar.YEAR, SaisieJournalItemTable.this.panel.getSelectedYear());
487
        c.set(Calendar.MONTH, SaisieJournalItemTable.this.panel.getSelectedMonth());
488
        c.set(Calendar.DAY_OF_MONTH, day);
489
        return Tuple2.create(c.getTime(), lib);
490
    }
491
 
156 ilm 492
    public void montantValid(final SQLRowValues defaultRowVals, final boolean fromAnalytique, final JTextField textPiece) {
149 ilm 493
        System.err.println("Enter");
494
        final SQLRowValues vals = SaisieJournalItemTable.this.table.getSelectedRowValues();
495
        final int selectedRow = SaisieJournalItemTable.this.table.getSelectedRow();
496
        SwingUtilities.invokeLater(new Runnable() {
497
            public void run() {
498
 
499
                if (boxAutoInsert.isSelected() && isSaisieValid()) {
500
                    if (SaisieJournalItemTable.this.panel.getSelectedJournal() == SQLRow.NONEXISTANT_ID || SaisieJournalItemTable.this.panel.getSelectedMonth() == -1) {
501
                        JOptionPane.showMessageDialog(SaisieJournalItemTable.this.panel, "Impossible de créer la saisie si aucun journal ou aucun mois n'est sélectionné!");
502
                    } else {
156 ilm 503
                        createSaisie(defaultRowVals, textPiece);
149 ilm 504
                    }
505
                } else {
506
                    if (!fromAnalytique && !hideAnalytique && vals.getString("NUMERO") != null && (vals.getString("NUMERO").startsWith("6") || vals.getString("NUMERO").startsWith("7"))) {
507
 
508
                        // Update montant
509
                        Collection<SQLRowValues> rowsLinked = vals.getReferentRows(vals.getTable().getTable("ASSOCIATION_ANALYTIQUE"));
510
                        long montant = vals.getLong("DEBIT") - vals.getLong("CREDIT");
511
                        for (SQLRowValues sqlRowValues : rowsLinked) {
512
                            sqlRowValues.put("MONTANT", sqlRowValues.getBigDecimal("POURCENT").movePointLeft(2).multiply(new BigDecimal(montant), DecimalUtils.HIGH_PRECISION)
513
                                    .setScale(0, RoundingMode.HALF_UP).longValue());
514
                        }
515
 
516
                        editCellAt(selectedRow, table.getRowValuesTableModel().getColumnForField("ANALYTIQUE"));
517
                    } else {
518
 
519
                        long l = getContrepartie();
520
                        SQLRowValues rowVals = new SQLRowValues(defaultRowVals);
521
                        if (l > 0) {
522
                            rowVals.put("DEBIT", 0L);
523
                            rowVals.put("CREDIT", l);
524
                        } else {
525
                            rowVals.put("DEBIT", -l);
526
                            rowVals.put("CREDIT", 0L);
527
                        }
528
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().addRow(rowVals);
529
                    }
530
                }
531
 
532
            }
533
        });
534
 
535
    }
536
 
156 ilm 537
    public synchronized void createSaisie(final SQLRowValues defaultRowVals, JTextField pieceText) {
149 ilm 538
 
539
        Tuple2<Date, String> t = getDateAndLabelFromSaisie();
540
        final Date d = t.get0();
156 ilm 541
        String pieceLabel = pieceText.getText();
542
        final String lib = pieceLabel == null || pieceLabel.trim().length() == 0 ? t.get1() : pieceLabel;
149 ilm 543
 
544
        // Create saisieKM
545
        SQLRowValues rowVAlsKM = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
546
 
547
        rowVAlsKM.put("DATE", d);
548
        rowVAlsKM.put("NOM", lib);
549
        rowVAlsKM.put("ID_JOURNAL", SaisieJournalItemTable.this.panel.getSelectedJournal());
550
        int id;
551
        try {
552
            id = rowVAlsKM.insert().getID();
553
 
554
            table.updateField("ID_SAISIE_KM", id);
555
            table.clear();
556
            GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id);
156 ilm 557
            int idMvt = gen.genereMouvement();
149 ilm 558
 
156 ilm 559
            // maj de l'id du mouvement correspondant
560
            SQLRowValues rowValsKMMvt = new SQLRowValues(SaisieJournalItemTable.this.table.getRowValuesTableModel().getSQLElement().getTable().getForeignTable("ID_SAISIE_KM"));
561
            rowValsKMMvt.put("ID_MOUVEMENT", new Integer(idMvt));
562
            rowValsKMMvt.update(id);
563
 
149 ilm 564
            defaultRowVals.put("NOM_PIECE", "");
565
            defaultRowVals.put("NOM_ECRITURE", "");
566
            table.getRowValuesTableModel().addNewRow();
156 ilm 567
            pieceText.setText("");
149 ilm 568
        } catch (SQLException e) {
569
            e.printStackTrace();
570
        }
571
 
572
    }
573
 
574
    public void updateField(final String field, final int id) {
575
        this.table.updateField(field, id);
576
    }
577
 
578
    public void insertFrom(final String field, final int id) {
579
        this.table.insertFrom(field, id);
580
    }
581
 
582
    public void insertFrom(final SQLRowAccessor row) {
583
        this.table.insertFrom(row);
584
    }
585
 
586
    public RowValuesTableModel getModel() {
587
        return this.table.getRowValuesTableModel();
588
    }
589
 
590
    public SQLTableElement getCreditElement() {
591
        return this.credit;
592
    }
593
 
594
    public SQLTableElement getDebitElement() {
595
        return this.debit;
596
    }
597
 
598
    public SQLTableElement getNumeroCompteElement() {
599
        return this.tableElementNumeroCompte;
600
    }
601
 
602
    public void setCreateAutoActive(final boolean b) {
603
        this.numeroCompteRenderer.setCreateActive(b);
604
        this.table.revalidate();
605
        this.table.repaint();
606
    }
607
 
608
    public void setRowDeviseValidAt(final boolean b, final int index) {
609
        this.deviseRenderer.setValid(b, index);
610
 
611
    }
612
 
613
    public void editCellAt(final int row, final int column) {
614
        assert SwingUtilities.isEventDispatchThread();
615
        this.table.setColumnSelectionInterval(column, column);
616
        this.table.setRowSelectionInterval(row, row);
617
        this.table.editCellAt(row, column);
618
    }
619
 
620
    private long getContrepartie() {
621
        assert SwingUtilities.isEventDispatchThread();
622
        long totalCred = 0;
623
        long totalDeb = 0;
624
        final RowValuesTableModel model = this.table.getRowValuesTableModel();
625
        final int creditIndex = model.getColumnIndexForElement(getCreditElement());
626
        final int debitIndex = model.getColumnIndexForElement(getDebitElement());
627
        for (int i = 0; i < this.table.getRowCount(); i++) {
628
            if (model.isRowValid(i)) {
629
                final Long fTc = (Long) model.getValueAt(i, creditIndex);
630
                if (fTc != null) {
631
                    totalCred += fTc.longValue();
632
                }
633
                final Long fTd = (Long) model.getValueAt(i, debitIndex);
634
                if (fTd != null) {
635
                    totalDeb += fTd.longValue();
636
                }
637
            }
638
        }
639
        return totalDeb - totalCred;
640
    }
641
 
642
    private long getSoldeRow(final int index) {
643
        assert SwingUtilities.isEventDispatchThread();
644
        if (index >= 0 && index < this.table.getRowCount()) {
645
            final SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(index);
646
            return rowVals.getLong("DEBIT") - rowVals.getLong("CREDIT");
647
        } else {
648
            return 0;
649
        }
650
    }
651
 
652
    public void fillEmptyEntryLabel(String previousText, String text) {
653
        assert SwingUtilities.isEventDispatchThread();
654
        if (text == null)
655
            return;
656
        RowValuesTableModel model = table.getRowValuesTableModel();
657
        int size = model.getRowCount();
658
        for (int i = 0; i < size; i++) {
659
            SQLRowValues r = model.getRowValuesAt(i);
660
            if (r.getString("NOM_ECRITURE") == null || r.getString("NOM_ECRITURE").trim().isEmpty() || r.getString("NOM_ECRITURE").trim().equals(previousText)) {
661
                r.put("NOM_ECRITURE", text);
662
            }
663
        }
664
        model.fireTableDataChanged();
665
    }
666
 
667
    public void mousePressed(final MouseEvent e) {
668
        final int rowSel = this.table.getSelectedRow();
669
        if (e.getButton() == MouseEvent.BUTTON3 && rowSel >= 0 && rowSel < this.table.getRowCount()) {
670
            final JPopupMenu menuDroit = new JPopupMenu();
671
 
672
            menuDroit.add(new AbstractAction("Contrepartie") {
673
                public void actionPerformed(final ActionEvent ev) {
674
 
675
                    long l = getContrepartie();
676
                    if (SaisieJournalItemTable.this.table.getRowValuesTableModel().isRowValid(rowSel)) {
677
                        l += getSoldeRow(rowSel);
678
                    }
679
 
680
                    if (l > 0) {
681
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "DEBIT");
682
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(l, rowSel, "CREDIT");
683
                    } else {
684
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(Long.valueOf(0), rowSel, "CREDIT");
685
                        SaisieJournalItemTable.this.table.getRowValuesTableModel().putValue(-l, rowSel, "DEBIT");
686
                    }
687
                }
688
            });
689
            menuDroit.pack();
690
            menuDroit.show(e.getComponent(), e.getPoint().x, e.getPoint().y);
691
            menuDroit.setVisible(true);
692
        }
693
    }
694
 
695
    public void mouseReleased(final MouseEvent e) {
696
    }
697
 
698
    public void mouseClicked(final MouseEvent e) {
699
    }
700
 
701
    public void mouseEntered(final MouseEvent e) {
702
    }
703
 
704
    public void mouseExited(final MouseEvent e) {
705
    }
706
 
174 ilm 707
    private void cloneLine(int row) {
708
        if (row < 0) {
709
            System.err.println("RowValuesTableControlPanel.cloneLine() wrong selected line, index = " + row);
710
            Thread.dumpStack();
711
            return;
712
        }
713
        SQLRowValues rowVals = this.table.getRowValuesTableModel().getRowValuesAt(row);
714
 
715
        SQLRowValues rowValsBis = rowVals.deepCopy();
716
        rowValsBis.clearPrimaryKeys();
717
        rowValsBis.put(rowValsBis.getTable().getOrderField().getName(), null);
718
 
719
        this.table.getRowValuesTableModel().getSQLElement().clearPrivateFields(rowValsBis);
720
        rowValsBis.putEmptyLink("ID_ECRITURE");
721
        for (String elt : this.table.getClearCloneTableElement()) {
722
            if (rowValsBis.getTable().getFieldsName().contains(elt)) {
723
                rowValsBis.putEmptyLink(elt);
724
            }
725
        }
726
 
727
        this.table.getRowValuesTableModel().addRow(rowValsBis);
728
    }
149 ilm 729
}