OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | 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.sales.product.element;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
174 ilm 17
import org.openconcerto.erp.config.update.Updater_1_5;
18 ilm 18
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
142 ilm 19
import org.openconcerto.erp.core.edm.AttachmentAction;
83 ilm 20
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
156 ilm 21
import org.openconcerto.erp.core.reports.history.ui.HistoriqueArticleFrame;
94 ilm 22
import org.openconcerto.erp.core.sales.product.action.InventairePanel;
18 ilm 23
import org.openconcerto.erp.core.sales.product.component.ReferenceArticleSQLComponent;
156 ilm 24
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
83 ilm 25
import org.openconcerto.erp.generationDoc.gestcomm.FicheArticleXmlSheet;
26
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
18 ilm 27
import org.openconcerto.erp.preferences.DefaultNXProps;
73 ilm 28
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
18 ilm 29
import org.openconcerto.sql.Configuration;
30
import org.openconcerto.sql.element.SQLComponent;
31
import org.openconcerto.sql.element.SQLElement;
94 ilm 32
import org.openconcerto.sql.model.FieldPath;
18 ilm 33
import org.openconcerto.sql.model.SQLRow;
94 ilm 34
import org.openconcerto.sql.model.SQLRowAccessor;
83 ilm 35
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 36
import org.openconcerto.sql.model.SQLRowValues;
37
import org.openconcerto.sql.model.SQLSelect;
38
import org.openconcerto.sql.model.SQLTable;
39
import org.openconcerto.sql.model.Where;
94 ilm 40
import org.openconcerto.sql.model.graph.Path;
73 ilm 41
import org.openconcerto.sql.preferences.SQLPreferences;
156 ilm 42
import org.openconcerto.sql.request.ComboSQLRequest;
90 ilm 43
import org.openconcerto.sql.view.EditFrame;
44
import org.openconcerto.sql.view.EditPanel.EditMode;
94 ilm 45
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
90 ilm 46
import org.openconcerto.sql.view.list.IListe;
47
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
48
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
83 ilm 49
import org.openconcerto.sql.view.list.SQLTableModelColumn;
142 ilm 50
import org.openconcerto.sql.view.list.SQLTableModelSource;
90 ilm 51
import org.openconcerto.ui.FrameUtil;
156 ilm 52
import org.openconcerto.ui.PanelFrame;
94 ilm 53
import org.openconcerto.utils.CollectionUtils;
90 ilm 54
import org.openconcerto.utils.DecimalUtils;
55
import org.openconcerto.utils.ListMap;
18 ilm 56
 
90 ilm 57
import java.awt.event.ActionEvent;
67 ilm 58
import java.math.BigDecimal;
18 ilm 59
import java.sql.SQLException;
60
import java.util.ArrayList;
94 ilm 61
import java.util.Collection;
18 ilm 62
import java.util.List;
94 ilm 63
import java.util.Set;
18 ilm 64
 
90 ilm 65
import javax.swing.AbstractAction;
66
 
18 ilm 67
import org.apache.commons.dbutils.handlers.ArrayListHandler;
68
 
69
public class ReferenceArticleSQLElement extends ComptaSQLConfElement {
70
    public static final int AU_METRE_LONGUEUR = 2;
71
    public static final int AU_METRE_CARRE = 3;
72
    public static final int AU_POID_METRECARRE = 4;
73
    public static final int A_LA_PIECE = 5;
74
    public static final int AU_METRE_LARGEUR = 6;
75
    private static final int PRIX_HA = 1;
76
    private static final int PRIX_VT = 2;
156 ilm 77
    protected PredicateRowAction stock;
18 ilm 78
 
94 ilm 79
    public static final String[] CONDITIONS = new String[] { "CFR", "CIF", "CPT", "DAT", "DDP", "DDU", "EXW", "FCA", "FOB" };
80
 
18 ilm 81
    public ReferenceArticleSQLElement() {
82
        super("ARTICLE", "un article", "articles");
83 ilm 83
 
84
        getRowActions().addAll(new MouseSheetXmlListeListener(FicheArticleXmlSheet.class).getRowActions());
94 ilm 85
        this.stock = new PredicateRowAction(new AbstractAction("Mettre à jour les stocks") {
86
 
87
            @Override
88
            public void actionPerformed(ActionEvent e) {
89
 
156 ilm 90
                final List<SQLRowValues> selectedRows = IListe.get(e).getSelectedRows();
91
                List<SQLRowAccessor> l = new ArrayList<SQLRowAccessor>();
92
                for (SQLRowValues sqlRowValues : selectedRows) {
93
                    l.add(sqlRowValues.asRow().getForeign("ID_STOCK"));
94
                }
95
 
96
                PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), l), "Mise à jour des stocks");
94 ilm 97
                FrameUtil.show(p);
98
 
99
            }
100
        }, true, false);
101
        stock.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
102
        getRowActions().add(stock);
103
 
156 ilm 104
        PredicateRowAction history = new PredicateRowAction(new AbstractAction("Historique") {
105
 
106
            @Override
107
            public void actionPerformed(ActionEvent e) {
108
                HistoriqueArticleFrame frame = new HistoriqueArticleFrame(ReferenceArticleSQLElement.this);
109
                frame.selectId(IListe.get(e).getSelectedId());
110
                frame.setVisible(true);
111
            }
112
        }, false, true);
113
        history.setPredicate(IListeEvent.getSingleSelectionPredicate());
114
        getRowActions().add(history);
115
 
90 ilm 116
        PredicateRowAction clone = new PredicateRowAction(new AbstractAction("Dupliquer") {
83 ilm 117
 
90 ilm 118
            @Override
119
            public void actionPerformed(ActionEvent e) {
120
 
121
                SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
122
                ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(IListe.get(e).getSelectedRow().asRow());
123
                for (SQLRow child : children.allValues()) {
124
                    Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
125
                }
126
                EditFrame f = new EditFrame(createComponent(), EditMode.CREATION);
127
                f.getSQLComponent().select(rowVals);
128
                FrameUtil.show(f);
129
 
130
            }
131
        }, true, false);
132
        clone.setPredicate(IListeEvent.getSingleSelectionPredicate());
133
        getRowActions().add(clone);
142 ilm 134
 
135
        PredicateRowAction actionAttachment = new PredicateRowAction(new AttachmentAction().getAction(), true);
136
        actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());
156 ilm 137
 
142 ilm 138
        getRowActions().add(actionAttachment);
18 ilm 139
    }
140
 
83 ilm 141
    @Override
142 ilm 142
    protected synchronized void _initTableSource(final SQLTableModelSource source) {
143
        super._initTableSource(source);
93 ilm 144
        source.init();
145
        final SQLTableModelColumn pvHA1Col = source.getColumn(getTable().getField("PRIX_METRIQUE_HA_1"));
146
        if (pvHA1Col != null) {
147
            pvHA1Col.setRenderer(CURRENCY_RENDERER);
148
        }
83 ilm 149
 
93 ilm 150
        final SQLTableModelColumn pvHT1Col = source.getColumn(getTable().getField("PRIX_METRIQUE_VT_1"));
151
        if (pvHT1Col != null) {
152
            pvHT1Col.setRenderer(CURRENCY_RENDERER);
153
        }
154
 
83 ilm 155
        final SQLTableModelColumn pvHTCol = source.getColumn(getTable().getField("PV_HT"));
156
        if (pvHTCol != null) {
157
            pvHTCol.setRenderer(CURRENCY_RENDERER);
158
        }
159
        final SQLTableModelColumn pvTTCCol = source.getColumn(getTable().getField("PV_TTC"));
160
        if (pvTTCCol != null) {
161
            pvTTCCol.setRenderer(CURRENCY_RENDERER);
162
        }
163
        final SQLTableModelColumn paHTCol = source.getColumn(getTable().getField("PA_HT"));
164
        if (paHTCol != null) {
165
            paHTCol.setRenderer(CURRENCY_RENDERER);
166
        }
167
 
94 ilm 168
        if (getTable().getDBRoot().contains("ARTICLE_ELEMENT") && !getTable().getDBRoot().contains("TARIF_AGENCE")) {
169
            source.getColumns().add(new BaseSQLTableModelColumn("Type", String.class) {
170
 
171
                @Override
172
                protected Object show_(SQLRowAccessor r) {
173
 
174
                    Collection<? extends SQLRowAccessor> c = r.getReferentRows(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
175
                    if (c.size() == 0) {
176
                        // "Article simple"
177
                        return "Article simple";
178
                    } else {
179
                        // "Kit
180
                        return "Nomenclature";
181
                    }
182
                }
183
 
184
                @Override
185
                public Set<FieldPath> getPaths() {
186
                    Path p = new Path(getTable());
187
                    p = p.add(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
188
                    return CollectionUtils.createSet(new FieldPath(p, "QTE"));
189
                }
190
            });
191
        }
83 ilm 192
    }
193
 
18 ilm 194
    protected List<String> getListFields() {
195
        final List<String> l = new ArrayList<String>();
196
 
197
        l.add("CODE");
93 ilm 198
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
199
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
200
            l.add("CODE_BARRE");
201
        }
18 ilm 202
        l.add("NOM");
203
        String articleAdvanced = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
204
        Boolean bArticleAdvanced = Boolean.valueOf(articleAdvanced);
41 ilm 205
 
206
        if (bArticleAdvanced) {
18 ilm 207
            l.add("POIDS");
208
            l.add("PRIX_METRIQUE_HA_1");
209
            l.add("PRIX_METRIQUE_VT_1");
41 ilm 210
        }
18 ilm 211
        l.add("PA_HT");
212
        l.add("PV_HT");
213
            l.add("ID_TAXE");
214
        l.add("PV_TTC");
28 ilm 215
        l.add("ID_FAMILLE_ARTICLE");
19 ilm 216
        l.add("ID_FOURNISSEUR");
177 ilm 217
        l.add("POIDS");
93 ilm 218
        l.add("SKU");
156 ilm 219
 
220
        // if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
174 ilm 221
        l.add("GESTION_STOCK");
18 ilm 222
        l.add("ID_STOCK");
156 ilm 223
        // }
18 ilm 224
        String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
225
        Boolean b = Boolean.valueOf(val);
226
        if (b != null && b.booleanValue()) {
227
            l.add("SERVICE");
228
        }
229
        return l;
230
    }
231
 
83 ilm 232
    @Override
132 ilm 233
    public ListMap<String, String> getShowAs() {
234
        final ListMap<String, String> res = new ListMap<String, String>();
93 ilm 235
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
236
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
132 ilm 237
            res.add(null, "CODE_BARRE");
93 ilm 238
        }
156 ilm 239
        res.addAll(null, "CODE", "NOM", "ID_FAMILLE_ARTICLE");
83 ilm 240
        return res;
241
    }
242
 
18 ilm 243
    protected List<String> getComboFields() {
244
        final List<String> l = new ArrayList<String>();
245
        l.add("CODE");
73 ilm 246
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
247
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
248
            l.add("CODE_BARRE");
249
        }
250
 
18 ilm 251
        l.add("NOM");
177 ilm 252
        l.add("PA_HT");
253
        l.add("PV_HT");
254
        l.add("DERNIER_DATE_ACHAT");
18 ilm 255
        return l;
256
    }
257
 
258
    /*
259
     * (non-Javadoc)
260
     *
261
     * @see org.openconcerto.devis.SQLElement#getComponent()
262
     */
263
    public SQLComponent createComponent() {
264
 
265
        return new ReferenceArticleSQLComponent(this);
266
    }
267
 
268
    /**
269
     * Calcul le prix d'HA total par rapport aux metriques
270
     *
271
     * @param rowVals
272
     * @return le prix d'achat en centimes
273
     */
67 ilm 274
    public static BigDecimal getPrixHAFromDetails(SQLRowValues rowVals) {
18 ilm 275
        return getValuePiece(rowVals, PRIX_HA);
276
    }
277
 
278
    /**
279
     * Calcul le prix de VT total par rapport aux metriques
280
     *
281
     * @param rowVals
282
     * @return le prix de vente en centimes
283
     */
67 ilm 284
    public static BigDecimal getPrixVTFromDetails(SQLRowValues rowVals) {
18 ilm 285
        return getValuePiece(rowVals, PRIX_VT);
286
    }
287
 
288
    /**
289
     * Calcul le poids total par rapport aux metriques
290
     *
291
     * @param rowVals
292
     * @return le poids total arrondi à trois chiffres apres la virgule
293
     */
294
    public static float getPoidsFromDetails(SQLRowValues rowVals) {
295
 
296
        // Valeur
297
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
298
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
299
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");
300
 
301
        final float produit = valMetrique1 * valMetrique2 * valMetrique3;
302
        if (produit > 0.0F) {
303
            return Math.round(produit * 1000.0F) / 1000.0F;
304
        }
305
        if (rowVals.getObject("POIDS") != null) {
306
            float p = rowVals.getFloat("POIDS");
307
            return p;
308
        }
309
        return 0.0F;
310
    }
311
 
67 ilm 312
    private static BigDecimal getValuePiece(SQLRowValues rowVals, int value) {
18 ilm 313
        if (rowVals.getObject("ID_MODE_VENTE_ARTICLE") == null) {
314
            throw new IllegalArgumentException("La SQLRowValues ne contient pas ID_MODE_VENTE_ARTICLE");
315
        }
316
        int mode = rowVals.getInt("ID_MODE_VENTE_ARTICLE");
317
        if (mode == 1) {
318
            mode = A_LA_PIECE;
319
        }
320
        // prix HA
67 ilm 321
        BigDecimal metrique1HA = rowVals.getObject("PRIX_METRIQUE_HA_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_HA_1"));
18 ilm 322
 
323
        // Prix VT
67 ilm 324
        BigDecimal metrique1VT = rowVals.getObject("PRIX_METRIQUE_VT_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_VT_1"));
18 ilm 325
 
326
        // Valeur
327
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
328
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
329
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");
330
 
331
        // Mode de vente au metre carré
332
        if (mode == AU_METRE_CARRE) {
333
            float surface = valMetrique1 * valMetrique2;
334
            if (value == PRIX_HA) {
90 ilm 335
                return metrique1HA.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
18 ilm 336
            }
90 ilm 337
            return metrique1VT.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
18 ilm 338
        }
339
        // Mode de vente au metre, largeur
340
        if (mode == AU_METRE_LARGEUR) {
341
            if (value == PRIX_HA) {
90 ilm 342
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
18 ilm 343
            }
90 ilm 344
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
18 ilm 345
        }
346
        // Mode de vente au metre, longueur
347
        if (mode == AU_METRE_LONGUEUR) {
348
            if (value == PRIX_HA) {
90 ilm 349
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
18 ilm 350
            }
90 ilm 351
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
18 ilm 352
        }
353
        // Mode de vente au poids / m2
354
        if (mode == AU_POID_METRECARRE) {
355
            float surface = valMetrique1 * valMetrique2;
356
            float p = surface * valMetrique3;
357
            if (value == PRIX_HA) {
90 ilm 358
                return metrique1HA.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
18 ilm 359
            }
90 ilm 360
            return metrique1VT.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
18 ilm 361
        }
362
 
93 ilm 363
        // Mode de vente à la piece et autres
364
        if (value == PRIX_HA) {
365
            if (rowVals.getObject("PA_HT") != null) {
366
                return (BigDecimal) rowVals.getObject("PA_HT");
367
            }
368
            return BigDecimal.ZERO;
369
        }
370
        if (rowVals.getObject("PV_HT") != null) {
371
            return (BigDecimal) rowVals.getObject("PV_HT");
372
        }
373
        return BigDecimal.ZERO;
374
 
18 ilm 375
    }
376
 
377
    /**
378
     * retourne l'id d'un article ayant le meme Code, Nom et valeur Metrique, le cas échéant -1
379
     *
380
     * @param row
381
     * @param createIfNotExist
382
     * @return id de l'article correspondant
383
     */
384
    public static int getIdForCNM(SQLRowValues row, boolean createIfNotExist) {
385
        return getIdFor(row, true, createIfNotExist);
386
    }
387
 
388
    /**
389
     * retourne l'id d'un article ayant le meme Code, Nom le cas échéant -1
390
     *
391
     * @param row
392
     * @param createIfNotExist
393
     * @return id de l'article correspondant
394
     */
395
    public static int getIdForCN(SQLRowValues row, boolean createIfNotExist) {
396
 
397
        return getIdFor(row, false, createIfNotExist);
398
    }
399
 
93 ilm 400
    @SuppressWarnings("rawtypes")
18 ilm 401
    private static int getIdFor(SQLRowValues row, boolean includeMetrique, boolean createIfNotExist) {
402
 
403
        // On cherche l'article qui lui correspond
404
        SQLTable tableArt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
405
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(tableArt);
406
        String req = getMatchRequest(row, includeMetrique);
407
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());
408
 
409
        if (result != null && result.size() != 0) {
410
            Object[] tmp = (Object[]) result.get(0);
411
            return ((Number) tmp[0]).intValue();
412
        }
413
 
93 ilm 414
        if (createIfNotExist && row.getString("CODE") != null && row.getString("CODE").trim().length() > 0 && row.getString("NOM") != null && row.getString("NOM").trim().length() > 0) {
18 ilm 415
            SQLRowValues vals = new SQLRowValues(row);
83 ilm 416
            BigDecimal taux = BigDecimal.ONE.add(new BigDecimal(TaxeCache.getCache().getTauxFromId(row.getForeignID("ID_TAXE")) / 100f));
417
            vals.put("PV_TTC", vals.getBigDecimal("PV_HT").multiply(taux));
156 ilm 418
            vals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
93 ilm 419
            int idArticle;
18 ilm 420
            try {
83 ilm 421
 
422
                // Liaison avec l'article fournisseur si il existe
423
                SQLSelect selMatchingCodeF = new SQLSelect();
424
                final SQLTable table = tableArt.getTable("ARTICLE_FOURNISSEUR");
425
                selMatchingCodeF.addSelect(table.getKey());
426
                selMatchingCodeF.addSelect(table.getField("ID_FOURNISSEUR"));
427
                selMatchingCodeF.addSelect(table.getField("CODE_BARRE"));
428
                Where wMatchingCodeF = new Where(table.getField("CODE"), "=", vals.getString("CODE"));
429
                wMatchingCodeF = wMatchingCodeF.and(new Where(table.getField("NOM"), "=", vals.getString("NOM")));
430
                selMatchingCodeF.setWhere(wMatchingCodeF);
431
 
93 ilm 432
                // FIXME utiliser une transaction bloquante sur la table
433
                List<SQLRow> l = SQLRowListRSH.execute(selMatchingCodeF, false, false);
83 ilm 434
                if (l.size() > 0) {
435
                    SQLRowValues rowVals = l.get(0).asRowValues();
436
                    vals.put("ID_FOURNISSEUR", rowVals.getObject("ID_FOURNISSEUR"));
437
                    vals.put("CODE_BARRE", rowVals.getObject("CODE_BARRE"));
90 ilm 438
                    vals.put("QTE_ACHAT", rowVals.getObject("QTE_ACHAT"));
93 ilm 439
                    SQLRow rowNew = vals.insert();
440
                    idArticle = rowNew.getID();
441
                    rowVals.put("ID_ARTICLE", idArticle);
83 ilm 442
                    rowVals.commit();
443
                } else {
93 ilm 444
                    SQLSelect selMatchingCodeArticle = new SQLSelect();
445
                    selMatchingCodeArticle.addSelect(tableArt.getKey());
446
                    Where wMatchingCode = new Where(tableArt.getField("CODE"), "=", vals.getString("CODE"));
447
                    wMatchingCode = wMatchingCode.and(new Where(tableArt.getField("NOM"), "=", vals.getString("NOM")));
448
                    selMatchingCodeArticle.setWhere(wMatchingCode);
449
                    List<SQLRow> matchingArticles = SQLRowListRSH.execute(selMatchingCodeArticle, false, false);
450
                    if (matchingArticles.size() > 0) {
451
                        idArticle = matchingArticles.get(0).getID();
452
                    } else {
453
                        SQLRow rowNew = vals.insert();
454
                        idArticle = rowNew.getID();
455
                    }
83 ilm 456
                }
93 ilm 457
                return idArticle;
18 ilm 458
            } catch (SQLException e) {
459
                e.printStackTrace();
460
            }
461
 
462
        }
463
        return -1;
464
 
465
    }
466
 
467
    /**
468
     * teste si un article ayant le meme nom et code existe
469
     *
470
     * @param row
471
     * @return true si au moins un article correspond
472
     */
473
    public static boolean isArticleForCNExist(SQLRowValues row) {
474
        return isArticleMatchExist(row, false);
475
    }
476
 
477
    /**
478
     * teste si un article ayant le meme nom, code et valeur metrique existe
479
     *
480
     * @param row
481
     * @return true si au moins un article correspond
482
     */
483
    public static boolean isArticleForCNMExist(SQLRowValues row) {
484
        return isArticleMatchExist(row, true);
485
    }
486
 
93 ilm 487
    @SuppressWarnings("rawtypes")
18 ilm 488
    private static boolean isArticleMatchExist(SQLRowValues row, boolean includeMetrique) {
489
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
490
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
491
        String req = getMatchRequest(row, includeMetrique);
492
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());
493
 
494
        return (result != null && result.size() != 0);
495
    }
496
 
497
    private static String getMatchRequest(SQLRowValues row, boolean includeMetrique) {
498
        // On cherche l'article qui lui correspond
499
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
500
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
501
        SQLSelect sel = new SQLSelect(eltArticle.getTable().getBase());
502
        sel.addSelect(eltArticle.getTable().getField("ID"));
503
 
90 ilm 504
        Where w = new Where(eltArticle.getTable().getField("CODE"), "=", row.getString("CODE").trim());
18 ilm 505
        if (includeMetrique) {
506
 
507
            float value1 = ((Number) row.getObject("VALEUR_METRIQUE_1")).floatValue();
508
            float value2 = ((Number) row.getObject("VALEUR_METRIQUE_2")).floatValue();
509
            float value3 = ((Number) row.getObject("VALEUR_METRIQUE_3")).floatValue();
510
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), "<=", new Float(value1 + 0.00001)));
511
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), ">=", new Float(value1 - 0.00001)));
512
 
513
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), "<=", new Float(value2 + 0.00001)));
514
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), ">=", new Float(value2 - 0.00001)));
515
 
516
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), "<=", new Float(value3 + 0.00001)));
517
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), ">=", new Float(value3 - 0.00001)));
518
 
519
        }
520
        sel.setWhere(w);
521
        return sel.asString();
522
    }
19 ilm 523
 
524
    public static boolean isReferenceEquals(SQLRowValues rowVals1, SQLRowValues rowVals2) {
525
        return (rowVals1.getObject("CODE").equals(rowVals2.getObject("CODE")) && rowVals1.getString("VALEUR_METRIQUE_1").equals(rowVals2.getString("VALEUR_METRIQUE_1"))
526
                && rowVals1.getString("VALEUR_METRIQUE_2").equals(rowVals2.getString("VALEUR_METRIQUE_2")) && rowVals1.getString("VALEUR_METRIQUE_3").equals(rowVals2.getString("VALEUR_METRIQUE_3")));
527
    }
57 ilm 528
 
156 ilm 529
    public void initStock(int id) {
530
        SQLRow row = getTable().getRow(id);
174 ilm 531
        Updater_1_5.initStock(row);
156 ilm 532
    }
533
 
57 ilm 534
    @Override
535
    protected String createCode() {
156 ilm 536
        return createCodeOfPackage() + ".ref";
57 ilm 537
    }
156 ilm 538
 
539
    @Override
540
    protected void _initComboRequest(ComboSQLRequest req) {
541
        super._initComboRequest(req);
542
        req.addToGraphToFetch("ID_DEPOT_STOCK");
543
        // req.addForeignToGraphToFetch("ID_DEPOT_STOCK", Arrays.asList("ID"));
544
    }
545
 
177 ilm 546
    static public void updateDateAchat(final SQLTable tableArticle, final SQLRow article) {
547
 
548
        assert article == null || article.getTable() == tableArticle;
549
        SQLTable tableTarifF = tableArticle.getTable("ARTICLE_TARIF_FOURNISSEUR");
550
        String up = "UPDATE " + tableArticle.getSQLName().quote() + " a SET " + tableArticle.getField("DERNIER_DATE_ACHAT").getQuotedName();
551
        up += " =(select MAX(" + tableTarifF.getField("DATE_PRIX").getQuotedName() + ")  ";
552
        up += " FROM " + tableTarifF.getSQLName().quote() + "  t" + " WHERE (t." + tableTarifF.getKey().getQuotedName() + " <> 1) ";
553
        up += " AND (t." + tableTarifF.getField("ARCHIVE").getQuotedName() + " = 0) ";
554
        up += "AND t." + tableTarifF.getField("ID_ARTICLE").getQuotedName() + " = " + (article == null ? "a." + tableArticle.getKey().getQuotedName() : article.getID()) + ")";
555
        if (article != null) {
556
            up += "WHERE " + tableArticle.getKey().getQuotedName() + " = " + article.getID();
557
        }
558
 
559
        tableArticle.getDBSystemRoot().getDataSource().execute(up);
560
    }
561
 
18 ilm 562
}