OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.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");
180 ilm 215
        l.add("ID_COMPTE_PCE");
216
        l.add("ID_COMPTE_PCE_ACHAT");
28 ilm 217
        l.add("ID_FAMILLE_ARTICLE");
19 ilm 218
        l.add("ID_FOURNISSEUR");
177 ilm 219
        l.add("POIDS");
93 ilm 220
        l.add("SKU");
156 ilm 221
 
222
        // if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
174 ilm 223
        l.add("GESTION_STOCK");
18 ilm 224
        l.add("ID_STOCK");
156 ilm 225
        // }
18 ilm 226
        String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
227
        Boolean b = Boolean.valueOf(val);
228
        if (b != null && b.booleanValue()) {
229
            l.add("SERVICE");
230
        }
180 ilm 231
 
18 ilm 232
        return l;
233
    }
234
 
83 ilm 235
    @Override
132 ilm 236
    public ListMap<String, String> getShowAs() {
237
        final ListMap<String, String> res = new ListMap<String, String>();
93 ilm 238
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
239
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
132 ilm 240
            res.add(null, "CODE_BARRE");
93 ilm 241
        }
156 ilm 242
        res.addAll(null, "CODE", "NOM", "ID_FAMILLE_ARTICLE");
83 ilm 243
        return res;
244
    }
245
 
18 ilm 246
    protected List<String> getComboFields() {
247
        final List<String> l = new ArrayList<String>();
248
        l.add("CODE");
73 ilm 249
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
250
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
251
            l.add("CODE_BARRE");
252
        }
253
 
18 ilm 254
        l.add("NOM");
177 ilm 255
        l.add("PA_HT");
256
        l.add("PV_HT");
257
        l.add("DERNIER_DATE_ACHAT");
18 ilm 258
        return l;
259
    }
260
 
261
    /*
262
     * (non-Javadoc)
263
     *
264
     * @see org.openconcerto.devis.SQLElement#getComponent()
265
     */
266
    public SQLComponent createComponent() {
267
 
268
        return new ReferenceArticleSQLComponent(this);
269
    }
270
 
271
    /**
272
     * Calcul le prix d'HA total par rapport aux metriques
273
     *
274
     * @param rowVals
275
     * @return le prix d'achat en centimes
276
     */
67 ilm 277
    public static BigDecimal getPrixHAFromDetails(SQLRowValues rowVals) {
18 ilm 278
        return getValuePiece(rowVals, PRIX_HA);
279
    }
280
 
281
    /**
282
     * Calcul le prix de VT total par rapport aux metriques
283
     *
284
     * @param rowVals
285
     * @return le prix de vente en centimes
286
     */
67 ilm 287
    public static BigDecimal getPrixVTFromDetails(SQLRowValues rowVals) {
18 ilm 288
        return getValuePiece(rowVals, PRIX_VT);
289
    }
290
 
291
    /**
292
     * Calcul le poids total par rapport aux metriques
293
     *
294
     * @param rowVals
295
     * @return le poids total arrondi à trois chiffres apres la virgule
296
     */
297
    public static float getPoidsFromDetails(SQLRowValues rowVals) {
298
 
299
        // Valeur
300
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
301
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
302
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");
303
 
304
        final float produit = valMetrique1 * valMetrique2 * valMetrique3;
305
        if (produit > 0.0F) {
306
            return Math.round(produit * 1000.0F) / 1000.0F;
307
        }
308
        if (rowVals.getObject("POIDS") != null) {
309
            float p = rowVals.getFloat("POIDS");
310
            return p;
311
        }
312
        return 0.0F;
313
    }
314
 
67 ilm 315
    private static BigDecimal getValuePiece(SQLRowValues rowVals, int value) {
18 ilm 316
        if (rowVals.getObject("ID_MODE_VENTE_ARTICLE") == null) {
317
            throw new IllegalArgumentException("La SQLRowValues ne contient pas ID_MODE_VENTE_ARTICLE");
318
        }
319
        int mode = rowVals.getInt("ID_MODE_VENTE_ARTICLE");
320
        if (mode == 1) {
321
            mode = A_LA_PIECE;
322
        }
323
        // prix HA
67 ilm 324
        BigDecimal metrique1HA = rowVals.getObject("PRIX_METRIQUE_HA_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_HA_1"));
18 ilm 325
 
326
        // Prix VT
67 ilm 327
        BigDecimal metrique1VT = rowVals.getObject("PRIX_METRIQUE_VT_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_VT_1"));
18 ilm 328
 
329
        // Valeur
330
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
331
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
332
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");
333
 
334
        // Mode de vente au metre carré
335
        if (mode == AU_METRE_CARRE) {
336
            float surface = valMetrique1 * valMetrique2;
337
            if (value == PRIX_HA) {
90 ilm 338
                return metrique1HA.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
18 ilm 339
            }
90 ilm 340
            return metrique1VT.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
18 ilm 341
        }
342
        // Mode de vente au metre, largeur
343
        if (mode == AU_METRE_LARGEUR) {
344
            if (value == PRIX_HA) {
90 ilm 345
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
18 ilm 346
            }
90 ilm 347
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
18 ilm 348
        }
349
        // Mode de vente au metre, longueur
350
        if (mode == AU_METRE_LONGUEUR) {
351
            if (value == PRIX_HA) {
90 ilm 352
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
18 ilm 353
            }
90 ilm 354
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
18 ilm 355
        }
356
        // Mode de vente au poids / m2
357
        if (mode == AU_POID_METRECARRE) {
358
            float surface = valMetrique1 * valMetrique2;
359
            float p = surface * valMetrique3;
360
            if (value == PRIX_HA) {
90 ilm 361
                return metrique1HA.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
18 ilm 362
            }
90 ilm 363
            return metrique1VT.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
18 ilm 364
        }
365
 
93 ilm 366
        // Mode de vente à la piece et autres
367
        if (value == PRIX_HA) {
368
            if (rowVals.getObject("PA_HT") != null) {
369
                return (BigDecimal) rowVals.getObject("PA_HT");
370
            }
371
            return BigDecimal.ZERO;
372
        }
373
        if (rowVals.getObject("PV_HT") != null) {
374
            return (BigDecimal) rowVals.getObject("PV_HT");
375
        }
376
        return BigDecimal.ZERO;
377
 
18 ilm 378
    }
379
 
380
    /**
381
     * retourne l'id d'un article ayant le meme Code, Nom et valeur Metrique, le cas échéant -1
382
     *
383
     * @param row
384
     * @param createIfNotExist
385
     * @return id de l'article correspondant
386
     */
387
    public static int getIdForCNM(SQLRowValues row, boolean createIfNotExist) {
388
        return getIdFor(row, true, createIfNotExist);
389
    }
390
 
391
    /**
392
     * retourne l'id d'un article ayant le meme Code, Nom le cas échéant -1
393
     *
394
     * @param row
395
     * @param createIfNotExist
396
     * @return id de l'article correspondant
397
     */
398
    public static int getIdForCN(SQLRowValues row, boolean createIfNotExist) {
399
 
400
        return getIdFor(row, false, createIfNotExist);
401
    }
402
 
93 ilm 403
    @SuppressWarnings("rawtypes")
18 ilm 404
    private static int getIdFor(SQLRowValues row, boolean includeMetrique, boolean createIfNotExist) {
405
 
406
        // On cherche l'article qui lui correspond
407
        SQLTable tableArt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
408
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(tableArt);
409
        String req = getMatchRequest(row, includeMetrique);
410
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());
411
 
412
        if (result != null && result.size() != 0) {
413
            Object[] tmp = (Object[]) result.get(0);
414
            return ((Number) tmp[0]).intValue();
415
        }
416
 
93 ilm 417
        if (createIfNotExist && row.getString("CODE") != null && row.getString("CODE").trim().length() > 0 && row.getString("NOM") != null && row.getString("NOM").trim().length() > 0) {
18 ilm 418
            SQLRowValues vals = new SQLRowValues(row);
83 ilm 419
            BigDecimal taux = BigDecimal.ONE.add(new BigDecimal(TaxeCache.getCache().getTauxFromId(row.getForeignID("ID_TAXE")) / 100f));
420
            vals.put("PV_TTC", vals.getBigDecimal("PV_HT").multiply(taux));
156 ilm 421
            vals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
93 ilm 422
            int idArticle;
18 ilm 423
            try {
83 ilm 424
 
425
                // Liaison avec l'article fournisseur si il existe
426
                SQLSelect selMatchingCodeF = new SQLSelect();
427
                final SQLTable table = tableArt.getTable("ARTICLE_FOURNISSEUR");
428
                selMatchingCodeF.addSelect(table.getKey());
429
                selMatchingCodeF.addSelect(table.getField("ID_FOURNISSEUR"));
430
                selMatchingCodeF.addSelect(table.getField("CODE_BARRE"));
431
                Where wMatchingCodeF = new Where(table.getField("CODE"), "=", vals.getString("CODE"));
432
                wMatchingCodeF = wMatchingCodeF.and(new Where(table.getField("NOM"), "=", vals.getString("NOM")));
433
                selMatchingCodeF.setWhere(wMatchingCodeF);
434
 
93 ilm 435
                // FIXME utiliser une transaction bloquante sur la table
436
                List<SQLRow> l = SQLRowListRSH.execute(selMatchingCodeF, false, false);
83 ilm 437
                if (l.size() > 0) {
438
                    SQLRowValues rowVals = l.get(0).asRowValues();
439
                    vals.put("ID_FOURNISSEUR", rowVals.getObject("ID_FOURNISSEUR"));
440
                    vals.put("CODE_BARRE", rowVals.getObject("CODE_BARRE"));
90 ilm 441
                    vals.put("QTE_ACHAT", rowVals.getObject("QTE_ACHAT"));
93 ilm 442
                    SQLRow rowNew = vals.insert();
443
                    idArticle = rowNew.getID();
444
                    rowVals.put("ID_ARTICLE", idArticle);
83 ilm 445
                    rowVals.commit();
446
                } else {
93 ilm 447
                    SQLSelect selMatchingCodeArticle = new SQLSelect();
448
                    selMatchingCodeArticle.addSelect(tableArt.getKey());
449
                    Where wMatchingCode = new Where(tableArt.getField("CODE"), "=", vals.getString("CODE"));
450
                    wMatchingCode = wMatchingCode.and(new Where(tableArt.getField("NOM"), "=", vals.getString("NOM")));
451
                    selMatchingCodeArticle.setWhere(wMatchingCode);
452
                    List<SQLRow> matchingArticles = SQLRowListRSH.execute(selMatchingCodeArticle, false, false);
453
                    if (matchingArticles.size() > 0) {
454
                        idArticle = matchingArticles.get(0).getID();
455
                    } else {
456
                        SQLRow rowNew = vals.insert();
457
                        idArticle = rowNew.getID();
458
                    }
83 ilm 459
                }
93 ilm 460
                return idArticle;
18 ilm 461
            } catch (SQLException e) {
462
                e.printStackTrace();
463
            }
464
 
465
        }
466
        return -1;
467
 
468
    }
469
 
470
    /**
471
     * teste si un article ayant le meme nom et code existe
472
     *
473
     * @param row
474
     * @return true si au moins un article correspond
475
     */
476
    public static boolean isArticleForCNExist(SQLRowValues row) {
477
        return isArticleMatchExist(row, false);
478
    }
479
 
480
    /**
481
     * teste si un article ayant le meme nom, code et valeur metrique existe
482
     *
483
     * @param row
484
     * @return true si au moins un article correspond
485
     */
486
    public static boolean isArticleForCNMExist(SQLRowValues row) {
487
        return isArticleMatchExist(row, true);
488
    }
489
 
93 ilm 490
    @SuppressWarnings("rawtypes")
18 ilm 491
    private static boolean isArticleMatchExist(SQLRowValues row, boolean includeMetrique) {
492
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
493
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
494
        String req = getMatchRequest(row, includeMetrique);
495
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());
496
 
497
        return (result != null && result.size() != 0);
498
    }
499
 
500
    private static String getMatchRequest(SQLRowValues row, boolean includeMetrique) {
501
        // On cherche l'article qui lui correspond
502
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
503
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
504
        SQLSelect sel = new SQLSelect(eltArticle.getTable().getBase());
505
        sel.addSelect(eltArticle.getTable().getField("ID"));
506
 
90 ilm 507
        Where w = new Where(eltArticle.getTable().getField("CODE"), "=", row.getString("CODE").trim());
18 ilm 508
        if (includeMetrique) {
509
 
510
            float value1 = ((Number) row.getObject("VALEUR_METRIQUE_1")).floatValue();
511
            float value2 = ((Number) row.getObject("VALEUR_METRIQUE_2")).floatValue();
512
            float value3 = ((Number) row.getObject("VALEUR_METRIQUE_3")).floatValue();
513
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), "<=", new Float(value1 + 0.00001)));
514
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), ">=", new Float(value1 - 0.00001)));
515
 
516
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), "<=", new Float(value2 + 0.00001)));
517
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), ">=", new Float(value2 - 0.00001)));
518
 
519
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), "<=", new Float(value3 + 0.00001)));
520
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), ">=", new Float(value3 - 0.00001)));
521
 
522
        }
523
        sel.setWhere(w);
524
        return sel.asString();
525
    }
19 ilm 526
 
527
    public static boolean isReferenceEquals(SQLRowValues rowVals1, SQLRowValues rowVals2) {
528
        return (rowVals1.getObject("CODE").equals(rowVals2.getObject("CODE")) && rowVals1.getString("VALEUR_METRIQUE_1").equals(rowVals2.getString("VALEUR_METRIQUE_1"))
529
                && rowVals1.getString("VALEUR_METRIQUE_2").equals(rowVals2.getString("VALEUR_METRIQUE_2")) && rowVals1.getString("VALEUR_METRIQUE_3").equals(rowVals2.getString("VALEUR_METRIQUE_3")));
530
    }
57 ilm 531
 
156 ilm 532
    public void initStock(int id) {
533
        SQLRow row = getTable().getRow(id);
174 ilm 534
        Updater_1_5.initStock(row);
156 ilm 535
    }
536
 
57 ilm 537
    @Override
538
    protected String createCode() {
156 ilm 539
        return createCodeOfPackage() + ".ref";
57 ilm 540
    }
156 ilm 541
 
542
    @Override
543
    protected void _initComboRequest(ComboSQLRequest req) {
544
        super._initComboRequest(req);
545
        req.addToGraphToFetch("ID_DEPOT_STOCK");
546
        // req.addForeignToGraphToFetch("ID_DEPOT_STOCK", Arrays.asList("ID"));
547
    }
548
 
177 ilm 549
    static public void updateDateAchat(final SQLTable tableArticle, final SQLRow article) {
550
 
551
        assert article == null || article.getTable() == tableArticle;
552
        SQLTable tableTarifF = tableArticle.getTable("ARTICLE_TARIF_FOURNISSEUR");
553
        String up = "UPDATE " + tableArticle.getSQLName().quote() + " a SET " + tableArticle.getField("DERNIER_DATE_ACHAT").getQuotedName();
554
        up += " =(select MAX(" + tableTarifF.getField("DATE_PRIX").getQuotedName() + ")  ";
555
        up += " FROM " + tableTarifF.getSQLName().quote() + "  t" + " WHERE (t." + tableTarifF.getKey().getQuotedName() + " <> 1) ";
556
        up += " AND (t." + tableTarifF.getField("ARCHIVE").getQuotedName() + " = 0) ";
557
        up += "AND t." + tableTarifF.getField("ID_ARTICLE").getQuotedName() + " = " + (article == null ? "a." + tableArticle.getKey().getQuotedName() : article.getID()) + ")";
558
        if (article != null) {
559
            up += "WHERE " + tableArticle.getKey().getQuotedName() + " = " + article.getID();
560
        }
561
 
562
        tableArticle.getDBSystemRoot().getDataSource().execute(up);
563
    }
564
 
18 ilm 565
}