OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Rev 182 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.common.ui;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
93 ilm 17
import org.openconcerto.erp.core.finance.accounting.model.CurrencyConverter;
18 ilm 18
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
142 ilm 19
import org.openconcerto.erp.core.sales.pos.io.BarcodeReader;
20
import org.openconcerto.erp.core.sales.pos.ui.BarcodeListener;
18 ilm 21
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
177 ilm 22
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
94 ilm 23
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
132 ilm 24
import org.openconcerto.erp.core.sales.product.model.ProductHelper;
25
import org.openconcerto.erp.core.sales.product.model.ProductHelper.TypePrice;
18 ilm 26
import org.openconcerto.erp.core.sales.product.ui.ArticleRowValuesRenderer;
94 ilm 27
import org.openconcerto.erp.core.sales.product.ui.CurrencyWithSymbolRenderer;
19 ilm 28
import org.openconcerto.erp.core.sales.product.ui.QteMultipleRowValuesRenderer;
61 ilm 29
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
177 ilm 30
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
174 ilm 31
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
94 ilm 32
import org.openconcerto.erp.importer.ArrayTableModel;
33
import org.openconcerto.erp.importer.DataImporter;
18 ilm 34
import org.openconcerto.erp.preferences.DefaultNXProps;
61 ilm 35
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
18 ilm 36
import org.openconcerto.sql.Configuration;
37
import org.openconcerto.sql.element.SQLElement;
94 ilm 38
import org.openconcerto.sql.model.FieldPath;
180 ilm 39
import org.openconcerto.sql.model.SQLBackgroundTableCache;
40
import org.openconcerto.sql.model.SQLBackgroundTableCacheItem;
19 ilm 41
import org.openconcerto.sql.model.SQLField;
42
import org.openconcerto.sql.model.SQLRow;
43
import org.openconcerto.sql.model.SQLRowAccessor;
94 ilm 44
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 45
import org.openconcerto.sql.model.SQLRowValues;
94 ilm 46
import org.openconcerto.sql.model.SQLSelect;
18 ilm 47
import org.openconcerto.sql.model.SQLTable;
80 ilm 48
import org.openconcerto.sql.model.UndefinedRowValuesCache;
18 ilm 49
import org.openconcerto.sql.model.Where;
94 ilm 50
import org.openconcerto.sql.model.graph.Path;
61 ilm 51
import org.openconcerto.sql.preferences.SQLPreferences;
83 ilm 52
import org.openconcerto.sql.sqlobject.ITextArticleWithCompletionCellEditor;
61 ilm 53
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
94 ilm 54
import org.openconcerto.sql.users.rights.UserRights;
142 ilm 55
import org.openconcerto.sql.users.rights.UserRightsManager;
174 ilm 56
import org.openconcerto.sql.view.EditFrame;
57
import org.openconcerto.sql.view.EditPanel.EditMode;
18 ilm 58
import org.openconcerto.sql.view.list.AutoCompletionManager;
59
import org.openconcerto.sql.view.list.CellDynamicModifier;
60
import org.openconcerto.sql.view.list.RowValuesTable;
61
import org.openconcerto.sql.view.list.RowValuesTableModel;
62
import org.openconcerto.sql.view.list.SQLTableElement;
93 ilm 63
import org.openconcerto.sql.view.list.SQLTextComboTableCellEditor;
65 ilm 64
import org.openconcerto.sql.view.list.ValidStateChecker;
177 ilm 65
import org.openconcerto.ui.preferences.DefaultProps;
93 ilm 66
import org.openconcerto.utils.CompareUtils;
90 ilm 67
import org.openconcerto.utils.DecimalUtils;
94 ilm 68
import org.openconcerto.utils.StringUtils;
69
import org.openconcerto.utils.Tuple3;
132 ilm 70
import org.openconcerto.utils.cc.ITransformer;
93 ilm 71
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 72
 
80 ilm 73
import java.awt.Component;
94 ilm 74
import java.awt.datatransfer.DataFlavor;
75
import java.awt.datatransfer.Transferable;
76
import java.awt.datatransfer.UnsupportedFlavorException;
77
import java.awt.dnd.DnDConstants;
78
import java.awt.dnd.DropTarget;
79
import java.awt.dnd.DropTargetDropEvent;
93 ilm 80
import java.awt.event.ActionEvent;
174 ilm 81
import java.awt.event.ActionListener;
142 ilm 82
import java.awt.event.HierarchyEvent;
83
import java.awt.event.HierarchyListener;
84
import java.awt.event.KeyEvent;
93 ilm 85
import java.awt.event.MouseAdapter;
86
import java.awt.event.MouseEvent;
94 ilm 87
import java.io.File;
88
import java.io.IOException;
19 ilm 89
import java.math.BigDecimal;
67 ilm 90
import java.math.RoundingMode;
18 ilm 91
import java.util.ArrayList;
19 ilm 92
import java.util.Collection;
93 ilm 93
import java.util.Date;
28 ilm 94
import java.util.HashMap;
18 ilm 95
import java.util.List;
28 ilm 96
import java.util.Map;
142 ilm 97
import java.util.Set;
18 ilm 98
import java.util.Vector;
99
 
93 ilm 100
import javax.swing.AbstractAction;
18 ilm 101
import javax.swing.JButton;
142 ilm 102
import javax.swing.JFrame;
80 ilm 103
import javax.swing.JLabel;
174 ilm 104
import javax.swing.JMenu;
105
import javax.swing.JMenuItem;
19 ilm 106
import javax.swing.JOptionPane;
93 ilm 107
import javax.swing.JPopupMenu;
80 ilm 108
import javax.swing.JTable;
109
import javax.swing.SwingUtilities;
18 ilm 110
import javax.swing.ToolTipManager;
93 ilm 111
import javax.swing.event.TableModelEvent;
112
import javax.swing.event.TableModelListener;
80 ilm 113
import javax.swing.table.DefaultTableCellRenderer;
18 ilm 114
import javax.swing.table.TableCellRenderer;
115
 
116
public abstract class AbstractVenteArticleItemTable extends AbstractArticleItemTable {
117
 
21 ilm 118
    public static final String ARTICLE_SHOW_DEVISE = "ArticleShowDevise";
28 ilm 119
    public static final String ARTICLE_SERVICE = "ArticleService";
19 ilm 120
 
94 ilm 121
    public static final String EDIT_PRIX_VENTE_CODE = "CORPS_EDITER_PRIX_VENTE";
122
    public static final String SHOW_PRIX_ACHAT_CODE = "CORPS_VOIR_PRIX_ACHAT";
156 ilm 123
    public static final String SHOW_PRIX_VENTE_CODE = "CORPS_VOIR_PRIX_VENTE";
94 ilm 124
    public static final String LOCK_PRIX_MIN_VENTE_CODE = "CORPS_VERROU_PRIX_MIN_VENTE";
125
 
18 ilm 126
    public AbstractVenteArticleItemTable() {
127
        super();
128
    }
129
 
130
    public AbstractVenteArticleItemTable(List<JButton> buttons) {
131
        super(buttons);
132
    }
133
 
132 ilm 134
    protected boolean isCellNiveauEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
93 ilm 135
        RowValuesTableModel model = getModel();
83 ilm 136
        int niveau = vals.getInt("NIVEAU");
132 ilm 137
        return rowIndex + 1 == model.getRowCount() || niveau >= model.getRowValuesAt(rowIndex + 1).getInt("NIVEAU");
83 ilm 138
    }
139
 
80 ilm 140
    SQLTableElement tableElementFacturable;
94 ilm 141
    protected SQLTableElement tableElementRemise;
80 ilm 142
 
83 ilm 143
    public enum TypeCalcul {
177 ilm 144
        CALCUL_MONTANT_TOTAL("MONTANT_FACTURABLE", "POURCENT_FACTURABLE"), CALCUL_FACTURABLE("MONTANT_FACTURABLE", "POURCENT_FACTURABLE"), CALCUL_REMISE("MONTANT_REMISE", "POURCENT_REMISE");
83 ilm 145
 
146
        String fieldMontant, fieldPourcent;
147
 
148
        TypeCalcul(String fieldMontant, String fieldPourcent) {
149
            this.fieldMontant = fieldMontant;
150
            this.fieldPourcent = fieldPourcent;
151
        }
152
 
153
        public String getFieldMontant() {
154
            return fieldMontant;
155
        }
156
 
157
        public String getFieldPourcent() {
158
            return fieldPourcent;
159
        }
160
    };
161
 
177 ilm 162
    private Acompte acompteFacturer = null;
163
 
83 ilm 164
    public void calculPourcentage(final Acompte a, final TypeCalcul type) {
177 ilm 165
        this.acompteFacturer = a;
80 ilm 166
        Runnable r = new Runnable() {
167
 
168
            @Override
169
            public void run() {
170
                SwingUtilities.invokeLater(new Runnable() {
171
 
172
                    @Override
173
                    public void run() {
83 ilm 174
                        SQLTableElement tableElement = (type == TypeCalcul.CALCUL_FACTURABLE ? tableElementFacturable : tableElementRemise);
93 ilm 175
                        RowValuesTableModel model = getModel();
80 ilm 176
                        if (a == null) {
177
                            for (int i = 0; i < model.getRowCount(); i++) {
83 ilm 178
                                model.putValue(null, i, type.getFieldMontant());
179
                                model.putValue(null, i, type.getFieldPourcent());
180
                                tableElement.fireModification(model.getRowValuesAt(i));
80 ilm 181
                            }
182
                        } else if (a.getPercent() != null) {
183
                            for (int i = 0; i < model.getRowCount(); i++) {
83 ilm 184
                                model.putValue(a.getPercent(), i, type.getFieldPourcent());
185
                                model.putValue(null, i, type.getFieldMontant());
186
                                tableElement.fireModification(model.getRowValuesAt(i));
80 ilm 187
                            }
188
                        } else {
177 ilm 189
                            BigDecimal totalHT = getTotalHT(type);
80 ilm 190
 
191
                            for (int i = 0; i < model.getRowCount(); i++) {
83 ilm 192
                                // Restrict to level 1
193
                                if (model.getRowValuesAt(i).getInt("NIVEAU") != 1) {
194
                                    continue;
195
                                }
196
                                model.putValue(null, i, type.getFieldPourcent());
80 ilm 197
                                SQLRowValues rowVals = model.getRowValuesAt(i);
198
                                int qte = rowVals.getInt("QTE");
199
                                BigDecimal qteU = rowVals.getBigDecimal("QTE_UNITAIRE");
200
                                BigDecimal pU = rowVals.getBigDecimal("PV_HT");
201
 
90 ilm 202
                                BigDecimal totalLine = pU.multiply(qteU, DecimalUtils.HIGH_PRECISION).multiply(new BigDecimal(qte), DecimalUtils.HIGH_PRECISION).setScale(2, RoundingMode.HALF_UP);
80 ilm 203
 
83 ilm 204
                                if (rowVals.getTable().getFieldsName().contains("MONTANT_REMISE")) {
205
                                    final BigDecimal acomptePercent = rowVals.getBigDecimal("POURCENT_REMISE");
206
                                    final BigDecimal acompteMontant = rowVals.getBigDecimal("MONTANT_REMISE");
207
                                    Remise remise = new Remise(acomptePercent, acompteMontant);
208
                                    totalLine = remise.getResultFrom(totalLine);
80 ilm 209
                                }
210
 
90 ilm 211
                                BigDecimal percent = (totalHT.signum() != 0 ? totalLine.divide(totalHT, DecimalUtils.HIGH_PRECISION) : BigDecimal.ZERO);
80 ilm 212
 
90 ilm 213
                                model.putValue(a.getMontant().multiply(percent, DecimalUtils.HIGH_PRECISION).setScale(6, RoundingMode.HALF_UP), i, type.getFieldMontant());
83 ilm 214
                                tableElement.fireModification(model.getRowValuesAt(i));
80 ilm 215
                            }
216
                        }
217
                        model.fireTableDataChanged();
218
                    }
177 ilm 219
 
80 ilm 220
                });
221
            }
222
        };
93 ilm 223
        getModel().submit(r);
80 ilm 224
 
225
    }
226
 
177 ilm 227
    public BigDecimal getTotalHT(final TypeCalcul type) {
228
        BigDecimal totalHT = BigDecimal.ZERO;
229
        for (SQLRowValues rowVals : getRowValuesAtLevel(1)) {
230
            int qte = rowVals.getInt("QTE");
231
            BigDecimal qteU = rowVals.getBigDecimal("QTE_UNITAIRE");
232
            BigDecimal pU = rowVals.getBigDecimal("PV_HT");
233
 
234
            BigDecimal totalLine = pU.multiply(qteU, DecimalUtils.HIGH_PRECISION).multiply(new BigDecimal(qte), DecimalUtils.HIGH_PRECISION).setScale(2, RoundingMode.HALF_UP);
235
 
236
            if (type == TypeCalcul.CALCUL_FACTURABLE || type == TypeCalcul.CALCUL_MONTANT_TOTAL) {
237
                if (rowVals.getTable().getFieldsName().contains("MONTANT_REMISE")) {
238
                    final BigDecimal acomptePercent = rowVals.getBigDecimal("POURCENT_REMISE");
239
                    final BigDecimal acompteMontant = rowVals.getBigDecimal("MONTANT_REMISE");
240
                    Remise remise = new Remise(acomptePercent, acompteMontant);
241
                    totalLine = remise.getResultFrom(totalLine);
242
                }
243
            }
244
 
245
            if (type == TypeCalcul.CALCUL_MONTANT_TOTAL) {
246
                if (rowVals.getTable().getFieldsName().contains("POURCENT_FACTURABLE")) {
247
                    final BigDecimal acomptePercent = rowVals.getBigDecimal("POURCENT_FACTURABLE");
248
                    final BigDecimal acompteMontant = rowVals.getBigDecimal("MONTANT_FACTURABLE");
249
                    Acompte acompte = new Acompte(acomptePercent, acompteMontant);
250
                    totalLine = acompte.getResultFrom(totalLine);
251
                }
252
            }
253
            totalHT = totalHT.add(totalLine);
254
        }
255
        return totalHT;
256
    }
257
 
28 ilm 258
    private static Map<String, Boolean> visibilityMap = new HashMap<String, Boolean>();
259
 
260
    public static Map<String, Boolean> getVisibilityMap() {
261
        return visibilityMap;
262
    }
263
 
19 ilm 264
    private SQLTable tableArticleTarif = Configuration.getInstance().getBase().getTable("ARTICLE_TARIF");
61 ilm 265
    private SQLTable tableArticle = Configuration.getInstance().getBase().getTable("ARTICLE");
19 ilm 266
 
18 ilm 267
    protected void init() {
268
 
67 ilm 269
        SQLPreferences prefs = SQLPreferences.getMemCached(getSQLElement().getTable().getDBRoot());
61 ilm 270
        final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
177 ilm 271
        final boolean activeCalculM2 = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVE_CALCUL_M2, false);
93 ilm 272
        final boolean filterFamilleArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.FILTER_BY_FAMILY, false);
61 ilm 273
        final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
142 ilm 274
        final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
156 ilm 275
        final boolean showDevise = prefs.getBoolean(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false);
61 ilm 276
 
142 ilm 277
        final UserRights rights = UserRightsManager.getCurrentUserRights();
94 ilm 278
        final boolean editVTPrice = rights.haveRight(EDIT_PRIX_VENTE_CODE);
279
        final boolean showHAPrice = rights.haveRight(SHOW_PRIX_ACHAT_CODE);
280
        final boolean lockVTMinPrice = rights.haveRight(LOCK_PRIX_MIN_VENTE_CODE);
281
 
18 ilm 282
        final SQLElement e = getSQLElement();
283
 
284
        final List<SQLTableElement> list = new Vector<SQLTableElement>();
83 ilm 285
        final SQLTableElement eNiveau = new SQLTableElement(e.getTable().getField("NIVEAU")) {
286
            @Override
287
            public void setValueFrom(SQLRowValues row, Object value) {
288
                super.setValueFrom(row, value);
289
            }
290
        };
291
        eNiveau.setRenderer(new NiveauTableCellRender());
292
        eNiveau.setEditor(new NiveauTableCellEditor());
293
        list.add(eNiveau);
294
 
18 ilm 295
        list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
28 ilm 296
 
174 ilm 297
        if (e.getTable().contains("ID_COMPTE_PCE")) {
298
            list.add(new SQLTableElement(e.getTable().getField("ID_COMPTE_PCE")));
299
        }
300
 
93 ilm 301
        final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE"));
302
        list.add(tableFamille);
303
 
61 ilm 304
        // Article
156 ilm 305
        SQLTableElement tableElementDepot = new SQLTableElement(e.getTable().getField("ID_DEPOT_STOCK"), true, true, true);
306
        list.add(tableElementDepot);
307
 
308
        // Article
67 ilm 309
        SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true);
61 ilm 310
        list.add(tableElementArticle);
28 ilm 311
 
142 ilm 312
        if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
313
            this.tableElementEcoID = new SQLTableElement(e.getTable().getField("ID_ECO_CONTRIBUTION"));
314
            list.add(this.tableElementEcoID);
315
        }
316
 
28 ilm 317
        // Code article
94 ilm 318
        final SQLTableElement tableElementCode = new SQLTableElement(e.getTable().getField("CODE"), String.class,
319
                new ITextArticleWithCompletionCellEditor(e.getTable().getTable("ARTICLE"), e.getTable().getTable("ARTICLE_FOURNISSEUR")));
18 ilm 320
        list.add(tableElementCode);
83 ilm 321
 
18 ilm 322
        // Désignation de l'article
323
        final SQLTableElement tableElementNom = new SQLTableElement(e.getTable().getField("NOM"));
324
        list.add(tableElementNom);
325
 
41 ilm 326
        if (e.getTable().getFieldsName().contains("COLORIS")) {
327
            final SQLTableElement tableElementColoris = new SQLTableElement(e.getTable().getField("COLORIS"));
328
            list.add(tableElementColoris);
329
        }
330
 
21 ilm 331
        if (e.getTable().getFieldsName().contains("DESCRIPTIF")) {
332
            final SQLTableElement tableElementDesc = new SQLTableElement(e.getTable().getField("DESCRIPTIF"));
333
            list.add(tableElementDesc);
334
        }
335
 
149 ilm 336
        if (e.getTable().getFieldsName().contains("DELAI")) {
337
            final SQLTableElement tableElementDelai = new SQLTableElement(e.getTable().getField("DELAI"));
338
            list.add(tableElementDelai);
339
        }
340
 
156 ilm 341
        if (showDevise) {
19 ilm 342
            // Code Douanier
343
            final SQLTableElement tableElementCodeDouane = new SQLTableElement(e.getTable().getField("CODE_DOUANIER"));
344
            list.add(tableElementCodeDouane);
345
            final SQLTableElement tableElementPays = new SQLTableElement(e.getTable().getField("ID_PAYS"));
346
            list.add(tableElementPays);
347
        }
348
 
18 ilm 349
        // Valeur des métriques
350
        final SQLTableElement tableElement_ValeurMetrique2 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_2"), Float.class) {
351
            @Override
132 ilm 352
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
18 ilm 353
                Number modeNumber = (Number) vals.getObject("ID_MODE_VENTE_ARTICLE");
354
                // int mode = vals.getInt("ID_MODE_VENTE_ARTICLE");
94 ilm 355
                if (modeNumber != null && (modeNumber.intValue() == ReferenceArticleSQLElement.A_LA_PIECE || modeNumber.intValue() == ReferenceArticleSQLElement.AU_POID_METRECARRE
356
                        || modeNumber.intValue() == ReferenceArticleSQLElement.AU_METRE_LONGUEUR)) {
18 ilm 357
                    return false;
358
                } else {
132 ilm 359
                    return super.isCellEditable(vals, rowIndex, columnIndex);
18 ilm 360
                }
361
            }
362
 
363
            @Override
364
            public TableCellRenderer getTableCellRenderer() {
365
 
366
                return new ArticleRowValuesRenderer(null);
367
            }
368
        };
369
        list.add(tableElement_ValeurMetrique2);
370
        final SQLTableElement tableElement_ValeurMetrique3 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_3"), Float.class) {
371
            @Override
132 ilm 372
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
18 ilm 373
 
374
                Number modeNumber = (Number) vals.getObject("ID_MODE_VENTE_ARTICLE");
375
                if (modeNumber != null && (!(modeNumber.intValue() == ReferenceArticleSQLElement.AU_POID_METRECARRE))) {
376
                    return false;
377
                } else {
132 ilm 378
                    return super.isCellEditable(vals, rowIndex, columnIndex);
18 ilm 379
                }
380
            }
381
 
382
            @Override
383
            public TableCellRenderer getTableCellRenderer() {
384
 
385
                return new ArticleRowValuesRenderer(null);
386
            }
387
        };
388
        list.add(tableElement_ValeurMetrique3);
389
        final SQLTableElement tableElement_ValeurMetrique1 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_1"), Float.class) {
390
            @Override
132 ilm 391
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
18 ilm 392
 
393
                Number modeNumber = (Number) vals.getObject("ID_MODE_VENTE_ARTICLE");
94 ilm 394
                if (modeNumber != null && (modeNumber.intValue() == ReferenceArticleSQLElement.A_LA_PIECE || modeNumber.intValue() == ReferenceArticleSQLElement.AU_POID_METRECARRE
395
                        || modeNumber.intValue() == ReferenceArticleSQLElement.AU_METRE_LARGEUR)) {
18 ilm 396
                    return false;
397
                } else {
132 ilm 398
                    return super.isCellEditable(vals, rowIndex, columnIndex);
18 ilm 399
                }
400
            }
401
 
402
            @Override
403
            public TableCellRenderer getTableCellRenderer() {
404
 
405
                return new ArticleRowValuesRenderer(null);
406
            }
407
        };
408
        list.add(tableElement_ValeurMetrique1);
409
 
41 ilm 410
        // Prébilan
61 ilm 411
 
41 ilm 412
        if (e.getTable().getFieldsName().contains("PREBILAN")) {
90 ilm 413
            prebilan = new SQLTableElement(e.getTable().getField("PREBILAN"), BigDecimal.class) {
414
                protected Object getDefaultNullValue() {
415
                    return BigDecimal.ZERO;
416
                }
417
 
418
                @Override
132 ilm 419
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
420
                    return isCellNiveauEditable(vals, rowIndex, columnIndex);
90 ilm 421
                }
422
 
423
            };
424
            prebilan.setRenderer(new DeviseTableCellRenderer());
41 ilm 425
            list.add(prebilan);
426
        }
427
 
18 ilm 428
        // Prix d'achat HT de la métrique 1
73 ilm 429
        final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), BigDecimal.class) {
430
            protected Object getDefaultNullValue() {
431
                return BigDecimal.ZERO;
432
            }
83 ilm 433
 
434
            @Override
132 ilm 435
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
436
                return isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 437
            }
438
 
73 ilm 439
        };
94 ilm 440
        tableElement_PrixMetrique1_AchatHT.setRenderer(new CurrencyWithSymbolRenderer());
18 ilm 441
        list.add(tableElement_PrixMetrique1_AchatHT);
442
 
19 ilm 443
        SQLTableElement eltDevise = null;
444
        SQLTableElement eltUnitDevise = null;
156 ilm 445
        if (showDevise) {
19 ilm 446
            // Devise
447
            eltDevise = new SQLTableElement(e.getTable().getField("ID_DEVISE"));
448
            list.add(eltDevise);
449
 
450
            // Prix vente devise
83 ilm 451
            eltUnitDevise = new SQLTableElement(e.getTable().getField("PV_U_DEVISE"), BigDecimal.class) {
452
                @Override
132 ilm 453
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
454
                    return editVTPrice && isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 455
                }
132 ilm 456
 
457
                protected Object getDefaultNullValue() {
458
                    return BigDecimal.ZERO;
459
                }
460
 
83 ilm 461
            };
94 ilm 462
            Path p = new Path(getSQLElement().getTable()).addForeignField("ID_DEVISE");
463
            eltUnitDevise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
19 ilm 464
            list.add(eltUnitDevise);
465
        }
18 ilm 466
        // Prix de vente HT de la métrique 1
73 ilm 467
 
67 ilm 468
        SQLField field = e.getTable().getField("PRIX_METRIQUE_VT_1");
73 ilm 469
        final DeviseNumericHTConvertorCellEditor editorPVHT = new DeviseNumericHTConvertorCellEditor(field);
18 ilm 470
 
83 ilm 471
        final SQLTableElement tableElement_PrixMetrique1_VenteHT = new SQLTableElement(field, BigDecimal.class, editorPVHT) {
472
            @Override
132 ilm 473
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
474
                return editVTPrice && isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 475
            }
476
        };
94 ilm 477
        tableElement_PrixMetrique1_VenteHT.setRenderer(new CurrencyWithSymbolRenderer());
18 ilm 478
        list.add(tableElement_PrixMetrique1_VenteHT);
19 ilm 479
 
142 ilm 480
        if (e.getTable().getFieldsName().contains("ECO_CONTRIBUTION")) {
481
            this.tableElementEco = new SQLTableElement(e.getTable().getField("ECO_CONTRIBUTION"));
482
            list.add(this.tableElementEco);
483
        }
484
 
177 ilm 485
        SQLTableElement eltLongueur = new SQLTableElement(e.getTable().getField("LONGUEUR")) {
486
            @Override
487
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
61 ilm 488
 
177 ilm 489
                int idUv = vals.getForeignID("ID_UNITE_VENTE");
490
                return idUv == UniteVenteArticleSQLElement.M2;
491
            }
492
        };
493
        list.add(eltLongueur);
494
 
495
        SQLTableElement eltLargeur = new SQLTableElement(e.getTable().getField("LARGEUR")) {
496
            @Override
497
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
498
 
499
                int idUv = vals.getForeignID("ID_UNITE_VENTE");
500
                return idUv == UniteVenteArticleSQLElement.M2;
501
            }
502
        };
503
        list.add(eltLargeur);
504
 
505
        SQLTableElement eltHauteur = new SQLTableElement(e.getTable().getField("HAUTEUR"));
506
        list.add(eltHauteur);
507
 
61 ilm 508
        SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
509
            @Override
132 ilm 510
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
61 ilm 511
 
512
                SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
513
                if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
514
                    return false;
177 ilm 515
                } else if (activeCalculM2 && row != null && !row.isUndefined() && row.getID() == UniteVenteArticleSQLElement.M2) {
516
                    return false;
61 ilm 517
                } else {
132 ilm 518
                    return super.isCellEditable(vals, rowIndex, columnIndex);
61 ilm 519
                }
520
            }
521
 
522
            @Override
523
            public TableCellRenderer getTableCellRenderer() {
524
                return new QteUnitRowValuesRenderer();
525
            }
67 ilm 526
 
527
            protected Object getDefaultNullValue() {
528
                return BigDecimal.ZERO;
529
            }
61 ilm 530
        };
531
        list.add(qteU);
532
 
533
        SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
534
        list.add(uniteVente);
535
 
18 ilm 536
        // Quantité
21 ilm 537
        this.qte = new SQLTableElement(e.getTable().getField("QTE"), Integer.class, new QteCellEditor()) {
19 ilm 538
            protected Object getDefaultNullValue() {
539
                return Integer.valueOf(0);
540
            }
541
 
542
            public TableCellRenderer getTableCellRenderer() {
543
                if (getSQLElement().getTable().getFieldsName().contains("QTE_ACHAT")) {
544
                    return new QteMultipleRowValuesRenderer();
545
                } else {
546
                    return super.getTableCellRenderer();
547
                }
548
            }
549
        };
18 ilm 550
        this.qte.setPreferredSize(20);
551
        list.add(this.qte);
552
 
132 ilm 553
        if (e.getTable().contains("RETOUR_STOCK")) {
554
            list.add(new SQLTableElement(e.getTable().getField("RETOUR_STOCK")));
555
        }
556
 
18 ilm 557
        // Mode de vente
558
        final SQLTableElement tableElement_ModeVente = new SQLTableElement(e.getTable().getField("ID_MODE_VENTE_ARTICLE"));
559
        list.add(tableElement_ModeVente);
560
 
561
        // // Prix d'achat unitaire HT
73 ilm 562
 
563
        final SQLField prixAchatHTField = e.getTable().getField("PA_HT");
564
        final DeviseNumericCellEditor editorPAchatHT = new DeviseNumericCellEditor(prixAchatHTField);
565
        this.ha = new SQLTableElement(e.getTable().getField("PA_HT"), BigDecimal.class, editorPAchatHT) {
566
            protected Object getDefaultNullValue() {
567
                return BigDecimal.ZERO;
568
            }
83 ilm 569
 
570
            @Override
132 ilm 571
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
572
                return isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 573
            }
73 ilm 574
        };
83 ilm 575
        this.ha = new SQLTableElement(prixAchatHTField, BigDecimal.class, editorPAchatHT) {
576
            @Override
132 ilm 577
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
578
                return isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 579
            }
580
        };
94 ilm 581
        this.ha.setRenderer(new CurrencyWithSymbolRenderer());
73 ilm 582
 
18 ilm 583
        list.add(this.ha);
584
 
585
        // Prix de vente unitaire HT
73 ilm 586
        final SQLField prixVenteHTField = e.getTable().getField("PV_HT");
587
        final DeviseNumericCellEditor editorPVenteHT = new DeviseNumericCellEditor(prixAchatHTField);
83 ilm 588
        final SQLTableElement tableElement_PrixVente_HT = new SQLTableElement(prixVenteHTField, BigDecimal.class, editorPVenteHT) {
589
            @Override
132 ilm 590
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
591
                return editVTPrice && isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 592
            }
593
        };
94 ilm 594
        tableElement_PrixVente_HT.setRenderer(new CurrencyWithSymbolRenderer());
18 ilm 595
        list.add(tableElement_PrixVente_HT);
596
 
597
        // TVA
61 ilm 598
        this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
599
        this.tableElementTVA.setPreferredSize(20);
600
        list.add(this.tableElementTVA);
18 ilm 601
        // Poids piece
80 ilm 602
        SQLTableElement tableElementPoids = new SQLTableElement(e.getTable().getField("POIDS"), Float.class) {
603
            protected Object getDefaultNullValue() {
604
                return 0F;
605
            }
606
 
607
            @Override
608
            public TableCellRenderer getTableCellRenderer() {
609
                return new QteUnitRowValuesRenderer();
610
            }
611
 
612
        };
18 ilm 613
        tableElementPoids.setPreferredSize(20);
614
        list.add(tableElementPoids);
615
 
616
        // Poids total
80 ilm 617
        this.tableElementPoidsTotal = new SQLTableElement(e.getTable().getField("T_POIDS"), Float.class) {
618
            @Override
619
            public TableCellRenderer getTableCellRenderer() {
620
                return new QteUnitRowValuesRenderer();
621
            }
622
        };
623
        this.tableElementPoidsTotal.setEditable(false);
18 ilm 624
        list.add(this.tableElementPoidsTotal);
625
 
80 ilm 626
        // Packaging
177 ilm 627
        if (e.getTable().contains("POIDS_COLIS_NET") && prefs.getBoolean(GestionArticleGlobalPreferencePanel.ITEM_PACKAGING, false)) {
80 ilm 628
 
177 ilm 629
            SQLTableElement tareColis = new SQLTableElement(e.getTable().getField("TARE"), BigDecimal.class) {
630
                @Override
631
                public TableCellRenderer getTableCellRenderer() {
632
                    return new QteUnitRowValuesRenderer();
633
                }
634
 
635
            };
636
            list.add(tareColis);
637
 
80 ilm 638
            SQLTableElement poidsColis = new SQLTableElement(e.getTable().getField("POIDS_COLIS_NET"), BigDecimal.class) {
639
                @Override
640
                public TableCellRenderer getTableCellRenderer() {
641
                    return new QteUnitRowValuesRenderer();
642
                }
643
 
644
            };
645
            list.add(poidsColis);
646
 
647
            SQLTableElement nbColis = new SQLTableElement(e.getTable().getField("NB_COLIS"), Integer.class);
648
            list.add(nbColis);
649
 
650
            final SQLTableElement totalPoidsColis = new SQLTableElement(e.getTable().getField("T_POIDS_COLIS_NET"), BigDecimal.class) {
651
                @Override
652
                public TableCellRenderer getTableCellRenderer() {
653
                    return new QteUnitRowValuesRenderer();
654
                }
655
 
656
            };
657
            list.add(totalPoidsColis);
658
 
659
            poidsColis.addModificationListener(totalPoidsColis);
660
            nbColis.addModificationListener(totalPoidsColis);
661
            totalPoidsColis.setModifier(new CellDynamicModifier() {
93 ilm 662
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
177 ilm 663
                    final BigDecimal pdsColis = row.getBigDecimal("POIDS_COLIS_NET");
80 ilm 664
                    final Object o3 = row.getObject("NB_COLIS");
177 ilm 665
 
666
                    BigDecimal pdsColisTotal = BigDecimal.ZERO;
667
 
668
                    if (pdsColis != null && o3 != null) {
80 ilm 669
                        int nb = (Integer) o3;
177 ilm 670
                        pdsColisTotal = pdsColis.multiply(new BigDecimal(nb), DecimalUtils.HIGH_PRECISION);
80 ilm 671
                    }
177 ilm 672
                    return pdsColisTotal.setScale(totalPoidsColis.getDecimalDigits(), RoundingMode.HALF_UP);
80 ilm 673
                }
674
            });
675
 
177 ilm 676
            final SQLTableElement totalPoidsBrut = new SQLTableElement(e.getTable().getField("T_POIDS_BRUT"), BigDecimal.class) {
677
                @Override
678
                public TableCellRenderer getTableCellRenderer() {
679
                    return new QteUnitRowValuesRenderer();
680
                }
681
 
682
            };
683
            list.add(totalPoidsBrut);
684
 
685
            tareColis.addModificationListener(totalPoidsBrut);
686
            poidsColis.addModificationListener(totalPoidsBrut);
687
            nbColis.addModificationListener(totalPoidsBrut);
688
            this.tableElementPoidsTotal.addModificationListener(totalPoidsBrut);
689
            totalPoidsBrut.setModifier(new CellDynamicModifier() {
690
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
691
                    final BigDecimal tare = row.getBigDecimal("TARE");
692
                    final int qte = row.getInt("QTE");
693
                    final BigDecimal pdsColis = row.getBigDecimal("POIDS_COLIS_NET");
694
                    final Object o3 = row.getObject("NB_COLIS");
695
 
696
                    BigDecimal pdsBrutTotal = BigDecimal.ZERO;
697
 
698
                    if (row.getObject("T_POIDS") != null) {
699
                        pdsBrutTotal = new BigDecimal(row.getFloat("T_POIDS"));
700
                    }
701
 
702
                    if (tare != null) {
703
                        pdsBrutTotal = pdsBrutTotal.add(tare.multiply(new BigDecimal(qte)));
704
                    }
705
 
706
                    if (pdsColis != null && o3 != null) {
707
                        int nb = (Integer) o3;
708
                        pdsBrutTotal = pdsBrutTotal.add(pdsColis.multiply(new BigDecimal(nb), DecimalUtils.HIGH_PRECISION));
709
                    }
710
                    return pdsBrutTotal.setScale(totalPoidsBrut.getDecimalDigits(), RoundingMode.HALF_UP);
711
                }
712
            });
713
 
80 ilm 714
        }
715
 
18 ilm 716
        // Service
19 ilm 717
        if (DefaultNXProps.getInstance().getBooleanValue(ARTICLE_SERVICE, false)) {
18 ilm 718
            this.service = new SQLTableElement(e.getTable().getField("SERVICE"), Boolean.class);
719
            list.add(this.service);
720
        }
721
 
83 ilm 722
        this.totalHT = new SQLTableElement(e.getTable().getField("T_PV_HT"), BigDecimal.class) {
723
            @Override
132 ilm 724
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
725
                return isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 726
            }
727
        };
174 ilm 728
        CurrencyWithSymbolRenderer totalRenderer = new CurrencyWithSymbolRenderer();
729
        totalRenderer.setHideZeroValue(true);
730
        this.totalHT.setRenderer(totalRenderer);
61 ilm 731
        this.totalHT.setEditable(false);
177 ilm 732
        this.totalHA = new SQLTableElement(e.getTable().getField("T_PA_HT"), BigDecimal.class);
733
 
80 ilm 734
        if (e.getTable().getFieldsName().contains("MONTANT_FACTURABLE")) {
735
            // SQLTableElement tableElementAcompte = new
736
            // SQLTableElement(e.getTable().getField("POURCENT_ACOMPTE"));
737
            // list.add(tableElementAcompte);
738
 
739
            this.tableElementFacturable = new SQLTableElement(e.getTable().getField("POURCENT_FACTURABLE"), Acompte.class, new AcompteCellEditor("POURCENT_FACTURABLE", "MONTANT_FACTURABLE")) {
740
                @Override
741
                public void setValueFrom(SQLRowValues row, Object value) {
742
 
743
                    if (value != null) {
744
                        Acompte a = (Acompte) value;
745
                        row.put("MONTANT_FACTURABLE", a.getMontant());
746
                        row.put("POURCENT_FACTURABLE", a.getPercent());
747
                    } else {
748
                        row.put("MONTANT_FACTURABLE", null);
749
                        row.put("POURCENT_FACTURABLE", BigDecimal.ONE.movePointRight(2));
750
                    }
751
                    fireModification(row);
752
                }
753
            };
754
            tableElementFacturable.setRenderer(new DefaultTableCellRenderer() {
755
                @Override
756
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
757
                    SQLRowValues rowVals = ((RowValuesTable) table).getRowValuesTableModel().getRowValuesAt(row);
758
                    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
759
                    BigDecimal percent = rowVals.getBigDecimal("POURCENT_FACTURABLE");
760
                    BigDecimal amount = rowVals.getBigDecimal("MONTANT_FACTURABLE");
761
                    Acompte a = new Acompte(percent, amount);
132 ilm 762
                    label.setText(a.toPlainString(true));
80 ilm 763
                    return label;
764
                }
765
            });
766
            tableElementFacturable.addModificationListener(this.totalHT);
177 ilm 767
            tableElementFacturable.addModificationListener(this.totalHA);
80 ilm 768
            list.add(tableElementFacturable);
28 ilm 769
        }
73 ilm 770
 
83 ilm 771
        final SQLField fieldRemise = e.getTable().getField("POURCENT_REMISE");
772
 
773
        if (e.getTable().getFieldsName().contains("MONTANT_REMISE")) {
774
            tableElementRemise = new SQLTableElement(e.getTable().getField("POURCENT_REMISE"), Acompte.class, new AcompteCellEditor("POURCENT_REMISE", "MONTANT_REMISE")) {
775
                @Override
776
                public void setValueFrom(SQLRowValues row, Object value) {
777
 
778
                    if (value != null) {
779
                        Acompte a = (Acompte) value;
780
                        row.put("MONTANT_REMISE", a.getMontant());
781
                        row.put("POURCENT_REMISE", a.getPercent());
782
                    } else {
783
                        row.put("MONTANT_REMISE", null);
784
                        row.put("POURCENT_REMISE", BigDecimal.ZERO);
785
                    }
786
                    fireModification(row);
787
                }
788
            };
789
            tableElementRemise.setRenderer(new DefaultTableCellRenderer() {
790
                @Override
791
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
792
                    SQLRowValues rowVals = ((RowValuesTable) table).getRowValuesTableModel().getRowValuesAt(row);
793
                    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
794
                    BigDecimal percent = rowVals.getBigDecimal("POURCENT_REMISE");
795
                    BigDecimal amount = rowVals.getBigDecimal("MONTANT_REMISE");
796
                    Remise a = new Remise(percent, amount);
132 ilm 797
                    label.setText(a.toPlainString(true));
83 ilm 798
                    return label;
799
                }
800
            });
801
        } else {
802
            tableElementRemise = new SQLTableElement(fieldRemise) {
803
                protected Object getDefaultNullValue() {
804
                    return BigDecimal.ZERO;
805
                }
806
            };
807
        }
19 ilm 808
        list.add(tableElementRemise);
28 ilm 809
        SQLTableElement tableElementRG = null;
810
        if (e.getTable().getFieldsName().contains("POURCENT_RG")) {
811
            tableElementRG = new SQLTableElement(e.getTable().getField("POURCENT_RG"));
812
            list.add(tableElementRG);
813
        }
814
 
18 ilm 815
        // Total HT
174 ilm 816
        this.totalHA.setRenderer(totalRenderer);
67 ilm 817
        this.totalHA.setEditable(false);
818
        list.add(this.totalHA);
18 ilm 819
 
156 ilm 820
        if (showDevise) {
19 ilm 821
            // Total HT
83 ilm 822
            this.tableElementTotalDevise = new SQLTableElement(e.getTable().getField("PV_T_DEVISE"), BigDecimal.class) {
823
                @Override
132 ilm 824
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
825
                    return isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 826
                }
827
            };
94 ilm 828
            Path p = new Path(getSQLElement().getTable()).addForeignField("ID_DEVISE");
174 ilm 829
            CurrencyWithSymbolRenderer currencyRenderer = new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE"));
830
            currencyRenderer.setHideZeroValue(true);
831
            this.tableElementTotalDevise.setRenderer(currencyRenderer);
832
            list.add(this.tableElementTotalDevise);
19 ilm 833
        }
21 ilm 834
 
835
        // Marge HT
836
        if (e.getTable().getFieldsName().contains("MARGE_HT")) {
837
 
90 ilm 838
            final SQLTableElement marge = new SQLTableElement(e.getTable().getField("MARGE_HT"), BigDecimal.class) {
839
                protected Object getDefaultNullValue() {
840
                    return BigDecimal.ZERO;
841
                }
842
 
843
                @Override
132 ilm 844
                public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
845
                    return isCellNiveauEditable(vals, rowIndex, columnIndex);
90 ilm 846
                }
847
 
848
            };
174 ilm 849
            marge.setRenderer(totalRenderer);
21 ilm 850
            marge.setEditable(false);
851
            list.add(marge);
852
            this.totalHT.addModificationListener(marge);
67 ilm 853
            this.totalHA.addModificationListener(marge);
21 ilm 854
            marge.setModifier(new CellDynamicModifier() {
855
                @Override
93 ilm 856
                public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
21 ilm 857
 
67 ilm 858
                    BigDecimal vt = (BigDecimal) row.getObject("T_PV_HT");
21 ilm 859
 
67 ilm 860
                    BigDecimal ha = (BigDecimal) row.getObject("T_PA_HT");
21 ilm 861
 
80 ilm 862
                    final BigDecimal acomptePercent = row.getBigDecimal("POURCENT_FACTURABLE");
863
                    final BigDecimal acompteMontant = row.getBigDecimal("MONTANT_FACTURABLE");
864
                    Acompte acompte = new Acompte(acomptePercent, acompteMontant);
865
                    ha = acompte.getResultFrom(ha);
866
                    vt = acompte.getResultFrom(vt);
28 ilm 867
 
67 ilm 868
                    return vt.subtract(ha).setScale(marge.getDecimalDigits(), RoundingMode.HALF_UP);
21 ilm 869
                }
870
 
871
            });
872
 
873
        }
874
 
61 ilm 875
        if (e.getTable().getFieldsName().contains("MARGE_PREBILAN_HT")) {
876
 
90 ilm 877
            final SQLTableElement marge = new SQLTableElement(e.getTable().getField("MARGE_PREBILAN_HT"), BigDecimal.class) {
878
                protected Object getDefaultNullValue() {
879
                    return BigDecimal.ZERO;
880
                }
881
            };
882
            marge.setRenderer(new DeviseTableCellRenderer());
61 ilm 883
            marge.setEditable(false);
884
            list.add(marge);
885
            this.totalHT.addModificationListener(marge);
886
            prebilan.addModificationListener(marge);
887
            marge.setModifier(new CellDynamicModifier() {
888
                @Override
93 ilm 889
                public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
61 ilm 890
 
67 ilm 891
                    BigDecimal vt = (BigDecimal) row.getObject("T_PV_HT");
61 ilm 892
 
67 ilm 893
                    BigDecimal ha = row.getObject("PREBILAN") == null ? BigDecimal.ZERO : (BigDecimal) row.getObject("PREBILAN");
61 ilm 894
 
80 ilm 895
                    final BigDecimal acomptePercent = row.getBigDecimal("POURCENT_FACTURABLE");
896
                    final BigDecimal acompteMontant = row.getBigDecimal("MONTANT_FACTURABLE");
897
                    Acompte acompte = new Acompte(acomptePercent, acompteMontant);
898
                    ha = acompte.getResultFrom(ha);
899
                    vt = acompte.getResultFrom(vt);
67 ilm 900
                    return vt.subtract(ha).setScale(marge.getDecimalDigits(), RoundingMode.HALF_UP);
61 ilm 901
                }
902
 
903
            });
904
 
905
        }
906
 
142 ilm 907
        if (e.getTable().getFieldsName().contains("T_ECO_CONTRIBUTION")) {
908
            this.tableElementEcoTotal = new SQLTableElement(e.getTable().getField("T_ECO_CONTRIBUTION"));
909
            list.add(this.tableElementEcoTotal);
910
        }
911
 
18 ilm 912
        // Total HT
73 ilm 913
 
67 ilm 914
        this.totalHT.setEditable(false);
18 ilm 915
        list.add(this.totalHT);
916
        // Total TTC
65 ilm 917
        // FIXME add a modifier -> T_TTC modify P_VT_METRIQUE_1 + fix CellDynamicModifier not fire
918
        // if value not changed
83 ilm 919
        this.tableElementTotalTTC = new SQLTableElement(e.getTable().getField("T_PV_TTC"), BigDecimal.class) {
920
            @Override
132 ilm 921
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
922
                return isCellNiveauEditable(vals, rowIndex, columnIndex);
83 ilm 923
            }
924
        };
174 ilm 925
        this.tableElementTotalTTC.setRenderer(totalRenderer);
67 ilm 926
        this.tableElementTotalTTC.setEditable(false);
18 ilm 927
        list.add(this.tableElementTotalTTC);
928
 
94 ilm 929
        this.defaultRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(e.getTable()));
930
        defaultRowVals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
931
        defaultRowVals.put("CODE", "");
932
        defaultRowVals.put("NOM", "");
177 ilm 933
        if (e.getTable().contains("ID_DEPOT_STOCK")) {
934
            DefaultProps props = DefaultNXProps.getInstance();
935
            Integer depotDefault = props.getIntProperty("DepotStockDefault", DepotStockSQLElement.DEFAULT_ID);
936
            this.defaultRowVals.put("ID_DEPOT_STOCK", depotDefault);
937
        }
938
 
156 ilm 939
        final RowValuesTableModel model = new RowValuesTableModel(e, list, e.getTable().getField("ID_TAXE"), false, defaultRowVals) {
940
            @Override
941
            public void commitData() {
942
                int size = getRowCount();
943
                for (int i = 0; i < size; i++) {
944
                    SQLRowValues rowVals = getRowValuesAt(i);
945
                    if (rowVals.getObject("PV_U_DEVISE") == null) {
946
                        rowVals.put("PV_U_DEVISE", rowVals.getObject("PRIX_METRIQUE_VT_1"));
947
                        final BigDecimal globalQty = rowVals.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(rowVals.getInt("QTE")));
948
                        rowVals.put("PV_T_DEVISE", rowVals.getBigDecimal("PRIX_METRIQUE_VT_1").multiply(globalQty));
949
                    }
950
                }
177 ilm 951
                super.commitData(true);
156 ilm 952
            }
953
        };
93 ilm 954
        setModel(model);
18 ilm 955
 
93 ilm 956
        this.table = new RowValuesTable(model, getConfigurationFile());
18 ilm 957
        ToolTipManager.sharedInstance().unregisterComponent(this.table);
958
        ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
177 ilm 959
        if (getSQLElement().getTable().getName().equals("COMMANDE_CLIENT_ELEMENT")) {
960
            this.table.getClearCloneTableElement().add("QTE_LIVREE");
961
            this.table.getClearCloneTableElement().add("LIVRE");
962
            this.table.getClearCloneTableElement().add("LIVRE_FORCED");
963
        }
18 ilm 964
 
174 ilm 965
        this.table.getTableHeader().addMouseListener(new MouseAdapter() {
966
            @Override
967
            public void mousePressed(MouseEvent e) {
968
                if (e.isPopupTrigger()) {
969
                    displayPopupMenu(e);
970
                }
971
            }
972
 
973
            @Override
974
            public void mouseReleased(MouseEvent e) {
975
                if (e.isPopupTrigger()) {
976
                    displayPopupMenu(e);
977
                }
978
            }
979
 
980
            private void displayPopupMenu(MouseEvent e) {
981
                JPopupMenu menu = new JPopupMenu();
982
 
983
                TaxeCache cache = TaxeCache.getCache();
984
                Set<SQLRowAccessor> taxes = cache.getAllTaxe();
985
                JMenu subMenuTVA = new JMenu("Appliquer une TVA spécifique sur toutes les lignes");
986
                menu.add(subMenuTVA);
987
                for (SQLRowAccessor taxe : taxes) {
988
 
989
                    subMenuTVA.add(new JMenuItem(new AbstractAction(taxe.getFloat("TAUX") + "%") {
990
 
991
                        @Override
992
                        public void actionPerformed(ActionEvent e) {
993
                            for (int i = 0; i < AbstractVenteArticleItemTable.this.table.getRowCount(); i++) {
994
                                AbstractVenteArticleItemTable.this.table.getRowValuesTableModel().putValue(taxe.getID(), i, "ID_TAXE");
995
                            }
996
                        }
997
                    }));
998
                }
999
                menu.show(e.getComponent(), e.getX(), e.getY());
1000
            }
1001
        });
1002
 
93 ilm 1003
        if (filterFamilleArticle) {
1004
            ((SQLTextComboTableCellEditor) tableElementArticle.getTableCellEditor(this.table)).setDynamicWhere(e.getTable().getTable("ARTICLE").getField("ID_FAMILLE_ARTICLE"));
1005
        }
1006
 
18 ilm 1007
        // Autocompletion
93 ilm 1008
        final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
28 ilm 1009
        List<String> completionField = new ArrayList<String>();
142 ilm 1010
        if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
1011
            completionField.add("ID_ECO_CONTRIBUTION");
1012
        }
177 ilm 1013
 
156 ilm 1014
        if (showDevise) {
28 ilm 1015
            completionField.add("CODE_DOUANIER");
1016
            completionField.add("ID_PAYS");
19 ilm 1017
        }
156 ilm 1018
        completionField.add("POURCENT_REMISE");
61 ilm 1019
        completionField.add("ID_UNITE_VENTE");
156 ilm 1020
        completionField.add("QTE_UNITAIRE");
28 ilm 1021
        completionField.add("PA_HT");
1022
        completionField.add("PV_HT");
1023
        completionField.add("ID_TAXE");
1024
        completionField.add("POIDS");
1025
        completionField.add("PRIX_METRIQUE_HA_1");
1026
        completionField.add("PRIX_METRIQUE_HA_2");
1027
        completionField.add("PRIX_METRIQUE_HA_3");
1028
        completionField.add("VALEUR_METRIQUE_1");
1029
        completionField.add("VALEUR_METRIQUE_2");
1030
        completionField.add("VALEUR_METRIQUE_3");
1031
        completionField.add("ID_MODE_VENTE_ARTICLE");
1032
        completionField.add("PRIX_METRIQUE_VT_1");
1033
        completionField.add("PRIX_METRIQUE_VT_2");
1034
        completionField.add("PRIX_METRIQUE_VT_3");
1035
        completionField.add("SERVICE");
93 ilm 1036
        completionField.add("ID_FAMILLE_ARTICLE");
177 ilm 1037
        completionField.add("LONGUEUR");
1038
        completionField.add("LARGEUR");
1039
        completionField.add("HAUTEUR");
21 ilm 1040
        if (getSQLElement().getTable().getFieldsName().contains("DESCRIPTIF")) {
28 ilm 1041
            completionField.add("DESCRIPTIF");
21 ilm 1042
        }
156 ilm 1043
        if (showDevise) {
28 ilm 1044
            completionField.add("ID_DEVISE");
1045
            completionField.add("PV_U_DEVISE");
19 ilm 1046
        }
1047
        if (getSQLElement().getTable().getFieldsName().contains("QTE_ACHAT") && sqlTableArticle.getTable().getFieldsName().contains("QTE_ACHAT")) {
28 ilm 1048
            completionField.add("QTE_ACHAT");
19 ilm 1049
        }
18 ilm 1050
 
177 ilm 1051
        if (getSQLElement().getTable().getFieldsName().contains("POIDS_COLIS_NET") && sqlTableArticle.getTable().getFieldsName().contains("POIDS_COLIS_NET")) {
1052
            completionField.add("POIDS_COLIS_NET");
1053
        }
1054
        if (getSQLElement().getTable().getFieldsName().contains("TARE") && sqlTableArticle.getTable().getFieldsName().contains("TARE")) {
1055
            completionField.add("TARE");
1056
        }
1057
 
28 ilm 1058
        final AutoCompletionManager m = new AutoCompletionManager(tableElementCode, sqlTableArticle.getField("CODE"), this.table, this.table.getRowValuesTableModel()) {
93 ilm 1059
 
28 ilm 1060
            @Override
93 ilm 1061
            protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
1062
                Object res = tarifCompletion(row, field, rowDest, true);
28 ilm 1063
                if (res == null) {
174 ilm 1064
                    res = super.getValueFrom(row, field, rowDest);
28 ilm 1065
                }
174 ilm 1066
                if (field.equals("POURCENT_REMISE")) {
1067
                    return getRemiseClient(row);
1068
                }
1069
                return res;
28 ilm 1070
            }
142 ilm 1071
 
28 ilm 1072
        };
1073
        m.fill("NOM", "NOM");
61 ilm 1074
        m.fill("ID", "ID_ARTICLE");
28 ilm 1075
        for (String string : completionField) {
1076
            m.fill(string, string);
1077
        }
1078
 
132 ilm 1079
        ITransformer<SQLSelect, SQLSelect> selTrans = new ITransformer<SQLSelect, SQLSelect>() {
1080
            @Override
1081
            public SQLSelect transformChecked(SQLSelect input) {
1082
 
149 ilm 1083
                // FIXME utiliser le stock sélectionné sur la ligne et non le stock par défaut de
1084
                // l'article
132 ilm 1085
                final SQLTable tableStock = sqlTableArticle.getTable("STOCK");
1086
                input.andWhere(new Where(tableStock.getKey(), "=", sqlTableArticle.getField("ID_STOCK")));
1087
                input.setExcludeUndefined(false, tableStock);
156 ilm 1088
                Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE)
1089
                        .or(new Where(input.getAlias(tableStock.getKey()), "!=", tableStock.getUndefinedID()).and(new Where(input.getAlias(tableStock.getField("QTE_REEL")), ">", 0)));
132 ilm 1090
 
1091
                if (input.getWhere() != null) {
1092
                    input.setWhere(input.getWhere().and(w));
1093
                } else {
1094
                    input.setWhere(w);
1095
                }
1096
                input.asString();
1097
                return input;
1098
            }
1099
        };
1100
 
1101
        m.setSelectTransformer(selTrans);
1102
 
94 ilm 1103
        this.table.setDropTarget(new DropTarget() {
1104
            @Override
1105
            public synchronized void drop(DropTargetDropEvent dtde) {
1106
                dropInTable(dtde, m);
1107
                // super.drop(dtde);
1108
            }
1109
        });
1110
 
132 ilm 1111
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.CAN_EXPAND_NOMENCLATURE_VT, true)) {
93 ilm 1112
 
132 ilm 1113
            table.addMouseListener(new MouseAdapter() {
93 ilm 1114
 
132 ilm 1115
                @Override
1116
                public void mousePressed(MouseEvent e) {
1117
 
1118
                    handlePopup(e);
93 ilm 1119
                }
1120
 
132 ilm 1121
                @Override
1122
                public void mouseReleased(MouseEvent e) {
1123
 
1124
                    handlePopup(e);
1125
                }
1126
 
1127
                public void handlePopup(MouseEvent e) {
1128
                    final int rowindex = table.getSelectedRow();
1129
                    if (rowindex < 0)
1130
                        return;
1131
                    if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
1132
                        JPopupMenu popup = new JPopupMenu();
1133
                        popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.expand")) {
1134
 
1135
                            @Override
1136
                            public void actionPerformed(ActionEvent arg0) {
1137
                                expandNomenclature(rowindex, m, EXPAND_TYPE.EXPAND);
1138
                            }
1139
                        });
1140
                        popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.expose")) {
1141
 
1142
                            @Override
1143
                            public void actionPerformed(ActionEvent arg0) {
1144
                                expandNomenclature(rowindex, m, EXPAND_TYPE.VIEW_ONLY);
1145
                            }
1146
                        });
142 ilm 1147
 
1148
                        for (AbstractAction action : getAdditionnalMouseAction(rowindex)) {
1149
                            popup.add(action);
1150
                        }
1151
 
132 ilm 1152
                        popup.show(e.getComponent(), e.getX(), e.getY());
1153
                    }
1154
                }
1155
            });
1156
        }
19 ilm 1157
        final AutoCompletionManager m2 = new AutoCompletionManager(tableElementNom, sqlTableArticle.getField("NOM"), this.table, this.table.getRowValuesTableModel()) {
1158
            @Override
93 ilm 1159
            protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
1160
                Object res = tarifCompletion(row, field, rowDest, true);
19 ilm 1161
                if (res == null) {
174 ilm 1162
                    res = super.getValueFrom(row, field, rowDest);
19 ilm 1163
                }
174 ilm 1164
                if (field.equals("POURCENT_REMISE")) {
1165
                    return getRemiseClient(row);
1166
                }
1167
                return res;
19 ilm 1168
            }
1169
 
1170
        };
18 ilm 1171
        m2.fill("CODE", "CODE");
61 ilm 1172
        m2.fill("ID", "ID_ARTICLE");
28 ilm 1173
        for (String string : completionField) {
1174
            m2.fill(string, string);
19 ilm 1175
        }
1176
 
132 ilm 1177
        m2.setSelectTransformer(selTrans);
18 ilm 1178
 
61 ilm 1179
        final AutoCompletionManager m3 = new AutoCompletionManager(tableElementArticle, sqlTableArticle.getField("NOM"), this.table, this.table.getRowValuesTableModel(),
65 ilm 1180
                ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker()) {
61 ilm 1181
            @Override
93 ilm 1182
            protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
1183
                Object res = tarifCompletion(row, field, rowDest, true);
61 ilm 1184
                if (res == null) {
174 ilm 1185
                    res = super.getValueFrom(row, field, rowDest);
61 ilm 1186
                }
174 ilm 1187
                if (field.equals("POURCENT_REMISE")) {
1188
                    return getRemiseClient(row);
1189
                }
1190
                return res;
61 ilm 1191
            }
28 ilm 1192
 
61 ilm 1193
        };
1194
        m3.fill("CODE", "CODE");
1195
        m3.fill("NOM", "NOM");
1196
        for (String string : completionField) {
1197
            m3.fill(string, string);
1198
        }
28 ilm 1199
 
132 ilm 1200
        m3.setSelectTransformer(selTrans);
61 ilm 1201
 
67 ilm 1202
        // Deselection de l'article si le code est modifié
93 ilm 1203
        tableFamille.addModificationListener(tableElementArticle);
61 ilm 1204
        tableElementCode.addModificationListener(tableElementArticle);
1205
        tableElementArticle.setModifier(new CellDynamicModifier() {
1206
            @Override
93 ilm 1207
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
83 ilm 1208
                try {
93 ilm 1209
                    if (filterFamilleArticle) {
1210
                        if (row.isForeignEmpty("ID_FAMILLE_ARTICLE")) {
132 ilm 1211
                            m.setWhere(null);
1212
                            m2.setWhere(null);
93 ilm 1213
                        } else {
132 ilm 1214
                            m.setWhere(new Where(sqlTableArticle.getField("ID_FAMILLE_ARTICLE"), "=", row.getForeignID("ID_FAMILLE_ARTICLE")));
1215
                            m2.setWhere(new Where(sqlTableArticle.getField("ID_FAMILLE_ARTICLE"), "=", row.getForeignID("ID_FAMILLE_ARTICLE")));
93 ilm 1216
                        }
1217
                    }
83 ilm 1218
                    SQLRowAccessor foreign = row.getForeign("ID_ARTICLE");
1219
                    if (foreign != null && !foreign.isUndefined() && foreign.getObject("CODE") != null && foreign.getString("CODE").equals(row.getString("CODE"))) {
1220
                        return foreign.getID();
1221
                    } else {
1222
                        return tableArticle.getUndefinedID();
1223
                    }
1224
                } catch (Exception e) {
61 ilm 1225
                    return tableArticle.getUndefinedID();
1226
                }
1227
            }
1228
        });
1229
 
142 ilm 1230
        // ECO Contribution
1231
        if (this.tableElementEco != null && this.tableElementEcoTotal != null && this.tableElementEcoID != null) {
1232
            this.qte.addModificationListener(this.tableElementEcoTotal);
1233
            this.tableElementEco.addModificationListener(this.tableElementEcoTotal);
1234
            this.tableElementEcoTotal.setModifier(new CellDynamicModifier() {
1235
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
1236
 
1237
                    int qte = Integer.parseInt(row.getObject("QTE").toString());
1238
                    BigDecimal f = (row.getObject("ECO_CONTRIBUTION") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("ECO_CONTRIBUTION");
1239
                    return f.multiply(new BigDecimal(qte));
1240
                }
1241
 
1242
            });
1243
            this.tableElementEcoID.addModificationListener(this.tableElementEco);
1244
            this.tableElementEco.setModifier(new CellDynamicModifier() {
1245
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
1246
 
1247
                    if (source != null && source.equals(tableElementEcoID)) {
1248
                        return row.getForeign("ID_ECO_CONTRIBUTION").getBigDecimal("TAUX");
1249
                    } else {
1250
                        return row.getObject("ECO_CONTRIBUTION");
1251
                    }
1252
                }
1253
            });
1254
        }
1255
 
18 ilm 1256
        // Calcul automatique du total HT
93 ilm 1257
        this.qte.addModificationListener(tableElement_PrixMetrique1_VenteHT);
18 ilm 1258
        this.qte.addModificationListener(this.totalHT);
67 ilm 1259
        this.qte.addModificationListener(this.totalHA);
61 ilm 1260
        qteU.addModificationListener(this.totalHT);
67 ilm 1261
        qteU.addModificationListener(this.totalHA);
28 ilm 1262
        if (tableElementRG != null) {
1263
            tableElementRG.addModificationListener(this.totalHT);
1264
        }
19 ilm 1265
        tableElementRemise.addModificationListener(this.totalHT);
28 ilm 1266
 
18 ilm 1267
        tableElement_PrixVente_HT.addModificationListener(this.totalHT);
19 ilm 1268
        // tableElement_PrixVente_HT.addModificationListener(tableElement_PrixMetrique1_VenteHT);
67 ilm 1269
        this.ha.addModificationListener(this.totalHA);
18 ilm 1270
 
1271
        this.totalHT.setModifier(new CellDynamicModifier() {
93 ilm 1272
            public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
19 ilm 1273
 
83 ilm 1274
                BigDecimal lremise = BigDecimal.ZERO;
28 ilm 1275
 
1276
                if (row.getTable().getFieldsName().contains("POURCENT_RG")) {
1277
                    final Object o3 = row.getObject("POURCENT_RG");
93 ilm 1278
                    if (o3 != null) {
1279
                        lremise = lremise.add(((BigDecimal) o3));
1280
                    }
28 ilm 1281
                }
1282
 
19 ilm 1283
                int qte = (row.getObject("QTE") == null) ? 0 : Integer.parseInt(row.getObject("QTE").toString());
61 ilm 1284
                BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
67 ilm 1285
                BigDecimal f = (BigDecimal) row.getObject("PV_HT");
90 ilm 1286
                BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte), DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION);
67 ilm 1287
                if (lremise.compareTo(BigDecimal.ZERO) > 0 && lremise.compareTo(BigDecimal.valueOf(100)) < 100) {
90 ilm 1288
                    r = r.multiply(BigDecimal.valueOf(100).subtract(lremise), DecimalUtils.HIGH_PRECISION).movePointLeft(2);
19 ilm 1289
                }
83 ilm 1290
 
1291
                if (row.getTable().getFieldsName().contains("MONTANT_REMISE")) {
1292
                    final BigDecimal acomptePercent = row.getBigDecimal("POURCENT_REMISE");
1293
                    final BigDecimal acompteMontant = row.getBigDecimal("MONTANT_REMISE");
1294
                    Remise remise = new Remise(acomptePercent, acompteMontant);
1295
                    r = remise.getResultFrom(r);
1296
                }
1297
 
80 ilm 1298
                if (row.getTable().getFieldsName().contains("POURCENT_FACTURABLE")) {
1299
                    final BigDecimal acomptePercent = row.getBigDecimal("POURCENT_FACTURABLE");
1300
                    final BigDecimal acompteMontant = row.getBigDecimal("MONTANT_FACTURABLE");
1301
                    Acompte acompte = new Acompte(acomptePercent, acompteMontant);
1302
                    r = acompte.getResultFrom(r);
1303
                }
1304
 
67 ilm 1305
                return r.setScale(totalHT.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
18 ilm 1306
            }
1307
        });
67 ilm 1308
        this.totalHA.setModifier(new CellDynamicModifier() {
18 ilm 1309
            @Override
93 ilm 1310
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
18 ilm 1311
                int qte = Integer.parseInt(row.getObject("QTE").toString());
61 ilm 1312
                BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
67 ilm 1313
                BigDecimal f = (BigDecimal) row.getObject("PA_HT");
142 ilm 1314
                BigDecimal rHA = b.multiply(new BigDecimal(qte), DecimalUtils.HIGH_PRECISION).multiply(f, DecimalUtils.HIGH_PRECISION).setScale(6, BigDecimal.ROUND_HALF_UP);
1315
                if (row.getTable().getFieldsName().contains("POURCENT_FACTURABLE")) {
1316
                    final BigDecimal acomptePercent = row.getBigDecimal("POURCENT_FACTURABLE");
1317
                    final BigDecimal acompteMontant = row.getBigDecimal("MONTANT_FACTURABLE");
1318
                    if (acomptePercent != null || acompteMontant != null) {
1319
                        if (acomptePercent != null) {
1320
                            rHA = rHA.multiply(acomptePercent.movePointLeft(2), DecimalUtils.HIGH_PRECISION);
1321
                        } else {
1322
                            // Calcul du T_HT vente origin
1323
                            BigDecimal lremise = BigDecimal.ZERO;
1324
 
1325
                            if (row.getTable().getFieldsName().contains("POURCENT_RG")) {
1326
                                final Object o3 = row.getObject("POURCENT_RG");
1327
                                if (o3 != null) {
1328
                                    lremise = lremise.add(((BigDecimal) o3));
1329
                                }
1330
                            }
1331
 
1332
                            BigDecimal fVT = (BigDecimal) row.getObject("PV_HT");
1333
                            BigDecimal r = b.multiply(fVT.multiply(BigDecimal.valueOf(qte), DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION);
177 ilm 1334
                            if (lremise.compareTo(BigDecimal.ZERO) > 0) {
142 ilm 1335
                                r = r.multiply(BigDecimal.valueOf(100).subtract(lremise), DecimalUtils.HIGH_PRECISION).movePointLeft(2);
1336
                            }
1337
 
1338
                            if (row.getTable().getFieldsName().contains("MONTANT_REMISE")) {
1339
                                final BigDecimal acomptePercentR = row.getBigDecimal("POURCENT_REMISE");
1340
                                final BigDecimal acompteMontantR = row.getBigDecimal("MONTANT_REMISE");
1341
                                Remise remise = new Remise(acomptePercentR, acompteMontantR);
1342
                                r = remise.getResultFrom(r);
177 ilm 1343
                                // Si factrue d'avancement et remise =100% ou pv =0 alors on
1344
                                // applique le
1345
                                // ratio entre le montant facturer et le montant global
1346
                                if (acompteMontant.signum() == 0 && (acomptePercentR != null && acomptePercentR.compareTo(BigDecimal.ONE.movePointRight(2)) == 0)) {
1347
                                    r = BigDecimal.ZERO;
1348
                                    BigDecimal totalHTGlobal = getTotalHT(TypeCalcul.CALCUL_FACTURABLE);
1349
                                    if (acompteFacturer != null && acompteFacturer.getMontant() != null && totalHTGlobal != null && totalHTGlobal.signum() != 0) {
1350
                                        rHA = rHA.multiply(acompteFacturer.getMontant().divide(totalHTGlobal, DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION);
1351
                                    }
1352
                                }
142 ilm 1353
                            }
1354
                            if (r.signum() != 0) {
1355
                                rHA = rHA.multiply(acompteMontant.divide(r, DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION);
1356
                            }
1357
                        }
1358
                    }
1359
 
1360
                }
1361
                return rHA.setScale(totalHA.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
18 ilm 1362
            }
83 ilm 1363
 
1364
            @Override
1365
            public void setValueFrom(SQLRowValues row, Object value) {
1366
                super.setValueFrom(row, value);
1367
            }
18 ilm 1368
        });
1369
 
156 ilm 1370
        if (showDevise) {
19 ilm 1371
            this.qte.addModificationListener(tableElementTotalDevise);
61 ilm 1372
            qteU.addModificationListener(tableElementTotalDevise);
80 ilm 1373
            if (eltUnitDevise != null) {
1374
                eltUnitDevise.addModificationListener(tableElementTotalDevise);
1375
            }
21 ilm 1376
            tableElementRemise.addModificationListener(this.tableElementTotalDevise);
19 ilm 1377
            tableElementTotalDevise.setModifier(new CellDynamicModifier() {
1378
                @Override
93 ilm 1379
                public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
1380
                    int qte = row.getInt("QTE");
1381
                    BigDecimal prixDeVenteUnitaireDevise = (row.getObject("PV_U_DEVISE") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("PV_U_DEVISE");
1382
                    BigDecimal qUnitaire = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
1383
                    // r = prixUnitaire x qUnitaire x qte
1384
                    BigDecimal prixVente = qUnitaire.multiply(prixDeVenteUnitaireDevise.multiply(BigDecimal.valueOf(qte), DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION);
67 ilm 1385
 
83 ilm 1386
                    if (row.getTable().getFieldsName().contains("MONTANT_REMISE")) {
1387
                        final BigDecimal acomptePercent = row.getBigDecimal("POURCENT_REMISE");
1388
                        final BigDecimal acompteMontant = row.getBigDecimal("MONTANT_REMISE");
1389
                        Remise remise = new Remise(acomptePercent, acompteMontant);
93 ilm 1390
                        prixVente = remise.getResultFrom(prixVente);
21 ilm 1391
                    }
83 ilm 1392
 
1393
                    // if (lremise.compareTo(BigDecimal.ZERO) > 0 &&
1394
                    // lremise.compareTo(BigDecimal.valueOf(100)) < 100) {
1395
                    // r = r.multiply(BigDecimal.valueOf(100).subtract(lremise),
90 ilm 1396
                    // DecimalUtils.HIGH_PRECISION).movePointLeft(2);
83 ilm 1397
                    // }
93 ilm 1398
                    return prixVente.setScale(tableElementTotalDevise.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
19 ilm 1399
                }
1400
            });
1401
        }
18 ilm 1402
        // Calcul automatique du total TTC
73 ilm 1403
 
18 ilm 1404
        this.totalHT.addModificationListener(this.tableElementTotalTTC);
61 ilm 1405
        this.tableElementTVA.addModificationListener(this.tableElementTotalTTC);
18 ilm 1406
        this.tableElementTotalTTC.setModifier(new CellDynamicModifier() {
1407
            @Override
93 ilm 1408
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
21 ilm 1409
 
73 ilm 1410
                BigDecimal ht = (BigDecimal) row.getObject("T_PV_HT");
93 ilm 1411
                int idTaux = row.getForeignID("ID_TAXE");
18 ilm 1412
 
1413
                Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
1414
 
1415
                if (resultTaux == null) {
80 ilm 1416
                    SQLRow rowTax = TaxeCache.getCache().getFirstTaxe();
1417
                    row.put("ID_TAXE", rowTax.getID());
1418
                    resultTaux = rowTax.getFloat("TAUX");
18 ilm 1419
                }
1420
 
1421
                float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
73 ilm 1422
                editorPVHT.setTaxe(taux);
94 ilm 1423
                editorPVHT.setMin(null);
1424
                if (!row.isForeignEmpty("ID_ARTICLE") && getSQLElement().getTable().getDBRoot().contains("ARTICLE_PRIX_MIN_VENTE") && !lockVTMinPrice) {
1425
                    List<SQLRow> minPrices = row.getForeign("ID_ARTICLE").asRow().getReferentRows(row.getTable().getTable("ARTICLE_PRIX_MIN_VENTE"));
1426
                    if (minPrices.size() > 0) {
1427
                        editorPVHT.setMin(minPrices.get(0).getBigDecimal("PRIX"));
1428
                    }
1429
                }
73 ilm 1430
 
90 ilm 1431
                BigDecimal r = ht.multiply(BigDecimal.valueOf(taux).movePointLeft(2).add(BigDecimal.ONE), DecimalUtils.HIGH_PRECISION);
73 ilm 1432
                final BigDecimal resultTTC = r.setScale(tableElementTotalTTC.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
83 ilm 1433
 
73 ilm 1434
                return resultTTC;
18 ilm 1435
            }
1436
 
83 ilm 1437
            @Override
1438
            public void setValueFrom(SQLRowValues row, Object value) {
1439
                super.setValueFrom(row, value);
1440
            }
1441
 
18 ilm 1442
        });
21 ilm 1443
 
18 ilm 1444
        // Calcul automatique du poids unitaire
1445
        tableElement_ValeurMetrique1.addModificationListener(tableElementPoids);
1446
        tableElement_ValeurMetrique2.addModificationListener(tableElementPoids);
1447
        tableElement_ValeurMetrique3.addModificationListener(tableElementPoids);
1448
        tableElementPoids.setModifier(new CellDynamicModifier() {
93 ilm 1449
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
18 ilm 1450
                return new Float(ReferenceArticleSQLElement.getPoidsFromDetails(row));
1451
            }
1452
 
1453
        });
1454
        // Calcul automatique du poids total
1455
        tableElementPoids.addModificationListener(this.tableElementPoidsTotal);
61 ilm 1456
        qteU.addModificationListener(tableElementPoidsTotal);
18 ilm 1457
        this.qte.addModificationListener(this.tableElementPoidsTotal);
1458
        this.tableElementPoidsTotal.setModifier(new CellDynamicModifier() {
93 ilm 1459
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
18 ilm 1460
                Number f = (Number) row.getObject("POIDS");
80 ilm 1461
                if (f == null) {
1462
                    f = 0;
1463
                }
18 ilm 1464
                int qte = Integer.parseInt(row.getObject("QTE").toString());
61 ilm 1465
                BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
1466
                // FIXME convertir en float autrement pour éviter une valeur non valeur transposable
1467
                // avec floatValue ou passer POIDS en bigDecimal
1468
                return b.multiply(new BigDecimal(f.floatValue() * qte)).floatValue();
18 ilm 1469
            }
1470
 
1471
        });
61 ilm 1472
        uniteVente.addModificationListener(qteU);
177 ilm 1473
        eltLargeur.addModificationListener(qteU);
1474
        eltLongueur.addModificationListener(qteU);
61 ilm 1475
        qteU.setModifier(new CellDynamicModifier() {
93 ilm 1476
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
61 ilm 1477
                SQLRowAccessor rowUnite = row.getForeign("ID_UNITE_VENTE");
1478
                if (rowUnite != null && !rowUnite.isUndefined() && rowUnite.getBoolean("A_LA_PIECE")) {
1479
                    return BigDecimal.ONE;
177 ilm 1480
                } else if (activeCalculM2 && rowUnite != null && !rowUnite.isUndefined() && rowUnite.getID() == UniteVenteArticleSQLElement.M2) {
1481
                    BigDecimal longueur = row.getBigDecimal("LONGUEUR");
1482
                    BigDecimal largeur = row.getBigDecimal("LARGEUR");
1483
                    if (longueur == null || largeur == null) {
1484
                        return BigDecimal.ONE;
1485
                    }
1486
                    return longueur.multiply(largeur);
61 ilm 1487
                } else {
1488
                    return row.getObject("QTE_UNITAIRE");
1489
                }
1490
            }
1491
 
1492
        });
93 ilm 1493
 
1494
        tableElement_PrixMetrique1_VenteHT.setModifier(new CellDynamicModifier() {
1495
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
1496
                if (source != null && source.getField().getName().equals("PRIX_METRIQUE_VT_1")) {
1497
                    return row.getObject("PRIX_METRIQUE_VT_1");
1498
                } else {
1499
                    if (source != null && source.getField().getName().equals("PV_U_DEVISE")) {
1500
                        if (!row.isForeignEmpty("ID_DEVISE")) {
1501
                            String devCode = row.getForeign("ID_DEVISE").getString("CODE");
1502
                            BigDecimal prixDeVenteUnitaireDevise = (row.getObject("PV_U_DEVISE") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("PV_U_DEVISE");
1503
 
1504
                            CurrencyConverter c = new CurrencyConverter();
1505
                            BigDecimal result = c.convert(prixDeVenteUnitaireDevise, devCode, c.getCompanyCurrencyCode(), getDateDevise(), isUsedBiasedDevise());
1506
                            if (result == null) {
1507
                                result = prixDeVenteUnitaireDevise;
1508
                            }
1509
                            return result.setScale(row.getTable().getField("PRIX_METRIQUE_VT_1").getType().getDecimalDigits(), RoundingMode.HALF_UP);
1510
                        } else {
1511
                            return row.getObject("PRIX_METRIQUE_VT_1");
1512
                        }
1513
                    }
1514
                    return tarifCompletion(row.getForeign("ID_ARTICLE"), "PRIX_METRIQUE_VT_1", row);
1515
                }
1516
            }
1517
 
1518
        });
1519
 
156 ilm 1520
        if (showDevise) {
80 ilm 1521
            if (eltUnitDevise != null) {
1522
                eltUnitDevise.addModificationListener(tableElement_PrixMetrique1_VenteHT);
1523
            }
83 ilm 1524
 
93 ilm 1525
            if (eltUnitDevise != null) {
1526
                tableElement_PrixMetrique1_VenteHT.addModificationListener(eltUnitDevise);
132 ilm 1527
                eltDevise.addModificationListener(eltUnitDevise);
93 ilm 1528
                eltUnitDevise.setModifier(new CellDynamicModifier() {
1529
                    public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
1530
                        if (source != null && source.getField().getName().equals("PV_U_DEVISE")) {
1531
                            BigDecimal prixDeVenteUnitaireDevise = (row.getObject("PV_U_DEVISE") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("PV_U_DEVISE");
1532
                            return prixDeVenteUnitaireDevise;
1533
                        } else {
1534
                            if (!row.isForeignEmpty("ID_DEVISE")) {
1535
                                String devCode = row.getForeign("ID_DEVISE").getString("CODE");
1536
                                BigDecimal bigDecimal = (BigDecimal) row.getObject("PRIX_METRIQUE_VT_1");
1537
 
1538
                                CurrencyConverter c = new CurrencyConverter();
1539
                                BigDecimal result = c.convert(bigDecimal, c.getCompanyCurrencyCode(), devCode, getDateDevise(), isUsedBiasedDevise());
1540
                                if (result == null) {
1541
                                    result = bigDecimal;
1542
                                }
1543
                                return result.setScale(row.getTable().getField("PRIX_METRIQUE_VT_1").getType().getDecimalDigits(), RoundingMode.HALF_UP);
1544
                            } else if (source != null && source.getField().getName().equalsIgnoreCase("PRIX_METRIQUE_VT_1")) {
1545
                                return row.getObject("PRIX_METRIQUE_VT_1");
1546
                            }
1547
                            BigDecimal prixDeVenteUnitaireDevise = (row.getObject("PV_U_DEVISE") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("PV_U_DEVISE");
1548
                            return prixDeVenteUnitaireDevise;
1549
                        }
19 ilm 1550
                    }
1551
 
93 ilm 1552
                });
1553
            }
19 ilm 1554
        }
1555
 
18 ilm 1556
        // Calcul automatique du prix de vente unitaire HT
1557
        tableElement_ValeurMetrique1.addModificationListener(tableElement_PrixVente_HT);
1558
        tableElement_ValeurMetrique2.addModificationListener(tableElement_PrixVente_HT);
1559
        tableElement_ValeurMetrique3.addModificationListener(tableElement_PrixVente_HT);
1560
        tableElement_PrixMetrique1_VenteHT.addModificationListener(tableElement_PrixVente_HT);
1561
        tableElement_PrixVente_HT.setModifier(new CellDynamicModifier() {
93 ilm 1562
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
1563
                if (row.isForeignEmpty("ID_MODE_VENTE_ARTICLE") || row.getInt("ID_MODE_VENTE_ARTICLE") == ReferenceArticleSQLElement.A_LA_PIECE) {
67 ilm 1564
                    return row.getObject("PRIX_METRIQUE_VT_1");
18 ilm 1565
                } else {
1566
 
67 ilm 1567
                    final BigDecimal prixVTFromDetails = ReferenceArticleSQLElement.getPrixVTFromDetails(row);
1568
                    return prixVTFromDetails.setScale(tableElement_PrixVente_HT.getDecimalDigits(), RoundingMode.HALF_UP);
18 ilm 1569
                }
1570
            }
1571
        });
1572
 
1573
        // Calcul automatique du prix d'achat unitaire HT
1574
        tableElement_ValeurMetrique1.addModificationListener(this.ha);
1575
        tableElement_ValeurMetrique2.addModificationListener(this.ha);
1576
        tableElement_ValeurMetrique3.addModificationListener(this.ha);
1577
        tableElement_PrixMetrique1_AchatHT.addModificationListener(this.ha);
1578
        this.ha.setModifier(new CellDynamicModifier() {
93 ilm 1579
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
1580
                if (row.isForeignEmpty("ID_MODE_VENTE_ARTICLE") || row.getInt("ID_MODE_VENTE_ARTICLE") == ReferenceArticleSQLElement.A_LA_PIECE) {
67 ilm 1581
                    return row.getObject("PRIX_METRIQUE_HA_1");
18 ilm 1582
                } else {
1583
 
67 ilm 1584
                    final BigDecimal prixHAFromDetails = ReferenceArticleSQLElement.getPrixHAFromDetails(row);
1585
                    return prixHAFromDetails.setScale(ha.getDecimalDigits(), RoundingMode.HALF_UP);
18 ilm 1586
                }
1587
            }
1588
 
1589
        });
1590
 
1591
        this.table.readState();
1592
 
93 ilm 1593
        setColumnVisible(model.getColumnForField("T_PA_HT"), true);
18 ilm 1594
 
80 ilm 1595
        // Packaging
1596
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ITEM_PACKAGING, false)) {
93 ilm 1597
            setColumnVisible(model.getColumnForField("T_POIDS_COLIS_NET"), false);
80 ilm 1598
        }
1599
 
18 ilm 1600
        // Mode Gestion article avancé
21 ilm 1601
        final boolean modeAvance = DefaultNXProps.getInstance().getBooleanValue("ArticleModeVenteAvance", false);
93 ilm 1602
        setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_1"), modeAvance);
1603
        setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_2"), modeAvance);
1604
        setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_3"), modeAvance);
1605
        setColumnVisible(model.getColumnForField("PV_HT"), modeAvance);
1606
        setColumnVisible(model.getColumnForField("PA_HT"), modeAvance);
1607
        setColumnVisible(model.getColumnForField("ID_MODE_VENTE_ARTICLE"), modeAvance);
18 ilm 1608
 
142 ilm 1609
        if (this.tableElementEco != null && this.tableElementEcoTotal != null && this.tableElementEcoID != null) {
1610
            setColumnVisible(model.getColumnForField("ID_ECO_CONTRIBUTION"), showEco);
1611
            setColumnVisible(model.getColumnForField("ECO_CONTRIBUTION"), showEco);
1612
            setColumnVisible(model.getColumnForField("T_ECO_CONTRIBUTION"), showEco);
1613
        }
1614
 
177 ilm 1615
        // ACtivation calcul m2
1616
        setColumnVisible(model.getColumnForField("HAUTEUR"), false);
1617
        setColumnVisible(model.getColumnForField("LARGEUR"), activeCalculM2);
1618
        setColumnVisible(model.getColumnForField("LONGUEUR"), activeCalculM2);
1619
 
61 ilm 1620
        // Gestion des unités de vente
1621
        final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
93 ilm 1622
        setColumnVisible(model.getColumnForField("QTE_UNITAIRE"), gestionUV);
1623
        setColumnVisible(model.getColumnForField("ID_UNITE_VENTE"), gestionUV);
61 ilm 1624
 
93 ilm 1625
        setColumnVisible(model.getColumnForField("ID_ARTICLE"), selectArticle);
1626
        setColumnVisible(model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
1627
        setColumnVisible(model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
61 ilm 1628
 
18 ilm 1629
        // Voir le poids
21 ilm 1630
        final boolean showPoids = DefaultNXProps.getInstance().getBooleanValue("ArticleShowPoids", false);
93 ilm 1631
        setColumnVisible(model.getColumnForField("POIDS"), showPoids);
1632
        setColumnVisible(model.getColumnForField("T_POIDS"), showPoids);
18 ilm 1633
 
1634
        // Voir le style
93 ilm 1635
        setColumnVisible(model.getColumnForField("ID_STYLE"), DefaultNXProps.getInstance().getBooleanValue("ArticleShowStyle", true));
1636
        setColumnVisible(model.getColumnForField("POURCENT_FACTURABLE"), false);
18 ilm 1637
 
93 ilm 1638
        setColumnVisible(getModel().getColumnForField("ID_FAMILLE_ARTICLE"), filterFamilleArticle);
28 ilm 1639
 
94 ilm 1640
        setColumnVisible(model.getColumnForField("PRIX_METRIQUE_HA_1"), showHAPrice);
156 ilm 1641
        setColumnVisible(model.getColumnForField("MARGE_HT"), showHAPrice);
94 ilm 1642
        setColumnVisible(model.getColumnForField("T_PA_HT"), showHAPrice);
93 ilm 1643
 
94 ilm 1644
 
156 ilm 1645
        setColumnVisible(model.getColumnForField("ID_DEPOT_STOCK"), prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false));
1646
 
177 ilm 1647
        setColumnVisible(model.getColumnForField("T_POIDS_COLIS_NET"), false);
1648
        setColumnVisible(model.getColumnForField("T_POIDS_BRUT"), false);
1649
 
28 ilm 1650
        for (String string : visibilityMap.keySet()) {
93 ilm 1651
            setColumnVisible(model.getColumnForField(string), visibilityMap.get(string));
28 ilm 1652
        }
1653
 
41 ilm 1654
        Map<String, Boolean> mapCustom = getCustomVisibilityMap();
1655
        if (mapCustom != null) {
1656
            for (String string : mapCustom.keySet()) {
93 ilm 1657
                setColumnVisible(model.getColumnForField(string), mapCustom.get(string));
41 ilm 1658
            }
1659
        }
1660
 
142 ilm 1661
        // Barcode reader
1662
        final BarcodeReader barcodeReader = ComptaPropsConfiguration.getInstanceCompta().getBarcodeReader();
1663
        if (barcodeReader != null) {
1664
 
1665
            final BarcodeListener l = new BarcodeListener() {
1666
 
1667
                @Override
1668
                public void keyReceived(KeyEvent ee) {
1669
                    // TODO Auto-generated method stub
1670
                }
1671
 
1672
                @Override
1673
                public void barcodeRead(String code) {
1674
                    if (((JFrame) SwingUtilities.getRoot(getRowValuesTable())).isActive()) {
1675
                        final SQLSelect selArticle = new SQLSelect();
1676
                        final SQLTable tableArticle = getSQLElement().getForeignElement("ID_ARTICLE").getTable();
1677
                        selArticle.addSelectStar(tableArticle);
1678
                        Where w = new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
1679
                        w = w.and(new Where(tableArticle.getField("CODE_BARRE"), "=", code));
1680
                        selArticle.setWhere(w);
1681
                        List<SQLRow> l2 = SQLRowListRSH.execute(selArticle);
1682
                        if (l2.size() > 0) {
1683
                            System.err.println("ARTICLE " + l2.get(0).getString("NOM"));
1684
                            Tuple3<Double, String, String> art = Tuple3.create(1.0D, l2.get(0).getString("CODE"), l2.get(0).getString("NOM"));
1685
                            List<Tuple3<Double, String, String>> l = new ArrayList<Tuple3<Double, String, String>>();
1686
                            l.add(art);
1687
                            insertFromDrop(l, m);
1688
                        } else {
1689
                            System.err.println("ARTICLE NOT FOUND !");
1690
                        }
1691
                    }
1692
 
1693
                }
1694
            };
1695
            getRowValuesTable().addHierarchyListener(new HierarchyListener() {
1696
                public void hierarchyChanged(HierarchyEvent e) {
1697
                    if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0)
1698
                        if (getRowValuesTable().isDisplayable()) {
1699
                            barcodeReader.addBarcodeListener(l);
1700
                        } else {
1701
                            barcodeReader.removeBarcodeListener(l);
1702
                        }
1703
                }
1704
            });
1705
 
1706
        }
1707
 
18 ilm 1708
        // On réécrit la configuration au cas ou les preferences aurait changé (ajout ou suppression
1709
        // du mode de vente specifique)
1710
        this.table.writeState();
174 ilm 1711
 
1712
        if (this.table.getRowValuesTableModel().getColumnForField("ID_DEPOT_STOCK") >= 0 && this.table.getRowValuesTableModel().getColumnForField("ID_ARTICLE") >= 0) {
1713
            if (this.buttons == null) {
1714
                this.buttons = new ArrayList<>();
1715
            }
1716
 
1717
            JButton buttonStock = new JButton("Consulter le stock");
1718
            buttonStock.addActionListener(new ActionListener() {
1719
                public void actionPerformed(ActionEvent event) {
1720
                    SQLRowValues rowValsSel = table.getSelectedRowValues();
1721
                    if (rowValsSel != null) {
1722
                        SQLRowAccessor foreignArt = rowValsSel.getForeign("ID_ARTICLE");
1723
                        if (foreignArt != null && !foreignArt.isUndefined()) {
1724
                            SQLRowAccessor rowValsStock = StockSQLElement.getStock(rowValsSel);
1725
                            if (rowValsStock != null && !rowValsStock.isUndefined()) {
1726
                                EditFrame frame = new EditFrame(table.getRowValuesTableModel().getSQLElement().getDirectory().getElement("STOCK"), EditMode.READONLY);
1727
                                frame.selectionId(rowValsStock.getID());
1728
                                frame.setVisible(true);
1729
                            }
1730
                        }
1731
                    }
1732
 
1733
                }
1734
            });
1735
 
1736
            this.buttons.add(buttonStock);
1737
 
1738
        }
1739
 
18 ilm 1740
    }
1741
 
174 ilm 1742
    Collection<? extends SQLRowAccessor> cacheRemise = null;
180 ilm 1743
    Collection<? extends SQLRowAccessor> cacheRemiseFamille = null;
174 ilm 1744
 
1745
    protected BigDecimal getTarifRemiseClient(SQLRowAccessor article, BigDecimal pv) {
1746
        if (cacheRemise != null) {
1747
            if (getRowClient() != null && !getRowClient().isUndefined() && article != null && !article.isUndefined()) {
1748
                for (SQLRowAccessor sqlRowAccessor : cacheRemise) {
1749
                    if (!sqlRowAccessor.isForeignEmpty("ID_ARTICLE") && sqlRowAccessor.getForeignID("ID_ARTICLE") == article.getID()) {
1750
                        BigDecimal remise = sqlRowAccessor.getBigDecimal("POURCENT_REMISE");
1751
                        if (remise != null) {
1752
                            return pv.multiply(BigDecimal.ONE.subtract(remise.movePointLeft(2)), DecimalUtils.HIGH_PRECISION).setScale(pv.scale(), RoundingMode.HALF_UP);
1753
                        }
1754
                    }
1755
                }
1756
            }
1757
        }
1758
        return pv;
1759
    }
1760
 
1761
    protected Acompte getRemiseClient(SQLRowAccessor article) {
180 ilm 1762
        Acompte remise = null;
1763
        if (this.cacheRemiseFamille != null) {
1764
            if (getRowClient() != null && !getRowClient().isUndefined() && article != null && !article.isUndefined()) {
1765
                if (article.getForeign("ID_FAMILLE_ARTICLE") != null && !article.isForeignEmpty("ID_FAMILLE_ARTICLE")) {
1766
                    Integer fID = article.getForeignID("ID_FAMILLE_ARTICLE");
1767
 
1768
                    remise = getRemiseFamille(fID);
1769
                    // TODO faire une fonction recursive avec un test pour eviter les boucles
1770
                    if (remise == null) {
1771
                        SQLBackgroundTableCacheItem cacheTableFamille = SQLBackgroundTableCache.getInstance().getCacheForTable(article.getTable().getForeignTable("ID_FAMILLE_ARTICLE"));
1772
                        SQLRow rowFamille = cacheTableFamille.getRowFromId(fID);
1773
                        if (rowFamille != null && rowFamille.getObject("ID_FAMILLE_ARTICLE_PERE") != null && !rowFamille.isForeignEmpty("ID_FAMILLE_ARTICLE_PERE")) {
1774
                            Integer fIDPere = rowFamille.getForeignID("ID_FAMILLE_ARTICLE_PERE");
1775
                            remise = getRemiseFamille(fIDPere);
1776
                            if (remise == null) {
1777
                                SQLRow rowFamille2 = cacheTableFamille.getRowFromId(fIDPere);
1778
                                if (rowFamille2 != null && rowFamille2.getObject("ID_FAMILLE_ARTICLE_PERE") != null && !rowFamille2.isForeignEmpty("ID_FAMILLE_ARTICLE_PERE")) {
1779
                                    Integer fIDPere2 = rowFamille2.getForeignID("ID_FAMILLE_ARTICLE_PERE");
1780
                                    remise = getRemiseFamille(fIDPere2);
1781
                                }
1782
                            }
1783
                        }
1784
 
1785
                    }
1786
                }
1787
            }
1788
        }
174 ilm 1789
        if (this.cacheRemise != null) {
1790
            if (getRowClient() != null && !getRowClient().isUndefined() && article != null && !article.isUndefined()) {
1791
                for (SQLRowAccessor sqlRowAccessor : this.cacheRemise) {
1792
                    if (!sqlRowAccessor.isForeignEmpty("ID_ARTICLE") && sqlRowAccessor.getForeignID("ID_ARTICLE") == article.getID()) {
1793
                        BigDecimal r = sqlRowAccessor.getBigDecimal("POURCENT_REMISE");
180 ilm 1794
                        remise = new Acompte(r, null);
1795
                        break;
174 ilm 1796
                    }
1797
                }
1798
            }
1799
        }
180 ilm 1800
        if (remise == null) {
1801
            return new Acompte(BigDecimal.ZERO, BigDecimal.ZERO);
1802
        } else {
1803
            return remise;
1804
        }
1805
    }
1806
 
1807
    private Acompte getRemiseFamille(int fID) {
1808
        Acompte remise = null;
1809
        for (SQLRowAccessor sqlRowAccessor : this.cacheRemiseFamille) {
1810
            if (!sqlRowAccessor.isForeignEmpty("ID_FAMILLE_ARTICLE") && sqlRowAccessor.getForeignID("ID_FAMILLE_ARTICLE") == fID) {
1811
                BigDecimal r = sqlRowAccessor.getBigDecimal("POURCENT_REMISE");
1812
                remise = new Acompte(r, null);
1813
                break;
1814
            }
1815
        }
174 ilm 1816
        return remise;
1817
    }
1818
 
93 ilm 1819
    @Override
1820
    protected void refreshDeviseAmount() {
1821
        int count = getRowValuesTable().getRowCount();
1822
        final int columnForField = getRowValuesTable().getRowValuesTableModel().getColumnForField("PV_U_DEVISE");
1823
        if (columnForField >= 0) {
1824
            SQLTableElement eltDevise = getRowValuesTable().getRowValuesTableModel().getSQLTableElementAt(columnForField);
1825
            for (int i = 0; i < count; i++) {
1826
                SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
1827
                // getRowValuesTable().getRowValuesTableModel().putValue(rowVals.getObject("PV_U_DEVISE"),
1828
                // i, "PV_U_DEVISE", true);
1829
                BigDecimal prixDeVenteUnitaireDevise = (rowVals.getObject("PV_U_DEVISE") == null) ? BigDecimal.ZERO : (BigDecimal) rowVals.getObject("PV_U_DEVISE");
1830
                eltDevise.setValueFrom(rowVals, prixDeVenteUnitaireDevise);
1831
                getRowValuesTable().getRowValuesTableModel().fireTableChanged(new TableModelEvent(getRowValuesTable().getRowValuesTableModel(), i, i, columnForField));
1832
            }
1833
        }
1834
    }
1835
 
41 ilm 1836
    protected Map<String, Boolean> getCustomVisibilityMap() {
1837
        return null;
1838
    }
1839
 
93 ilm 1840
    protected Object tarifCompletion(SQLRowAccessor row, String field, SQLRowAccessor rowDest) {
1841
        return tarifCompletion(row, field, rowDest, false);
1842
    }
19 ilm 1843
 
93 ilm 1844
    protected Object tarifCompletion(SQLRowAccessor row, String field, SQLRowAccessor rowDest, boolean fromCompletion) {
1845
 
156 ilm 1846
        if (row != null && !row.isUndefined() && (field.equalsIgnoreCase("PRIX_METRIQUE_HA_1") || field.equalsIgnoreCase("PA_HT"))) {
132 ilm 1847
 
156 ilm 1848
            if (getSQLElement().getTable().getDBRoot().contains("ARTICLE_PRIX_REVIENT")) {
1849
                final BigDecimal prc;
1850
                if (row.getBoolean("AUTO_PRIX_REVIENT_NOMENCLATURE")) {
1851
                    ProductHelper helper = new ProductHelper(row.getTable().getDBRoot());
1852
                    prc = helper.getBomPriceForQuantity(1, row.getReferentRows(row.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT")), TypePrice.ARTICLE_PRIX_REVIENT);
1853
                } else {
1854
                    ProductComponent productComp = new ProductComponent(row, BigDecimal.ONE, null, null);
1855
                    prc = productComp.getPRC(new Date());
1856
                }
1857
                if (prc == null) {
1858
                    return BigDecimal.ZERO;
1859
                }
1860
                return prc;
1861
            } else if (getSQLElement().getTable().getDBRoot().contains("COUT_REVIENT") && row.getObject("ID_COUT_REVIENT") != null && !row.isForeignEmpty("ID_COUT_REVIENT")) {
1862
                BigDecimal ha = row.getBigDecimal(field);
1863
                BigDecimal percent = row.getForeign("ID_COUT_REVIENT").getBigDecimal("POURCENT");
1864
                return ha.multiply(percent.movePointLeft(2).add(BigDecimal.ONE)).setScale(ha.precision(), RoundingMode.HALF_UP);
132 ilm 1865
            }
94 ilm 1866
        }
1867
 
73 ilm 1868
        if (getTarif() != null && !getTarif().isUndefined()) {
28 ilm 1869
            Collection<? extends SQLRowAccessor> rows = row.getReferentRows(tableArticleTarif);
19 ilm 1870
 
93 ilm 1871
            // Récupération du tarif associé à la quantité
1872
            int quantite = 0;
1873
            BigDecimal b = rowDest.getBigDecimal("QTE_UNITAIRE");
1874
            int q = rowDest.getInt("QTE");
1875
            BigDecimal qteTotal = b.multiply(new BigDecimal(q), DecimalUtils.HIGH_PRECISION);
28 ilm 1876
            SQLRowAccessor rowTarif = null;
93 ilm 1877
 
1878
            for (SQLRowAccessor sqlRowAccessor : rows) {
1879
 
1880
                if (!sqlRowAccessor.getTable().contains("OBSOLETE") || !sqlRowAccessor.getBoolean("OBSOLETE")) {
1881
                    // FIXME BigDecimal??
1882
                    // BigDecimal bigDecimal = sqlRowAccessor.getBigDecimal("QTE");
1883
                    int qteTarif = sqlRowAccessor.getInt("QTE");
1884
                    if (sqlRowAccessor.getForeignID("ID_TARIF") == getTarif().getID() && CompareUtils.compare(qteTarif, qteTotal) <= 0 && CompareUtils.compare(qteTarif, quantite) > 0) {
1885
                        quantite = qteTarif;
1886
                        rowTarif = sqlRowAccessor;
1887
                        // else {
1888
                        // result = null;
1889
                        // remise = sqlRowAccessor.getBigDecimal("POURCENT_REMISE");
1890
                        // }
1891
                    }
19 ilm 1892
                }
1893
            }
1894
 
1895
            if (rowTarif == null) {
93 ilm 1896
                if (!getTarif().isForeignEmpty("ID_DEVISE")) {
19 ilm 1897
                    if ((field.equalsIgnoreCase("ID_DEVISE"))) {
1898
                        return getTarif().getObject("ID_DEVISE");
1899
                    } else if ((field.equalsIgnoreCase("PV_U_DEVISE"))) {
1900
 
132 ilm 1901
                        return getQtyTarifPvM1(rowDest, fromCompletion);
93 ilm 1902
                    }
1903
                }
1904
                if ((field.equalsIgnoreCase("ID_TAXE"))) {
83 ilm 1905
 
93 ilm 1906
                    if (!getTarif().isForeignEmpty("ID_TAXE")) {
1907
                        return getTarif().getForeignID("ID_TAXE");
19 ilm 1908
                    }
1909
                }
1910
 
93 ilm 1911
            } else {
1912
                if (field.equalsIgnoreCase("PRIX_METRIQUE_VT_1")) {
1913
                    if (rowTarif.isForeignEmpty("ID_DEVISE"))
1914
                        return rowTarif.getObject(field);
1915
                    else {
19 ilm 1916
 
93 ilm 1917
                        String devCode = getTarif().getForeign("ID_DEVISE").getString("CODE");
1918
                        CurrencyConverter c = new CurrencyConverter();
1919
                        BigDecimal result = c.convert(rowTarif.getBigDecimal(field), devCode, c.getCompanyCurrencyCode(), new Date(), true);
1920
                        return result.setScale(row.getTable().getField(field).getType().getDecimalDigits(), RoundingMode.HALF_UP);
1921
                    }
19 ilm 1922
 
93 ilm 1923
                } else if ((field.equalsIgnoreCase("ID_DEVISE"))) {
19 ilm 1924
 
93 ilm 1925
                    return rowTarif.getObject("ID_DEVISE");
1926
                }
19 ilm 1927
 
93 ilm 1928
                else if ((field.equalsIgnoreCase("PV_U_DEVISE"))) {
19 ilm 1929
 
93 ilm 1930
                    return rowTarif.getObject("PRIX_METRIQUE_VT_1");
19 ilm 1931
 
93 ilm 1932
                } else if ((field.equalsIgnoreCase("ID_TAXE"))) {
1933
 
1934
                    if (!rowTarif.isForeignEmpty("ID_TAXE")) {
1935
                        return rowTarif.getObject("ID_TAXE");
1936
 
1937
                    }
94 ilm 1938
                } else if ((field.equalsIgnoreCase("POURCENT_REMISE"))) {
1939
                    Acompte remise = new Acompte(rowTarif.getBigDecimal("POURCENT_REMISE"), BigDecimal.ZERO);
1940
                    return remise;
19 ilm 1941
                }
1942
            }
1943
        }
93 ilm 1944
 
156 ilm 1945
        if (field.equalsIgnoreCase("ID_TAXE_VENTE") && this.rowCatComptable != null) {
1946
            return this.rowCatComptable.getForeignID("ID_TAXE_VENTE");
1947
        }
1948
 
94 ilm 1949
        if ((field.equalsIgnoreCase("POURCENT_REMISE"))) {
1950
            return new Acompte(BigDecimal.ZERO, BigDecimal.ZERO);
1951
        }
1952
 
93 ilm 1953
        if ((field.equalsIgnoreCase("PRIX_METRIQUE_VT_1"))) {
1954
            return getQtyTarifPvM1(rowDest, fromCompletion);
1955
        } else {
1956
            return null;
1957
        }
19 ilm 1958
    }
1959
 
1960
    @Override
174 ilm 1961
    public void setClient(SQLRowAccessor rowClient, boolean ask) {
1962
        if (rowClient == null || getRowClient() == null || rowClient.getID() != getRowClient().getID()) {
1963
            super.setClient(rowClient, ask);
1964
            if (getRowClient() != null && !getRowClient().isUndefined()) {
1965
                this.cacheRemise = getRowClient().getReferentRows(getSQLElement().getTable().getTable("TARIF_ARTICLE_CLIENT"));
180 ilm 1966
                this.cacheRemiseFamille = getRowClient().getReferentRows(getSQLElement().getTable().getTable("TARIF_FAMILLE_ARTICLE_CLIENT"));
1967
                if (ask && (!this.cacheRemise.isEmpty() || !this.cacheRemiseFamille.isEmpty()) && getRowValuesTable().getRowCount() > 0
174 ilm 1968
                        && JOptionPane.showConfirmDialog(null, "Appliquer les remises associées au client sur les lignes déjà présentes?") == JOptionPane.YES_OPTION) {
1969
                    int nbRows = this.table.getRowCount();
1970
                    for (int i = 0; i < nbRows; i++) {
1971
                        SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
1972
 
1973
                        if (!rowVals.isForeignEmpty("ID_ARTICLE")) {
1974
                            SQLRowAccessor rowValsArt = rowVals.getForeign("ID_ARTICLE");
1975
                            final Object taxeValue = tarifCompletion(rowValsArt, "ID_TAXE", rowVals);
1976
                            if (taxeValue != null) {
1977
                                getRowValuesTable().getRowValuesTableModel().putValue(taxeValue, i, "ID_TAXE");
1978
                            }
1979
 
1980
                            final Object deviseValue = tarifCompletion(rowValsArt, "ID_DEVISE", rowVals);
1981
                            if (deviseValue != null) {
1982
                                getRowValuesTable().getRowValuesTableModel().putValue(deviseValue, i, "ID_DEVISE");
1983
                            }
1984
                            getRowValuesTable().getRowValuesTableModel().putValue(tarifCompletion(rowValsArt, "PV_U_DEVISE", rowVals), i, "PV_U_DEVISE");
1985
                            getRowValuesTable().getRowValuesTableModel().putValue(tarifCompletion(rowValsArt, "PRIX_METRIQUE_VT_1", rowVals), i, "PRIX_METRIQUE_VT_1");
1986
                        }
1987
                    }
1988
                }
1989
            } else {
1990
                this.cacheRemise = null;
180 ilm 1991
                this.cacheRemiseFamille = null;
174 ilm 1992
            }
1993
        }
1994
    }
1995
 
1996
    @Override
19 ilm 1997
    public void setTarif(SQLRowAccessor rowValuesTarif, boolean ask) {
1998
        if (rowValuesTarif == null || getTarif() == null || rowValuesTarif.getID() != getTarif().getID()) {
1999
            super.setTarif(rowValuesTarif, ask);
177 ilm 2000
            if (ask && getRowValuesTable().getRowCount() > 0 && (rowValuesTarif == null || getTarif() == null || rowValuesTarif.isUndefined()
2001
                    || JOptionPane.showConfirmDialog(null, "Appliquer les tarifs associés au client sur les lignes déjà présentes?") == JOptionPane.YES_OPTION)) {
19 ilm 2002
                int nbRows = this.table.getRowCount();
2003
                for (int i = 0; i < nbRows; i++) {
2004
                    SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
2005
 
93 ilm 2006
                    if (!rowVals.isForeignEmpty("ID_ARTICLE")) {
2007
                        SQLRowAccessor rowValsArt = rowVals.getForeign("ID_ARTICLE");
2008
                        final Object taxeValue = tarifCompletion(rowValsArt, "ID_TAXE", rowVals);
2009
                        if (taxeValue != null) {
2010
                            getRowValuesTable().getRowValuesTableModel().putValue(taxeValue, i, "ID_TAXE");
19 ilm 2011
                        }
93 ilm 2012
 
2013
                        final Object deviseValue = tarifCompletion(rowValsArt, "ID_DEVISE", rowVals);
2014
                        if (deviseValue != null) {
2015
                            getRowValuesTable().getRowValuesTableModel().putValue(deviseValue, i, "ID_DEVISE");
2016
                        }
2017
                        getRowValuesTable().getRowValuesTableModel().putValue(tarifCompletion(rowValsArt, "PV_U_DEVISE", rowVals), i, "PV_U_DEVISE");
2018
                        getRowValuesTable().getRowValuesTableModel().putValue(tarifCompletion(rowValsArt, "PRIX_METRIQUE_VT_1", rowVals), i, "PRIX_METRIQUE_VT_1");
19 ilm 2019
                    }
93 ilm 2020
                }
2021
            }
2022
        }
2023
    }
28 ilm 2024
 
93 ilm 2025
    protected Object getQtyTarifPvM1(SQLRowAccessor row, boolean fromCompletion) {
73 ilm 2026
 
93 ilm 2027
        // Test si un tarif spécial est associé à l'article
2028
        // Object o = tarifCompletion(row.getForeign("ID_ARTICLE"), "PRIX_METRIQUE_VT_1", row,
2029
        // false);
2030
        // if (o != null) {
2031
        // return o;
2032
        // }
2033
 
2034
        SQLRowAccessor rowA = row.getForeign("ID_ARTICLE");
177 ilm 2035
 
2036
        if (rowA != null && !rowA.isUndefined() && rowA.getTable().getDBRoot().contains("ARTICLE_PRIX_PUBLIC") && rowA.getTable().contains("AUTO_PRIX_MIN_VENTE_NOMENCLATURE")
2037
                && rowA.getBoolean("AUTO_PRIX_MIN_VENTE_NOMENCLATURE")) {
132 ilm 2038
            BigDecimal b = row.getBigDecimal("QTE_UNITAIRE");
2039
            int q = row.getInt("QTE");
2040
            BigDecimal qteTotal = b.multiply(new BigDecimal(q), DecimalUtils.HIGH_PRECISION);
2041
            ProductHelper helper = new ProductHelper(rowA.getTable().getDBRoot());
2042
 
2043
            return helper.getBomPriceForQuantity(qteTotal.setScale(0, RoundingMode.HALF_UP).intValue(), rowA.getReferentRows(rowA.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT")),
2044
                    TypePrice.ARTICLE_PRIX_PUBLIC);
2045
        }
93 ilm 2046
        BigDecimal result = null;
2047
        // BigDecimal remise = null;
2048
        if (rowA != null && !rowA.isUndefined() && rowA.getTable().getDBRoot().contains("ARTICLE_PRIX_PUBLIC")) {
2049
            Collection<? extends SQLRowAccessor> col = rowA.getReferentRows(rowA.getTable().getTable("ARTICLE_PRIX_PUBLIC"));
2050
            int quantite = 0;
2051
            BigDecimal b = row.getBigDecimal("QTE_UNITAIRE");
2052
            int q = row.getInt("QTE");
2053
            BigDecimal qteTotal = b.multiply(new BigDecimal(q), DecimalUtils.HIGH_PRECISION);
2054
 
2055
            for (SQLRowAccessor sqlRowAccessor : col) {
2056
 
2057
                // FIXME BigDecimal??
2058
                // BigDecimal bigDecimal = sqlRowAccessor.getBigDecimal("QTE");
2059
                int qtePublic = sqlRowAccessor.getInt("QTE");
2060
                if (CompareUtils.compare(qtePublic, qteTotal) <= 0 && CompareUtils.compare(qtePublic, quantite) > 0) {
2061
                    quantite = qtePublic;
2062
                    if (sqlRowAccessor.getBigDecimal("PRIX") != null) {
2063
                        result = sqlRowAccessor.getBigDecimal("PRIX");
2064
                        // remise = null;
19 ilm 2065
                    }
93 ilm 2066
                    // else {
2067
                    // result = null;
2068
                    // remise = sqlRowAccessor.getBigDecimal("POURCENT_REMISE");
2069
                    // }
2070
                }
2071
            }
2072
        }
94 ilm 2073
        if (result == null && rowA != null && !rowA.isUndefined() && rowA.getTable().getDBRoot().contains("ARTICLE_PRIX_MIN_VENTE")) {
93 ilm 2074
            Collection<? extends SQLRowAccessor> col = rowA.getReferentRows(rowA.getTable().getTable("ARTICLE_PRIX_MIN_VENTE"));
2075
            int quantite = 0;
2076
            BigDecimal b = row.getBigDecimal("QTE_UNITAIRE");
2077
            int q = row.getInt("QTE");
2078
            BigDecimal qteTotal = b.multiply(new BigDecimal(q), DecimalUtils.HIGH_PRECISION);
19 ilm 2079
 
93 ilm 2080
            for (SQLRowAccessor sqlRowAccessor : col) {
2081
 
2082
                int qteMinVente = sqlRowAccessor.getInt("QTE");
2083
                if (CompareUtils.compare(qteMinVente, qteTotal) <= 0 && CompareUtils.compare(qteMinVente, quantite) > 0) {
2084
                    quantite = qteMinVente;
2085
                    if (sqlRowAccessor.getBigDecimal("PRIX") != null) {
2086
                        result = sqlRowAccessor.getBigDecimal("PRIX");
19 ilm 2087
                    }
2088
                }
2089
            }
18 ilm 2090
        }
94 ilm 2091
 
2092
        BigDecimal remise = null;
2093
 
2094
        if (rowA != null && !rowA.isUndefined() && rowA.getTable().getDBRoot().contains("TARIF_QUANTITE")) {
2095
            Collection<? extends SQLRowAccessor> col = rowA.getReferentRows(rowA.getTable().getTable("TARIF_QUANTITE"));
2096
            BigDecimal quantite = BigDecimal.ZERO;
2097
            BigDecimal b = row.getBigDecimal("QTE_UNITAIRE");
2098
            int q = row.getInt("QTE");
2099
            BigDecimal qteTotal = b.multiply(new BigDecimal(q), DecimalUtils.HIGH_PRECISION);
2100
 
2101
            for (SQLRowAccessor sqlRowAccessor : col) {
2102
 
2103
                BigDecimal bigDecimal = sqlRowAccessor.getBigDecimal("QUANTITE");
2104
                if (CompareUtils.compare(bigDecimal, qteTotal) <= 0 && CompareUtils.compare(bigDecimal, quantite) > 0) {
2105
                    quantite = bigDecimal;
2106
                    if (sqlRowAccessor.getBigDecimal("PRIX_METRIQUE_VT_1") != null) {
2107
                        result = sqlRowAccessor.getBigDecimal("PRIX_METRIQUE_VT_1");
2108
                        remise = null;
2109
                    } else {
2110
                        result = null;
2111
                        remise = sqlRowAccessor.getBigDecimal("POURCENT_REMISE");
2112
                    }
2113
                }
2114
            }
2115
            if (!col.isEmpty() && result == null && remise == null) {
2116
                result = rowA.getBigDecimal("PRIX_METRIQUE_VT_1");
2117
            }
2118
        }
2119
        int index = getRowValuesTable().getRowValuesTableModel().row2index(row);
2120
        if (result == null && remise == null) {
93 ilm 2121
            // getRowValuesTable().getRowValuesTableModel().putValue(BigDecimal.ZERO, index,
2122
            // "POURCENT_REMISE");
2123
            return (fromCompletion ? null : row.getObject("PRIX_METRIQUE_VT_1"));
2124
        } else {
2125
            if (result != null) {
2126
                // getRowValuesTable().getRowValuesTableModel().putValue(BigDecimal.ZERO, index,
2127
                // "POURCENT_REMISE");
2128
                return result;
2129
            } else {
94 ilm 2130
                getRowValuesTable().getRowValuesTableModel().putValue(remise, index, "POURCENT_REMISE");
93 ilm 2131
                return row.getBigDecimal("PRIX_METRIQUE_VT_1");
2132
            }
2133
        }
2134
 
18 ilm 2135
    }
93 ilm 2136
 
2137
    @Override
2138
    protected void setModel(RowValuesTableModel model) {
2139
        super.setModel(model);
2140
        model.addTableModelListener(new TableModelListener() {
2141
 
2142
            @Override
2143
            public void tableChanged(TableModelEvent e) {
2144
 
2145
                calculTarifNomenclature();
2146
 
2147
            }
2148
        });
2149
    }
94 ilm 2150
 
2151
    private void dropInTable(DropTargetDropEvent dtde, final AutoCompletionManager autoM) {
2152
        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
2153
        Transferable t = dtde.getTransferable();
2154
        try {
2155
 
2156
            List<Tuple3<Double, String, String>> articles = new ArrayList<Tuple3<Double, String, String>>();
2157
            if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
2158
                List<File> fileList = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
2159
                final DataImporter importer = new DataImporter(getSQLElement().getTable());
2160
                final File file = fileList.get(0);
2161
                if (file.getName().endsWith(".ods") || file.getName().endsWith(".xls")) {
2162
                    ArrayTableModel m = importer.createModelFrom(file);
2163
                    for (int i = 0; i < m.getRowCount(); i++) {
2164
                        List<Object> l = m.getLineValuesAt(i);
2165
                        if (l.size() > 1) {
2166
                            if (l.get(0) == null || l.get(0).toString().length() == 0) {
2167
                                break;
2168
                            }
2169
                            Double qte = ((Number) l.get(1)).doubleValue();
2170
                            String code = "";
2171
                            if (l.get(0) instanceof Number) {
2172
                                code = String.valueOf(((Number) l.get(0)).intValue());
2173
                            } else {
2174
                                code = l.get(0).toString();
2175
                            }
2176
                            String nom = "";
2177
                            if (l.size() > 2) {
2178
                                nom = (String) l.get(2);
2179
                            }
2180
                            if (qte > 0) {
2181
                                articles.add(Tuple3.create(qte, code, nom));
2182
                            }
2183
                        }
2184
                    }
2185
                } else {
2186
                    JOptionPane.showMessageDialog(null, "Les formats de fichiers pris en charge sont ods et xls!");
2187
                }
2188
            } else if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
2189
                final String transferData = (String) t.getTransferData(DataFlavor.stringFlavor);
2190
                List<String> l = StringUtils.fastSplitTrimmed(transferData, '\n');
2191
                for (String string : l) {
2192
                    List<String> line = StringUtils.fastSplitTrimmed(string, '\t');
2193
                    if (line.size() >= 2) {
2194
                        Double qte = Double.valueOf(line.get(1));
2195
                        String code = (line.get(0) == null ? "" : line.get(0).toString());
2196
                        String nom = "";
2197
                        if (line.size() > 2) {
2198
                            nom = (String) line.get(2);
2199
                        }
2200
                        if (qte > 0) {
2201
                            articles.add(Tuple3.create(qte, code, nom));
2202
                        }
2203
                    } else {
2204
                        break;
2205
                    }
2206
                }
2207
            }
2208
            if (articles.size() > 0) {
2209
                insertFromDrop(articles, autoM);
2210
                for (Tuple3<Double, String, String> tuple3 : articles) {
2211
                    System.err.println("ADD LINE " + tuple3);
2212
                }
2213
            }
2214
        } catch (UnsupportedFlavorException e) {
2215
            // TODO Auto-generated catch block
2216
            e.printStackTrace();
2217
        } catch (IOException e) {
2218
            // TODO Auto-generated catch block
2219
            e.printStackTrace();
2220
        }
2221
 
2222
        // dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
2223
        // Transferable t = dtde.getTransferable();
2224
        // List fileList = (List)t.getTransferData(DataFlavor.javaFileListFlavor);
2225
        // File f = (File)fileList.get(0);
2226
        // table.setValueAt(f.getAbsolutePath(), row, column);
2227
        // table.setValueAt(f.length(), row, column+1);
2228
    }
2229
 
142 ilm 2230
    protected void insertFromDrop(List<Tuple3<Double, String, String>> articles, AutoCompletionManager m) {
94 ilm 2231
 
2232
        List<String> code = new ArrayList<String>(articles.size());
2233
        for (int i = articles.size() - 1; i >= 0; i--) {
2234
 
2235
            Tuple3<Double, String, String> tuple = articles.get(i);
2236
            code.add(tuple.get1());
2237
        }
2238
        SQLSelect sel = new SQLSelect();
2239
        final SQLTable articleTable = getSQLElement().getTable().getForeignTable("ID_ARTICLE");
2240
        sel.addSelectStar(articleTable);
2241
        sel.setWhere(new Where(articleTable.getField("CODE"), code));
2242
        List<SQLRow> matchCode = SQLRowListRSH.execute(sel);
2243
        Map<String, SQLRow> mapCode = new HashMap<String, SQLRow>();
2244
        for (SQLRow sqlRow : matchCode) {
2245
            mapCode.put(sqlRow.getString("CODE"), sqlRow);
2246
        }
2247
 
142 ilm 2248
        int rowCount = getRowValuesTable().getRowValuesTableModel().getRowCount();
2249
        Map<Integer, Integer> mapRows = new HashMap<Integer, Integer>();
2250
        for (int i = 0; i < rowCount; i++) {
2251
            SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
2252
            if (rowVals.getObject("ID_ARTICLE") != null && !rowVals.isForeignEmpty("ID_ARTICLE")) {
2253
                mapRows.put(rowVals.getForeignID("ID_ARTICLE"), i);
2254
            }
2255
        }
2256
 
2257
        Set<String> fieldsFrom = m.getFieldsFrom();
2258
        fieldsFrom.remove("POURCENT_REMISE");
94 ilm 2259
        for (int i = articles.size() - 1; i >= 0; i--) {
2260
 
2261
            Tuple3<Double, String, String> tuple = articles.get(i);
2262
 
2263
            SQLRow article = mapCode.get(tuple.get1());
142 ilm 2264
            String fieldQte = "QTE";
94 ilm 2265
 
142 ilm 2266
            if (article != null && mapRows.containsKey(article.getID())) {
2267
                Integer index = mapRows.get(article.getID());
2268
                SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(index);
2269
                if (rowVals.getTable().getName().equals("BON_DE_LIVRAISON_ELEMENT")) {
2270
                    fieldQte = "QTE_LIVREE";
2271
                }
2272
                getRowValuesTable().getRowValuesTableModel().putValue(rowVals.getInt(fieldQte) + 1, index, fieldQte);
94 ilm 2273
            } else {
142 ilm 2274
                final SQLRowValues row2Insert = new SQLRowValues(getRowValuesTable().getRowValuesTableModel().getDefaultRowValues());
94 ilm 2275
 
142 ilm 2276
                // Completion depuis l'article trouvé
2277
                if (article != null) {
2278
                    m.fillRowValues(article, fieldsFrom, row2Insert);
2279
                    // Fill prix total
2280
                    row2Insert.put("ID_ARTICLE", article.getID());
2281
                    row2Insert.put("CODE", article.getObject("CODE"));
2282
                    row2Insert.put("NOM", article.getObject("NOM"));
2283
                } else {
2284
                    row2Insert.put("CODE", tuple.get1());
2285
                    row2Insert.put("NOM", tuple.get2());
2286
                }
94 ilm 2287
 
142 ilm 2288
                row2Insert.put(fieldQte, Math.round(tuple.get0().floatValue()));
2289
                if (row2Insert.getTable().getName().equals("BON_DE_LIVRAISON_ELEMENT")) {
2290
                    row2Insert.put("QTE_LIVREE", Math.round(tuple.get0().floatValue()));
2291
                }
2292
                row2Insert.put("POURCENT_REMISE", BigDecimal.ZERO);
2293
                row2Insert.put("MONTANT_REMISE", BigDecimal.ZERO);
94 ilm 2294
 
142 ilm 2295
                row2Insert.put("PV_HT", row2Insert.getObject("PRIX_METRIQUE_VT_1"));
2296
                //
2297
                final BigDecimal resultTotalHT = row2Insert.getBigDecimal("PV_HT").multiply(new BigDecimal(row2Insert.getInt(fieldQte)));
2298
                row2Insert.put("T_PV_HT", resultTotalHT);
94 ilm 2299
 
142 ilm 2300
                Float resultTaux = TaxeCache.getCache().getTauxFromId(row2Insert.getForeignID("ID_TAXE"));
94 ilm 2301
 
142 ilm 2302
                if (resultTaux == null) {
2303
                    SQLRow rowTax = TaxeCache.getCache().getFirstTaxe();
2304
                    resultTaux = rowTax.getFloat("TAUX");
2305
                }
94 ilm 2306
 
142 ilm 2307
                float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
94 ilm 2308
 
142 ilm 2309
                BigDecimal r = resultTotalHT.multiply(BigDecimal.valueOf(taux).movePointLeft(2).add(BigDecimal.ONE), DecimalUtils.HIGH_PRECISION);
94 ilm 2310
 
142 ilm 2311
                row2Insert.put("T_PV_TTC", r);
2312
                // row2Insert.put("ID_STYLE", allStyleByName.get("Composant"));
2313
                getRowValuesTable().getRowValuesTableModel().addRowAt(0, row2Insert);
2314
            }
94 ilm 2315
        }
2316
    }
18 ilm 2317
}