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