OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 149 | 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 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.
 */
 
 /*
 * Créé le 18 oct. 2011
 */
package org.openconcerto.erp.core.supplychain.order.element;

import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.element.StyleSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.supplychain.order.ui.EtatDemandeAchatRenderer;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLInjector;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowAccessor;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
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.view.EditFrame;
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
import org.openconcerto.sql.view.list.IListe;
import org.openconcerto.sql.view.list.RowAction;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
import org.openconcerto.utils.cc.ITransformer;

import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.swing.AbstractAction;

public class DemandeAchatItemSQLElement extends ComptaSQLConfElement {

    public DemandeAchatItemSQLElement() {
        super("DEMANDE_ACHAT_ELEMENT", "une demande d'achat", "demandes d'achat");

        {
            RowAction actionP = new RowAction(new AbstractAction("Transfert en demande de prix") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    List<SQLRowValues> rows = IListe.get(e).getSelectedRows();
                    StyleSQLElement styleElt = getDirectory().getElement(StyleSQLElement.class);
                    int idNormal = styleElt.getAllStyleByName().get("Normal");

                    SQLRowValues rowVals = new SQLRowValues(getTable().getTable("DEMANDE_PRIX"));
                    rowVals.put("DATE", new Date());
                    SQLInjector inj = SQLInjector.getInjector(getTable(), getTable().getTable("DEMANDE_PRIX_ELEMENT"));
                    for (SQLRowValues sqlRowValues : rows) {
                        SQLRow row = sqlRowValues.asRow();
                        row.fetchValues();
                        rowVals.put("ID_AFFAIRE", row.getForeignID("ID_AFFAIRE"));
                        SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row);
                        rowValsCmdElt.put("ID_STYLE", idNormal);
                        rowValsCmdElt.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
                        rowValsCmdElt.put("ID_DEMANDE_PRIX", rowVals);
                        rowValsCmdElt.put("ID_DEMANDE_ACHAT_ELEMENT", row.getID());
                        if (row.getObject("ID_ARTICLE") != null && !row.isForeignEmpty("ID_ARTICLE")) {
                            BigDecimal ha = row.getForeign("ID_ARTICLE").getBigDecimal("PA_HT");
                            rowValsCmdElt.put("PA_HT", ha);
                            rowValsCmdElt.put("PRIX_METRIQUE_HA_1", ha);
                        } else {
                            rowValsCmdElt.put("PA_HT", BigDecimal.ZERO);
                            rowValsCmdElt.put("PRIX_METRIQUE_HA_1", BigDecimal.ZERO);
                        }
                    }

                    EditFrame frame = new EditFrame(getDirectory().getElement("DEMANDE_PRIX"));
                    frame.getSQLComponent().select(rowVals);
                    FrameUtil.showPacked(frame);
                }
            }, true) {
                @Override
                public boolean enabledFor(List<SQLRowValues> selection) {
                    if (selection != null && selection.size() > 0) {
                        int idAff = -1;
                        for (SQLRowValues sqlRowValues : selection) {
                            if (getTable().contains("ID_AFFAIRE")) {
                                if (sqlRowValues.getObject("ID_AFFAIRE") != null && !sqlRowValues.isForeignEmpty("ID_AFFAIRE")) {
                                    if (idAff == -1) {
                                        idAff = sqlRowValues.getForeignID("ID_AFFAIRE");
                                    }
                                    if (idAff != sqlRowValues.getForeignID("ID_AFFAIRE")) {
                                        return false;
                                    }
                                }
                            }
                        }
                        return true;
                    }
                    return false;
                }
            };
            getRowActions().add(actionP);
        }
        {
            RowAction actionP = new RowAction(new AbstractAction("Transfert en commande") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    List<SQLRowValues> rows = IListe.get(e).getSelectedRows();
                    StyleSQLElement styleElt = getDirectory().getElement(StyleSQLElement.class);
                    int idNormal = styleElt.getAllStyleByName().get("Normal");

                    SQLRowValues rowVals = new SQLRowValues(getTable().getTable("COMMANDE"));
                    rowVals.put("DATE", new Date());
                    SQLInjector inj = SQLInjector.getInjector(getTable(), getTable().getTable("COMMANDE_ELEMENT"));
                    for (SQLRowValues sqlRowValues : rows) {
                        SQLRow row = sqlRowValues.asRow();
                        row.fetchValues();
                        rowVals.put("ID_AFFAIRE", row.getForeignID("ID_AFFAIRE"));
                        SQLRowValues rowValsCmdElt = inj.createRowValuesFrom(row);
                        rowValsCmdElt.put("ID_STYLE", idNormal);
                        rowValsCmdElt.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
                        rowValsCmdElt.put("ID_COMMANDE", rowVals);
                        rowValsCmdElt.put("ID_DEMANDE_ACHAT_ELEMENT", row.getID());
                        if (row.getObject("ID_ARTICLE") != null && !row.isForeignEmpty("ID_ARTICLE")) {
                            BigDecimal ha = row.getForeign("ID_ARTICLE").getBigDecimal("PA_HT");
                            rowValsCmdElt.put("PA_HT", ha);
                            rowValsCmdElt.put("PRIX_METRIQUE_HA_1", ha);
                        } else {
                            rowValsCmdElt.put("PA_HT", BigDecimal.ZERO);
                            rowValsCmdElt.put("PRIX_METRIQUE_HA_1", BigDecimal.ZERO);
                        }
                    }

                    EditFrame frame = new EditFrame(getDirectory().getElement("COMMANDE"));
                    frame.getSQLComponent().select(rowVals);
                    FrameUtil.showPacked(frame);
                }
            }, true) {
                @Override
                public boolean enabledFor(List<SQLRowValues> selection) {
                    if (selection != null && selection.size() > 0) {
                        int idAff = -1;
                        for (SQLRowValues sqlRowValues : selection) {
                            if (getTable().contains("ID_AFFAIRE")) {
                                if (sqlRowValues.getObject("ID_AFFAIRE") != null && !sqlRowValues.isForeignEmpty("ID_AFFAIRE")) {
                                    if (idAff == -1) {
                                        idAff = sqlRowValues.getForeignID("ID_AFFAIRE");
                                    }
                                    if (idAff != sqlRowValues.getForeignID("ID_AFFAIRE")) {
                                        return false;
                                    }
                                }
                            }
                        }
                        return true;
                    }
                    return false;
                }
            };
            getRowActions().add(actionP);
        }
    }

    public void updateStatus(final SQLTable table, final SQLTable tableElt, final int id) {
        SQLRowValues rowVals = new SQLRowValues(tableElt);
        rowVals.put("ID_DEMANDE_ACHAT_ELEMENT", null);
        SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
        fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {

            @Override
            public SQLSelect transformChecked(SQLSelect input) {

                Where w = new Where(tableElt.getField("ID_" + table.getName()), "=", id);
                w = w.and(new Where(tableElt.getField("ID_DEMANDE_ACHAT_ELEMENT"), "!=", (Object) null));
                w = w.and(new Where(tableElt.getField("ID_DEMANDE_ACHAT_ELEMENT"), ">", 1));
                input.setWhere(w);

                return input;
            }
        });

        List<SQLRowValues> result = fetcher.fetch();
        List<Integer> ids = new ArrayList<Integer>();
        for (SQLRowValues sqlRowValues : result) {
            ids.add(sqlRowValues.getForeignID("ID_DEMANDE_ACHAT_ELEMENT"));
        }
        updateAllStatus(ids);
    }

    private void updateAllStatus(final List<Integer> ids) {

        SQLRowValues rowVals = new SQLRowValues(getTable());
        rowVals.put("QTE", null);
        rowVals.put("ID_ETAT_DEMANDE_ACHAT_ELEMENT", null);

        final List<String> refTable = Arrays.asList("COMMANDE_ELEMENT", "DEMANDE_PRIX_ELEMENT", "BON_RECEPTION_ELEMENT");
        for (String tableName : refTable) {
            SQLRowValues rowValsRef = new SQLRowValues(getTable().getTable(tableName));
            rowValsRef.put("QTE", null);
            rowValsRef.put("ID_DEMANDE_ACHAT_ELEMENT", rowVals);
            rowValsRef.put("QTE_UNITAIRE", null);
            rowValsRef.put("ID_" + tableName.replaceAll("_ELEMENT", ""), null);
        }

        SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
        fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {

            @Override
            public SQLSelect transformChecked(SQLSelect input) {

                input.setWhere(new Where(input.getTable("DEMANDE_ACHAT_ELEMENT").getKey(), ids));

                return input;
            }
        });
        final List<SQLRowValues> result = fetcher.fetch();
        for (SQLRowValues sqlRowValues : result) {
            updateStatus(sqlRowValues);
        }
    }

    private void updateStatus(SQLRowValues rowValsDmd) {
        Collection<SQLRowValues> rowValsBR = rowValsDmd.getReferentRows(getTable().getTable("BON_RECEPTION_ELEMENT"));
        int newStatus = EtatDemandeAchatItemSQLElement.EN_ATTENTE;
        final SQLRowValues createEmptyUpdateRow = rowValsDmd.createEmptyUpdateRow();
        if (!rowValsBR.isEmpty()) {
            int qte = 0;
            int idBR = 1;
            for (SQLRowValues sqlRowValues : rowValsBR) {
                qte += sqlRowValues.getInt("QTE");
                idBR = sqlRowValues.getForeignID("ID_BON_RECEPTION");
            }
            if (qte > 0) {
                createEmptyUpdateRow.put("ID_BON_RECEPTION", idBR);
                createEmptyUpdateRow.put("QTE_RECUE", qte);
                if (qte >= rowValsDmd.getInt("QTE")) {
                    newStatus = EtatDemandeAchatItemSQLElement.RECPETION;
                } else {
                    newStatus = EtatDemandeAchatItemSQLElement.RECPETION_PARTIEL;
                }
            }
        } else {
            Collection<SQLRowValues> rowValsCmd = rowValsDmd.getReferentRows(getTable().getTable("COMMANDE_ELEMENT"));
            if (!rowValsCmd.isEmpty()) {
                createEmptyUpdateRow.put("ID_COMMANDE", rowValsCmd.iterator().next().getForeignID("ID_COMMANDE"));
                newStatus = EtatDemandeAchatItemSQLElement.COMMANDE;
            } else {
                Collection<SQLRowValues> rowValsDmdElt = rowValsDmd.getReferentRows(getTable().getTable("DEMANDE_PRIX_ELEMENT"));
                if (!rowValsDmdElt.isEmpty()) {
                    newStatus = EtatDemandeAchatItemSQLElement.DEMANDE;
                }

            }
        }

        // if (newStatus != rowValsDmd.getForeignID("ID_ETAT_DEMANDE_ACHAT_ELEMENT")) {
        try {

            createEmptyUpdateRow.put("ID_ETAT_DEMANDE_ACHAT_ELEMENT", newStatus).commit();
        } catch (SQLException e) {
            ExceptionHandler.handle("Erreur lors la mise à jour de l'état de la demande d'achat [" + rowValsDmd.getID() + "]", e);
        }
        // }
    }

    @Override
    protected List<String> getListFields() {
        final List<String> l = new ArrayList<String>();

        l.add("REVISION");
        l.add("CODE");
        l.add("NOM");
        l.add("QTE_UNITAIRE");
        l.add("ID_UNITE_VENTE");
        l.add("QTE");
        l.add("ID_FABRICANT");
        l.add("ID_FOURNISSEUR");
        l.add("CODE_SOURCE");
        l.add("NOM_SOURCE");
        l.add("ID_COMMANDE");
        l.add("ID_BON_RECEPTION");
        l.add("QTE_RECUE");
        l.add("ID_ETAT_DEMANDE_ACHAT_ELEMENT");
        return l;
    }

    @Override
    protected void _initTableSource(SQLTableModelSource res) {
        final SQLTable foreignTable = getTable().getForeignTable("ID_ETAT_DEMANDE_ACHAT_ELEMENT");
        res.init();
        res.getColumn(foreignTable.getField("NOM")).setRenderer(new EtatDemandeAchatRenderer(foreignTable));

        BaseSQLTableModelColumn dpt = new BaseSQLTableModelColumn("Prix", BigDecimal.class) {

            @Override
            protected Object show_(SQLRowAccessor r) {

                if (r.getObject("ID_ARTICLE") != null && !r.isForeignEmpty("ID_ARTICLE")) {
                    SQLRowAccessor rA = r.getForeign("ID_ARTICLE");
                    return rA.getBigDecimal("PA_HT");
                } else {
                    return null;
                }
            }

            @Override
            public Set<FieldPath> getPaths() {
                Path p = new Path(getTable());
                final SQLTable clientT = getTable().getForeignTable("ID_ARTICLE");
                p = p.add(clientT);
                return CollectionUtils.createSet(new FieldPath(p, "PA_HT"));
            }
        };

        res.getColumns().add(dpt);

        super._initTableSource(res);
    }

    // @Override
    // public Set<String> getReadOnlyFields() {
    // Set<String> s = new HashSet<String>(super.getReadOnlyFields());
    // s.add("NUMERO_CARTE");
    // return s;
    // }

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

    @Override
    public ListMap<String, String> getShowAs() {
        return ListMap.singleton(null, "CODE", "NOM");
    }

    @Override
    public SQLComponent createComponent() {
        return new DemandeAchatItemSQLComponent(this);
    }

    @Override
    protected String createCode() {
        return createCodeFromPackage() + ".demande.achat";
    }

}