OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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