OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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