OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Rev 182 | 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.element;
15
 
80 ilm 16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
18 ilm 17
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
19
import org.openconcerto.erp.core.finance.payment.component.EncaisserMontantSQLComponent;
174 ilm 20
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
21
import org.openconcerto.erp.generationEcritures.GenerationReglementVenteNG;
22
import org.openconcerto.erp.model.PrixTTC;
149 ilm 23
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
18 ilm 24
import org.openconcerto.sql.Configuration;
25
import org.openconcerto.sql.element.SQLComponent;
174 ilm 26
import org.openconcerto.sql.element.SQLElement;
18 ilm 27
import org.openconcerto.sql.element.TreesOfSQLRows;
80 ilm 28
import org.openconcerto.sql.model.FieldPath;
18 ilm 29
import org.openconcerto.sql.model.SQLRow;
80 ilm 30
import org.openconcerto.sql.model.SQLRowAccessor;
18 ilm 31
import org.openconcerto.sql.model.SQLRowListRSH;
32
import org.openconcerto.sql.model.SQLRowValues;
33
import org.openconcerto.sql.model.SQLSelect;
34
import org.openconcerto.sql.model.SQLTable;
35
import org.openconcerto.sql.model.Where;
83 ilm 36
import org.openconcerto.sql.model.graph.Path;
37
import org.openconcerto.sql.model.graph.PathBuilder;
149 ilm 38
import org.openconcerto.sql.preferences.SQLPreferences;
174 ilm 39
import org.openconcerto.sql.view.EditFrame;
80 ilm 40
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
149 ilm 41
import org.openconcerto.sql.view.list.IListe;
42
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
43
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
142 ilm 44
import org.openconcerto.sql.view.list.SQLTableModelSource;
83 ilm 45
import org.openconcerto.utils.CollectionUtils;
149 ilm 46
import org.openconcerto.utils.ExceptionHandler;
174 ilm 47
import org.openconcerto.utils.StringUtils;
18 ilm 48
 
149 ilm 49
import java.awt.event.ActionEvent;
18 ilm 50
import java.sql.SQLException;
51
import java.util.ArrayList;
83 ilm 52
import java.util.Arrays;
53
import java.util.Collection;
18 ilm 54
import java.util.Collections;
132 ilm 55
import java.util.HashSet;
18 ilm 56
import java.util.List;
57
import java.util.Set;
58
 
149 ilm 59
import javax.swing.AbstractAction;
174 ilm 60
import javax.swing.JOptionPane;
61
import javax.swing.SwingUtilities;
149 ilm 62
 
18 ilm 63
public class EncaisserMontantSQLElement extends ComptaSQLConfElement {
64
 
65
    public EncaisserMontantSQLElement() {
66
        super("ENCAISSER_MONTANT", "un encaissement de montant", "encaissements de montant");
149 ilm 67
 
68
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
69
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
70
            PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Annuler l'acompte") {
71
 
72
                public void actionPerformed(ActionEvent e) {
73
                    final SQLRow selRow = IListe.get(e).getSelectedRow().asRow();
74
                    if (selRow.getBoolean("ACOMPTE")) {
75
                        int idDevis = selRow.getForeignID("ID_DEVIS");
76
                        try {
77
                            archive(selRow.getID());
78
                            String up = "UPDATE " + getTable().getTable("DEVIS").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
79
                                    + getTable().getSQLName().quote() + " where \"ID_DEVIS\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID_DEVIS\"=" + idDevis;
80
                            getTable().getDBSystemRoot().getDataSource().execute(up);
81
                        } catch (SQLException e1) {
82
                            e1.printStackTrace();
83
                            ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
84
                        }
85
                    }
86
                }
87
            }, false);
88
            actionClient.setPredicate(IListeEvent.getSingleSelectionPredicate());
89
            getRowActions().add(actionClient);
90
        }
91
 
18 ilm 92
    }
93
 
94
    @Override
95
    protected List<String> getListFields() {
96
        final List<String> l = new ArrayList<String>();
83 ilm 97
            l.add("DATE");
98
            l.add("NOM");
99
            l.add("ID_CLIENT");
100
            // l.add("ID_MOUVEMENT");
101
            l.add("ID_MODE_REGLEMENT");
102
            l.add("MONTANT");
149 ilm 103
            SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
104
            if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
105
                l.add("ACOMPTE");
106
            }
18 ilm 107
        return l;
108
    }
109
 
110
    @Override
111
    protected List<String> getComboFields() {
112
        final List<String> l = new ArrayList<String>();
113
        l.add("DATE");
114
        l.add("MONTANT");
115
        return l;
116
    }
117
 
118
    @Override
119
    public Set<String> getReadOnlyFields() {
120
 
121
        return Collections.singleton("ID_CLIENT");
122
    }
123
 
180 ilm 124
    @Override
125
    protected synchronized void _initTableSource(final SQLTableModelSource table) {
126
        super._initTableSource(table);
80 ilm 127
 
180 ilm 128
        final BaseSQLTableModelColumn racCol = new BaseSQLTableModelColumn("Report échéance", Boolean.class) {
129
            @Override
130
            protected Object show_(SQLRowAccessor r) {
131
 
132
                return !r.getForeign("ID_MODE_REGLEMENT").getBoolean("COMPTANT");
133
            }
134
 
135
            @Override
136
            public Set<FieldPath> getPaths() {
137
                Path p = new Path(getTable());
138
                Path p2 = p.add(p.getLast().getField("ID_MODE_REGLEMENT"));
139
                return CollectionUtils.createSet(new FieldPath(p2, "COMPTANT"));
140
            }
141
        };
142
 
143
        table.getColumns().add(racCol);
144
 
145
    }
146
 
18 ilm 147
    /*
148
     * (non-Javadoc)
149
     *
150
     * @see org.openconcerto.devis.SQLElement#getComponent()
151
     */
152
    @Override
153
    public SQLComponent createComponent() {
154
        return new EncaisserMontantSQLComponent(this);
155
    }
156
 
157
    @Override
158
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
159
 
160
        // On rétablit les échéances
161
        for (SQLRow row : trees.getRows()) {
162
            for (SQLRow rowEncaisse : row.getReferentRows()) {
163
 
164
                SQLRow rowEch = rowEncaisse.getForeignRow("ID_ECHEANCE_CLIENT");
165
                // SI une echeance est associée (paiement non comptant)
166
                if (rowEch.getID() > 1) {
167
                    SQLRowValues rowVals = rowEch.createEmptyUpdateRow();
168
                    rowVals.put("REGLE", Boolean.FALSE);
169
                    if (rowEch.getBoolean("REGLE")) {
170
                        rowVals.put("MONTANT", rowEncaisse.getLong("MONTANT_REGLE"));
171
                    } else {
172
                        rowVals.put("MONTANT", rowEch.getLong("MONTANT") + rowEncaisse.getLong("MONTANT_REGLE"));
173
                    }
174
                    rowVals.update();
175
                }
176
                Configuration.getInstance().getDirectory().getElement(rowEncaisse.getTable()).archive(rowEncaisse);
177
            }
178
 
179
            // On supprime les mouvements
180
            SQLSelect sel = new SQLSelect(getTable().getBase());
181
 
182
            SQLTable tableMvt = getTable().getTable("MOUVEMENT");
183
            EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement(tableMvt.getTable("ECRITURE"));
184
            sel.addSelectStar(tableMvt);
185
            Where w = new Where(tableMvt.getField("SOURCE"), "=", getTable().getName());
186
            w = w.and(new Where(tableMvt.getField("IDSOURCE"), "=", row.getID()));
187
            sel.setWhere(w);
188
            List<SQLRow> list = (List<SQLRow>) getTable().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, tableMvt));
189
            for (SQLRow sqlRow : list) {
190
                eltEcr.archiveMouvementProfondeur(sqlRow.getID(), true);
191
            }
192
        }
193
 
194
        super.archive(trees, cutLinks);
195
    }
156 ilm 196
 
180 ilm 197
    public void regleFacture(SQLRow rowAfter, SQLRowValues rowBefore, boolean update) throws Exception {
174 ilm 198
 
180 ilm 199
        if (update && rowBefore == null) {
200
            throw new IllegalArgumentException();
201
        } else if (update) {
202
 
203
            // Recalcul des échéances
204
            for (SQLRowAccessor rowEncaisse : rowBefore.getReferentRows(getTable().getTable("ENCAISSER_MONTANT_ELEMENT"))) {
205
 
206
                SQLRowAccessor rowEch = rowEncaisse.getForeign("ID_ECHEANCE_CLIENT");
207
                // SI une echeance est associée (paiement non comptant)
208
                if (rowEch.getID() > 1) {
209
                    SQLRowValues rowVals = rowEch.createEmptyUpdateRow();
210
                    rowVals.put("REGLE", Boolean.FALSE);
211
                    if (rowEch.getBoolean("REGLE")) {
212
                        rowVals.put("MONTANT", rowEncaisse.getLong("MONTANT_REGLE"));
213
                    } else {
214
                        rowVals.put("MONTANT", rowEch.getLong("MONTANT") + rowEncaisse.getLong("MONTANT_REGLE"));
215
                    }
216
                    rowVals.update();
217
                }
218
                // TODO si pas une echeance, echeance à creer
219
            }
220
 
221
            // On supprime les mouvements
222
            SQLSelect sel = new SQLSelect(getTable().getBase());
223
 
224
            SQLTable tableMvt = getTable().getTable("MOUVEMENT");
225
            EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement(tableMvt.getTable("ECRITURE"));
226
            sel.addSelectStar(tableMvt);
227
            Where w = new Where(tableMvt.getField("SOURCE"), "=", getTable().getName());
228
            w = w.and(new Where(tableMvt.getField("IDSOURCE"), "=", rowBefore.getID()));
229
            sel.setWhere(w);
230
            List<SQLRow> list = (List<SQLRow>) getTable().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, tableMvt));
231
            for (SQLRow sqlRow : list) {
232
                eltEcr.archiveMouvementProfondeur(sqlRow.getID(), false);
233
            }
234
 
235
            // On supprime si une prochaine échéance a été créé (ex: prélévement)
236
            final SQLRowAccessor nonEmptyForeignMvt = rowBefore.getNonEmptyForeign("ID_MOUVEMENT");
237
            if (nonEmptyForeignMvt != null && nonEmptyForeignMvt.getString("SOURCE").equals("ECHEANCE_CLIENT")) {
238
                eltEcr.archiveMouvementProfondeur(nonEmptyForeignMvt.getID(), true);
239
            }
240
        }
241
 
174 ilm 242
        System.out.println("Génération des ecritures du reglement");
180 ilm 243
        String s = rowAfter.getString("NOM");
244
        SQLRow rowModeRegl = rowAfter.getForeignRow("ID_MODE_REGLEMENT");
174 ilm 245
        SQLRow rowTypeRegl = rowModeRegl.getForeignRow("ID_TYPE_REGLEMENT");
246
 
247
        // Compte Client
180 ilm 248
        SQLRow clientRow = rowAfter.getForeignRow("ID_CLIENT");
174 ilm 249
 
250
        String label = "Règlement vente " + ((s == null) ? "" : s) + " (" + rowTypeRegl.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
180 ilm 251
        long montant = rowAfter.getLong("MONTANT");
174 ilm 252
        PrixTTC ttc = new PrixTTC(montant);
253
 
180 ilm 254
        List<SQLRow> l = rowAfter.getReferentRows(rowAfter.getTable().getTable("ENCAISSER_MONTANT_ELEMENT"));
174 ilm 255
        if (l.isEmpty()) {
256
            SwingUtilities.invokeLater(new Runnable() {
257
 
258
                @Override
259
                public void run() {
260
                    JOptionPane.showMessageDialog(null, "Un problème a été rencontré lors de l'encaissement! \n Les écritures comptables non pu être générer!");
261
                }
262
            });
180 ilm 263
            System.err.println("Liste des échéances vides pour l'encaissement ID " + rowAfter.getID());
174 ilm 264
            Thread.dumpStack();
265
            return;
266
        }
180 ilm 267
        new GenerationReglementVenteNG(label, clientRow, ttc, rowAfter.getDate("DATE").getTime(), rowModeRegl, rowAfter, l.get(0).getForeignRow("ID_MOUVEMENT_ECHEANCE"), false, false,
268
                rowAfter.getString("TIERS"), rowAfter.getForeign("ID_COMPTE_PCE_TIERS"));
174 ilm 269
 
270
        // Mise a jour du montant de l'echeance
271
        boolean supplement = false;
272
 
180 ilm 273
        if (!rowAfter.getBoolean("ACOMPTE")) {
174 ilm 274
            // On marque les echeances comme reglees
275
            for (SQLRow sqlRow : l) {
276
 
277
                final SQLRow rowEch = sqlRow.getForeignRow("ID_ECHEANCE_CLIENT");
278
                SQLRowValues rowValsEch = rowEch.createEmptyUpdateRow();
279
                if (sqlRow.getLong("MONTANT_REGLE") >= sqlRow.getLong("MONTANT_A_REGLER")) {
280
                    rowValsEch.put("REGLE", Boolean.TRUE);
281
                    if (sqlRow.getLong("MONTANT_REGLE") > sqlRow.getLong("MONTANT_A_REGLER")) {
282
                        supplement = true;
283
                    }
284
                }
285
                rowValsEch.put("MONTANT", Long.valueOf(rowEch.getLong("MONTANT") - sqlRow.getLong("MONTANT_REGLE")));
286
 
287
                rowValsEch.update();
288
                // this.comboEcheance.rowDeleted(tableEch, rowEch.getID());
289
                // getTable().fireTableModified(rowEch.getID());
290
            }
291
        }
292
        // si le montant réglé est supérieur, on crée une facture de complément
293
        if (supplement) {
294
            SQLElement elt = getDirectory().getElement("SAISIE_VENTE_FACTURE");
295
            SwingUtilities.invokeLater(new Runnable() {
296
 
297
                @Override
298
                public void run() {
299
 
300
                    EditFrame f = new EditFrame(elt, EditFrame.CREATION);
301
                    SaisieVenteFactureSQLComponent comp = (SaisieVenteFactureSQLComponent) f.getSQLComponent();
302
                    comp.setComplement(true);
303
                    f.setVisible(true);
304
                }
305
            });
306
        }
307
 
308
    }
309
 
156 ilm 310
    @Override
311
    protected String createCodeSuffix() {
312
        return ".category";
313
    }
18 ilm 314
}