OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 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")) {
                        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);
                        }
                    }
                }
            }, 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() {

        return Collections.singleton("ID_CLIENT");
    }


    /*
     * (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 rowEncaisse : row.getReferentRows()) {

                SQLRow rowEch = rowEncaisse.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", rowEncaisse.getLong("MONTANT_REGLE"));
                    } else {
                        rowVals.put("MONTANT", rowEch.getLong("MONTANT") + rowEncaisse.getLong("MONTANT_REGLE"));
                    }
                    rowVals.update();
                }
                Configuration.getInstance().getDirectory().getElement(rowEncaisse.getTable()).archive(rowEncaisse);
            }

            // 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 row) throws Exception {

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

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

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

        List<SQLRow> l = row.getReferentRows(row.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 " + row.getID());
            Thread.dumpStack();
            return;
        }
        new GenerationReglementVenteNG(label, clientRow, ttc, row.getDate("DATE").getTime(), rowModeRegl, row, l.get(0).getForeignRow("ID_MOUVEMENT_ECHEANCE"), false, false, row.getString("TIERS"),
                row.getForeign("ID_COMPTE_PCE_TIERS"));

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

        if (!row.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";
    }
}