OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.common.ui;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
93 ilm 17
import org.openconcerto.erp.core.finance.accounting.model.CurrencyConverter;
18 ilm 18
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
142 ilm 19
import org.openconcerto.erp.core.sales.pos.io.BarcodeReader;
20
import org.openconcerto.erp.core.sales.pos.ui.BarcodeListener;
18 ilm 21
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
94 ilm 22
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
23
import org.openconcerto.erp.core.sales.product.ui.CurrencyWithSymbolRenderer;
174 ilm 24
import org.openconcerto.erp.core.sales.product.ui.DeliveredQtyRowValuesRenderer;
61 ilm 25
import org.openconcerto.erp.core.sales.product.ui.QteUnitRowValuesRenderer;
18 ilm 26
import org.openconcerto.erp.preferences.DefaultNXProps;
61 ilm 27
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
18 ilm 28
import org.openconcerto.sql.Configuration;
29
import org.openconcerto.sql.element.SQLElement;
94 ilm 30
import org.openconcerto.sql.model.FieldPath;
19 ilm 31
import org.openconcerto.sql.model.SQLRow;
32
import org.openconcerto.sql.model.SQLRowAccessor;
142 ilm 33
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 34
import org.openconcerto.sql.model.SQLRowValues;
142 ilm 35
import org.openconcerto.sql.model.SQLSelect;
41 ilm 36
import org.openconcerto.sql.model.SQLTable;
80 ilm 37
import org.openconcerto.sql.model.UndefinedRowValuesCache;
41 ilm 38
import org.openconcerto.sql.model.Where;
94 ilm 39
import org.openconcerto.sql.model.graph.Path;
61 ilm 40
import org.openconcerto.sql.preferences.SQLPreferences;
83 ilm 41
import org.openconcerto.sql.sqlobject.ITextArticleWithCompletionCellEditor;
61 ilm 42
import org.openconcerto.sql.sqlobject.ITextWithCompletion;
18 ilm 43
import org.openconcerto.sql.view.list.AutoCompletionManager;
44
import org.openconcerto.sql.view.list.CellDynamicModifier;
45
import org.openconcerto.sql.view.list.RowValuesTable;
46
import org.openconcerto.sql.view.list.RowValuesTableModel;
47
import org.openconcerto.sql.view.list.SQLTableElement;
65 ilm 48
import org.openconcerto.sql.view.list.ValidStateChecker;
90 ilm 49
import org.openconcerto.utils.DecimalUtils;
142 ilm 50
import org.openconcerto.utils.Tuple3;
94 ilm 51
import org.openconcerto.utils.i18n.TranslationManager;
18 ilm 52
 
174 ilm 53
import java.awt.Component;
132 ilm 54
import java.awt.event.ActionEvent;
142 ilm 55
import java.awt.event.HierarchyEvent;
56
import java.awt.event.HierarchyListener;
57
import java.awt.event.KeyEvent;
132 ilm 58
import java.awt.event.MouseAdapter;
59
import java.awt.event.MouseEvent;
60
import java.math.BigDecimal;
61
import java.math.RoundingMode;
62
import java.util.ArrayList;
63
import java.util.Arrays;
64
import java.util.Calendar;
65
import java.util.HashMap;
66
import java.util.HashSet;
67
import java.util.List;
68
import java.util.Map;
69
import java.util.Set;
70
import java.util.Vector;
71
 
72
import javax.swing.AbstractAction;
142 ilm 73
import javax.swing.JFrame;
174 ilm 74
import javax.swing.JLabel;
132 ilm 75
import javax.swing.JOptionPane;
76
import javax.swing.JPopupMenu;
77
import javax.swing.JTable;
78
import javax.swing.SwingUtilities;
79
import javax.swing.ToolTipManager;
80
import javax.swing.event.TableModelEvent;
81
import javax.swing.event.TableModelListener;
174 ilm 82
import javax.swing.table.DefaultTableCellRenderer;
132 ilm 83
import javax.swing.table.TableCellRenderer;
84
 
18 ilm 85
public abstract class AbstractAchatArticleItemTable extends AbstractArticleItemTable {
86
 
73 ilm 87
    private AutoCompletionManager m;
88
    private AutoCompletionManager m2, m3;
89
    private AutoCompletionManager m4;
90
    private final SQLTable tableArticle = getSQLElement().getTable().getTable("ARTICLE");
91
    private SQLRowAccessor rowDevise;
92
    private boolean supplierCode;
93
 
18 ilm 94
    public AbstractAchatArticleItemTable() {
95
        super();
96
    }
97
 
94 ilm 98
    @Override
99
    protected void setModel(RowValuesTableModel model) {
100
        super.setModel(model);
101
        model.addTableModelListener(new TableModelListener() {
102
 
103
            @Override
104
            public void tableChanged(TableModelEvent e) {
105
 
106
                calculTarifNomenclature();
107
 
108
            }
109
        });
110
    }
111
 
18 ilm 112
    protected void init() {
113
 
114
        final SQLElement e = getSQLElement();
132 ilm 115
        final SQLPreferences prefs = SQLPreferences.getMemCached(getSQLElement().getTable().getDBRoot());
61 ilm 116
        final boolean selectArticle = prefs.getBoolean(GestionArticleGlobalPreferencePanel.USE_CREATED_ARTICLE, false);
117
        final boolean createAuto = prefs.getBoolean(GestionArticleGlobalPreferencePanel.CREATE_ARTICLE_AUTO, true);
142 ilm 118
        final boolean showEco = prefs.getBoolean(AbstractVenteArticleItemTable.SHOW_ECO_CONTRIBUTION_COLUMNS, false);
149 ilm 119
        final boolean showDmdAchat = prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVE_DEMANDE_ACHAT, false);
156 ilm 120
        final boolean showDevise = prefs.getBoolean(AbstractVenteArticleItemTable.ARTICLE_SHOW_DEVISE, false);
67 ilm 121
        this.supplierCode = prefs.getBoolean(GestionArticleGlobalPreferencePanel.SUPPLIER_PRODUCT_CODE, false);
61 ilm 122
 
18 ilm 123
        final List<SQLTableElement> list = new Vector<SQLTableElement>();
94 ilm 124
        final SQLTableElement eNiveau = new SQLTableElement(e.getTable().getField("NIVEAU")) {
125
            @Override
126
            public void setValueFrom(SQLRowValues row, Object value) {
127
                super.setValueFrom(row, value);
128
            }
129
        };
130
        eNiveau.setRenderer(new NiveauTableCellRender());
131
        eNiveau.setEditor(new NiveauTableCellEditor());
132
        list.add(eNiveau);
18 ilm 133
        list.add(new SQLTableElement(e.getTable().getField("ID_STYLE")));
28 ilm 134
 
149 ilm 135
        SQLTableElement dmdElt = null;
136
        if (showDmdAchat && e.getTable().contains("ID_DEMANDE_ACHAT_ELEMENT")) {
137
            dmdElt = new SQLTableElement(e.getTable().getField("ID_DEMANDE_ACHAT_ELEMENT"));
138
            list.add(dmdElt);
139
        }
140
 
174 ilm 141
        if (e.getTable().contains("ID_AFFAIRE")) {
142
            list.add(new SQLTableElement(e.getTable().getField("ID_AFFAIRE")));
143
        }
144
 
67 ilm 145
        SQLTableElement tableElementCodeFournisseur = null;
146
 
147
        if (e.getTable().contains("ID_CODE_FOURNISSEUR") && supplierCode) {
148
            tableElementCodeFournisseur = new SQLTableElement(e.getTable().getField("ID_CODE_FOURNISSEUR"), true, true, true);
149
            list.add(tableElementCodeFournisseur);
150
        }
151
 
174 ilm 152
        if (e.getTable().contains("ID_COMPTE_PCE")) {
153
            list.add(new SQLTableElement(e.getTable().getField("ID_COMPTE_PCE")));
154
        }
155
 
142 ilm 156
        SQLTableElement tableElementArticle = new SQLTableElement(e.getTable().getField("ID_ARTICLE"), true, true, true) {
157
            @Override
158
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
159
                boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
160
                if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
161
                    boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
162
                    return b && noCmdElt;
163
                } else {
164
                    return b;
165
                }
166
 
167
            }
168
        };
61 ilm 169
        list.add(tableElementArticle);
28 ilm 170
 
156 ilm 171
        // Article
172
        SQLTableElement tableElementDepot = new SQLTableElement(e.getTable().getField("ID_DEPOT_STOCK"), true, true, true);
173
        list.add(tableElementDepot);
174
 
28 ilm 175
        if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
176
            final SQLTableElement tableFamille = new SQLTableElement(e.getTable().getField("ID_FAMILLE_ARTICLE"));
177
            list.add(tableFamille);
178
        }
179
 
142 ilm 180
        if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
181
            this.tableElementEcoID = new SQLTableElement(e.getTable().getField("ID_ECO_CONTRIBUTION"));
182
            list.add(this.tableElementEcoID);
183
        }
184
 
94 ilm 185
        if (e.getTable().getFieldsName().contains("INCOTERM")) {
186
            final SQLTableElement tableElementInco = new SQLTableElement(e.getTable().getField("INCOTERM"));
187
            tableElementInco.setEditable(false);
188
            list.add(tableElementInco);
189
        }
190
 
28 ilm 191
        if (e.getTable().getFieldsName().contains("PREBILAN")) {
93 ilm 192
            final SQLTableElement tableElementPre = new SQLTableElement(e.getTable().getField("PREBILAN"), BigDecimal.class);
193
            tableElementPre.setRenderer(new DeviseTableCellRenderer());
28 ilm 194
            list.add(tableElementPre);
195
        }
196
 
18 ilm 197
        // Code article
94 ilm 198
        final SQLTableElement tableElementCode = new SQLTableElement(e.getTable().getField("CODE"), String.class,
142 ilm 199
                new ITextArticleWithCompletionCellEditor(e.getTable().getTable("ARTICLE"), e.getTable().getTable("ARTICLE_FOURNISSEUR"))) {
200
            @Override
201
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
202
                boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
203
                if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
204
                    boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
205
                    return b && noCmdElt;
206
                } else {
207
                    return b;
208
                }
209
 
210
            }
211
        };
18 ilm 212
        list.add(tableElementCode);
213
        // Désignation de l'article
142 ilm 214
        final SQLTableElement tableElementNom = new SQLTableElement(e.getTable().getField("NOM")) {
215
            @Override
216
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
217
                boolean b = super.isCellEditable(vals, rowIndex, columnIndex);
218
                if (vals.getTable().contains("ID_COMMANDE_ELEMENT")) {
219
                    boolean noCmdElt = vals.getObject("ID_COMMANDE_ELEMENT") == null || vals.isForeignEmpty("ID_COMMANDE_ELEMENT");
220
                    return b && noCmdElt;
221
                } else {
222
                    return b;
223
                }
224
 
225
            }
226
        };
18 ilm 227
        list.add(tableElementNom);
142 ilm 228
 
73 ilm 229
        if (e.getTable().getFieldsName().contains("DESCRIPTIF")) {
230
            final SQLTableElement tableElementDesc = new SQLTableElement(e.getTable().getField("DESCRIPTIF"));
231
            list.add(tableElementDesc);
232
        }
41 ilm 233
        if (e.getTable().getFieldsName().contains("COLORIS")) {
234
            final SQLTableElement tableElementColoris = new SQLTableElement(e.getTable().getField("COLORIS"));
235
            list.add(tableElementColoris);
236
        }
18 ilm 237
        // Valeur des métriques
238
        final SQLTableElement tableElement_ValeurMetrique2 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_2"), Float.class);
239
        list.add(tableElement_ValeurMetrique2);
240
        final SQLTableElement tableElement_ValeurMetrique3 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_3"), Float.class);
241
        list.add(tableElement_ValeurMetrique3);
242
        final SQLTableElement tableElement_ValeurMetrique1 = new SQLTableElement(e.getTable().getField("VALEUR_METRIQUE_1"), Float.class);
243
        list.add(tableElement_ValeurMetrique1);
244
        // Prix d'achat HT de la métrique 1
156 ilm 245
        final DeviseNumericHTConvertorCellEditor editorPAHT = new DeviseNumericHTConvertorCellEditor(e.getTable().getField("PRIX_METRIQUE_HA_1"));
246
        final SQLTableElement tableElement_PrixMetrique1_AchatHT = new SQLTableElement(e.getTable().getField("PRIX_METRIQUE_HA_1"), BigDecimal.class, editorPAHT);
94 ilm 247
        tableElement_PrixMetrique1_AchatHT.setRenderer(new CurrencyWithSymbolRenderer());
18 ilm 248
        list.add(tableElement_PrixMetrique1_AchatHT);
19 ilm 249
 
142 ilm 250
        if (e.getTable().getFieldsName().contains("ECO_CONTRIBUTION")) {
251
            this.tableElementEco = new SQLTableElement(e.getTable().getField("ECO_CONTRIBUTION"));
252
            list.add(this.tableElementEco);
253
        }
254
 
19 ilm 255
        final SQLTableElement tableElement_Devise = new SQLTableElement(e.getTable().getField("ID_DEVISE"));
94 ilm 256
        tableElement_Devise.setEditable(false);
67 ilm 257
        final SQLTableElement tableElement_PA_Devise = new SQLTableElement(e.getTable().getField("PA_DEVISE"), BigDecimal.class);
94 ilm 258
        Path p = new Path(getSQLElement().getTable()).addForeignField("ID_DEVISE");
259
        tableElement_PA_Devise.setRenderer(new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE")));
156 ilm 260
        if (showDevise) {
28 ilm 261
            // Devise
262
            list.add(tableElement_Devise);
19 ilm 263
 
28 ilm 264
            // Prix d'achat HT devise
265
            list.add(tableElement_PA_Devise);
266
        }
18 ilm 267
        // Mode de vente
268
        final SQLTableElement tableElement_ModeVente = new SQLTableElement(e.getTable().getField("ID_MODE_VENTE_ARTICLE"));
269
        list.add(tableElement_ModeVente);
19 ilm 270
 
18 ilm 271
        // Prix d'achat unitaire HT
67 ilm 272
        this.ha = new SQLTableElement(e.getTable().getField("PA_HT"), BigDecimal.class);
94 ilm 273
        this.ha.setRenderer(new CurrencyWithSymbolRenderer());
18 ilm 274
        list.add(this.ha);
19 ilm 275
 
61 ilm 276
        SQLTableElement qteU = new SQLTableElement(e.getTable().getField("QTE_UNITAIRE"), BigDecimal.class) {
277
            @Override
132 ilm 278
            public boolean isCellEditable(SQLRowValues vals, int rowIndex, int columnIndex) {
61 ilm 279
 
280
                SQLRowAccessor row = vals.getForeign("ID_UNITE_VENTE");
281
                if (row != null && !row.isUndefined() && row.getBoolean("A_LA_PIECE")) {
282
                    return false;
283
                } else {
132 ilm 284
                    return super.isCellEditable(vals, rowIndex, columnIndex);
61 ilm 285
                }
286
            }
287
 
288
            @Override
289
            public TableCellRenderer getTableCellRenderer() {
290
                return new QteUnitRowValuesRenderer();
291
            }
67 ilm 292
 
293
            protected Object getDefaultNullValue() {
294
                return BigDecimal.ZERO;
295
            }
61 ilm 296
        };
297
        list.add(qteU);
298
 
299
        SQLTableElement uniteVente = new SQLTableElement(e.getTable().getField("ID_UNITE_VENTE"));
300
        list.add(uniteVente);
301
 
174 ilm 302
        SQLTableElement tableCmdElt = null;
303
        if (e.getTable().contains("ID_COMMANDE_ELEMENT")) {
304
            tableCmdElt = new SQLTableElement(e.getTable().getField("ID_COMMANDE_ELEMENT"));
305
            tableCmdElt.setRenderer(new DefaultTableCellRenderer() {
306
                @Override
307
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
308
                    SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(row);
309
 
310
                    JLabel tableCellRendererComponent = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
311
                    tableCellRendererComponent.setText("");
312
                    if (rowVals.getObject("ID_COMMANDE_ELEMENT") != null && !rowVals.isForeignEmpty("ID_COMMANDE_ELEMENT")) {
313
                        SQLRowAccessor rowCmdItem = rowVals.getForeign("ID_COMMANDE_ELEMENT");
314
                        int qte = rowCmdItem.getInt("QTE");
315
                        BigDecimal qteU = rowCmdItem.getBigDecimal("QTE_UNITAIRE");
316
                        BigDecimal qteR = rowCmdItem.getBigDecimal("QTE_RECUE");
317
                        qteU = qteU.multiply(new BigDecimal(qte));
318
                        if (qteR != null) {
319
                            tableCellRendererComponent.setText(qteU.subtract(qteR).setScale(2, RoundingMode.HALF_UP).toString());
320
                        } else {
321
                            tableCellRendererComponent.setText(qteU.setScale(2, RoundingMode.HALF_UP).toString());
322
                        }
323
                    }
324
 
325
                    return tableCellRendererComponent;
326
                }
327
            });
328
            tableCmdElt.setEditable(false);
329
            list.add(tableCmdElt);
330
        }
331
 
149 ilm 332
        if (e.getTable().getFieldsName().contains("QTE_ORIGINE")) {
333
            final SQLTableElement tableQteO = new SQLTableElement(e.getTable().getField("QTE_ORIGINE"));
334
            tableQteO.setEditable(false);
335
            list.add(tableQteO);
336
        }
337
 
19 ilm 338
        // Quantité
339
        final SQLTableElement qteElement = new SQLTableElement(e.getTable().getField("QTE"), Integer.class) {
340
            protected Object getDefaultNullValue() {
341
                return Integer.valueOf(0);
342
            }
343
        };
174 ilm 344
        if (e.getTable().getFieldsName().contains("QTE_ORIGINE")) {
345
            qteElement.setRenderer(new DeliveredQtyRowValuesRenderer(false));
346
        }
19 ilm 347
        list.add(qteElement);
18 ilm 348
        // TVA
61 ilm 349
        this.tableElementTVA = new SQLTableElement(e.getTable().getField("ID_TAXE"));
350
        list.add(this.tableElementTVA);
18 ilm 351
        // Poids piece
352
        SQLTableElement tableElementPoids = new SQLTableElement(e.getTable().getField("POIDS"), Float.class);
353
        list.add(tableElementPoids);
354
 
355
        // Poids total
356
        this.tableElementPoidsTotal = new SQLTableElement(e.getTable().getField("T_POIDS"), Float.class);
357
        list.add(this.tableElementPoidsTotal);
358
 
359
        // Service
360
        String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
361
        Boolean b = Boolean.valueOf(val);
362
        if (b != null && b.booleanValue()) {
363
            this.service = new SQLTableElement(e.getTable().getField("SERVICE"), Boolean.class);
364
            list.add(this.service);
365
        }
366
 
156 ilm 367
        if (showDevise) {
28 ilm 368
            // Prix d'achat HT devise
67 ilm 369
            this.tableElementTotalDevise = new SQLTableElement(e.getTable().getField("PA_DEVISE_T"), BigDecimal.class);
174 ilm 370
            CurrencyWithSymbolRenderer deviseTotalRenderer = new CurrencyWithSymbolRenderer(new FieldPath(p, "CODE"));
371
            deviseTotalRenderer.setHideZeroValue(true);
372
            this.tableElementTotalDevise.setRenderer(deviseTotalRenderer);
28 ilm 373
            list.add(tableElementTotalDevise);
374
        }
67 ilm 375
 
376
        SQLTableElement tableElementRemise = null;
377
        if (e.getTable().contains("POURCENT_REMISE")) {
378
            tableElementRemise = new SQLTableElement(e.getTable().getField("POURCENT_REMISE"));
379
            list.add(tableElementRemise);
380
        }
381
 
142 ilm 382
        if (e.getTable().getFieldsName().contains("T_ECO_CONTRIBUTION")) {
383
            this.tableElementEcoTotal = new SQLTableElement(e.getTable().getField("T_ECO_CONTRIBUTION"));
384
            list.add(this.tableElementEcoTotal);
385
        }
386
 
18 ilm 387
        // Total HT
67 ilm 388
        this.totalHT = new SQLTableElement(e.getTable().getField("T_PA_HT"), BigDecimal.class);
174 ilm 389
        DeviseTableCellRenderer totalRenderer = new DeviseTableCellRenderer();
390
        totalRenderer.setHideZeroValue(true);
391
        this.totalHT.setRenderer(totalRenderer);
65 ilm 392
        this.totalHT.setEditable(false);
73 ilm 393
        if (e.getTable().contains("POURCENT_REMISE") && tableElementRemise != null) {
67 ilm 394
            tableElementRemise.addModificationListener(this.totalHT);
395
        }
18 ilm 396
        list.add(this.totalHT);
67 ilm 397
        this.totalHA = this.totalHT;
18 ilm 398
        // Total TTC
67 ilm 399
        this.tableElementTotalTTC = new SQLTableElement(e.getTable().getField("T_PA_TTC"), BigDecimal.class);
174 ilm 400
        this.tableElementTotalTTC.setRenderer(totalRenderer);
18 ilm 401
        list.add(this.tableElementTotalTTC);
402
 
94 ilm 403
        this.defaultRowVals = new SQLRowValues(UndefinedRowValuesCache.getInstance().getDefaultRowValues(e.getTable()));
404
        this.defaultRowVals.put("ID_TAXE", TaxeCache.getCache().getFirstTaxe().getID());
405
        this.defaultRowVals.put("CODE", "");
406
        this.defaultRowVals.put("NOM", "");
407
        this.defaultRowVals.put("QTE", 1);
408
        this.defaultRowVals.put("QTE_UNITAIRE", BigDecimal.ONE);
409
        this.defaultRowVals.put("ID_UNITE_VENTE", UniteVenteArticleSQLElement.A_LA_PIECE);
410
        this.defaultRowVals.put("ID_MODE_VENTE_ARTICLE", ReferenceArticleSQLElement.A_LA_PIECE);
411
        final RowValuesTableModel model = new RowValuesTableModel(e, list, e.getTable().getField("NOM"), false, this.defaultRowVals);
93 ilm 412
        setModel(model);
80 ilm 413
 
93 ilm 414
        this.table = new RowValuesTable(model, getConfigurationFile());
18 ilm 415
        ToolTipManager.sharedInstance().unregisterComponent(this.table);
416
        ToolTipManager.sharedInstance().unregisterComponent(this.table.getTableHeader());
417
 
94 ilm 418
        table.addMouseListener(new MouseAdapter() {
419
            @Override
420
            public void mouseReleased(MouseEvent e) {
132 ilm 421
                handlePopup(e);
422
            }
423
 
424
            @Override
425
            public void mousePressed(MouseEvent e) {
426
                handlePopup(e);
427
            }
428
 
429
            public void handlePopup(MouseEvent e) {
94 ilm 430
                final int rowindex = table.getSelectedRow();
431
                if (rowindex < 0)
432
                    return;
433
                if (e.isPopupTrigger() && e.getComponent() instanceof JTable) {
434
                    JPopupMenu popup = new JPopupMenu();
132 ilm 435
                    if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.CAN_EXPAND_NOMENCLATURE_HA, true)) {
436
                        popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.expand")) {
94 ilm 437
 
132 ilm 438
                            @Override
439
                            public void actionPerformed(ActionEvent arg0) {
440
                                expandNomenclature(rowindex, m, EXPAND_TYPE.EXPAND);
441
                            }
442
                        });
443
                        popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.expose")) {
94 ilm 444
 
132 ilm 445
                            @Override
446
                            public void actionPerformed(ActionEvent arg0) {
447
                                expandNomenclature(rowindex, m, EXPAND_TYPE.VIEW_ONLY);
448
                            }
449
                        });
450
                        popup.add(new AbstractAction(TranslationManager.getInstance().getTranslationForItem("product.bom.flat")) {
94 ilm 451
 
132 ilm 452
                            @Override
453
                            public void actionPerformed(ActionEvent arg0) {
454
                                expandNomenclature(rowindex, m, EXPAND_TYPE.FLAT);
455
                            }
456
                        });
457
                    }
94 ilm 458
                    for (AbstractAction action : getAdditionnalMouseAction(rowindex)) {
459
                        popup.add(action);
460
                    }
461
 
462
                    popup.show(e.getComponent(), e.getX(), e.getY());
463
                }
464
            }
465
        });
466
 
18 ilm 467
        // Autocompletion
149 ilm 468
        if (dmdElt != null) {
469
            AutoCompletionManager dmd = new AutoCompletionManager(dmdElt, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("DEMANDE_ACHAT_ELEMENT.ID"), this.table,
470
                    this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker());
471
            dmd.fill("ID_FAMILLE_ARTICLE", "ID_FAMILLE_ARTICLE");
472
        }
28 ilm 473
        List<String> completionFields = new ArrayList<String>();
132 ilm 474
        if (e.getTable().getFieldsName().contains("INCOTERM")) {
475
            completionFields.add("INCOTERM");
476
        }
142 ilm 477
        if (e.getTable().getFieldsName().contains("ID_ECO_CONTRIBUTION")) {
478
            completionFields.add("ID_ECO_CONTRIBUTION");
479
        }
61 ilm 480
        completionFields.add("ID_UNITE_VENTE");
156 ilm 481
        completionFields.add("QTE_UNITAIRE");
28 ilm 482
        completionFields.add("PA_HT");
483
        completionFields.add("PV_HT");
484
        completionFields.add("POIDS");
485
        completionFields.add("ID_TAXE");
486
        completionFields.add("PRIX_METRIQUE_HA_1");
487
        completionFields.add("PRIX_METRIQUE_HA_2");
488
        completionFields.add("PRIX_METRIQUE_HA_3");
489
        completionFields.add("VALEUR_METRIQUE_1");
490
        completionFields.add("VALEUR_METRIQUE_2");
491
        completionFields.add("VALEUR_METRIQUE_3");
492
        completionFields.add("ID_MODE_VENTE_ARTICLE");
493
        completionFields.add("PRIX_METRIQUE_VT_1");
494
        completionFields.add("PRIX_METRIQUE_VT_2");
495
        completionFields.add("PRIX_METRIQUE_VT_3");
496
        completionFields.add("SERVICE");
497
        completionFields.add("ID_DEVISE");
498
        completionFields.add("PA_DEVISE");
41 ilm 499
        if (e.getTable().getFieldsName().contains("COLORIS")) {
500
            completionFields.add("COLORIS");
501
        }
132 ilm 502
 
73 ilm 503
        if (e.getTable().getFieldsName().contains("DESCRIPTIF")) {
504
            completionFields.add("DESCRIPTIF");
505
        }
28 ilm 506
        if (e.getTable().getFieldsName().contains("ID_FAMILLE_ARTICLE")) {
507
            completionFields.add("ID_FAMILLE_ARTICLE");
508
        }
509
 
41 ilm 510
        this.m = new AutoCompletionManager(tableElementCode, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.CODE"), this.table,
19 ilm 511
                this.table.getRowValuesTableModel()) {
512
            @Override
93 ilm 513
            protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
19 ilm 514
                Object res = tarifCompletion(row, field);
515
                if (res == null) {
93 ilm 516
                    return super.getValueFrom(row, field, rowDest);
19 ilm 517
                } else {
518
                    return res;
519
                }
520
            }
521
        };
18 ilm 522
        m.fill("NOM", "NOM");
61 ilm 523
        m.fill("ID", "ID_ARTICLE");
28 ilm 524
        for (String string : completionFields) {
525
            m.fill(string, string);
526
        }
93 ilm 527
        final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
528
        final Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
529
        m.setWhere(w);
530
 
41 ilm 531
        this.m2 = new AutoCompletionManager(tableElementNom, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
19 ilm 532
                this.table.getRowValuesTableModel()) {
533
            @Override
93 ilm 534
            protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
19 ilm 535
                Object res = tarifCompletion(row, field);
536
                if (res == null) {
93 ilm 537
                    return super.getValueFrom(row, field, rowDest);
19 ilm 538
                } else {
539
                    return res;
540
                }
541
            }
542
        };
18 ilm 543
        m2.fill("CODE", "CODE");
61 ilm 544
        m2.fill("ID", "ID_ARTICLE");
28 ilm 545
        for (String string : completionFields) {
546
            m2.fill(string, string);
547
        }
93 ilm 548
        m2.setWhere(w);
28 ilm 549
 
61 ilm 550
        this.m3 = new AutoCompletionManager(tableElementArticle, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
65 ilm 551
                this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker()) {
61 ilm 552
            @Override
93 ilm 553
            protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
61 ilm 554
                Object res = tarifCompletion(row, field);
555
                if (res == null) {
93 ilm 556
                    return super.getValueFrom(row, field, rowDest);
61 ilm 557
                } else {
558
                    return res;
559
                }
560
            }
561
        };
562
        m3.fill("CODE", "CODE");
563
        m3.fill("NOM", "NOM");
564
        for (String string : completionFields) {
565
            m3.fill(string, string);
566
        }
93 ilm 567
        m3.setWhere(w);
28 ilm 568
 
67 ilm 569
        if (e.getTable().contains("ID_CODE_FOURNISSEUR") && supplierCode) {
570
            this.m4 = new AutoCompletionManager(tableElementCodeFournisseur, ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getField("ARTICLE.NOM"), this.table,
571
                    this.table.getRowValuesTableModel(), ITextWithCompletion.MODE_CONTAINS, true, true, new ValidStateChecker()) {
572
                @Override
93 ilm 573
                protected Object getValueFrom(SQLRow row, String field, SQLRowAccessor rowDest) {
67 ilm 574
                    Object res = tarifCompletion(row, field);
575
                    if (res == null) {
93 ilm 576
                        return super.getValueFrom(row, field, rowDest);
67 ilm 577
                    } else {
578
                        return res;
579
                    }
580
                }
581
            };
582
            m4.fill("CODE", "CODE");
583
            m4.fill("NOM", "NOM");
584
            for (String string : completionFields) {
585
                m4.fill(string, string);
586
            }
587
        }
588
 
589
        tableElementCode.addModificationListener(tableElementArticle);
590
        tableElementArticle.setModifier(new CellDynamicModifier() {
591
            @Override
93 ilm 592
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
83 ilm 593
                try {
594
                    SQLRowAccessor foreign = row.getForeign("ID_ARTICLE");
595
                    if (foreign != null && !foreign.isUndefined() && foreign.getObject("CODE") != null && foreign.getString("CODE").equals(row.getString("CODE"))) {
596
                        return foreign.getID();
597
                    } else {
598
                        return tableArticle.getUndefinedID();
599
                    }
600
                } catch (Exception e) {
67 ilm 601
                    return tableArticle.getUndefinedID();
602
                }
603
            }
604
        });
605
 
142 ilm 606
        // ECO Contribution
607
        if (this.tableElementEco != null && this.tableElementEcoTotal != null && this.tableElementEcoID != null) {
608
            qteElement.addModificationListener(this.tableElementEcoTotal);
609
            this.tableElementEco.addModificationListener(this.tableElementEcoTotal);
610
            this.tableElementEcoTotal.setModifier(new CellDynamicModifier() {
611
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
612
 
613
                    int qte = Integer.parseInt(row.getObject("QTE").toString());
614
                    BigDecimal f = (row.getObject("ECO_CONTRIBUTION") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("ECO_CONTRIBUTION");
615
                    return f.multiply(new BigDecimal(qte));
616
                }
617
 
618
            });
619
            this.tableElementEcoID.addModificationListener(this.tableElementEco);
620
            this.tableElementEco.setModifier(new CellDynamicModifier() {
621
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
622
 
623
                    if (source.equals(tableElementEcoID)) {
624
                        return row.getForeign("ID_ECO_CONTRIBUTION").getBigDecimal("TAUX");
625
                    } else {
626
                        return row.getObject("ECO_CONTRIBUTION");
627
                    }
628
                }
629
            });
630
        }
631
 
18 ilm 632
        // Calcul automatique du total HT
633
        qteElement.addModificationListener(this.totalHT);
61 ilm 634
        qteU.addModificationListener(this.totalHT);
18 ilm 635
        this.ha.addModificationListener(this.totalHT);
636
        this.totalHT.setModifier(new CellDynamicModifier() {
93 ilm 637
            public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
18 ilm 638
 
639
                int qte = Integer.parseInt(row.getObject("QTE").toString());
83 ilm 640
                BigDecimal f = (row.getObject("PA_HT") == null) ? BigDecimal.ZERO : (BigDecimal) row.getObject("PA_HT");
61 ilm 641
                BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
90 ilm 642
                BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte)), DecimalUtils.HIGH_PRECISION).setScale(totalHT.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
67 ilm 643
 
644
                if (row.getTable().contains("POURCENT_REMISE")) {
645
                    final Object o2 = row.getObject("POURCENT_REMISE");
646
 
647
                    BigDecimal lremise = (o2 == null) ? BigDecimal.ZERO : ((BigDecimal) o2);
648
                    if (lremise.compareTo(BigDecimal.ZERO) >= 0 && lremise.compareTo(BigDecimal.valueOf(100)) < 0) {
649
 
650
                        r = r.multiply(new BigDecimal(100).subtract(lremise).movePointLeft(2)).setScale(totalHT.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
651
                    }
652
                }
653
 
654
                return r;
18 ilm 655
            }
656
 
657
        });
156 ilm 658
        if (showDevise) {
93 ilm 659
 
660
            if (tableElement_PA_Devise != null) {
661
                tableElement_PA_Devise.addModificationListener(tableElement_PrixMetrique1_AchatHT);
662
            }
663
 
664
            if (tableElement_PA_Devise != null) {
665
                tableElement_PrixMetrique1_AchatHT.addModificationListener(tableElement_PA_Devise);
666
 
667
                tableElement_PA_Devise.setModifier(new CellDynamicModifier() {
668
                    public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
669
                        if (source != null && source.getField().getName().equals("PA_DEVISE")) {
670
                            return row.getObject("PA_DEVISE");
671
                        } else {
142 ilm 672
                            if (!row.isForeignEmpty("ID_DEVISE") && row.getForeign("ID_DEVISE") != null) {
93 ilm 673
                                String devCode = row.getForeign("ID_DEVISE").getString("CODE");
674
                                BigDecimal bigDecimal = (BigDecimal) row.getObject("PRIX_METRIQUE_HA_1");
675
 
676
                                CurrencyConverter c = new CurrencyConverter();
94 ilm 677
                                BigDecimal result = convert(bigDecimal, devCode, true);
93 ilm 678
                                if (result == null) {
679
                                    JOptionPane.showMessageDialog(AbstractAchatArticleItemTable.this, "Unable to convert " + bigDecimal + " from " + c.getCompanyCurrencyCode() + " to " + devCode);
680
                                    return BigDecimal.ZERO;
681
                                }
682
                                return result;
683
                            } else if (source != null && source.getField().getName().equalsIgnoreCase("PRIX_METRIQUE_HA_1")) {
684
                                return row.getObject("PRIX_METRIQUE_HA_1");
685
                            }
686
                            return row.getObject("PA_DEVISE");
687
                        }
688
                    }
689
 
690
                });
691
            }
692
 
28 ilm 693
            qteElement.addModificationListener(this.tableElementTotalDevise);
61 ilm 694
            qteU.addModificationListener(this.tableElementTotalDevise);
28 ilm 695
            tableElement_PA_Devise.addModificationListener(this.tableElementTotalDevise);
73 ilm 696
            if (e.getTable().contains("POURCENT_REMISE") && tableElementRemise != null) {
67 ilm 697
                tableElementRemise.addModificationListener(this.tableElementTotalDevise);
698
            }
28 ilm 699
            this.tableElementTotalDevise.setModifier(new CellDynamicModifier() {
93 ilm 700
                public Object computeValueFrom(final SQLRowValues row, SQLTableElement source) {
28 ilm 701
                    int qte = Integer.parseInt(row.getObject("QTE").toString());
67 ilm 702
                    BigDecimal f = (BigDecimal) row.getObject("PA_DEVISE");
61 ilm 703
                    BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
90 ilm 704
                    BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte)), DecimalUtils.HIGH_PRECISION).setScale(tableElementTotalDevise.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
67 ilm 705
 
706
                    if (row.getTable().contains("POURCENT_REMISE")) {
707
                        final Object o2 = row.getObject("POURCENT_REMISE");
708
                        BigDecimal lremise = (o2 == null) ? BigDecimal.ZERO : ((BigDecimal) o2);
709
                        if (lremise.compareTo(BigDecimal.ZERO) >= 0 && lremise.compareTo(BigDecimal.valueOf(100)) < 0) {
710
 
711
                            r = r.multiply(new BigDecimal(100).subtract(lremise).movePointLeft(2)).setScale(tableElementTotalDevise.getDecimalDigits(), BigDecimal.ROUND_HALF_UP);
712
                        }
713
                    }
61 ilm 714
                    return r;
28 ilm 715
                }
19 ilm 716
 
28 ilm 717
            });
718
        }
18 ilm 719
        // Calcul automatique du total TTC
720
        qteElement.addModificationListener(this.tableElementTotalTTC);
61 ilm 721
        qteU.addModificationListener(this.tableElementTotalTTC);
18 ilm 722
        this.ha.addModificationListener(this.tableElementTotalTTC);
61 ilm 723
        this.tableElementTVA.addModificationListener(this.tableElementTotalTTC);
18 ilm 724
        this.tableElementTotalTTC.setModifier(new CellDynamicModifier() {
725
            @Override
93 ilm 726
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
18 ilm 727
                int qte = Integer.parseInt(row.getObject("QTE").toString());
67 ilm 728
                BigDecimal f = (BigDecimal) row.getObject("PA_HT");
18 ilm 729
                int idTaux = Integer.parseInt(row.getObject("ID_TAXE").toString());
730
                if (idTaux < 0) {
731
                    System.out.println(row);
732
                }
733
                Float resultTaux = TaxeCache.getCache().getTauxFromId(idTaux);
156 ilm 734
                editorPAHT.setTaxe(resultTaux);
61 ilm 735
                BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
90 ilm 736
                BigDecimal r = b.multiply(f.multiply(BigDecimal.valueOf(qte), DecimalUtils.HIGH_PRECISION), DecimalUtils.HIGH_PRECISION).setScale(tableElementTotalTTC.getDecimalDigits(),
67 ilm 737
                        BigDecimal.ROUND_HALF_UP);
73 ilm 738
                float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
67 ilm 739
 
740
                BigDecimal total = r.multiply(BigDecimal.ONE.add(new BigDecimal(taux / 100f))).setScale(tableElementTotalTTC.getDecimalDigits(), RoundingMode.HALF_UP);
61 ilm 741
                return total;
18 ilm 742
            }
743
 
744
        });
745
 
746
        this.table.readState();
747
 
748
        // Mode Gestion article avancé
749
        String valModeAvanceVt = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
750
        Boolean bModeAvance = Boolean.valueOf(valModeAvanceVt);
28 ilm 751
        boolean view = !(bModeAvance != null && !bModeAvance.booleanValue());
93 ilm 752
        setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_1"), view);
753
        setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_2"), view);
754
        setColumnVisible(model.getColumnForField("VALEUR_METRIQUE_3"), view);
755
        setColumnVisible(model.getColumnForField("PRIX_METRIQUE_VT_1"), view);
756
        setColumnVisible(model.getColumnForField("ID_MODE_VENTE_ARTICLE"), view);
757
        setColumnVisible(model.getColumnForField("PA_HT"), view);
18 ilm 758
 
142 ilm 759
        if (e.getTable().contains("ID_COMMANDE_ELEMENT")) {
760
            setColumnVisible(model.getColumnForField("ID_COMMANDE_ELEMENT"), false);
761
        }
762
 
61 ilm 763
        // Gestion des unités de vente
764
        final boolean gestionUV = prefs.getBoolean(GestionArticleGlobalPreferencePanel.UNITE_VENTE, true);
93 ilm 765
        setColumnVisible(model.getColumnForField("QTE_UNITAIRE"), gestionUV);
766
        setColumnVisible(model.getColumnForField("ID_UNITE_VENTE"), gestionUV);
61 ilm 767
 
93 ilm 768
        setColumnVisible(model.getColumnForField("ID_STYLE"), DefaultNXProps.getInstance().getBooleanValue("ArticleShowStyle", true));
61 ilm 769
 
142 ilm 770
        if (this.tableElementEco != null && this.tableElementEcoTotal != null && this.tableElementEcoID != null) {
771
            setColumnVisible(model.getColumnForField("ID_ECO_CONTRIBUTION"), showEco);
772
            setColumnVisible(model.getColumnForField("ECO_CONTRIBUTION"), showEco);
773
            setColumnVisible(model.getColumnForField("T_ECO_CONTRIBUTION"), showEco);
774
        }
775
 
93 ilm 776
        setColumnVisible(model.getColumnForField("ID_ARTICLE"), selectArticle);
777
        setColumnVisible(model.getColumnForField("CODE"), !selectArticle || (selectArticle && createAuto));
778
        setColumnVisible(model.getColumnForField("NOM"), !selectArticle || (selectArticle && createAuto));
61 ilm 779
 
156 ilm 780
        setColumnVisible(model.getColumnForField("ID_DEPOT_STOCK"), prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false));
781
 
18 ilm 782
        // Calcul automatique du poids unitaire
783
        tableElement_ValeurMetrique1.addModificationListener(tableElementPoids);
784
        tableElement_ValeurMetrique2.addModificationListener(tableElementPoids);
785
        tableElement_ValeurMetrique3.addModificationListener(tableElementPoids);
786
        tableElementPoids.setModifier(new CellDynamicModifier() {
93 ilm 787
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
18 ilm 788
                return new Float(ReferenceArticleSQLElement.getPoidsFromDetails(row));
789
            }
790
 
791
        });
792
        // Calcul automatique du poids total
793
        tableElementPoids.addModificationListener(this.tableElementPoidsTotal);
794
        qteElement.addModificationListener(this.tableElementPoidsTotal);
61 ilm 795
        qteU.addModificationListener(this.tableElementPoidsTotal);
18 ilm 796
        this.tableElementPoidsTotal.setModifier(new CellDynamicModifier() {
93 ilm 797
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
73 ilm 798
 
65 ilm 799
                Number f = (row.getObject("POIDS") == null) ? 0 : (Number) row.getObject("POIDS");
18 ilm 800
                int qte = Integer.parseInt(row.getObject("QTE").toString());
61 ilm 801
 
802
                BigDecimal b = (row.getObject("QTE_UNITAIRE") == null) ? BigDecimal.ONE : (BigDecimal) row.getObject("QTE_UNITAIRE");
803
                // FIXME convertir en float autrement pour éviter une valeur non transposable
804
                // avec floatValue ou passer POIDS en bigDecimal
805
                return b.multiply(new BigDecimal(f.floatValue() * qte)).floatValue();
18 ilm 806
            }
807
 
808
        });
809
 
93 ilm 810
        tableElement_PrixMetrique1_AchatHT.setModifier(new CellDynamicModifier() {
811
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
812
                if (source != null && source.getField().getName().equals("PRIX_METRIQUE_HA_1")) {
813
                    return row.getObject("PRIX_METRIQUE_HA_1");
814
                } else {
815
                    if (source != null && source.getField().getName().equals("PA_DEVISE")) {
142 ilm 816
                        if (!row.isForeignEmpty("ID_DEVISE") && row.getForeign("ID_DEVISE") != null) {
93 ilm 817
                            String devCode = row.getForeign("ID_DEVISE").getString("CODE");
818
                            BigDecimal bigDecimal = (BigDecimal) row.getObject("PA_DEVISE");
819
 
94 ilm 820
                            return convert(bigDecimal, devCode, false);
93 ilm 821
                        } else {
822
                            return row.getObject("PRIX_METRIQUE_HA_1");
823
                        }
824
                    }
825
                    return row.getObject("PRIX_METRIQUE_HA_1");
826
                }
827
            }
828
 
829
        });
830
 
18 ilm 831
        // Calcul automatique du prix d'achat unitaire HT
832
        tableElement_ValeurMetrique1.addModificationListener(this.ha);
833
        tableElement_ValeurMetrique2.addModificationListener(this.ha);
834
        tableElement_ValeurMetrique3.addModificationListener(this.ha);
835
        tableElement_PrixMetrique1_AchatHT.addModificationListener(this.ha);
836
        this.ha.setModifier(new CellDynamicModifier() {
93 ilm 837
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
18 ilm 838
 
93 ilm 839
                if (row.isForeignEmpty("ID_MODE_VENTE_ARTICLE") || row.getInt("ID_MODE_VENTE_ARTICLE") == ReferenceArticleSQLElement.A_LA_PIECE) {
67 ilm 840
                    return row.getObject("PRIX_METRIQUE_HA_1");
18 ilm 841
                } else {
842
 
67 ilm 843
                    final BigDecimal prixHAFromDetails = ReferenceArticleSQLElement.getPrixHAFromDetails(row);
844
                    return prixHAFromDetails.setScale(ha.getDecimalDigits(), RoundingMode.HALF_UP);
18 ilm 845
                }
846
 
847
            }
848
 
849
        });
850
 
61 ilm 851
        uniteVente.addModificationListener(qteU);
852
        qteU.setModifier(new CellDynamicModifier() {
93 ilm 853
            public Object computeValueFrom(SQLRowValues row, SQLTableElement source) {
61 ilm 854
                SQLRowAccessor rowUnite = row.getForeign("ID_UNITE_VENTE");
855
                if (rowUnite != null && !rowUnite.isUndefined() && rowUnite.getBoolean("A_LA_PIECE")) {
856
                    return BigDecimal.ONE;
857
                } else {
858
                    return row.getObject("QTE_UNITAIRE");
859
                }
860
            }
861
 
862
        });
132 ilm 863
        // La devise est renseignée globalement dans la commande et est reportée automatiquement sur
864
        // les lignes
865
        setColumnVisible(model.getColumnIndexForElement(tableElement_Devise), false);
28 ilm 866
        for (String string : visibilityMap.keySet()) {
93 ilm 867
            setColumnVisible(model.getColumnForField(string), visibilityMap.get(string));
28 ilm 868
        }
869
 
142 ilm 870
        // Barcode reader
871
        final BarcodeReader barcodeReader = ComptaPropsConfiguration.getInstanceCompta().getBarcodeReader();
872
        if (barcodeReader != null) {
873
 
874
            final BarcodeListener l = new BarcodeListener() {
875
 
876
                @Override
877
                public void keyReceived(KeyEvent ee) {
878
                    // TODO Auto-generated method stub
879
                }
880
 
881
                @Override
882
                public void barcodeRead(String code) {
883
                    if (((JFrame) SwingUtilities.getRoot(getRowValuesTable())).isActive()) {
884
                        final SQLSelect selArticle = new SQLSelect();
885
                        final SQLTable tableArticle = getSQLElement().getForeignElement("ID_ARTICLE").getTable();
886
                        selArticle.addSelectStar(tableArticle);
887
                        Where w = new Where(tableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
888
                        w = w.and(new Where(tableArticle.getField("CODE_BARRE"), "=", code));
889
                        selArticle.setWhere(w);
890
                        List<SQLRow> l2 = SQLRowListRSH.execute(selArticle);
891
                        if (l2.size() > 0) {
892
                            System.err.println("ARTICLE " + l2.get(0).getString("NOM"));
893
                            Tuple3<Double, String, String> art = Tuple3.create(1.0D, l2.get(0).getString("CODE"), l2.get(0).getString("NOM"));
894
                            List<Tuple3<Double, String, String>> l = new ArrayList<Tuple3<Double, String, String>>();
895
                            l.add(art);
896
                            insertFromDrop(l, m);
897
                        } else {
898
                            System.err.println("ARTICLE NOT FOUND !");
899
                        }
900
                    }
901
 
902
                }
903
            };
904
            getRowValuesTable().addHierarchyListener(new HierarchyListener() {
905
                public void hierarchyChanged(HierarchyEvent e) {
906
                    if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0)
907
                        if (getRowValuesTable().isDisplayable()) {
908
                            barcodeReader.addBarcodeListener(l);
909
                        } else {
910
                            barcodeReader.removeBarcodeListener(l);
911
                        }
912
                }
913
            });
914
 
915
        }
916
 
19 ilm 917
        // On réécrit la configuration au cas ou les preferences aurait changé
18 ilm 918
        this.table.writeState();
919
    }
920
 
28 ilm 921
    private static Map<String, Boolean> visibilityMap = new HashMap<String, Boolean>();
922
 
923
    public static Map<String, Boolean> getVisibilityMap() {
924
        return visibilityMap;
925
    }
926
 
132 ilm 927
    private String incoterm = "";
928
 
929
    public void setIncoterms(String incoterm) {
930
        if (incoterm == null) {
931
            incoterm = "";
932
        }
933
        this.incoterm = incoterm;
934
    }
935
 
936
    private SQLRow rowFournisseur = null;
937
 
67 ilm 938
    public void setFournisseur(SQLRow rowFournisseur) {
132 ilm 939
        this.rowFournisseur = rowFournisseur;
67 ilm 940
        if (getSQLElement().getTable().contains("ID_CODE_FOURNISSEUR") && this.supplierCode) {
941
 
942
            if (rowFournisseur != null && !rowFournisseur.isUndefined()) {
943
                Where w = new Where(getSQLElement().getTable().getTable("CODE_FOURNISSEUR").getField("ID_FOURNISSEUR"), "=", rowFournisseur.getID());
944
                this.m4.setWhere(w);
945
            } else {
946
                this.m4.setWhere(null);
947
            }
948
        }
949
    }
950
 
93 ilm 951
    private BigDecimal getPrice(final SQLRowAccessor r, List<String> list) {
952
        BigDecimal result = r.getBigDecimal(list.get(0));
953
 
954
        for (int i = 1; i < list.size(); i++) {
955
            BigDecimal m0 = r.getBigDecimal(list.get(i));
956
            if (m0 != null && m0.floatValue() > 0) {
957
                result = result.divide(m0, 2, RoundingMode.HALF_UP);
958
            }
959
        }
960
        return result;
961
    }
962
 
149 ilm 963
    public Object tarifCompletion(SQLRow row, String field) {
132 ilm 964
        final SQLTable tTarifFournisseur = this.getSQLElement().getTable().getDBRoot().getTable("ARTICLE_TARIF_FOURNISSEUR");
94 ilm 965
 
174 ilm 966
        if (row != null && !row.isUndefined() && (field.equalsIgnoreCase("PRIX_METRIQUE_HA_1") || field.equalsIgnoreCase("PA_HT")) && tTarifFournisseur != null) {
132 ilm 967
            List<String> incoTerms;
968
 
969
            if (this.incoterm != null && this.incoterm.equalsIgnoreCase("CPT")) {
970
                incoTerms = Arrays.asList("PRIX_ACHAT", "COEF_TRANSPORT_PORT");
971
            } else if (this.incoterm != null && this.incoterm.equalsIgnoreCase("DDP")) {
972
                incoTerms = Arrays.asList("PRIX_ACHAT", "COEF_TRANSPORT_PORT", "COEF_TAXE_D");
973
            } else {
974
                incoTerms = Arrays.asList("PRIX_ACHAT");
975
            }
93 ilm 976
            List<SQLRow> rows = row.getReferentRows(tTarifFournisseur);
132 ilm 977
            if (row.getBoolean("AUTO_PRIX_ACHAT_NOMENCLATURE")) {
19 ilm 978
 
132 ilm 979
                List<SQLRow> rowsElt = row.getReferentRows(row.getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
980
                BigDecimal price = BigDecimal.ZERO;
981
                final Set<String> tarifNotFound = new HashSet<String>();
982
                for (SQLRow sqlRow : rowsElt) {
983
                    List<SQLRow> rowsT = sqlRow.getForeign("ID_ARTICLE").getReferentRows(tTarifFournisseur);
94 ilm 984
 
132 ilm 985
                    boolean priceFound = false;
986
                    boolean tarifFound = false;
987
                    if (rowsT.size() > 0) {
988
                        BigDecimal min = BigDecimal.ZERO;
989
 
174 ilm 990
                        BigDecimal defaultPrice = sqlRow.getForeign("ID_ARTICLE").getBigDecimal("PRIX_METRIQUE_HA_1");
132 ilm 991
                        Calendar c = null;
992
                        for (SQLRow sqlRowT : rowsT) {
993
                            if (this.rowFournisseur != null && this.rowFournisseur.getID() == sqlRowT.getForeignID("ID_FOURNISSEUR")) {
994
                                BigDecimal priceT = getPrice(sqlRowT, incoTerms);
995
                                defaultPrice = priceT;
996
                                final Calendar datePrice = sqlRowT.getDate("DATE_PRIX");
142 ilm 997
                                datePrice.set(Calendar.HOUR, 0);
998
                                datePrice.set(Calendar.MINUTE, 0);
999
                                datePrice.set(Calendar.SECOND, 0);
1000
                                datePrice.set(Calendar.MILLISECOND, 0);
132 ilm 1001
                                if (datePrice == null || (this.getDateDevise() != null && !this.getDateDevise().before(datePrice.getTime()))) {
1002
                                    if (c == null || c.before(datePrice)) {
1003
 
1004
                                        min = priceT;
1005
                                        c = datePrice;
1006
                                        priceFound = true;
1007
                                    } else if (c != null) {
1008
                                        defaultPrice = priceT;
1009
                                    }
1010
                                }
1011
                                tarifFound = true;
1012
                            }
1013
                        }
1014
 
1015
                        if (priceFound) {
1016
                            price = price.add(min.multiply(sqlRow.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRow.getInt("QTE"), DecimalUtils.HIGH_PRECISION))));
1017
                        } else {
1018
                            price = price.add(defaultPrice.multiply(sqlRow.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(sqlRow.getInt("QTE"), DecimalUtils.HIGH_PRECISION))));
1019
                        }
1020
                    }
1021
                    if (!tarifFound) {
1022
                        tarifNotFound.add(sqlRow.getForeign("ID_ARTICLE").getString("CODE"));
1023
                    }
93 ilm 1024
                }
132 ilm 1025
                if (!tarifNotFound.isEmpty()) {
1026
                    SwingUtilities.invokeLater(new Runnable() {
93 ilm 1027
 
132 ilm 1028
                        @Override
1029
                        public void run() {
1030
                            JOptionPane.showMessageDialog(AbstractAchatArticleItemTable.this.table,
1031
                                    "Attention, impossible de calculer le tarif.\nLes articles suivants n'ont pas de tarif associé :\n" + tarifNotFound);
1032
                        }
1033
                    });
1034
                }
1035
                return price;
1036
            } else if (!rows.isEmpty()) {
174 ilm 1037
 
1038
                BigDecimal min = row.getBigDecimal("PRIX_METRIQUE_HA_1");
1039
 
132 ilm 1040
                Calendar c = null;
93 ilm 1041
                for (SQLRow sqlRow : rows) {
132 ilm 1042
                    if (this.rowFournisseur != null && this.rowFournisseur.getID() == sqlRow.getForeignID("ID_FOURNISSEUR")) {
1043
                        BigDecimal price = getPrice(sqlRow, incoTerms);
1044
                        final Calendar datePrice = sqlRow.getDate("DATE_PRIX");
1045
                        if (datePrice == null || (this.getDateDevise() != null && !this.getDateDevise().before(datePrice.getTime()))) {
1046
                            if (c == null || c.before(datePrice)) {
1047
                                min = price;
1048
                                c = datePrice;
1049
                            }
1050
                        }
93 ilm 1051
                    }
1052
                }
94 ilm 1053
                return min.setScale(2, RoundingMode.HALF_UP);
93 ilm 1054
            }
1055
        }
94 ilm 1056
        if (field.equalsIgnoreCase("INCOTERM")) {
132 ilm 1057
            // if (tTarifFournisseur != null) {
1058
            // List<SQLRow> rows = row.getReferentRows(tTarifFournisseur);
1059
            // if (!rows.isEmpty()) {
1060
            // final SQLRow sqlRow0 = rows.get(0);
1061
            // return sqlRow0.getString("CONDITIONS");
1062
            // }
1063
            // }
1064
            return this.incoterm;
94 ilm 1065
        }
93 ilm 1066
 
19 ilm 1067
        if (getDevise() != null && !getDevise().isUndefined()) {
1068
            if ((field.equalsIgnoreCase("ID_DEVISE") || field.equalsIgnoreCase("ID_DEVISE_HA"))) {
1069
                return getDevise().getID();
1070
            } else if ((field.equalsIgnoreCase("PA_DEVISE"))) {
132 ilm 1071
                if (row.getBigDecimal("PA_DEVISE") != null && row.getBigDecimal("PA_DEVISE").signum() != 0 && this.incoterm.length() == 0) {
93 ilm 1072
                    return row.getBigDecimal("PA_DEVISE");
1073
                } else {
132 ilm 1074
                    String devCode = getDevise().getString("CODE");
93 ilm 1075
 
132 ilm 1076
                    BigDecimal tarifCompletion = (BigDecimal) tarifCompletion(row, "PRIX_METRIQUE_HA_1");
1077
                    if (tarifCompletion == null) {
1078
                        tarifCompletion = row.getBigDecimal("PRIX_METRIQUE_HA_1");
93 ilm 1079
                    }
132 ilm 1080
                    if (tarifCompletion == null) {
1081
                        return null;
1082
                    } else {
1083
                        // Remove set scale 2 --> if scale ex : PA = 95.74MAD --> 0.76592€
1084
                        // with Scale 0.77€ so put 96.25MAD in PA
1085
                        return convert(tarifCompletion, devCode, true);
1086
                    }
93 ilm 1087
                }
132 ilm 1088
 
19 ilm 1089
            }
1090
        } else {
1091
            if ((field.equalsIgnoreCase("ID_DEVISE") || field.equalsIgnoreCase("ID_DEVISE_HA"))) {
1092
                return Configuration.getInstance().getDirectory().getElement("DEVISE").getTable().getUndefinedID();
1093
            } else if ((field.equalsIgnoreCase("PA_DEVISE"))) {
1094
 
67 ilm 1095
                return BigDecimal.ZERO;
19 ilm 1096
            }
156 ilm 1097
 
19 ilm 1098
        }
156 ilm 1099
        if (field.equalsIgnoreCase("ID_TAXE") && this.rowCatComptable != null) {
1100
            return this.rowCatComptable.getForeignID("ID_TAXE_VENTE");
1101
        }
19 ilm 1102
        return null;
132 ilm 1103
 
19 ilm 1104
    }
1105
 
93 ilm 1106
    @Override
1107
    protected void refreshDeviseAmount() {
1108
        int count = getRowValuesTable().getRowCount();
1109
        final int columnForField = getRowValuesTable().getRowValuesTableModel().getColumnForField("PA_DEVISE");
1110
        if (columnForField >= 0) {
1111
            SQLTableElement eltDevise = getRowValuesTable().getRowValuesTableModel().getSQLTableElementAt(columnForField);
1112
            for (int i = 0; i < count; i++) {
1113
                SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
1114
                // getRowValuesTable().getRowValuesTableModel().putValue(rowVals.getObject("PV_U_DEVISE"),
1115
                // i, "PV_U_DEVISE", true);
1116
                eltDevise.setValueFrom(rowVals, rowVals.getObject("PA_DEVISE"));
1117
                getRowValuesTable().getRowValuesTableModel().fireTableChanged(new TableModelEvent(getRowValuesTable().getRowValuesTableModel(), i, i, columnForField));
1118
            }
1119
        }
1120
    }
1121
 
19 ilm 1122
    public SQLRowAccessor getDevise() {
1123
        return this.rowDevise;
1124
    }
1125
 
1126
    public void setDevise(SQLRowAccessor deviseRow) {
1127
        this.rowDevise = deviseRow;
94 ilm 1128
        if (deviseRow == null) {
1129
            getDefaultRowValues().put("ID_DEVISE", null);
1130
        } else {
1131
            getDefaultRowValues().put("ID_DEVISE", this.rowDevise.getID());
1132
        }
19 ilm 1133
    }
41 ilm 1134
 
94 ilm 1135
    private BigDecimal tauxConversion = null;
1136
 
1137
    public void setTauxConversion(BigDecimal tauxConversion) {
1138
        if (tauxConversion != null && tauxConversion.signum() == 0) {
1139
            tauxConversion = null;
1140
        }
1141
        this.tauxConversion = tauxConversion;
1142
        refreshDeviseAmount();
1143
    }
1144
 
1145
    public BigDecimal convert(BigDecimal val, String devCode, boolean fromCompanyCurrency) {
1146
        if (val == null) {
1147
            return val;
1148
        }
1149
        if (this.tauxConversion == null) {
1150
            CurrencyConverter c = new CurrencyConverter();
1151
            if (fromCompanyCurrency) {
1152
                return c.convert(val, c.getCompanyCurrencyCode(), devCode, getDateDevise(), isUsedBiasedDevise());
1153
            } else {
1154
                return c.convert(val, devCode, c.getCompanyCurrencyCode(), getDateDevise(), isUsedBiasedDevise());
1155
            }
1156
        } else {
1157
            if (fromCompanyCurrency) {
1158
                return val.divide(this.tauxConversion, DecimalUtils.HIGH_PRECISION).setScale(val.scale(), RoundingMode.HALF_UP);
1159
            } else {
1160
                return val.multiply(this.tauxConversion, DecimalUtils.HIGH_PRECISION).setScale(val.scale(), RoundingMode.HALF_UP);
1161
            }
1162
        }
1163
    }
1164
 
41 ilm 1165
    public void setFournisseurFilterOnCompletion(SQLRow row) {
93 ilm 1166
        final SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
1167
        Where w = new Where(sqlTableArticle.getField("OBSOLETE"), "=", Boolean.FALSE);
41 ilm 1168
        if (row != null && !row.isUndefined()) {
93 ilm 1169
            w = w.and(new Where(this.tableArticle.getField("ID_FOURNISSEUR"), "=", row.getID()));
41 ilm 1170
        }
93 ilm 1171
        this.m.setWhere(w);
1172
        this.m2.setWhere(w);
1173
        this.m3.setWhere(w);
41 ilm 1174
    }
1175
 
142 ilm 1176
    private void insertFromDrop(List<Tuple3<Double, String, String>> articles, AutoCompletionManager m) {
94 ilm 1177
 
142 ilm 1178
        List<String> code = new ArrayList<String>(articles.size());
1179
        for (int i = articles.size() - 1; i >= 0; i--) {
94 ilm 1180
 
142 ilm 1181
            Tuple3<Double, String, String> tuple = articles.get(i);
1182
            code.add(tuple.get1());
1183
        }
94 ilm 1184
 
142 ilm 1185
        int rowCount = getRowValuesTable().getRowValuesTableModel().getRowCount();
1186
        Map<Integer, Integer> mapRows = new HashMap<Integer, Integer>();
1187
        for (int i = 0; i < rowCount; i++) {
1188
            SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(i);
1189
            if (rowVals.getObject("ID_ARTICLE") != null && !rowVals.isForeignEmpty("ID_ARTICLE")) {
1190
                mapRows.put(rowVals.getForeignID("ID_ARTICLE"), i);
1191
            }
1192
        }
94 ilm 1193
 
142 ilm 1194
        SQLSelect sel = new SQLSelect();
1195
        final SQLTable articleTable = getSQLElement().getTable().getForeignTable("ID_ARTICLE");
1196
        sel.addSelectStar(articleTable);
1197
        sel.setWhere(new Where(articleTable.getField("CODE"), code));
1198
        List<SQLRow> matchCode = SQLRowListRSH.execute(sel);
1199
        Map<String, SQLRow> mapCode = new HashMap<String, SQLRow>();
1200
        for (SQLRow sqlRow : matchCode) {
1201
            mapCode.put(sqlRow.getString("CODE"), sqlRow);
1202
        }
1203
        Set<String> fieldsFrom = m.getFieldsFrom();
1204
        fieldsFrom.remove("POURCENT_REMISE");
1205
        for (int i = articles.size() - 1; i >= 0; i--) {
94 ilm 1206
 
142 ilm 1207
            Tuple3<Double, String, String> tuple = articles.get(i);
94 ilm 1208
 
142 ilm 1209
            SQLRow article = mapCode.get(tuple.get1());
1210
            if (article != null && mapRows.containsKey(article.getID())) {
1211
                Integer index = mapRows.get(article.getID());
1212
                SQLRowValues rowVals = getRowValuesTable().getRowValuesTableModel().getRowValuesAt(index);
1213
                getRowValuesTable().getRowValuesTableModel().putValue(rowVals.getInt("QTE") + 1, index, "QTE");
1214
            } else {
1215
                final SQLRowValues row2Insert = new SQLRowValues(getRowValuesTable().getRowValuesTableModel().getDefaultRowValues());
1216
 
1217
                // Completion depuis l'article trouvé
1218
                if (article != null) {
1219
                    m.fillRowValues(article, fieldsFrom, row2Insert);
1220
                    // Fill prix total
1221
                    row2Insert.put("ID_ARTICLE", article.getID());
1222
                    row2Insert.put("CODE", article.getObject("CODE"));
1223
                    row2Insert.put("NOM", article.getObject("NOM"));
1224
                } else {
1225
                    row2Insert.put("CODE", tuple.get1());
1226
                    row2Insert.put("NOM", tuple.get2());
1227
                }
1228
 
1229
                row2Insert.put("QTE", Math.round(tuple.get0().floatValue()));
1230
 
1231
                row2Insert.put("PA_HT", row2Insert.getObject("PRIX_METRIQUE_HA_1"));
1232
                //
1233
                final BigDecimal resultTotalHT = row2Insert.getBigDecimal("PA_HT").multiply(new BigDecimal(row2Insert.getInt("QTE")));
1234
                row2Insert.put("T_PA_HT", resultTotalHT);
1235
 
1236
                Float resultTaux = TaxeCache.getCache().getTauxFromId(row2Insert.getForeignID("ID_TAXE"));
1237
 
1238
                if (resultTaux == null) {
1239
                    SQLRow rowTax = TaxeCache.getCache().getFirstTaxe();
1240
                    resultTaux = rowTax.getFloat("TAUX");
1241
                }
1242
 
1243
                float taux = (resultTaux == null) ? 0.0F : resultTaux.floatValue();
1244
 
1245
                BigDecimal r = resultTotalHT.multiply(BigDecimal.valueOf(taux).movePointLeft(2).add(BigDecimal.ONE), DecimalUtils.HIGH_PRECISION);
1246
 
1247
                row2Insert.put("T_PA_TTC", r);
1248
                // row2Insert.put("ID_STYLE", allStyleByName.get("Composant"));
1249
                getRowValuesTable().getRowValuesTableModel().addRowAt(0, row2Insert);
1250
            }
94 ilm 1251
        }
1252
    }
1253
 
18 ilm 1254
}