OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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