OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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