OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 80 | Rev 93 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 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.element;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18
import org.openconcerto.erp.core.finance.accounting.ui.SaisieKmItemTable;
19
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieKm;
20
import org.openconcerto.sql.Configuration;
21
import org.openconcerto.sql.element.BaseSQLComponent;
22
import org.openconcerto.sql.element.SQLComponent;
23
import org.openconcerto.sql.element.SQLElement;
24
import org.openconcerto.sql.model.SQLBase;
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.SQLSelect;
29
import org.openconcerto.sql.model.SQLTable;
30
import org.openconcerto.sql.model.UndefinedRowValuesCache;
31
import org.openconcerto.sql.model.Where;
32
import org.openconcerto.sql.sqlobject.ElementComboBox;
21 ilm 33
import org.openconcerto.sql.utils.SQLUtils;
18 ilm 34
import org.openconcerto.sql.view.list.RowValuesTableModel;
35
import org.openconcerto.ui.DefaultGridBagConstraints;
36
import org.openconcerto.ui.JDate;
37
import org.openconcerto.ui.warning.JLabelWarning;
21 ilm 38
import org.openconcerto.utils.ExceptionHandler;
18 ilm 39
import org.openconcerto.utils.GestionDevise;
21 ilm 40
import org.openconcerto.utils.checks.ValidState;
18 ilm 41
import org.openconcerto.utils.text.SimpleDocumentListener;
42
 
43
import java.awt.Dimension;
44
import java.awt.GridBagConstraints;
45
import java.awt.GridBagLayout;
46
import java.awt.event.ActionEvent;
47
import java.awt.event.ActionListener;
83 ilm 48
import java.beans.PropertyChangeEvent;
49
import java.beans.PropertyChangeListener;
18 ilm 50
import java.sql.SQLException;
51
import java.util.ArrayList;
83 ilm 52
import java.util.Calendar;
18 ilm 53
import java.util.Date;
54
import java.util.HashSet;
55
import java.util.List;
56
import java.util.Set;
57
 
58
import javax.swing.BorderFactory;
59
import javax.swing.JCheckBox;
60
import javax.swing.JLabel;
61
import javax.swing.JOptionPane;
62
import javax.swing.JPanel;
63
import javax.swing.JTextField;
64
import javax.swing.SwingConstants;
65
import javax.swing.SwingUtilities;
66
import javax.swing.event.DocumentEvent;
67
import javax.swing.event.TableModelEvent;
68
import javax.swing.event.TableModelListener;
69
 
70
import org.apache.commons.dbutils.handlers.ArrayListHandler;
71
 
72
public class SaisieKmSQLElement extends ComptaSQLConfElement {
73
 
74
    public SaisieKmSQLElement() {
75
        super("SAISIE_KM", "une saisie au kilomètre", "saisies au kilomètre");
76
    }
77
 
78
    protected List<String> getListFields() {
79
        final List<String> l = new ArrayList<String>();
80
        l.add("DATE");
81
        l.add("NOM");
82
        l.add("ID_JOURNAL");
83
        return l;
84
    }
85
 
86
    protected List<String> getComboFields() {
87
        final List<String> l = new ArrayList<String>();
88
        l.add("DATE");
89
        l.add("NOM");
90
 
91
        return l;
92
    }
93
 
94
    /*
95
     * (non-Javadoc)
96
     *
97
     * @see org.openconcerto.devis.SQLElement#getComponent()
98
     */
99
    public SQLComponent createComponent() {
100
 
101
        return new SaisieKmComponent();
102
    }
103
 
104
    @Override
105
    protected Set<String> getChildren() {
106
        Set<String> set = new HashSet<String>();
107
        set.add("SAISIE_KM_ELEMENT");
108
        return set;
109
    }
110
 
111
    /**
112
     * Genere une saisie au kilometre à partir d'un mouvement
113
     *
114
     * @param idMvt
115
     *
116
     * @return l'id de la saisie au kilometre créé
73 ilm 117
     * @throws SQLException
18 ilm 118
     */
73 ilm 119
    public static int createSaisie(int idMvt) throws SQLException {
18 ilm 120
        int idSaisie = 1;
121
        SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
122
        SQLTable ecrTable = base.getTable("ECRITURE");
123
        SQLTable compteTable = base.getTable("COMPTE_PCE");
124
        SQLTable saisieKmTable = base.getTable("SAISIE_KM_ELEMENT");
125
 
126
        SQLRowValues vals = new SQLRowValues(base.getTable("SAISIE_KM"));
127
        vals.put("ID_MOUVEMENT", new Integer(idMvt));
128
 
73 ilm 129
        SQLRow rowSaisieKm = vals.insert();
130
        idSaisie = rowSaisieKm.getID();
18 ilm 131
 
73 ilm 132
        SQLSelect selEcriture = new SQLSelect();
133
        selEcriture.addSelect(ecrTable.getField("ID"));
18 ilm 134
 
73 ilm 135
        Where w = new Where(ecrTable.getField("ID_MOUVEMENT"), "=", idMvt);
136
        selEcriture.setWhere(w);
18 ilm 137
 
73 ilm 138
        String reqEcriture = selEcriture.asString();
18 ilm 139
 
73 ilm 140
        Object obEcriture = base.getDataSource().execute(reqEcriture, new ArrayListHandler());
18 ilm 141
 
73 ilm 142
        List myListEcriture = (List) obEcriture;
18 ilm 143
 
73 ilm 144
        if (myListEcriture.size() != 0) {
18 ilm 145
 
73 ilm 146
            for (int i = 0; i < myListEcriture.size(); i++) {
147
                Object[] objTmp = (Object[]) myListEcriture.get(i);
18 ilm 148
 
149
                SQLRow rowEcrTmp = ecrTable.getRow(Integer.parseInt(objTmp[0].toString()));
73 ilm 150
                SQLRow rowCompteTmp = compteTable.getRow(rowEcrTmp.getInt("ID_COMPTE_PCE"));
18 ilm 151
 
73 ilm 152
                SQLRowValues valsTmp = new SQLRowValues(saisieKmTable);
153
                valsTmp.put("ID_SAISIE_KM", new Integer(rowSaisieKm.getID()));
154
                valsTmp.put("NUMERO", rowCompteTmp.getString("NUMERO"));
155
                valsTmp.put("NOM", rowCompteTmp.getString("NOM"));
156
                valsTmp.put("NOM_ECRITURE", rowEcrTmp.getString("NOM"));
157
                valsTmp.put("DEBIT", rowEcrTmp.getObject("DEBIT"));
158
                valsTmp.put("CREDIT", rowEcrTmp.getObject("CREDIT"));
159
                valsTmp.put("ID_ECRITURE", new Integer(rowEcrTmp.getID()));
160
                valsTmp.insert();
18 ilm 161
            }
162
 
73 ilm 163
            Object[] objTmp = (Object[]) myListEcriture.get(0);
164
            SQLRow rowEcrTmp = ecrTable.getRow(Integer.parseInt(objTmp[0].toString()));
165
            vals.put("NOM", rowEcrTmp.getString("NOM"));
166
            vals.put("DATE", rowEcrTmp.getObject("DATE"));
167
            vals.put("ID_JOURNAL", rowEcrTmp.getObject("ID_JOURNAL"));
18 ilm 168
 
73 ilm 169
            vals.update(idSaisie);
170
        }
18 ilm 171
 
73 ilm 172
        SQLTable mouvementTable = base.getTable("MOUVEMENT");
173
        SQLRow rowMvt = mouvementTable.getRow(idMvt);
18 ilm 174
 
73 ilm 175
        if ((rowMvt.getString("SOURCE").trim().length() == 0) || (rowMvt.getInt("IDSOURCE") == 1)) {
176
            SQLRowValues valsMouvement = new SQLRowValues(mouvementTable);
177
            valsMouvement.put("SOURCE", "SAISIE_KM");
178
            valsMouvement.put("IDSOURCE", new Integer(rowSaisieKm.getID()));
179
            valsMouvement.update(idMvt);
18 ilm 180
        }
73 ilm 181
 
18 ilm 182
        return idSaisie;
183
    }
184
 
185
    public static void loadContrePassation(SQLComponent comp, int idMvt) {
186
        SaisieKmComponent compKm = (SaisieKmComponent) comp;
187
        compKm.loadContrepassation(idMvt);
188
    }
189
 
190
    class SaisieKmComponent extends BaseSQLComponent {
191
 
192
        private JTextField textNom;
193
        private JDate date;
194
        private RowValuesTableModel model;
195
        private ElementComboBox comboJrnl;
196
        private JLabel labelTotalDebit;
197
        private JLabel labelTotalCredit;
198
        private long totalCred;
199
        private long totalDeb;
200
        private int debitIndex, creditIndex;
201
        private JCheckBox checkCreateCompte;
73 ilm 202
        private JCheckBox checkCreateLineAuto;
18 ilm 203
        private boolean isCompteExist = false;
204
        private boolean allLineValid = true;
205
        private SaisieKmItemTable tableKm;
21 ilm 206
        private final JLabel labelMotifWarning = new JLabelWarning();
18 ilm 207
        private SQLElement eltKmItem = Configuration.getInstance().getDirectory().getElement("SAISIE_KM_ELEMENT");
208
        private SQLRowValues defaultEcritureRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(this.eltKmItem.getTable()));
209
 
21 ilm 210
        // depends on inner table, at creation it's empty and thus valid
211
        private ValidState validState = ValidState.getTrueInstance();
212
 
83 ilm 213
        private ValidState validStateCloture = ValidState.getTrueInstance();
214
        private final SQLRow rowExercice = ComptaPropsConfiguration.getInstanceCompta().getRowSociete().getForeign("ID_EXERCICE_COMMON");
215
 
18 ilm 216
        private TableModelListener tableListener = new TableModelListener() {
217
            public void tableChanged(TableModelEvent e) {
21 ilm 218
                SaisieKmComponent.this.tableChanged(e);
18 ilm 219
            }
220
        };
221
 
222
        public SaisieKmComponent() {
223
            super(SaisieKmSQLElement.this);
224
        }
225
 
226
        public void addViews() {
227
 
228
            this.setLayout(new GridBagLayout());
229
 
230
            GridBagConstraints c = new DefaultGridBagConstraints();
231
 
232
            this.textNom = new JTextField();
233
            this.labelTotalCredit = new JLabel("0.00", SwingConstants.RIGHT);
234
            this.labelTotalDebit = new JLabel("0.00", SwingConstants.RIGHT);
80 ilm 235
            this.date = new JDate();
83 ilm 236
            this.date.addValueListener(new PropertyChangeListener() {
18 ilm 237
 
83 ilm 238
                @Override
239
                public void propertyChange(PropertyChangeEvent evt) {
240
                    Calendar cDeb = rowExercice.getDate("DATE_DEB");
241
                    Calendar cClo = rowExercice.getDate("DATE_CLOTURE");
242
                    if (date.getValue() != null && cDeb.getTime().after(date.getValue())) {
243
                        validStateCloture = new ValidState(false, "La date de saisie doit être supérieure à celle du début de l'exercice!");
244
                    } else if (date.getValue() != null && cClo != null && cClo.getTime().after(date.getValue())) {
245
                        validStateCloture = new ValidState(false, "La date de saisie doit être supérieure à celle de la période de clôture définie dans l'exercice courant!");
246
                    } else {
247
                        validStateCloture = ValidState.getTrueInstance();
248
                    }
249
                    fireValidChange();
250
                }
251
            });
18 ilm 252
            this.comboJrnl = new ElementComboBox(false, 20);
253
 
254
            // Libellé
255
            this.add(new JLabel("Libellé", SwingConstants.RIGHT), c);
256
 
257
            c.gridx++;
258
            c.weightx = 1;
259
            c.gridwidth = 1;
260
            this.add(this.textNom, c);
261
 
262
            // Date
263
            JLabel labelDate = new JLabel("Date");
264
            c.gridx++;
265
            c.weightx = 0;
266
            c.gridwidth = 1;
267
            this.add(labelDate, c);
268
            c.gridx++;
269
            c.gridwidth = 1;
270
            this.add(this.date, c);
271
 
272
            // Journal
273
            c.gridy++;
274
            c.gridx = 0;
275
            c.gridwidth = 1;
276
            c.weightx = 0;
277
            this.add(new JLabel("Journal", SwingConstants.RIGHT), c);
278
 
279
            c.gridx++;
280
            c.gridwidth = 3;
281
            c.fill = GridBagConstraints.NONE;
282
            c.weightx = 1;
283
            this.add(this.comboJrnl, c);
284
 
285
            // Km ItemTable
286
            this.tableKm = new SaisieKmItemTable(this.defaultEcritureRowVals);
287
            c.gridx = 0;
288
            c.gridy++;
289
            c.weightx = 1;
290
            c.weighty = 1;
291
            c.gridwidth = GridBagConstraints.REMAINDER;
292
            c.fill = GridBagConstraints.BOTH;
293
            this.add(this.tableKm, c);
294
 
295
            // Initialisation du panel des Totaux
296
            JPanel panelTotal = new JPanel();
297
            panelTotal.setLayout(new GridBagLayout());
298
            panelTotal.setBorder(BorderFactory.createTitledBorder("Totaux"));
299
            final GridBagConstraints cc = new DefaultGridBagConstraints();
300
            cc.anchor = GridBagConstraints.EAST;
301
 
302
            // Total Debit
303
            cc.fill = GridBagConstraints.NONE;
304
            panelTotal.add(new JLabel("Débit"), cc);
305
            cc.fill = GridBagConstraints.HORIZONTAL;
306
            cc.gridx++;
307
            cc.weightx = 1;
308
            panelTotal.add(this.labelTotalDebit, cc);
309
 
310
            // Total Credit
311
            cc.gridy++;
312
            cc.gridx = 0;
313
            cc.weightx = 0;
314
            cc.fill = GridBagConstraints.NONE;
315
            panelTotal.add(new JLabel("Crédit"), cc);
316
            cc.weightx = 1;
317
            cc.gridx++;
318
            cc.fill = GridBagConstraints.HORIZONTAL;
319
            panelTotal.add(this.labelTotalCredit, cc);
320
 
321
            // Création auto des comptes
322
            this.checkCreateCompte = new JCheckBox("Création automatique des comptes");
323
 
324
            c.gridy++;
325
            c.gridx = 0;
326
            c.gridwidth = 2;
327
            c.weightx = 0;
328
            c.weighty = 0;
329
            this.add(this.checkCreateCompte, c);
330
 
73 ilm 331
            // Création de ligne auto
332
            this.checkCreateLineAuto = new JCheckBox("Ligne de contrepartie automatique");
333
            c.gridy++;
334
            this.checkCreateLineAuto.setSelected(true);
335
            this.add(this.checkCreateLineAuto, c);
336
 
18 ilm 337
            // Ligne : Warning
338
 
339
            c.gridy++;
340
            c.weightx = 0;
21 ilm 341
            c.gridwidth = 2;
342
            this.labelMotifWarning.setText("Le solde des écritures n'est pas nul!");
18 ilm 343
            DefaultGridBagConstraints.lockMinimumSize(this.labelMotifWarning);
344
            this.add(this.labelMotifWarning, c);
345
            this.labelMotifWarning.setVisible(false);
21 ilm 346
            c.gridwidth = 1;
18 ilm 347
 
348
            c.gridy--;
349
            c.gridx = 2;
350
 
351
            c.anchor = GridBagConstraints.EAST;
352
            c.weightx = 0;
353
            c.weighty = 0;
354
            c.fill = GridBagConstraints.NONE;
355
            c.gridwidth = 2;
356
            c.gridheight = 2;
357
            panelTotal.setPreferredSize(new Dimension(250, panelTotal.getPreferredSize().height));
358
            DefaultGridBagConstraints.lockMinimumSize(panelTotal);
359
            this.add(panelTotal, c);
360
 
361
            this.model = this.tableKm.getModel();
362
            this.creditIndex = this.model.getColumnIndexForElement(this.tableKm.getCreditElement());
363
            this.debitIndex = this.model.getColumnIndexForElement(this.tableKm.getDebitElement());
364
 
365
            // Listeners
366
 
367
            this.tableKm.getModel().addTableModelListener(this.tableListener);
368
 
369
            this.addSQLObject(this.textNom, "NOM");
370
            this.addRequiredSQLObject(this.date, "DATE");
371
            this.addRequiredSQLObject(this.comboJrnl, "ID_JOURNAL");
372
            this.comboJrnl.setButtonsVisible(false);
373
            this.textNom.getDocument().addDocumentListener(new SimpleDocumentListener() {
73 ilm 374
                String previousName = "";
18 ilm 375
 
376
                @Override
377
                public void update(DocumentEvent e) {
378
                    SaisieKmComponent.this.defaultEcritureRowVals.put("NOM_ECRITURE", SaisieKmComponent.this.textNom.getText());
73 ilm 379
                    tableKm.fillEmptyEntryLabel(previousName, textNom.getText());
380
                    previousName = textNom.getText();
18 ilm 381
                }
382
            });
383
 
384
            this.checkCreateCompte.addActionListener(new ActionListener() {
385
                public void actionPerformed(ActionEvent e) {
386
                    SaisieKmComponent.this.tableKm.setCreateAutoActive(SaisieKmComponent.this.checkCreateCompte.isSelected());
21 ilm 387
                    updateValidState();
18 ilm 388
                }
389
            });
390
 
391
            // Lock (after adding to this *and* after adding to the request since some items
392
            // initialize themselves when added)
393
            DefaultGridBagConstraints.lockMinimumSize(this.comboJrnl);
394
        }
395
 
396
        public int insert(SQLRow order) {
21 ilm 397
            final int id = super.insert(order);
18 ilm 398
 
399
            this.tableKm.updateField("ID_SAISIE_KM", id);
400
 
401
            try {
21 ilm 402
                SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLUtils.SQLFactory<Object>() {
403
                    @Override
404
                    public Object create() throws SQLException {
18 ilm 405
 
21 ilm 406
                        GenerationMvtSaisieKm gen = new GenerationMvtSaisieKm(id);
407
                        int idMvt = gen.genereMouvement();
408
 
409
                        // maj de l'id du mouvement correspondant
410
                        SQLRowValues valEcriture = new SQLRowValues(SaisieKmSQLElement.this.getTable());
411
                        valEcriture.put("ID_MOUVEMENT", new Integer(idMvt));
412
                        if (valEcriture.getInvalid() == null) {
413
 
414
                            valEcriture.update(id);
415
                        }
416
 
417
                        SQLElement eltMvt = Configuration.getInstance().getDirectory().getElement("MOUVEMENT");
418
                        final SQLRow rowMvt = eltMvt.getTable().getRow(idMvt);
419
                        SwingUtilities.invokeLater(new Runnable() {
420
                            @Override
421
                            public void run() {
422
                                JOptionPane.showMessageDialog(SaisieKmComponent.this, "Numéro de mouvement associé : " + rowMvt.getObject("NUMERO"));
423
                            }
424
                        });
425
                        return null;
426
                    }
427
                });
428
            } catch (SQLException exn) {
429
                // TODO Bloc catch auto-généré
430
                ExceptionHandler.handle("Erreur lors de la création des écritures associées à la saisie au kilometre.", exn);
18 ilm 431
            }
432
            return id;
433
        }
434
 
435
        public void loadMouvement(int idMvt) {
436
            this.tableKm.loadMouvement(idMvt, false);
437
        }
438
 
439
        public void loadContrepassation(int idMvt) {
440
            this.tableKm.loadMouvement(idMvt, true);
441
        }
442
 
443
        public void select(SQLRowAccessor r) {
444
            if (r == null) {
445
                this.dTemp = this.date.getDate();
446
            }
447
            super.select(r);
448
            if (r != null) {
80 ilm 449
                this.tableKm.insertFrom(r);
18 ilm 450
            }
451
        }
452
 
453
        public void update() {
454
            super.update();
455
            this.tableKm.updateField("ID_SAISIE_KM", getSelectedID());
456
            System.err.println("UPDATE ECRITURE");
457
            this.updateEcriture();
458
        }
459
 
460
        private Date dTemp = null;
461
 
462
        @Override
463
        protected SQLRowValues createDefaults() {
80 ilm 464
            assert SwingUtilities.isEventDispatchThread();
18 ilm 465
            SQLRowValues rowVals = new SQLRowValues(this.getTable());
466
 
80 ilm 467
            if (this.dTemp != null) {
468
                rowVals.put("DATE", this.dTemp);
18 ilm 469
            }
470
            this.tableKm.getModel().clearRows();
471
            this.tableKm.revalidate();
472
            this.tableKm.repaint();
473
 
474
            return rowVals;
475
        }
476
 
477
        public void updateEcriture() {
21 ilm 478
            try {
479
                SQLUtils.executeAtomic(Configuration.getInstance().getSystemRoot().getDataSource(), new SQLUtils.SQLFactory<Object>() {
480
                    @Override
481
                    public Object create() throws SQLException {
18 ilm 482
 
21 ilm 483
                        SQLTable ecritureTable = getTable().getBase().getTable("ECRITURE");
484
                        final SQLRow rowSaisieKm = getElement().getTable().getRow(getSelectedID());
485
                        List<SQLRow> myListDevisItem = rowSaisieKm.getReferentRows(getTable().getBase().getTable("SAISIE_KM_ELEMENT"));
18 ilm 486
 
21 ilm 487
                        List<SQLRow> listEcr = rowSaisieKm.getForeignRow("ID_MOUVEMENT").getReferentRows(ecritureTable);
18 ilm 488
 
21 ilm 489
                        if (myListDevisItem != null) {
18 ilm 490
 
21 ilm 491
                            for (SQLRow rowElement : myListDevisItem) {
18 ilm 492
 
21 ilm 493
                                int idCpt = ComptePCESQLElement.getId(rowElement.getString("NUMERO"), rowElement.getString("NOM"));
18 ilm 494
 
21 ilm 495
                                if (rowElement.getID() > 1) {
496
                                    SQLRowValues vals = new SQLRowValues(ecritureTable);
497
                                    vals.put("ID_COMPTE_PCE", idCpt);
498
                                    vals.put("COMPTE_NUMERO", rowElement.getString("NUMERO"));
499
                                    vals.put("COMPTE_NOM", rowElement.getString("NOM"));
500
                                    vals.put("DEBIT", rowElement.getObject("DEBIT"));
501
                                    vals.put("CREDIT", rowElement.getObject("CREDIT"));
502
                                    vals.put("DATE", rowSaisieKm.getObject("DATE"));
503
                                    SQLRow rowJournal = rowSaisieKm.getForeignRow("ID_JOURNAL");
504
                                    vals.put("ID_JOURNAL", rowJournal.getID());
505
                                    vals.put("JOURNAL_NOM", rowJournal.getString("NOM"));
506
                                    vals.put("JOURNAL_CODE", rowJournal.getString("CODE"));
507
                                    vals.put("NOM", rowElement.getObject("NOM_ECRITURE"));
18 ilm 508
 
21 ilm 509
                                    if (rowElement.getInt("ID_ECRITURE") > 1) {
510
                                        SQLRow rowTmp = ecritureTable.getRow(rowElement.getInt("ID_ECRITURE"));
18 ilm 511
 
73 ilm 512
                                        if (!rowTmp.getBoolean("VALIDE")) {
513
                                            vals.update(rowElement.getInt("ID_ECRITURE"));
514
                                        } else {
515
                                            System.err.println("Impossible de modifier une ecriture valide");
516
                                        }
18 ilm 517
 
21 ilm 518
                                    } else {
18 ilm 519
 
21 ilm 520
                                        vals.put("ID_MOUVEMENT", rowSaisieKm.getObject("ID_MOUVEMENT"));
18 ilm 521
 
73 ilm 522
                                        if (MouvementSQLElement.isEditable(rowSaisieKm.getInt("ID_MOUVEMENT"))) {
523
                                            SQLRow rowEcr = vals.insert();
524
                                            SQLRowValues rowElementVals = rowElement.createEmptyUpdateRow();
525
                                            rowElementVals.put("ID_ECRITURE", rowEcr.getID());
526
                                            rowElement = rowElementVals.update();
527
                                        }
18 ilm 528
 
21 ilm 529
                                    }
18 ilm 530
 
21 ilm 531
                                    List<SQLRow> l = new ArrayList<SQLRow>(listEcr);
532
                                    for (SQLRow sqlRow : l) {
533
                                        if (sqlRow.getID() == rowElement.getInt("ID_ECRITURE")) {
534
                                            listEcr.remove(sqlRow);
535
                                        }
536
                                    }
537
                                }
18 ilm 538
 
539
                            }
540
                        }
541
 
21 ilm 542
                        if (!listEcr.isEmpty()) {
73 ilm 543
                            final EcritureSQLElement e = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement(ecritureTable);
21 ilm 544
                            for (SQLRow sqlRow : listEcr) {
73 ilm 545
                                e.archiveEcriture(sqlRow);
18 ilm 546
                            }
547
                        }
21 ilm 548
                        return null;
549
                    }
550
                });
551
            } catch (SQLException exn) {
552
                ExceptionHandler.handle("Erreur lors de la mise à jour des écritures associées à la saisie au kilometre.", exn);
553
            }
554
        }
18 ilm 555
 
21 ilm 556
        @Override
557
        public synchronized ValidState getValidState() {
80 ilm 558
            assert SwingUtilities.isEventDispatchThread();
83 ilm 559
            return super.getValidState().and(this.validState).and(this.validStateCloture);
21 ilm 560
        }
561
 
562
        private void updateValidState() {
80 ilm 563
            assert SwingUtilities.isEventDispatchThread();
21 ilm 564
            ValidState state = ValidState.create(!this.labelMotifWarning.isVisible(), this.labelMotifWarning.getText());
565
            if (!this.isCompteExist && !this.checkCreateCompte.isSelected())
566
                state = state.and(ValidState.createCached(false, "Certains comptes n'existent pas"));
567
            if (!this.allLineValid)
568
                state = state.and(ValidState.createCached(false, "Certaines lignes n'ont pas de crédit ni de débit"));
569
            this.setValidState(state);
570
        }
571
 
572
        private void setValidState(final ValidState state) {
80 ilm 573
            assert SwingUtilities.isEventDispatchThread();
21 ilm 574
            if (!state.equals(this.validState)) {
575
                this.validState = state;
576
                fireValidChange();
577
            }
578
        }
579
 
580
        private void setTotals(final long totalCred, final long totalDeb) {
80 ilm 581
            assert SwingUtilities.isEventDispatchThread();
21 ilm 582
            this.totalCred = totalCred;
583
            this.totalDeb = totalDeb;
584
            this.labelTotalCredit.setText(GestionDevise.currencyToString(this.totalCred));
585
            this.labelTotalDebit.setText(GestionDevise.currencyToString(this.totalDeb));
586
 
587
            final long diff = this.totalDeb - this.totalCred;
588
            final String reason;
589
            if (diff == 0) {
590
                reason = null;
591
            } else if (diff > 0) {
592
                reason = "Le solde des écritures n'est pas nul! Il manque " + GestionDevise.currencyToString(diff) + " en crédit.";
593
            } else {
594
                reason = "Le solde des écritures n'est pas nul! Il manque " + GestionDevise.currencyToString(diff) + " en débit.";
595
            }
596
            this.labelMotifWarning.setVisible(reason != null);
597
            if (reason != null)
598
                this.labelMotifWarning.setText(reason);
599
        }
600
 
601
        private void tableChanged(TableModelEvent e) {
80 ilm 602
            assert SwingUtilities.isEventDispatchThread();
21 ilm 603
            long totalCred = 0;
604
            long totalDeb = 0;
605
            long totalCredWithNoValid = 0;
606
            long totalDebWithNoValid = 0;
607
            boolean isCompteExist = true;
608
            boolean allLineValid = true;
609
            for (int i = 0; i < this.model.getRowCount(); i++) {
610
                final boolean rowValid = this.model.isRowValid(i);
611
                final long fTc = ((Number) this.model.getValueAt(i, this.creditIndex)).longValue();
612
                final long fTd = ((Number) this.model.getValueAt(i, this.debitIndex)).longValue();
613
                String numCpt = this.model.getValueAt(i, this.model.getColumnIndexForElement(this.tableKm.getNumeroCompteElement())).toString();
614
                isCompteExist &= ComptePCESQLElement.isExist(numCpt);
615
                // see SaisieKmItemTable RowValuesTableModel, one of the values will be zeroed
616
                if (fTc != 0 && fTd != 0)
617
                    return;
618
 
73 ilm 619
                if (rowValid) {
21 ilm 620
                    totalCred += fTc;
73 ilm 621
                    totalDeb += fTd;
622
                }
21 ilm 623
                totalCredWithNoValid += fTc;
624
 
625
                totalDebWithNoValid += fTd;
626
 
627
                final boolean emptyAmount = fTc == 0 && fTd == 0;
628
                this.tableKm.setRowDeviseValidAt(!emptyAmount, i);
629
                allLineValid &= !emptyAmount;
630
            }
631
            this.tableKm.revalidate();
632
            this.tableKm.repaint();
633
            this.isCompteExist = isCompteExist;
634
            this.allLineValid = allLineValid;
635
            this.setTotals(totalCred, totalDeb);
636
            updateValidState();
637
 
638
            // add a row to balance totals
639
            final long diffWithNoValid = totalDebWithNoValid - totalCredWithNoValid;
640
            if (diffWithNoValid != 0) {
641
                if (diffWithNoValid > 0) {
642
                    this.defaultEcritureRowVals.put("DEBIT", Long.valueOf(0));
643
                    this.defaultEcritureRowVals.put("CREDIT", Long.valueOf(diffWithNoValid));
67 ilm 644
 
21 ilm 645
                } else {
646
                    this.defaultEcritureRowVals.put("DEBIT", Long.valueOf(-diffWithNoValid));
647
                    this.defaultEcritureRowVals.put("CREDIT", Long.valueOf(0));
73 ilm 648
 
18 ilm 649
                }
73 ilm 650
                if (this.model.isLastRowValid() && checkCreateLineAuto.isSelected()) {
651
                    this.tableKm.getModel().addRow(new SQLRowValues(this.defaultEcritureRowVals));
652
                }
21 ilm 653
            } else {
654
                this.defaultEcritureRowVals.put("DEBIT", Long.valueOf(0));
655
                this.defaultEcritureRowVals.put("CREDIT", Long.valueOf(0));
18 ilm 656
            }
657
        }
21 ilm 658
 
18 ilm 659
    }
57 ilm 660
 
661
    @Override
662
    protected String createCode() {
663
        return createCodeFromPackage() + ".userentry";
664
    }
18 ilm 665
}