OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.core.finance.payment.element;

import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
import org.openconcerto.erp.core.finance.payment.component.EncaisserMontantSQLComponent;
import org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent;
import org.openconcerto.erp.generationEcritures.GenerationReglementVenteNG;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.TreesOfSQLRows;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.sql.model.Where;
import org.openconcerto.sql.model.graph.Path;
import org.openconcerto.sql.model.graph.PathBuilder;
import org.openconcerto.sql.preferences.SQLPreferences;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.StringUtils;

import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class EncaisserMontantSQLElement extends ComptaSQLConfElement {

    public EncaisserMontantSQLElement() {
        super("ENCAISSER_MONTANT", "un encaissement de montant", "encaissements de montant");

        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
            PredicateRowAction actionClient = new PredicateRowAction(new AbstractAction("Annuler l'acompte") {

                public void actionPerformed(ActionEvent e) {
                    final SQLRow selRow = IListe.get(e).getSelectedRow().asRow();
                    if (selRow.getBoolean("ACOMPTE")) {
                        if (!selRow.isForeignEmpty("ID_DEVIS")) {
                            int idDevis = selRow.getForeignID("ID_DEVIS");
                            try {
                                archive(selRow.getID());
                                String up = "UPDATE " + getTable().getTable("DEVIS").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
                                        + getTable().getSQLName().quote() + " where \"ID_DEVIS\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID_DEVIS\"=" + idDevis;
                                getTable().getDBSystemRoot().getDataSource().execute(up);
                            } catch (SQLException e1) {
                                e1.printStackTrace();
                                ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
                            }
                        } else if (!selRow.isForeignEmpty("ID_COMMANDE_CLIENT")) {
                            int idDevis = selRow.getForeignID("ID_COMMANDE_CLIENT");
                            try {
                                archive(selRow.getID());
                                String up = "UPDATE " + getTable().getTable("COMMANDE_CLIENT").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
                                        + getTable().getSQLName().quote() + " where \"ID_COMMANDE_CLIENT\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID\"=" + idDevis;
                                getTable().getDBSystemRoot().getDataSource().execute(up);
                            } catch (SQLException e1) {
                                e1.printStackTrace();
                                ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
                            }
                        }
                    }
                }
            }, false);
            actionClient.setPredicate(IListeEvent.getSingleSelectionPredicate());
            getRowActions().add(actionClient);
        }

    }

    @Override
    protected List<String> getListFields() {
        final List<String> l = new ArrayList<String>();
            l.add("DATE");
            l.add("NOM");
            l.add("ID_CLIENT");
            // l.add("ID_MOUVEMENT");
            l.add("ID_MODE_REGLEMENT");
            l.add("MONTANT");
            SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
            if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ACOMPTE_DEVIS, false)) {
                l.add("ACOMPTE");
            }
        return l;
    }

    @Override
    protected List<String> getComboFields() {
        final List<String> l = new ArrayList<String>();
        l.add("DATE");
        l.add("MONTANT");
        return l;
    }

    @Override
    public Set<String> getReadOnlyFields() {

        Set<String> s = new HashSet<>();
        s.add("ACOMPTE");
        s.add("ID_CLIENT");
        return s;
    }

    @Override
    protected synchronized void _initTableSource(final SQLTableModelSource table) {
        super._initTableSource(table);

        final BaseSQLTableModelColumn racCol = new BaseSQLTableModelColumn("Report échéance", Boolean.class) {
            @Override
            protected Object show_(SQLRowAccessor r) {

                return !r.getForeign("ID_MODE_REGLEMENT").getBoolean("COMPTANT");
            }

            @Override
            public Set<FieldPath> getPaths() {
                Path p = new Path(getTable());
                Path p2 = p.add(p.getLast().getField("ID_MODE_REGLEMENT"));
                return CollectionUtils.createSet(new FieldPath(p2, "COMPTANT"));
            }
        };

        table.getColumns().add(racCol);

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.openconcerto.devis.SQLElement#getComponent()
     */
    @Override
    public SQLComponent createComponent() {
        return new EncaisserMontantSQLComponent(this);
    }

    @Override
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {

        // On rétablit les échéances
        for (SQLRow row : trees.getRows()) {
            for (SQLRow rowEncaisseItems : row.getReferentRows(row.getTable().getTable("ENCAISSER_MONTANT_ELEMENT").getField("ID_ENCAISSER_MONTANT"))) {

                SQLRow rowEch = rowEncaisseItems.getForeignRow("ID_ECHEANCE_CLIENT");
                // SI une echeance est associée (paiement non comptant)
                if (rowEch.getID() > 1) {
                    SQLRowValues rowVals = rowEch.createEmptyUpdateRow();
                    rowVals.put("REGLE", Boolean.FALSE);
                    if (rowEch.getBoolean("REGLE")) {
                        rowVals.put("MONTANT", rowEncaisseItems.getLong("MONTANT_REGLE"));
                    } else {
                        rowVals.put("MONTANT", rowEch.getLong("MONTANT") + rowEncaisseItems.getLong("MONTANT_REGLE"));
                    }
                    rowVals.update();
                }
                Configuration.getInstance().getDirectory().getElement(rowEncaisseItems.getTable()).archive(rowEncaisseItems);
            }
            if (row.getBoolean("ACOMPTE")) {
                if (!row.isForeignEmpty("ID_DEVIS")) {
                    int idDevis = row.getForeignID("ID_DEVIS");
                    try {
                        archive(row.getID());
                        String up = "UPDATE " + getTable().getTable("DEVIS").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from " + getTable().getSQLName().quote()
                                + " where \"ID_DEVIS\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID_DEVIS\"=" + idDevis;
                        getTable().getDBSystemRoot().getDataSource().execute(up);
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                        ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
                    }
                } else if (!row.isForeignEmpty("ID_COMMANDE_CLIENT")) {
                    int idDevis = row.getForeignID("ID_COMMANDE_CLIENT");
                    try {
                        archive(row.getID());
                        String up = "UPDATE " + getTable().getTable("COMMANDE_CLIENT").getSQLName().quote() + " set \"T_ACOMPTE\"=(SELECT COALESCE(SUM(\"MONTANT\"),0) from "
                                + getTable().getSQLName().quote() + " where \"ID_COMMANDE_CLIENT\"=" + idDevis + " AND \"ARCHIVE\"=0) where \"ID\"=" + idDevis;
                        getTable().getDBSystemRoot().getDataSource().execute(up);
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                        ExceptionHandler.handle("Erreur lors de l'annulation de l'acompte!", e1);
                    }
                }
            }

            // On supprime les mouvements
            SQLSelect sel = new SQLSelect(getTable().getBase());

            SQLTable tableMvt = getTable().getTable("MOUVEMENT");
            EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement(tableMvt.getTable("ECRITURE"));
            sel.addSelectStar(tableMvt);
            Where w = new Where(tableMvt.getField("SOURCE"), "=", getTable().getName());
            w = w.and(new Where(tableMvt.getField("IDSOURCE"), "=", row.getID()));
            sel.setWhere(w);
            List<SQLRow> list = (List<SQLRow>) getTable().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, tableMvt));
            for (SQLRow sqlRow : list) {
                eltEcr.archiveMouvementProfondeur(sqlRow.getID(), true);
            }
        }

        super.archive(trees, cutLinks);
    }

    public void regleFacture(SQLRow rowAfter, SQLRowValues rowBefore, boolean update) throws Exception {

        if (update && rowBefore == null) {
            throw new IllegalArgumentException();
        } else if (update) {

            // Recalcul des échéances
            for (SQLRowAccessor rowEncaisse : rowBefore.getReferentRows(getTable().getTable("ENCAISSER_MONTANT_ELEMENT"))) {

                SQLRowAccessor rowEch = rowEncaisse.getForeign("ID_ECHEANCE_CLIENT");
                // SI une echeance est associée (paiement non comptant)
                if (rowEch.getID() > 1) {
                    SQLRowValues rowVals = rowEch.createEmptyUpdateRow();
                    rowVals.put("REGLE", Boolean.FALSE);
                    if (rowEch.getBoolean("REGLE")) {
                        rowVals.put("MONTANT", rowEncaisse.getLong("MONTANT_REGLE"));
                    } else {
                        rowVals.put("MONTANT", rowEch.getLong("MONTANT") + rowEncaisse.getLong("MONTANT_REGLE"));
                    }
                    rowVals.update();
                }
                // TODO si pas une echeance, echeance à creer
            }

            // On supprime les mouvements
            SQLSelect sel = new SQLSelect(getTable().getBase());

            SQLTable tableMvt = getTable().getTable("MOUVEMENT");
            EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement(tableMvt.getTable("ECRITURE"));
            sel.addSelectStar(tableMvt);
            Where w = new Where(tableMvt.getField("SOURCE"), "=", getTable().getName());
            w = w.and(new Where(tableMvt.getField("IDSOURCE"), "=", rowBefore.getID()));
            sel.setWhere(w);
            List<SQLRow> list = (List<SQLRow>) getTable().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel, tableMvt));
            for (SQLRow sqlRow : list) {
                eltEcr.archiveMouvementProfondeur(sqlRow.getID(), false);
            }

            // On supprime si une prochaine échéance a été créé (ex: prélévement)
            final SQLRowAccessor nonEmptyForeignMvt = rowBefore.getNonEmptyForeign("ID_MOUVEMENT");
            if (nonEmptyForeignMvt != null && nonEmptyForeignMvt.getString("SOURCE").equals("ECHEANCE_CLIENT")) {
                eltEcr.archiveMouvementProfondeur(nonEmptyForeignMvt.getID(), true);
            }
        }

        System.out.println("Génération des ecritures du reglement");
        String s = rowAfter.getString("NOM");
        SQLRow rowModeRegl = rowAfter.getForeignRow("ID_MODE_REGLEMENT");
        SQLRow rowTypeRegl = rowModeRegl.getForeignRow("ID_TYPE_REGLEMENT");

        // Compte Client
        SQLRow clientRow = rowAfter.getForeignRow("ID_CLIENT");

        String label = "Règlement vente " + ((s == null) ? "" : s) + " (" + rowTypeRegl.getString("NOM") + ") " + StringUtils.limitLength(clientRow.getString("NOM"), 20);
        long montant = rowAfter.getLong("MONTANT");
        PrixTTC ttc = new PrixTTC(montant);

        List<SQLRow> l = rowAfter.getReferentRows(rowAfter.getTable().getTable("ENCAISSER_MONTANT_ELEMENT"));
        if (l.isEmpty()) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    JOptionPane.showMessageDialog(null, "Un problème a été rencontré lors de l'encaissement! \n Les écritures comptables non pu être générer!");
                }
            });
            System.err.println("Liste des échéances vides pour l'encaissement ID " + rowAfter.getID());
            Thread.dumpStack();
            return;
        }
        new GenerationReglementVenteNG(label, clientRow, ttc, rowAfter.getDate("DATE").getTime(), rowModeRegl, rowAfter, l.get(0).getForeignRow("ID_MOUVEMENT_ECHEANCE"), false, false,
                rowAfter.getString("TIERS"), rowAfter.getForeign("ID_COMPTE_PCE_TIERS"));

        // Mise a jour du montant de l'echeance
        boolean supplement = false;

        if (!rowAfter.getBoolean("ACOMPTE")) {
            // On marque les echeances comme reglees
            for (SQLRow sqlRow : l) {

                final SQLRow rowEch = sqlRow.getForeignRow("ID_ECHEANCE_CLIENT");
                SQLRowValues rowValsEch = rowEch.createEmptyUpdateRow();
                if (sqlRow.getLong("MONTANT_REGLE") >= sqlRow.getLong("MONTANT_A_REGLER")) {
                    rowValsEch.put("REGLE", Boolean.TRUE);
                    if (sqlRow.getLong("MONTANT_REGLE") > sqlRow.getLong("MONTANT_A_REGLER")) {
                        supplement = true;
                    }
                }
                rowValsEch.put("MONTANT", Long.valueOf(rowEch.getLong("MONTANT") - sqlRow.getLong("MONTANT_REGLE")));

                rowValsEch.update();
                // this.comboEcheance.rowDeleted(tableEch, rowEch.getID());
                // getTable().fireTableModified(rowEch.getID());
            }
        }
        // si le montant réglé est supérieur, on crée une facture de complément
        if (supplement) {
            SQLElement elt = getDirectory().getElement("SAISIE_VENTE_FACTURE");
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {

                    EditFrame f = new EditFrame(elt, EditFrame.CREATION);
                    SaisieVenteFactureSQLComponent comp = (SaisieVenteFactureSQLComponent) f.getSQLComponent();
                    comp.setComplement(true);
                    f.setVisible(true);
                }
            });
        }

    }

    @Override
    protected String createCodeSuffix() {
        return ".category";
    }
}