OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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