OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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