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
80 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.payment.element;
15
 
83 ilm 16
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
80 ilm 17
import org.openconcerto.erp.core.common.ui.DeviseField;
18
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
19
import org.openconcerto.erp.core.finance.payment.ui.RegleMontantTable;
20
import org.openconcerto.erp.generationEcritures.GenerationReglementAchat;
21
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
22
import org.openconcerto.sql.Configuration;
23
import org.openconcerto.sql.element.BaseSQLComponent;
24
import org.openconcerto.sql.element.ElementSQLObject;
25
import org.openconcerto.sql.element.SQLComponent;
26
import org.openconcerto.sql.element.SQLElement;
27
import org.openconcerto.sql.model.SQLInjector;
28
import org.openconcerto.sql.model.SQLRow;
29
import org.openconcerto.sql.model.SQLRowAccessor;
30
import org.openconcerto.sql.model.SQLRowValues;
31
import org.openconcerto.sql.model.SQLTable;
32
import org.openconcerto.sql.sqlobject.ElementComboBox;
33
import org.openconcerto.sql.view.list.RowValuesTableModel;
34
import org.openconcerto.ui.DefaultGridBagConstraints;
35
import org.openconcerto.ui.JDate;
36
import org.openconcerto.ui.TitledSeparator;
37
import org.openconcerto.ui.warning.JLabelWarning;
38
import org.openconcerto.utils.ExceptionHandler;
39
import org.openconcerto.utils.GestionDevise;
40
import org.openconcerto.utils.text.SimpleDocumentListener;
41
 
42
import java.awt.GridBagConstraints;
43
import java.awt.GridBagLayout;
44
import java.awt.Insets;
45
import java.sql.SQLException;
46
import java.util.Calendar;
47
import java.util.Collections;
48
import java.util.Comparator;
49
import java.util.List;
50
 
51
import javax.swing.JLabel;
52
import javax.swing.JOptionPane;
53
import javax.swing.SwingConstants;
54
import javax.swing.event.DocumentEvent;
55
import javax.swing.event.TableModelEvent;
56
import javax.swing.event.TableModelListener;
57
 
58
public class ReglerMontantSQLComponent extends BaseSQLComponent {
59
 
60
    private RegleMontantTable table = new RegleMontantTable();
61
 
62
    SQLElement eltEch = Configuration.getInstance().getDirectory().getElement("ECHEANCE_FOURNISSEUR");
63
    private DeviseField montant = new DeviseField(15);
64
    private JDate date;
65
    private JLabel labelWarning = new JLabelWarning();
66
    private JLabel labelWarningText = new JLabel("Le montant n'est pas valide!");
67
 
68
    public ReglerMontantSQLComponent(SQLElement elt) {
69
        super(elt);
70
    }
71
 
72
    public void addViews() {
73
        this.setLayout(new GridBagLayout());
74
        final GridBagConstraints c = new DefaultGridBagConstraints();
75
 
76
        // Echeance
77
        c.gridwidth = GridBagConstraints.REMAINDER;
78
        c.weightx = 1;
79
        this.add(new TitledSeparator("Echéances"), c);
80
        c.gridy++;
81
        c.weighty = 1;
82
        c.fill = GridBagConstraints.BOTH;
83
        this.add(this.table, c);
84
        this.table.getRowValuesTable().setEnabled(false);
85
        c.fill = GridBagConstraints.HORIZONTAL;
86
        c.gridwidth = 1;
87
        c.gridy++;
88
        c.weighty = 0;
89
 
90
        // Fournisseur
91
        final ElementComboBox comboFournisseur = new ElementComboBox(true, 25);
92
        c.gridx = 0;
93
        c.gridy++;
94
        c.weightx = 0;
95
        this.add(new JLabel(getLabelFor("ID_FOURNISSEUR")), c);
96
 
97
        c.gridx++;
98
        c.weightx = 1;
99
        c.gridwidth = 3;
100
        this.add(comboFournisseur, c);
101
        this.addSQLObject(comboFournisseur, "ID_FOURNISSEUR");
102
        c.gridwidth = 1;
103
 
104
        // Date
105
        this.date = new JDate(true);
106
        c.gridx = GridBagConstraints.RELATIVE;
107
        c.weightx = 0;
108
        c.gridwidth = 1;
109
        this.add(new JLabel("Date"), c);
110
        // c.gridx++;
111
        c.weightx = 1;
112
        this.add(this.date, c);
113
 
114
        // Montant
115
        c.gridy++;
116
        c.gridx = 0;
117
        c.weightx = 0;
118
        this.add(new JLabel("Montant réglé"), c);
119
 
120
        c.gridx++;
121
        c.weightx = 0;
122
        this.add(this.montant, c);
123
 
124
        // Warning
125
        c.gridx++;
126
        this.labelWarning.setHorizontalAlignment(SwingConstants.RIGHT);
127
        this.add(this.labelWarning, c);
128
        c.gridx++;
129
        c.gridwidth = GridBagConstraints.REMAINDER;
130
        this.add(this.labelWarningText, c);
131
 
132
        // this.montant.getDocument().addDocumentListener(new DocumentListener() {
133
        //
134
        // public void insertUpdate(DocumentEvent e) {
135
        //
136
        // fireValidChange();
137
        // }
138
        //
139
        // public void removeUpdate(DocumentEvent e) {
140
        //
141
        // fireValidChange();
142
        // }
143
        //
144
        // public void changedUpdate(DocumentEvent e) {
145
        //
146
        // fireValidChange();
147
        // }
148
        // });
149
 
150
        /***********************************************************************************
151
         * * MODE DE REGLEMENT
152
         **********************************************************************************/
153
        c.gridwidth = GridBagConstraints.REMAINDER;
154
        c.gridx = 0;
155
        c.gridy++;
156
        c.weightx = 1;
157
        TitledSeparator sep = new TitledSeparator("Mode de règlement");
158
        c.insets = new Insets(10, 2, 1, 2);
159
        this.add(sep, c);
160
        c.insets = new Insets(2, 2, 1, 2);
161
 
162
        c.gridx = 0;
163
        c.gridy++;
164
        c.gridwidth = GridBagConstraints.REMAINDER;
165
        this.addView("ID_MODE_REGLEMENT", BaseSQLComponent.REQ + ";" + BaseSQLComponent.DEC + ";" + BaseSQLComponent.SEP);
166
        final ElementSQLObject eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");
167
        this.add(eltModeRegl, c);
168
 
169
        this.addRequiredSQLObject(this.date, "DATE");
170
        this.addRequiredSQLObject(this.montant, "MONTANT");
171
 
172
        final TableModelListener tableListener = new TableModelListener() {
173
 
174
            @Override
175
            public void tableChanged(TableModelEvent e) {
176
                final RowValuesTableModel model = table.getRowValuesTable().getRowValuesTableModel();
177
                if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == model.getColumnIndexForElement(table.getMontantElement())) {
178
 
179
                    final int rowCount = model.getRowCount();
180
                    long total = 0;
181
                    for (int i = 0; i < rowCount; i++) {
182
                        Number nHT = (Number) model.getValueAt(i, model.getColumnIndexForElement(table.getMontantElement()));
183
                        if (nHT != null) {
184
                            total += nHT.longValue();
185
                        }
186
                    }
187
 
188
                    montant.setText(GestionDevise.currencyToString(total));
189
 
190
                    // Selection du mode de reglement
191
                    if (getMode() == SQLComponent.Mode.INSERTION) {
192
                        if (rowCount >= 1) {
193
                            final int idScr = MouvementSQLElement.getSourceId(model.getRowValuesAt(0).getInt("ID_MOUVEMENT_ECHEANCE"));
194
                            SQLTable tableMvt = Configuration.getInstance().getDirectory().getElement("MOUVEMENT").getTable();
195
                            if (idScr > 1) {
196
                                SQLRow rowMvt = tableMvt.getRow(idScr);
197
                                String source = rowMvt.getString("SOURCE");
198
                                int idSource = rowMvt.getInt("IDSOURCE");
199
                                SQLElement eltSource = Configuration.getInstance().getDirectory().getElement(source);
200
                                if (eltSource != null) {
201
                                    SQLRow rowSource = eltSource.getTable().getRow(idSource);
202
 
203
                                    if (rowSource != null) {
204
                                        SQLRow rowModeRegl = rowSource.getForeignRow("ID_MODE_REGLEMENT");
205
                                        if (rowModeRegl != null) {
206
                                            System.err.println("Set mode de règlement");
207
                                            int idTypeRegl = rowModeRegl.getInt("ID_TYPE_REGLEMENT");
208
                                            SQLTable tableModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT").getTable();
209
                                            SQLRowValues rowVals = new SQLRowValues(tableModeRegl);
210
                                            if (idTypeRegl > TypeReglementSQLElement.TRAITE) {
211
                                                idTypeRegl = TypeReglementSQLElement.CHEQUE;
212
                                            }
213
                                            rowVals.put("ID_TYPE_REGLEMENT", idTypeRegl);
214
                                            rowVals.put("COMPTANT", Boolean.TRUE);
215
                                            rowVals.put("AJOURS", 0);
216
                                            rowVals.put("LENJOUR", 0);
83 ilm 217
                                            rowVals.put("ID_" + BanqueSQLElement.TABLENAME, rowModeRegl.getInt("ID_" + BanqueSQLElement.TABLENAME));
80 ilm 218
                                            eltModeRegl.setValue(rowVals);
219
                                        }
220
                                    }
221
                                }
222
                            }
223
                        }
224
                    }
225
 
226
                }
227
                if (e.getColumn() == TableModelEvent.ALL_COLUMNS || e.getColumn() == model.getColumnIndexForElement(table.getMontantAReglerElement())) {
228
                    updateWarning();
229
                }
230
            }
231
        };
232
 
233
        this.montant.getDocument().addDocumentListener(new SimpleDocumentListener() {
234
 
235
            @Override
236
            public void update(DocumentEvent e) {
237
                table.getRowValuesTable().getRowValuesTableModel().removeTableModelListener(tableListener);
238
                updateMontant(montant.getText());
239
                table.getRowValuesTable().getRowValuesTableModel().addTableModelListener(tableListener);
240
                updateWarning();
241
 
242
            }
243
        });
244
        this.table.getRowValuesTable().getRowValuesTableModel().addTableModelListener(tableListener);
245
 
246
    }
247
 
248
    public int insert(SQLRow order) {
249
 
250
        int id = super.insert(order);
251
        try {
252
 
253
            this.table.updateField("ID_REGLER_MONTANT", id);
254
 
255
            // Génération des ecritures du reglement
256
            System.out.println("Génération des ecritures du reglement");
257
            new GenerationReglementAchat(id);
258
 
259
            SQLRow row = getTable().getRow(id);
260
 
261
            // SQLTable tableEch = getTable().getBase().getTable("ECHEANCE_FOURNISSEUR");
262
            // int idEchFourn = row.getInt("ID_ECHEANCE_FOURNISSEUR");
263
            // System.out.println("ID ECHEANCE FOURNISSEUR" + idEchFourn);
264
            // if (idEchFourn > 1) {
265
            // SQLRow rowEch = tableEch.getRow(idEchFourn);
266
            //
267
            // // Mise a jour du montant de l'echeance
268
            // System.out.println("Mise à jour du montant de l'échéance");
269
            // long montant = ((Long) row.getObject("MONTANT")).longValue();
270
            //
271
            // SQLRowValues rowVals = rowEch.createEmptyUpdateRow();
272
            //
273
            // if (montant == ((Long) rowEch.getObject("MONTANT")).longValue()) {
274
            // rowVals.put("REGLE", Boolean.TRUE);
275
            // } else {
276
            // rowVals.put("MONTANT", new Long(((Long) rowEch.getObject("MONTANT")).longValue() -
277
            // montant));
278
            // }
279
            //
280
            // rowVals.commit();
281
            //
282
            // }
283
            List<SQLRow> l = row.getReferentRows(Configuration.getInstance().getDirectory().getElement("REGLER_MONTANT_ELEMENT").getTable());
284
            if (l.isEmpty()) {
285
                JOptionPane.showMessageDialog(null, "Un problème a été rencontré lors du décaissement! \n Les écritures comptables non pu être générer!");
286
                System.err.println("Liste des échéances vides pour le décaissement ID " + id);
287
                Thread.dumpStack();
288
            }
289
            // On marque les echeances comme reglees
290
            for (SQLRow sqlRow : l) {
291
 
292
                final SQLRow rowEch = sqlRow.getForeignRow("ID_ECHEANCE_FOURNISSEUR");
293
                SQLRowValues rowValsEch = rowEch.createEmptyUpdateRow();
294
                if (sqlRow.getLong("MONTANT_REGLE") >= sqlRow.getLong("MONTANT_A_REGLER")) {
295
                    rowValsEch.put("REGLE", Boolean.TRUE);
296
 
297
                }
298
                rowValsEch.put("MONTANT", Long.valueOf(rowEch.getLong("MONTANT") - sqlRow.getLong("MONTANT_REGLE")));
299
 
300
                rowValsEch.update();
301
                // this.comboEcheance.rowDeleted(tableEch, rowEch.getID());
302
                // getTable().fireTableModified(rowEch.getID());
303
            }
304
        } catch (Exception e) {
305
            ExceptionHandler.handle("Erreur lors de la génération des ecritures du reglement", e);
306
        }
307
        return id;
308
    }
309
 
310
    // @Override
311
    // public synchronized ValidState getValidState() {
312
    // return super.getValidState().and(ValidState.createCached(montantIsValidated(),
313
    // "Le montant est négatif ou supérieur à l'échéance"));
314
    // }
315
 
316
    private void updateMontant(String s) {
317
 
318
        long total = 0;
319
        if (s.trim().length() > 0) {
320
            total = GestionDevise.parseLongCurrency(s);
321
        }
322
        final RowValuesTableModel model = table.getRowValuesTable().getRowValuesTableModel();
323
 
324
        final int rowCount = model.getRowCount();
325
        for (int i = 0; i < rowCount; i++) {
326
            Number nHT = (Number) model.getValueAt(i, model.getColumnIndexForElement(table.getMontantAReglerElement()));
327
            Long value = Long.valueOf(0);
328
            if (i < rowCount - 1) {
329
                if (nHT.longValue() <= total) {
330
                    value = nHT.longValue();
331
                } else {
332
                    value = total;
333
                }
334
            } else {
335
                value = total;
336
            }
337
            model.putValue(value, i, "MONTANT_REGLE");
338
            total = total - value;
339
        }
340
    }
341
 
342
    @Override
343
    protected SQLRowValues createDefaults() {
344
        SQLRowValues vals = new SQLRowValues(this.getTable());
345
        SQLRowAccessor r;
346
        this.table.getModel().clearRows();
347
        try {
348
            r = ModeReglementDefautPrefPanel.getDefaultRow(false);
349
            SQLElement eltModeReglement = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
350
            if (r.getID() > 1) {
351
                SQLRowValues rowVals = eltModeReglement.createCopy(r.getID());
352
                System.err.println(rowVals.getInt("ID_TYPE_REGLEMENT"));
353
                vals.put("ID_MODE_REGLEMENT", rowVals);
354
            }
355
        } catch (SQLException e) {
356
            System.err.println("Impossible de sélectionner le mode de règlement par défaut du client.");
357
            e.printStackTrace();
358
        }
359
        return vals;
360
    }
361
 
362
    // test si le montant est correct par rapport à l'echeance selectionnée
363
    private final void updateWarning() {
364
 
365
        long montantValue = 0;
366
 
367
        if (this.table.getRowValuesTable().getRowCount() == 0) {
368
            this.labelWarning.setVisible(false);
369
            this.labelWarningText.setVisible(false);
370
            return;
371
        }
372
 
373
        try {
374
            if (this.montant.getText().trim().length() != 0) {
375
                montantValue = GestionDevise.parseLongCurrency(this.montant.getText().trim());
376
            }
377
        } catch (NumberFormatException e) {
378
            System.err.println("format float incorrect " + e);
379
            e.printStackTrace();
380
        }
381
 
382
        final RowValuesTableModel model = table.getRowValuesTable().getRowValuesTableModel();
383
 
384
        final int rowCount = model.getRowCount();
385
        long total = 0;
386
        for (int i = 0; i < rowCount; i++) {
387
            Number nHT = (Number) model.getValueAt(i, model.getColumnIndexForElement(table.getMontantAReglerElement()));
388
            total += nHT.longValue();
389
        }
390
 
391
        this.labelWarning.setVisible(montantValue <= 0 || montantValue > total);
392
        this.labelWarningText.setVisible(montantValue <= 0 || montantValue > total);
393
    }
394
 
395
    public void loadEcheancesFromRows(List<SQLRow> rows) {
396
 
397
        Collections.sort(rows, new Comparator<SQLRow>() {
398
            @Override
399
            public int compare(SQLRow o1, SQLRow o2) {
400
                Calendar c1 = o1.getDate("DATE");
401
                Calendar c2 = o2.getDate("DATE");
402
                if (c1 == null) {
403
                    return -1;
404
                }
405
                if (c2 == null) {
406
                    return 1;
407
                }
408
                if (c1.getTime().before(c2.getTime())) {
409
                    return -1;
410
                } else {
411
                    return 1;
412
                }
413
            }
414
        });
415
 
416
        SQLTable tableEch = Configuration.getInstance().getDirectory().getElement("ECHEANCE_FOURNISSEUR").getTable();
417
        SQLTable tableEnc = Configuration.getInstance().getDirectory().getElement("REGLER_MONTANT_ELEMENT").getTable();
418
        SQLInjector inj = SQLInjector.getInjector(tableEch, tableEnc);
419
        for (SQLRow row : rows) {
420
 
421
            SQLRowValues rowVals = inj.createRowValuesFrom(row.getID());
422
            rowVals.put("MONTANT_REGLE", rowVals.getObject("MONTANT_A_REGLER"));
423
            table.getModel().addRow(rowVals);
424
            int rowIndex = table.getModel().getRowCount() - 1;
425
            table.getModel().fireTableModelModified(rowIndex);
426
        }
427
        this.table.getModel().fireTableDataChanged();
428
        this.table.repaint();
429
 
430
    }
431
 
432
    // // test si le montant est correct par rapport à l'echeance selectionnée
433
    // public boolean montantIsValidated() {
434
    // final SQLRow echRow = this.comboEcheance.getSelectedRow();
435
    // final boolean res;
436
    // if (echRow == null) {
437
    // res = true;
438
    // } else {
439
    // final long montantValue =
440
    // GestionDevise.parseLongCurrency(this.montant.getText().trim());
441
    // res = (montantValue > 0) && (montantValue <= echRow.getLong("MONTANT"));
442
    // }
443
    //
444
    // this.labelWarning.setVisible(!res);
445
    // this.labelWarningText.setVisible(!res);
446
    // return res;
447
    // }
448
 
449
}