OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 182 | 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.sales.product.element;

import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.config.update.Updater_1_5;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
import org.openconcerto.erp.core.common.ui.NumberCellRenderer;
import org.openconcerto.erp.core.edm.AttachmentAction;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.reports.history.ui.HistoriqueArticleFrame;
import org.openconcerto.erp.core.sales.product.action.InitializeStockPanel;
import org.openconcerto.erp.core.sales.product.action.InventairePanel;
import org.openconcerto.erp.core.sales.product.action.TransfertStockFromArticlePanel;
import org.openconcerto.erp.core.sales.product.component.ReferenceArticleSQLComponent;
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
import org.openconcerto.erp.core.supplychain.stock.action.ListeDesMouvementsStockAction;
import org.openconcerto.erp.core.supplychain.stock.element.ComposedItemStockUpdater;
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
import org.openconcerto.erp.core.supplychain.stock.element.StockConsultPanel;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem;
import org.openconcerto.erp.core.supplychain.stock.element.StockItem.TypeStockMouvement;
import org.openconcerto.erp.generationDoc.gestcomm.FicheArticleXmlSheet;
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
import org.openconcerto.erp.preferences.DefaultNXProps;
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
import org.openconcerto.sql.model.DBRoot;
import org.openconcerto.sql.model.DBSystemRoot;
import org.openconcerto.sql.model.FieldPath;
import org.openconcerto.sql.model.SQLDataSource;
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.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.preferences.SQLPreferences;
import org.openconcerto.sql.request.ComboSQLRequest;
import org.openconcerto.sql.request.ComboSQLRequest.KeepMode;
import org.openconcerto.sql.request.ListSQLRequest;
import org.openconcerto.sql.users.rights.UserRightsManager;
import org.openconcerto.sql.utils.SQLUtils;
import org.openconcerto.sql.view.EditFrame;
import org.openconcerto.sql.view.EditPanel.EditMode;
import org.openconcerto.sql.view.ListeAddPanel;
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;
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
import org.openconcerto.sql.view.list.SQLTableModelColumn;
import org.openconcerto.sql.view.list.SQLTableModelSource;
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
import org.openconcerto.sql.view.list.action.ListEvent;
import org.openconcerto.ui.DefaultGridBagConstraints;
import org.openconcerto.ui.FrameUtil;
import org.openconcerto.ui.PanelFrame;
import org.openconcerto.utils.CollectionUtils;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;
import org.openconcerto.utils.ListMap;
import org.openconcerto.utils.Tuple2;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;

public class ReferenceArticleSQLElement extends ComptaSQLConfElement {
    public static final int AU_METRE_LONGUEUR = 2;
    public static final int AU_METRE_CARRE = 3;
    public static final int AU_POID_METRECARRE = 4;
    public static final int A_LA_PIECE = 5;
    public static final int AU_METRE_LARGEUR = 6;
    public static final int AU_KILO = 7;
    private static final int PRIX_HA = 1;
    private static final int PRIX_VT = 2;
    protected PredicateRowAction stock;

    public static final String[] CONDITIONS = new String[] { "CFR", "CIF", "CPT", "DAT", "DDP", "DDU", "EXW", "FCA", "FOB" };

    public ReferenceArticleSQLElement() {
        super("ARTICLE", "un article", "articles");
        NumerotationAutoSQLElement.addClass(this.getClass(), "ARTICLE");

        getRowActions().addAll(new MouseSheetXmlListeListener(this, FicheArticleXmlSheet.class).getRowActions());
        this.stock = new PredicateRowAction(new AbstractAction("Mettre à jour les stocks") {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (UserRightsManager.getCurrentUserRights().canAdd(getTable().getDBRoot().getTable("STOCK"))) {

                    try {
                        final List<SQLRowAccessor> selectedRows = IListe.get(e).getSelectedRowAccessors();
                        List<SQLRowAccessor> l = new ArrayList<SQLRowAccessor>();
                        for (SQLRowAccessor sqlRowValues : selectedRows) {

                            final SQLRowAccessor stock = sqlRowValues.asRow().getNonEmptyForeign("ID_STOCK");
                            if (stock != null) {
                                l.add(stock);
                            } else {
                                SQLRowValues rowValsArt = sqlRowValues.createEmptyUpdateRow();
                                SQLRowValues insert = rowValsArt.putRowValues("ID_STOCK");
                                insert.put("ID_ARTICLE", sqlRowValues.getID());
                                insert.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);

                                l.add(rowValsArt.commit().getForeign("ID_STOCK"));
                            }
                        }

                        PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), l), "Mise à jour des stocks");
                        FrameUtil.show(p);
                    } catch (SQLException e1) {
                        ExceptionHandler.handle("Erreur lors de la mise à jour du stock", e1);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Vous n'avez les droits suffisants pour modifier manuellement les stocks!");
                }

            }
        }, true, false);
        stock.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
        getRowActions().add(stock);

        final SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false) && UserRightsManager.getCurrentUserRights().canAdd(getTable().getDBRoot().getTable("STOCK"))) {

            RowAction actionConvVirtuel = new PredicateRowAction(new AbstractAction("Initialiser les stocks") {

                @Override
                public void actionPerformed(ActionEvent e) {

                    PanelFrame frame = new PanelFrame(new InitializeStockPanel(ReferenceArticleSQLElement.this, IListe.get(e).getSelectedRowAccessors()), "Initialisation du stock");
                    FrameUtil.showPacked(frame);

                }
            }, true, false).setPredicate(ListEvent.getNonEmptySelectionPredicate());
            getRowActions().add(actionConvVirtuel);

            RowAction actionTransfert = new RowAction(new AbstractAction("Transfert de stock") {

                @Override
                public void actionPerformed(ActionEvent e) {

                    final SQLRowAccessor selectedRowAccessor = IListe.get(e).getSelectedRowAccessor().fetchNewRow(false);
                    PanelFrame frame = new PanelFrame(new TransfertStockFromArticlePanel(ComptaPropsConfiguration.getInstance(), selectedRowAccessor, null), "Transfert de stock");
                    FrameUtil.showPacked(frame);
                    frame.setLocationRelativeTo(IListe.get(e));
                }
            }, true, false) {

                @Override
                public boolean enabledFor(ListEvent evt) {
                    return evt.getSelectedRowAccessors().size() == 1 && evt.getSelectedRowAccessors().get(0).getBoolean("GESTION_STOCK");
                }
            };
            getRowActions().add(actionTransfert);

            RowAction actionStockShow = new RowAction(new AbstractAction("Consulter le stock") {

                @Override
                public void actionPerformed(ActionEvent e) {

                    final StockConsultPanel p = new StockConsultPanel(ReferenceArticleSQLElement.this, IListe.get(e).getSelectedRowAccessor());
                    // p.load(IListe.get(e).getSelectedRowAccessor());
                    PanelFrame frame = new PanelFrame(p, "Consultation du stock");
                    FrameUtil.showPacked(frame);
                    frame.setLocationRelativeTo(IListe.get(e));
                }
            }, true, false) {

                @Override
                public boolean enabledFor(ListEvent evt) {
                    return evt.getSelectedRowAccessors().size() == 1 && evt.getSelectedRowAccessors().get(0).getBoolean("GESTION_STOCK");
                }
            };
            getRowActions().add(actionStockShow);

        }
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false)) {

            RowAction actionConvVirtuel = new RowAction(new AbstractAction("Convertir en article virtuel") {

                @Override
                public void actionPerformed(ActionEvent e) {

                    final SQLRowAccessor selectedRow = IListe.get(e).getSelectedRowAccessor();
                    try {
                        selectedRow.createEmptyUpdateRow().put("VIRTUEL", Boolean.TRUE).commit();
                    } catch (SQLException e1) {
                        ExceptionHandler.handle("Erreur lors de la conversion de l'article en virtuel", e1);
                    }

                }
            }, true, false) {

                @Override
                public boolean enabledFor(ListEvent evt) {
                    final List<? extends SQLRowAccessor> selection = evt.getSelectedRowAccessors();
                    if (selection.size() == 1) {
                        return !selection.get(0).getBoolean("VIRTUEL") && selection.get(0).isForeignEmpty("ID_ARTICLE_VIRTUEL_PERE");

                    }
                    return false;
                }
            };
            getRowActions().add(actionConvVirtuel);

            RowAction actionCreateDecl = new RowAction(new AbstractAction("Créer une déclinaison") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
                    ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(IListe.get(e).getSelectedRowAccessor().asRow());
                    for (SQLRow child : children.allValues()) {
                        if (!child.getTable().getName().equals("STOCK")) {
                            Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
                        }
                    }
                    rowVals.put("ID_ARTICLE_VIRTUEL_PERE", IListe.get(e).getSelectedId());
                    rowVals.put("VIRTUEL", Boolean.FALSE);
                    rowVals.putEmptyLink("ID_STOCK");

                    EditFrame f = new EditFrame(createComponent(), EditMode.CREATION);
                    f.getSQLComponent().select(rowVals);
                    FrameUtil.show(f);

                }
            }, true, false) {

                @Override
                public boolean enabledFor(ListEvent evt) {
                    final List<? extends SQLRowAccessor> selection = evt.getSelectedRowAccessors();
                    if (selection.size() == 1) {
                        return selection.get(0).getBoolean("VIRTUEL");
                    }
                    return false;
                }
            };
            getRowActions().add(actionCreateDecl);

            RowAction actionCreateDecls = new RowAction(new AbstractAction("Créer des déclinaisons") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
                    final SQLRow selectedRow = IListe.get(e).getSelectedRowAccessor().asRow();
                    ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(selectedRow);
                    for (SQLRow child : children.allValues()) {
                        if (!child.getTable().getName().equals("STOCK")) {
                            Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
                        }
                    }
                    rowVals.put("ID_ARTICLE_VIRTUEL_PERE", IListe.get(e).getSelectedId());
                    rowVals.put("VIRTUEL", Boolean.FALSE);
                    rowVals.putEmptyLink("ID_STOCK");

                    NouvellesDeclinaisonsFrame f = new NouvellesDeclinaisonsFrame(ReferenceArticleSQLElement.this, selectedRow);
                    f.pack();
                    f.setLocationRelativeTo(null);
                    FrameUtil.show(f);

                }
            }, false, true) {

                @Override
                public boolean enabledFor(ListEvent evt) {
                    final List<? extends SQLRowAccessor> selection = evt.getSelectedRowAccessors();
                    if (selection.size() == 1) {
                        return selection.get(0).getBoolean("VIRTUEL");
                    }
                    return false;
                }
            };
            getRowActions().add(actionCreateDecls);

        }

        PredicateRowAction history = new PredicateRowAction(new AbstractAction("Historique") {

            @Override
            public void actionPerformed(ActionEvent e) {
                HistoriqueArticleFrame frame = new HistoriqueArticleFrame(ReferenceArticleSQLElement.this);
                frame.selectId(IListe.get(e).getSelectedId());
                frame.setVisible(true);
            }
        }, false, true);
        history.setPredicate(IListeEvent.getSingleSelectionPredicate());
        getRowActions().add(history);

        PredicateRowAction mvtStock = new PredicateRowAction(new AbstractAction("Consulter les mouvements de stocks") {

            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame frame = new ListeDesMouvementsStockAction(ComptaPropsConfiguration.getInstanceCompta(), IListe.get(e).getSelectedRowAccessor()).getFrame();
                frame.setVisible(true);
            }
        }, false, true);
        mvtStock.setPredicate(IListeEvent.getSingleSelectionPredicate());
        getRowActions().add(mvtStock);

        PredicateRowAction batches = new PredicateRowAction(new AbstractAction("Lots et numéros de série") {
            @Override
            public void actionPerformed(ActionEvent e) {
                ListeDesLotsAction action = new ListeDesLotsAction(ReferenceArticleSQLElement.this.getDirectory(), IListe.get(e).getSelectedRowAccessor());
                action.actionPerformed(e);
            }
        }, false, true);
        batches.setPredicate(IListeEvent.getSingleSelectionPredicate());
        getRowActions().add(batches);

        PredicateRowAction clone = new PredicateRowAction(new AbstractAction("Dupliquer") {

            @Override
            public void actionPerformed(ActionEvent e) {

                SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
                ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(IListe.get(e).getSelectedRowAccessor().asRow());
                for (SQLRow child : children.allValues()) {
                    Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
                }
                EditFrame f = new EditFrame(createComponent(), EditMode.CREATION);
                f.getSQLComponent().select(rowVals);
                FrameUtil.show(f);

            }
        }, true, false);
        clone.setPredicate(IListeEvent.getSingleSelectionPredicate());
        getRowActions().add(clone);

        PredicateRowAction actionAttachment = new PredicateRowAction(new AttachmentAction().getAction(), true);
        actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());

        getRowActions().add(actionAttachment);

        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false)) {

            PredicateRowAction actionADeclinaison = new PredicateRowAction(new AbstractAction("Gérer les déclinaisons") {

                @Override
                public void actionPerformed(ActionEvent e) {
                    List<SQLElement> declElts = new ArrayList<>();
                    for (SQLTable table : getTable().getDBRoot().getTables()) {
                        if (table.getName().startsWith("ARTICLE_DECLINAISON_")) {
                            declElts.add(getDirectory().getElement(table));
                        }
                    }

                    JTabbedPane tabs = new JTabbedPane();
                    for (SQLElement elt : declElts) {
                        final IListe liste = new IListe(elt.createTableSource());
                        ListeAddPanel panel = new ListeAddPanel(elt, liste);
                        tabs.add(elt.getPluralName(), panel);
                    }

                    JPanel panel = new JPanel(new GridBagLayout());
                    GridBagConstraints c = new DefaultGridBagConstraints();
                    c.fill = GridBagConstraints.BOTH;
                    c.weightx = 1;
                    c.weighty = 1;
                    panel.add(tabs, c);
                    PanelFrame frame = new PanelFrame(panel, "Liste des déclinaisons");
                    FrameUtil.showPacked(frame);
                }
            }, true);
            actionADeclinaison.setPredicate(IListeEvent.createTotalRowCountPredicate(0, Integer.MAX_VALUE));
            getRowActions().add(actionADeclinaison);
        }
    }

    @Override
    protected SQLTableModelSourceOnline instantiateTableSourceOnline(ListSQLRequest req) {
        return new SQLTableModelSourceOnline(req, this, KeepMode.ROW);
    }

    @Override
    protected synchronized void _initTableSource(final SQLTableModelSource source) {
        super._initTableSource(source);
        source.getReq().addToGraphToFetch("ID_ARTICLE_VIRTUEL_PERE", "VIRTUEL", "ID_DEPOT_STOCK");
        source.init();
        final SQLTableModelColumn pvHA1Col = source.getColumn(getTable().getField("PRIX_METRIQUE_HA_1"));
        if (pvHA1Col != null) {
            pvHA1Col.setRenderer(CURRENCY_RENDERER);
        }

        final SQLTableModelColumn pvHT1Col = source.getColumn(getTable().getField("PRIX_METRIQUE_VT_1"));
        if (pvHT1Col != null) {
            pvHT1Col.setRenderer(CURRENCY_RENDERER);
        }

        final SQLTableModelColumn pvHTCol = source.getColumn(getTable().getField("PV_HT"));
        if (pvHTCol != null) {
            pvHTCol.setRenderer(CURRENCY_RENDERER);
        }
        final SQLTableModelColumn pvTTCCol = source.getColumn(getTable().getField("PV_TTC"));
        if (pvTTCCol != null) {
            pvTTCCol.setRenderer(CURRENCY_RENDERER);
        }
        final SQLTableModelColumn paHTCol = source.getColumn(getTable().getField("PA_HT"));
        if (paHTCol != null) {
            paHTCol.setRenderer(CURRENCY_RENDERER);
        }

        final SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());

        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
            final BaseSQLTableModelColumn colStockGlobal = new BaseSQLTableModelColumn("Stock Global", BigDecimal.class) {

                @Override
                protected Object show_(SQLRowAccessor r) {

                    if (!r.getBoolean("GESTION_STOCK")) {
                        return null;
                    }
                    BigDecimal totalQte = BigDecimal.ZERO;

                    Collection<? extends SQLRowAccessor> stockElt = r.getReferentRows(getTable().getTable("STOCK").getField("ID_ARTICLE"));
                    for (SQLRowAccessor rowElt : stockElt) {
                        BigDecimal qteCmd = new BigDecimal(rowElt.getFloat("QTE_REEL"));
                        totalQte = totalQte.add(qteCmd);
                    }
                    return totalQte;
                }

                @Override
                public Set<FieldPath> getPaths() {
                    final Path p = new Path(getTable());
                    Path p2 = p.add(getTable().getTable("STOCK").getField("ID_ARTICLE"));

                    return CollectionUtils.createSet(new FieldPath(p, "GESTION_STOCK"), new FieldPath(p2, "QTE_REEL"));
                }
            };
            colStockGlobal.setRenderer(new NumberCellRenderer());
            source.getColumns().add(colStockGlobal);
        }

        if (getTable().getDBRoot().contains("ARTICLE_ELEMENT") && !getTable().getDBRoot().contains("TARIF_AGENCE")) {
            source.getColumns().add(new BaseSQLTableModelColumn("Type", String.class) {

                @Override
                protected Object show_(SQLRowAccessor r) {

                    Collection<? extends SQLRowAccessor> c = r.getReferentRows(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
                    if (c.size() == 0) {
                        // "Article simple"
                        return "Article simple";
                    } else {
                        // "Kit
                        return "Nomenclature";
                    }
                }

                @Override
                public Set<FieldPath> getPaths() {
                    Path p = new Path(getTable());
                    p = p.add(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
                    return CollectionUtils.createSet(new FieldPath(p, "QTE"));
                }

            });
        }
    }

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

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

        l.add("CODE");
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
            l.add("CODE_BARRE");
        }
        l.add("NOM");
        String articleAdvanced = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
        Boolean bArticleAdvanced = Boolean.valueOf(articleAdvanced);

        if (bArticleAdvanced) {
            l.add("POIDS");
            l.add("PRIX_METRIQUE_HA_1");
            l.add("PRIX_METRIQUE_VT_1");
        }
        l.add("PA_HT");
        l.add("PV_HT");
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_TAXE, false)) {
            l.add("ID_TAXE");
        }
        l.add("PV_TTC");
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_COMPTE, false)) {
            l.add("ID_COMPTE_PCE");
            l.add("ID_COMPTE_PCE_ACHAT");
        }
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_FAMILLE, false)) {
            l.add("ID_FAMILLE_ARTICLE");
        }
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_FOURNISSEUR, false)) {
            l.add("ID_FOURNISSEUR");
        }
        l.add("POIDS");
        l.add("SKU");

        if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
            l.add("GESTION_STOCK");
            l.add("ID_STOCK");
        }
        String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
        Boolean b = Boolean.valueOf(val);
        if (b != null && b.booleanValue()) {
            l.add("SERVICE");
        }

        return l;
    }

    @Override
    public ListMap<String, String> getShowAs() {
        final ListMap<String, String> res = new ListMap<String, String>();
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
            res.add(null, "CODE_BARRE");
        }
        List<String> fieldDecl = new ArrayList<>();

        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false)) {

            for (String fieldName : getTable().getFieldsName()) {
                if (fieldName.startsWith("ID_ARTICLE_DECLINAISON_")) {
                    fieldDecl.add(fieldName);
                }
            }
        }
        res.addAll(null, "CODE", "NOM", "ID_FAMILLE_ARTICLE", "ID_FOURNISSEUR");
        res.addAll(null, fieldDecl);
        return res;
    }

    protected List<String> getComboFields() {
        final List<String> l = new ArrayList<String>();
        l.add("CODE");
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
            l.add("CODE_BARRE");
        }

        l.add("NOM");
        List<String> fieldDecl = new ArrayList<>();
        for (String fieldName : getTable().getFieldsName()) {
            if (fieldName.startsWith("ID_ARTICLE_DECLINAISON_")) {
                fieldDecl.add(fieldName);
            }
        }
        l.addAll(fieldDecl);
        l.add("PA_HT");
        l.add("PV_HT");
        l.add("DERNIER_DATE_ACHAT");
        return l;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.openconcerto.devis.SQLElement#getComponent()
     */
    public SQLComponent createComponent() {

        return new ReferenceArticleSQLComponent(this);
    }

    /**
     * Calcul le prix d'HA total par rapport aux metriques
     * 
     * @param rowVals
     * @return le prix d'achat en centimes
     */
    public static BigDecimal getPrixHAFromDetails(SQLRowValues rowVals) {
        return getValuePiece(rowVals, PRIX_HA);
    }

    /**
     * Calcul le prix de VT total par rapport aux metriques
     * 
     * @param rowVals
     * @return le prix de vente en centimes
     */
    public static BigDecimal getPrixVTFromDetails(SQLRowValues rowVals) {
        return getValuePiece(rowVals, PRIX_VT);
    }

    /**
     * Calcul le poids total par rapport aux metriques
     * 
     * @param rowVals
     * @return le poids total arrondi à trois chiffres apres la virgule
     */
    public static float getPoidsFromDetails(SQLRowValues rowVals) {

        // Valeur
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");

        final float produit = valMetrique1 * valMetrique2 * valMetrique3;
        if (produit > 0.0F) {
            return Math.round(produit * 1000.0F) / 1000.0F;
        }
        if (rowVals.getObject("POIDS") != null) {
            float p = rowVals.getFloat("POIDS");
            return p;
        }
        return 0.0F;
    }

    private static BigDecimal getValuePiece(SQLRowValues rowVals, int value) {
        if (rowVals.getObject("ID_MODE_VENTE_ARTICLE") == null) {
            throw new IllegalArgumentException("La SQLRowValues ne contient pas ID_MODE_VENTE_ARTICLE");
        }
        int mode = rowVals.getInt("ID_MODE_VENTE_ARTICLE");
        if (mode == 1) {
            mode = A_LA_PIECE;
        }
        // prix HA
        BigDecimal metrique1HA = rowVals.getObject("PRIX_METRIQUE_HA_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_HA_1"));

        // Prix VT
        BigDecimal metrique1VT = rowVals.getObject("PRIX_METRIQUE_VT_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_VT_1"));

        // Valeur
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");

        // Mode de vente au metre carré
        if (mode == AU_METRE_CARRE) {
            float surface = valMetrique1 * valMetrique2;
            if (value == PRIX_HA) {
                return metrique1HA.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
            }
            return metrique1VT.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
        }
        // Mode de vente au metre, largeur
        if (mode == AU_METRE_LARGEUR) {
            if (value == PRIX_HA) {
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
            }
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
        }
        // Mode de vente au metre, longueur
        if (mode == AU_METRE_LONGUEUR) {
            if (value == PRIX_HA) {
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
            }
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
        }
        // Mode de vente au poids / m2
        if (mode == AU_POID_METRECARRE) {
            float surface = valMetrique1 * valMetrique2;
            float p = surface * valMetrique3;
            if (value == PRIX_HA) {
                return metrique1HA.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
            }
            return metrique1VT.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
        }

        // Mode de vente à la piece et autres
        if (value == PRIX_HA) {
            if (rowVals.getObject("PA_HT") != null) {
                return (BigDecimal) rowVals.getObject("PA_HT");
            }
            return BigDecimal.ZERO;
        }
        if (rowVals.getObject("PV_HT") != null) {
            return (BigDecimal) rowVals.getObject("PV_HT");
        }
        return BigDecimal.ZERO;

    }

    /**
     * retourne l'id d'un article ayant le meme Code, Nom et valeur Metrique, le cas échéant -1
     * 
     * @param row
     * @param createIfNotExist
     * @return id de l'article correspondant
     */
    public static int getIdForCNM(SQLRowValues row, boolean createIfNotExist) {
        return getIdFor(row, true, createIfNotExist);
    }

    /**
     * retourne l'id d'un article ayant le meme Code, Nom le cas échéant -1
     * 
     * @param row
     * @param createIfNotExist
     * @return id de l'article correspondant
     */
    public static int getIdForCN(SQLRowValues row, boolean createIfNotExist) {

        return getIdFor(row, false, createIfNotExist);
    }

    @SuppressWarnings("rawtypes")
    private static int getIdFor(SQLRowValues row, boolean includeMetrique, boolean createIfNotExist) {

        // On cherche l'article qui lui correspond
        SQLTable tableArt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(tableArt);
        String req = getMatchRequest(row, includeMetrique);
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());

        if (result != null && result.size() != 0) {
            Object[] tmp = (Object[]) result.get(0);
            return ((Number) tmp[0]).intValue();
        }

        if (createIfNotExist && row.getString("CODE") != null && row.getString("CODE").trim().length() > 0 && row.getString("NOM") != null && row.getString("NOM").trim().length() > 0) {
            SQLRowValues vals = new SQLRowValues(row);
            BigDecimal taux = BigDecimal.ONE.add(new BigDecimal(TaxeCache.getCache().getTauxFromId(row.getForeignID("ID_TAXE")) / 100f));
            vals.put("PV_TTC", vals.getBigDecimal("PV_HT").multiply(taux));
            vals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
            int idArticle;
            try {

                // Liaison avec l'article fournisseur si il existe
                SQLSelect selMatchingCodeF = new SQLSelect();
                final SQLTable table = tableArt.getTable("ARTICLE_FOURNISSEUR");
                selMatchingCodeF.addSelect(table.getKey());
                selMatchingCodeF.addSelect(table.getField("ID_FOURNISSEUR"));
                selMatchingCodeF.addSelect(table.getField("CODE_BARRE"));
                Where wMatchingCodeF = new Where(table.getField("CODE"), "=", vals.getString("CODE"));
                wMatchingCodeF = wMatchingCodeF.and(new Where(table.getField("NOM"), "=", vals.getString("NOM")));
                selMatchingCodeF.setWhere(wMatchingCodeF);

                // FIXME utiliser une transaction bloquante sur la table
                List<SQLRow> l = SQLRowListRSH.execute(selMatchingCodeF, false, false);
                if (l.size() > 0) {
                    SQLRowValues rowVals = l.get(0).asRowValues();
                    vals.put("ID_FOURNISSEUR", rowVals.getObject("ID_FOURNISSEUR"));
                    vals.put("CODE_BARRE", rowVals.getObject("CODE_BARRE"));
                    vals.put("QTE_ACHAT", rowVals.getObject("QTE_ACHAT"));
                    SQLRow rowNew = vals.insert();
                    idArticle = rowNew.getID();
                    rowVals.put("ID_ARTICLE", idArticle);
                    rowVals.commit();
                } else {
                    SQLSelect selMatchingCodeArticle = new SQLSelect();
                    selMatchingCodeArticle.addSelect(tableArt.getKey());
                    Where wMatchingCode = new Where(tableArt.getField("CODE"), "=", vals.getString("CODE"));
                    wMatchingCode = wMatchingCode.and(new Where(tableArt.getField("NOM"), "=", vals.getString("NOM")));
                    selMatchingCodeArticle.setWhere(wMatchingCode);
                    List<SQLRow> matchingArticles = SQLRowListRSH.execute(selMatchingCodeArticle, false, false);
                    if (matchingArticles.size() > 0) {
                        idArticle = matchingArticles.get(0).getID();
                    } else {
                        Collection<SQLRowValues> refTarif = row.getReferentRows(row.getTable().getTable("ARTICLE_TARIF_FOURNISSEUR"));
                        if (!refTarif.isEmpty()) {
                            for (SQLRowValues sqlRowValues : refTarif) {
                                SQLRowValues rowValsTarif = new SQLRowValues(sqlRowValues);
                                rowValsTarif.put("ID_ARTICLE", vals);
                            }
                        }

                        SQLRow rowNew = vals.insert();
                        idArticle = rowNew.getID();
                    }
                }
                return idArticle;
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return -1;

    }

    /**
     * teste si un article ayant le meme nom et code existe
     * 
     * @param row
     * @return true si au moins un article correspond
     */
    public static boolean isArticleForCNExist(SQLRowValues row) {
        return isArticleMatchExist(row, false);
    }

    /**
     * teste si un article ayant le meme nom, code et valeur metrique existe
     * 
     * @param row
     * @return true si au moins un article correspond
     */
    public static boolean isArticleForCNMExist(SQLRowValues row) {
        return isArticleMatchExist(row, true);
    }

    @SuppressWarnings("rawtypes")
    private static boolean isArticleMatchExist(SQLRowValues row, boolean includeMetrique) {
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
        String req = getMatchRequest(row, includeMetrique);
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());

        return (result != null && result.size() != 0);
    }

    private static String getMatchRequest(SQLRowValues row, boolean includeMetrique) {
        // On cherche l'article qui lui correspond
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
        SQLSelect sel = new SQLSelect(eltArticle.getTable().getBase());
        sel.addSelect(eltArticle.getTable().getField("ID"));

        Where w = new Where(eltArticle.getTable().getField("CODE"), "=", row.getString("CODE").trim());
        if (includeMetrique) {

            float value1 = ((Number) row.getObject("VALEUR_METRIQUE_1")).floatValue();
            float value2 = ((Number) row.getObject("VALEUR_METRIQUE_2")).floatValue();
            float value3 = ((Number) row.getObject("VALEUR_METRIQUE_3")).floatValue();
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), "<=", new Float(value1 + 0.00001)));
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), ">=", new Float(value1 - 0.00001)));

            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), "<=", new Float(value2 + 0.00001)));
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), ">=", new Float(value2 - 0.00001)));

            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), "<=", new Float(value3 + 0.00001)));
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), ">=", new Float(value3 - 0.00001)));

        }
        sel.setWhere(w);
        return sel.asString();
    }

    public static boolean isReferenceEquals(SQLRowValues rowVals1, SQLRowValues rowVals2) {
        return (rowVals1.getObject("CODE").equals(rowVals2.getObject("CODE")) && rowVals1.getString("VALEUR_METRIQUE_1").equals(rowVals2.getString("VALEUR_METRIQUE_1"))
                && rowVals1.getString("VALEUR_METRIQUE_2").equals(rowVals2.getString("VALEUR_METRIQUE_2")) && rowVals1.getString("VALEUR_METRIQUE_3").equals(rowVals2.getString("VALEUR_METRIQUE_3")));
    }

    public void initStock(int id) {
        SQLRow row = getTable().getRow(id);
        Updater_1_5.initStock(row);
    }

    @Override
    protected String createCode() {
        return createCodeOfPackage() + ".ref";
    }

    @Override
    protected void _initComboRequest(ComboSQLRequest req) {
        super._initComboRequest(req);
        req.addToGraphToFetch("ID_DEPOT_STOCK");
        req.setWhere(new Where(getTable().getField("VIRTUEL"), "=", Boolean.FALSE));

    }

    static public void updateDateAchat(final SQLTable tableArticle, final SQLRow article) {

        assert article == null || article.getTable() == tableArticle;
        SQLTable tableTarifF = tableArticle.getTable("ARTICLE_TARIF_FOURNISSEUR");
        String up = "UPDATE " + tableArticle.getSQLName().quote() + " a SET " + tableArticle.getField("DERNIER_DATE_ACHAT").getQuotedName();
        up += " =(select MAX(" + tableTarifF.getField("DATE_PRIX").getQuotedName() + ")  ";
        up += " FROM " + tableTarifF.getSQLName().quote() + "  t" + " WHERE (t." + tableTarifF.getKey().getQuotedName() + " <> 1) ";
        up += " AND (t." + tableTarifF.getField("ARCHIVE").getQuotedName() + " = 0) ";
        up += "AND t." + tableTarifF.getField("ID_ARTICLE").getQuotedName() + " = " + (article == null ? "a." + tableArticle.getKey().getQuotedName() : article.getID()) + ")";
        if (article != null) {
            up += "WHERE " + tableArticle.getKey().getQuotedName() + " = " + article.getID();
        }

        tableArticle.getDBSystemRoot().getDataSource().execute(up);
    }

    /**
     * Création des déclinaisons tailles/couleurs à partir de l'article virtuel passé en parametre
     * 
     * @param idArticlePere
     * @param tupleTailleCouleur
     * @throws SQLException
     */
    public void createDeclinaison(int idArticlePere, List<Tuple2<SQLRow, SQLRow>> tupleTailleCouleur) throws SQLException {

        final SQLRow row = getTable().getRow(idArticlePere);
        if (!row.getBoolean("VIRTUEL")) {
            throw new IllegalArgumentException("L'article n'est pas un article virtuel");
        }
        ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(row);
        for (Tuple2<SQLRow, SQLRow> t : tupleTailleCouleur) {

            SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(idArticlePere);
            for (SQLRow child : children.allValues()) {
                Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
            }
            rowVals.put("ID_ARTICLE_VIRTUEL_PERE", idArticlePere);
            rowVals.put("VIRTUEL", Boolean.FALSE);
            rowVals.put("ID_ARTICLE_DECLINAISON_TAILLE", t.get0().getID());
            rowVals.put("ID_ARTICLE_DECLINAISON_COULEUR", t.get1().getID());

            rowVals.commit();

        }

    }

    public void transfert(final List<Tuple2<SQLRow, BigDecimal>> articles, final SQLRowAccessor selectedRowDepotDepart, final SQLRowAccessor selectedRowDepotArrivee, final String label,
            final Date dateValue) {

        final SQLTable mvtStockTable = getTable().getDBRoot().findTable("MOUVEMENT_STOCK");

        List<String> multipleRequestsHundred = new ArrayList<String>(100);
        boolean usePrice = mvtStockTable.contains("PRICE");
        List<StockItem> stockItems = new ArrayList<StockItem>();

        try {
            final DBSystemRoot dbSystemRoot = selectedRowDepotDepart.getTable().getDBSystemRoot();
            SQLUtils.executeAtomic(dbSystemRoot.getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() {
                @Override
                public Object handle(SQLDataSource ds) throws SQLException {

                    for (Tuple2<SQLRow, BigDecimal> t : articles) {

                        SQLRow selectedRowArticle = t.get0();
                        BigDecimal qteReel = t.get1();
                        {
                            // DEPART
                            final SQLRowAccessor rowStockDepart = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotDepart);
                            StockItem item = new StockItem(selectedRowArticle, rowStockDepart);
                            if (!item.isStockInit()) {
                                SQLRowValues rowVals = new SQLRowValues(mvtStockTable.getTable("STOCK"));
                                rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
                                rowVals.put("ID_DEPOT_STOCK", selectedRowDepotDepart.getID());
                                rowVals.commit();
                                selectedRowArticle.fetchValues();
                                item = new StockItem(selectedRowArticle, rowStockDepart);
                            }
                            stockItems.add(item);
                            double diff = -qteReel.doubleValue();
                            item.updateQty(diff, TypeStockMouvement.REEL);
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), true, usePrice));
                            item.updateQty(diff, TypeStockMouvement.THEORIQUE);
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), false, usePrice));
                            multipleRequestsHundred.add(item.getUpdateRequest());
                        }
                        // ARRIVEE
                        {
                            final SQLRowAccessor rowStockArrivee = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotArrivee);
                            StockItem item = new StockItem(selectedRowArticle, rowStockArrivee);
                            if (!item.isStockInit()) {
                                SQLRowValues rowVals = new SQLRowValues(mvtStockTable.getTable("STOCK"));
                                rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
                                rowVals.put("ID_DEPOT_STOCK", selectedRowDepotArrivee.getID());
                                rowVals.commit();
                                selectedRowArticle.fetchValues();
                                item = new StockItem(selectedRowArticle, rowStockArrivee);
                            }
                            stockItems.add(item);
                            double diff = qteReel.doubleValue();
                            item.updateQty(diff, TypeStockMouvement.REEL);
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), true, usePrice));
                            item.updateQty(diff, TypeStockMouvement.THEORIQUE);
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), false, usePrice));
                            multipleRequestsHundred.add(item.getUpdateRequest());
                        }

                        final int size = multipleRequestsHundred.size();
                        List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(size);
                        for (int i = 0; i < size; i++) {
                            handlers.add(null);
                        }
                        SQLUtils.executeMultiple(dbSystemRoot, multipleRequestsHundred, handlers);

                        final DBRoot root = mvtStockTable.getDBRoot();
                        if (root.contains("ARTICLE_ELEMENT")) {
                            // Mise à jour des stocks des nomenclatures
                            ComposedItemStockUpdater comp = new ComposedItemStockUpdater(root, stockItems);
                            comp.update();
                        }
                    }
                    return null;
                }
            });
        } catch (SQLException e1) {
            ExceptionHandler.handle("Stock update error", e1);
        }
    }

    private String getLabel(String label, SQLRowAccessor fromDepot, SQLRowAccessor toDepot) {
        return label + " de " + fromDepot.getString("NOM") + " vers " + toDepot.getString("NOM");
    }

    private String getMvtRequest(Date time, BigDecimal prc, double qteFinal, StockItem item, String label, boolean reel, boolean usePrice) {
        final SQLTable mvtStockTable = getTable().getDBRoot().findTable("MOUVEMENT_STOCK");
        final String mvtStockTableQuoted = mvtStockTable.getSQLName().quote();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"NOM\",\"REEL\",\"ORDRE\"";

        if (usePrice && prc != null) {
            mvtStockQuery += ",\"PRICE\"";
        }

        mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + item.getArticle().getID() + "," + item.stock.getID() + ",'" + label + "'," + reel
                + ", (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
        if (usePrice && prc != null) {
            mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
        }
        mvtStockQuery += ")";
        return mvtStockQuery;
    }

    /**
     * Article qui ont comme code les codes fournis en paramètre,
     */
    public Map<String, SQLRowAccessor> findArticleFromCode(List<String> codes) {
        final SQLRowValues rv = new SQLRowValues(getTable());
        rv.setAllToNull();
        final SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rv);
        final List<SQLRowValues> list = fetcher.fetch(Where.inValues(getTable().getField("CODE"), codes));
        final Map<String, SQLRowAccessor> result = new HashMap<>(list.size());
        for (SQLRowValues r : list) {
            result.put(r.getString("CODE"), r);
        }
        return result;
    }

}