OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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