OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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