OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | 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
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
18 ilm 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;
182 ilm 19
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
20
import org.openconcerto.erp.core.common.ui.NumberCellRenderer;
142 ilm 21
import org.openconcerto.erp.core.edm.AttachmentAction;
83 ilm 22
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
156 ilm 23
import org.openconcerto.erp.core.reports.history.ui.HistoriqueArticleFrame;
182 ilm 24
import org.openconcerto.erp.core.sales.product.action.InitializeStockPanel;
94 ilm 25
import org.openconcerto.erp.core.sales.product.action.InventairePanel;
18 ilm 26
import org.openconcerto.erp.core.sales.product.component.ReferenceArticleSQLComponent;
182 ilm 27
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
28
import org.openconcerto.erp.core.supplychain.stock.action.ListeDesMouvementsStockAction;
29
import org.openconcerto.erp.core.supplychain.stock.element.ComposedItemStockUpdater;
156 ilm 30
import org.openconcerto.erp.core.supplychain.stock.element.DepotStockSQLElement;
182 ilm 31
import org.openconcerto.erp.core.supplychain.stock.element.StockItem;
32
import org.openconcerto.erp.core.supplychain.stock.element.StockItem.TypeStockMouvement;
83 ilm 33
import org.openconcerto.erp.generationDoc.gestcomm.FicheArticleXmlSheet;
34
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
18 ilm 35
import org.openconcerto.erp.preferences.DefaultNXProps;
73 ilm 36
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
18 ilm 37
import org.openconcerto.sql.Configuration;
38
import org.openconcerto.sql.element.SQLComponent;
39
import org.openconcerto.sql.element.SQLElement;
182 ilm 40
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
41
import org.openconcerto.sql.model.DBRoot;
42
import org.openconcerto.sql.model.DBSystemRoot;
94 ilm 43
import org.openconcerto.sql.model.FieldPath;
182 ilm 44
import org.openconcerto.sql.model.SQLDataSource;
18 ilm 45
import org.openconcerto.sql.model.SQLRow;
94 ilm 46
import org.openconcerto.sql.model.SQLRowAccessor;
83 ilm 47
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 48
import org.openconcerto.sql.model.SQLRowValues;
49
import org.openconcerto.sql.model.SQLSelect;
50
import org.openconcerto.sql.model.SQLTable;
51
import org.openconcerto.sql.model.Where;
94 ilm 52
import org.openconcerto.sql.model.graph.Path;
73 ilm 53
import org.openconcerto.sql.preferences.SQLPreferences;
156 ilm 54
import org.openconcerto.sql.request.ComboSQLRequest;
182 ilm 55
import org.openconcerto.sql.request.ComboSQLRequest.KeepMode;
56
import org.openconcerto.sql.request.ListSQLRequest;
57
import org.openconcerto.sql.users.rights.UserRightsManager;
58
import org.openconcerto.sql.utils.SQLUtils;
90 ilm 59
import org.openconcerto.sql.view.EditFrame;
60
import org.openconcerto.sql.view.EditPanel.EditMode;
182 ilm 61
import org.openconcerto.sql.view.ListeAddPanel;
94 ilm 62
import org.openconcerto.sql.view.list.BaseSQLTableModelColumn;
90 ilm 63
import org.openconcerto.sql.view.list.IListe;
64
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
182 ilm 65
import org.openconcerto.sql.view.list.RowAction;
90 ilm 66
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
83 ilm 67
import org.openconcerto.sql.view.list.SQLTableModelColumn;
142 ilm 68
import org.openconcerto.sql.view.list.SQLTableModelSource;
182 ilm 69
import org.openconcerto.sql.view.list.SQLTableModelSourceOnline;
70
import org.openconcerto.sql.view.list.action.ListEvent;
71
import org.openconcerto.ui.DefaultGridBagConstraints;
90 ilm 72
import org.openconcerto.ui.FrameUtil;
156 ilm 73
import org.openconcerto.ui.PanelFrame;
94 ilm 74
import org.openconcerto.utils.CollectionUtils;
90 ilm 75
import org.openconcerto.utils.DecimalUtils;
182 ilm 76
import org.openconcerto.utils.ExceptionHandler;
90 ilm 77
import org.openconcerto.utils.ListMap;
182 ilm 78
import org.openconcerto.utils.Tuple2;
18 ilm 79
 
182 ilm 80
import java.awt.GridBagConstraints;
81
import java.awt.GridBagLayout;
90 ilm 82
import java.awt.event.ActionEvent;
67 ilm 83
import java.math.BigDecimal;
182 ilm 84
import java.math.RoundingMode;
18 ilm 85
import java.sql.SQLException;
182 ilm 86
import java.text.SimpleDateFormat;
18 ilm 87
import java.util.ArrayList;
94 ilm 88
import java.util.Collection;
182 ilm 89
import java.util.Date;
90
import java.util.HashSet;
18 ilm 91
import java.util.List;
94 ilm 92
import java.util.Set;
18 ilm 93
 
90 ilm 94
import javax.swing.AbstractAction;
182 ilm 95
import javax.swing.JFrame;
96
import javax.swing.JOptionPane;
97
import javax.swing.JPanel;
98
import javax.swing.JTabbedPane;
90 ilm 99
 
182 ilm 100
import org.apache.commons.dbutils.ResultSetHandler;
18 ilm 101
import org.apache.commons.dbutils.handlers.ArrayListHandler;
102
 
103
public class ReferenceArticleSQLElement extends ComptaSQLConfElement {
104
    public static final int AU_METRE_LONGUEUR = 2;
105
    public static final int AU_METRE_CARRE = 3;
106
    public static final int AU_POID_METRECARRE = 4;
107
    public static final int A_LA_PIECE = 5;
108
    public static final int AU_METRE_LARGEUR = 6;
109
    private static final int PRIX_HA = 1;
110
    private static final int PRIX_VT = 2;
156 ilm 111
    protected PredicateRowAction stock;
18 ilm 112
 
94 ilm 113
    public static final String[] CONDITIONS = new String[] { "CFR", "CIF", "CPT", "DAT", "DDP", "DDU", "EXW", "FCA", "FOB" };
114
 
18 ilm 115
    public ReferenceArticleSQLElement() {
116
        super("ARTICLE", "un article", "articles");
182 ilm 117
        NumerotationAutoSQLElement.addClass(this.getClass(), "ARTICLE");
83 ilm 118
 
182 ilm 119
        getRowActions().addAll(new MouseSheetXmlListeListener(this, FicheArticleXmlSheet.class).getRowActions());
94 ilm 120
        this.stock = new PredicateRowAction(new AbstractAction("Mettre à jour les stocks") {
121
 
122
            @Override
123
            public void actionPerformed(ActionEvent e) {
182 ilm 124
                if (UserRightsManager.getCurrentUserRights().canAdd(getTable().getDBRoot().getTable("STOCK"))) {
94 ilm 125
 
182 ilm 126
                    try {
127
                        final List<SQLRowAccessor> selectedRows = IListe.get(e).getSelectedRowAccessors();
128
                        List<SQLRowAccessor> l = new ArrayList<SQLRowAccessor>();
129
                        for (SQLRowAccessor sqlRowValues : selectedRows) {
130
 
131
                            final SQLRowAccessor stock = sqlRowValues.asRow().getNonEmptyForeign("ID_STOCK");
132
                            if (stock != null) {
133
                                l.add(stock);
134
                            } else {
135
                                SQLRowValues rowValsArt = sqlRowValues.createEmptyUpdateRow();
136
                                SQLRowValues insert = rowValsArt.putRowValues("ID_STOCK");
137
                                insert.put("ID_ARTICLE", sqlRowValues.getID());
138
                                insert.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
139
 
140
                                l.add(rowValsArt.commit().getForeign("ID_STOCK"));
141
                            }
142
                        }
143
 
144
                        PanelFrame p = new PanelFrame(new InventairePanel(IListe.get(e), l), "Mise à jour des stocks");
145
                        FrameUtil.show(p);
146
                    } catch (SQLException e1) {
147
                        ExceptionHandler.handle("Erreur lors de la mise à jour du stock", e1);
148
                    }
149
                } else {
150
                    JOptionPane.showMessageDialog(null, "Vous n'avez les droits suffisants pour modifier manuellement les stocks!");
156 ilm 151
                }
152
 
94 ilm 153
            }
154
        }, true, false);
155
        stock.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
156
        getRowActions().add(stock);
157
 
182 ilm 158
        final SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
159
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false) && UserRightsManager.getCurrentUserRights().canAdd(getTable().getDBRoot().getTable("STOCK"))) {
160
 
161
            RowAction actionConvVirtuel = new PredicateRowAction(new AbstractAction("Initialiser les stocks") {
162
 
163
                @Override
164
                public void actionPerformed(ActionEvent e) {
165
 
166
                    PanelFrame frame = new PanelFrame(new InitializeStockPanel(ReferenceArticleSQLElement.this, IListe.get(e).getSelectedRowAccessors()), "Initialisation du stock");
167
                    FrameUtil.showPacked(frame);
168
 
169
                }
170
            }, true, false).setPredicate(ListEvent.getNonEmptySelectionPredicate());
171
            getRowActions().add(actionConvVirtuel);
172
        }
173
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false)) {
174
 
175
            RowAction actionConvVirtuel = new RowAction(new AbstractAction("Convertir en article virtuel") {
176
 
177
                @Override
178
                public void actionPerformed(ActionEvent e) {
179
 
180
                    final SQLRowAccessor selectedRow = IListe.get(e).getSelectedRowAccessor();
181
                    try {
182
                        selectedRow.createEmptyUpdateRow().put("VIRTUEL", Boolean.TRUE).commit();
183
                    } catch (SQLException e1) {
184
                        ExceptionHandler.handle("Erreur lors de la conversion de l'article en virtuel", e1);
185
                    }
186
 
187
                }
188
            }, true, false) {
189
                @Override
190
                public boolean enabledFor(ListEvent evt) {
191
                    final List<? extends SQLRowAccessor> selection = evt.getSelectedRowAccessors();
192
                    if (selection.size() == 1) {
193
                        return !selection.get(0).getBoolean("VIRTUEL") && selection.get(0).isForeignEmpty("ID_ARTICLE_VIRTUEL_PERE");
194
                    }
195
                    return false;
196
                }
197
            };
198
            getRowActions().add(actionConvVirtuel);
199
 
200
            RowAction actionCreateDecl = new RowAction(new AbstractAction("Créer une déclinaison") {
201
 
202
                @Override
203
                public void actionPerformed(ActionEvent e) {
204
                    SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
205
                    ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(IListe.get(e).getSelectedRowAccessor().asRow());
206
                    for (SQLRow child : children.allValues()) {
207
                        if (!child.getTable().getName().equals("STOCK")) {
208
                            Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
209
                        }
210
                    }
211
                    rowVals.put("ID_ARTICLE_VIRTUEL_PERE", IListe.get(e).getSelectedId());
212
                    rowVals.put("VIRTUEL", Boolean.FALSE);
213
                    rowVals.putEmptyLink("ID_STOCK");
214
 
215
                    EditFrame f = new EditFrame(createComponent(), EditMode.CREATION);
216
                    f.getSQLComponent().select(rowVals);
217
                    FrameUtil.show(f);
218
 
219
                }
220
            }, true, false) {
221
                @Override
222
                public boolean enabledFor(ListEvent evt) {
223
                    final List<? extends SQLRowAccessor> selection = evt.getSelectedRowAccessors();
224
                    if (selection.size() == 1) {
225
                        return selection.get(0).getBoolean("VIRTUEL");
226
                    }
227
                    return false;
228
                }
229
            };
230
            getRowActions().add(actionCreateDecl);
231
 
232
            RowAction actionCreateDecls = new RowAction(new AbstractAction("Créer des déclinaisons") {
233
 
234
                @Override
235
                public void actionPerformed(ActionEvent e) {
236
                    SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
237
                    final SQLRow selectedRow = IListe.get(e).getSelectedRowAccessor().asRow();
238
                    ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(selectedRow);
239
                    for (SQLRow child : children.allValues()) {
240
                        if (!child.getTable().getName().equals("STOCK")) {
241
                            Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
242
                        }
243
                    }
244
                    rowVals.put("ID_ARTICLE_VIRTUEL_PERE", IListe.get(e).getSelectedId());
245
                    rowVals.put("VIRTUEL", Boolean.FALSE);
246
                    rowVals.putEmptyLink("ID_STOCK");
247
 
248
                    NouvellesDeclinaisonsFrame f = new NouvellesDeclinaisonsFrame(ReferenceArticleSQLElement.this, selectedRow);
249
                    f.pack();
250
                    f.setLocationRelativeTo(null);
251
                    FrameUtil.show(f);
252
 
253
                }
254
            }, false, true) {
255
                @Override
256
                public boolean enabledFor(ListEvent evt) {
257
                    final List<? extends SQLRowAccessor> selection = evt.getSelectedRowAccessors();
258
                    if (selection.size() == 1) {
259
                        return selection.get(0).getBoolean("VIRTUEL");
260
                    }
261
                    return false;
262
                }
263
            };
264
            getRowActions().add(actionCreateDecls);
265
 
266
        }
156 ilm 267
        PredicateRowAction history = new PredicateRowAction(new AbstractAction("Historique") {
268
 
269
            @Override
270
            public void actionPerformed(ActionEvent e) {
271
                HistoriqueArticleFrame frame = new HistoriqueArticleFrame(ReferenceArticleSQLElement.this);
272
                frame.selectId(IListe.get(e).getSelectedId());
273
                frame.setVisible(true);
274
            }
275
        }, false, true);
276
        history.setPredicate(IListeEvent.getSingleSelectionPredicate());
277
        getRowActions().add(history);
278
 
182 ilm 279
        PredicateRowAction mvtStock = new PredicateRowAction(new AbstractAction("Consulter les mouvements de stocks") {
280
 
281
            @Override
282
            public void actionPerformed(ActionEvent e) {
283
                JFrame frame = new ListeDesMouvementsStockAction(ComptaPropsConfiguration.getInstanceCompta(), IListe.get(e).getSelectedRowAccessor()).getFrame();
284
                frame.setVisible(true);
285
            }
286
        }, false, true);
287
        mvtStock.setPredicate(IListeEvent.getSingleSelectionPredicate());
288
        getRowActions().add(mvtStock);
289
 
290
        if (ComptaPropsConfiguration.getInstanceCompta().isExperimental()) {
291
            PredicateRowAction batches = new PredicateRowAction(new AbstractAction("Lots et numéros de série") {
292
                @Override
293
                public void actionPerformed(ActionEvent e) {
294
                    ListeDesLotsAction action = new ListeDesLotsAction(ReferenceArticleSQLElement.this.getDirectory(), IListe.get(e).getSelectedRowAccessor());
295
                    action.actionPerformed(e);
296
                }
297
            }, false, true);
298
            batches.setPredicate(IListeEvent.getSingleSelectionPredicate());
299
            getRowActions().add(batches);
300
        }
90 ilm 301
        PredicateRowAction clone = new PredicateRowAction(new AbstractAction("Dupliquer") {
83 ilm 302
 
90 ilm 303
            @Override
304
            public void actionPerformed(ActionEvent e) {
305
 
306
                SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(IListe.get(e).getSelectedId());
182 ilm 307
                ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(IListe.get(e).getSelectedRowAccessor().asRow());
90 ilm 308
                for (SQLRow child : children.allValues()) {
309
                    Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
310
                }
311
                EditFrame f = new EditFrame(createComponent(), EditMode.CREATION);
312
                f.getSQLComponent().select(rowVals);
313
                FrameUtil.show(f);
314
 
315
            }
316
        }, true, false);
317
        clone.setPredicate(IListeEvent.getSingleSelectionPredicate());
318
        getRowActions().add(clone);
142 ilm 319
 
320
        PredicateRowAction actionAttachment = new PredicateRowAction(new AttachmentAction().getAction(), true);
321
        actionAttachment.setPredicate(IListeEvent.getSingleSelectionPredicate());
156 ilm 322
 
142 ilm 323
        getRowActions().add(actionAttachment);
182 ilm 324
 
325
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false)) {
326
 
327
            PredicateRowAction actionADeclinaison = new PredicateRowAction(new AbstractAction("Gérer les déclinaisons") {
328
 
329
                @Override
330
                public void actionPerformed(ActionEvent e) {
331
                    List<SQLElement> declElts = new ArrayList<>();
332
                    for (SQLTable table : getTable().getDBRoot().getTables()) {
333
                        if (table.getName().startsWith("ARTICLE_DECLINAISON_")) {
334
                            declElts.add(getDirectory().getElement(table));
335
                        }
336
                    }
337
 
338
                    JTabbedPane tabs = new JTabbedPane();
339
                    for (SQLElement elt : declElts) {
340
                        final IListe liste = new IListe(elt.createTableSource());
341
                        ListeAddPanel panel = new ListeAddPanel(elt, liste);
342
                        tabs.add(elt.getPluralName(), panel);
343
                    }
344
 
345
                    JPanel panel = new JPanel(new GridBagLayout());
346
                    GridBagConstraints c = new DefaultGridBagConstraints();
347
                    c.fill = GridBagConstraints.BOTH;
348
                    c.weightx = 1;
349
                    c.weighty = 1;
350
                    panel.add(tabs, c);
351
                    PanelFrame frame = new PanelFrame(panel, "Liste des déclinaisons");
352
                    FrameUtil.showPacked(frame);
353
                }
354
            }, true);
355
            actionADeclinaison.setPredicate(IListeEvent.createTotalRowCountPredicate(0, Integer.MAX_VALUE));
356
            getRowActions().add(actionADeclinaison);
357
        }
18 ilm 358
    }
359
 
83 ilm 360
    @Override
182 ilm 361
    protected SQLTableModelSourceOnline instantiateTableSourceOnline(ListSQLRequest req) {
362
        return new SQLTableModelSourceOnline(req, this, KeepMode.ROW);
363
    }
364
 
365
    @Override
142 ilm 366
    protected synchronized void _initTableSource(final SQLTableModelSource source) {
367
        super._initTableSource(source);
182 ilm 368
        source.getReq().addToGraphToFetch("ID_ARTICLE_VIRTUEL_PERE", "VIRTUEL", "ID_DEPOT_STOCK");
93 ilm 369
        source.init();
370
        final SQLTableModelColumn pvHA1Col = source.getColumn(getTable().getField("PRIX_METRIQUE_HA_1"));
371
        if (pvHA1Col != null) {
372
            pvHA1Col.setRenderer(CURRENCY_RENDERER);
373
        }
83 ilm 374
 
93 ilm 375
        final SQLTableModelColumn pvHT1Col = source.getColumn(getTable().getField("PRIX_METRIQUE_VT_1"));
376
        if (pvHT1Col != null) {
377
            pvHT1Col.setRenderer(CURRENCY_RENDERER);
378
        }
379
 
83 ilm 380
        final SQLTableModelColumn pvHTCol = source.getColumn(getTable().getField("PV_HT"));
381
        if (pvHTCol != null) {
382
            pvHTCol.setRenderer(CURRENCY_RENDERER);
383
        }
384
        final SQLTableModelColumn pvTTCCol = source.getColumn(getTable().getField("PV_TTC"));
385
        if (pvTTCCol != null) {
386
            pvTTCCol.setRenderer(CURRENCY_RENDERER);
387
        }
388
        final SQLTableModelColumn paHTCol = source.getColumn(getTable().getField("PA_HT"));
389
        if (paHTCol != null) {
390
            paHTCol.setRenderer(CURRENCY_RENDERER);
391
        }
392
 
182 ilm 393
        final SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
394
 
395
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
396
            final BaseSQLTableModelColumn colStockGlobal = new BaseSQLTableModelColumn("Stock Global", BigDecimal.class) {
397
 
398
                @Override
399
                protected Object show_(SQLRowAccessor r) {
400
 
401
                    BigDecimal totalQte = BigDecimal.ZERO;
402
 
403
                    Collection<? extends SQLRowAccessor> stockElt = r.getReferentRows(getTable().getTable("STOCK").getField("ID_ARTICLE"));
404
                    for (SQLRowAccessor rowElt : stockElt) {
405
                        BigDecimal qteCmd = new BigDecimal(rowElt.getFloat("QTE_REEL"));
406
                        totalQte = totalQte.add(qteCmd);
407
                    }
408
                    return totalQte;
409
                }
410
 
411
                @Override
412
                public Set<FieldPath> getPaths() {
413
                    Path p2 = new Path(getTable()).add(getTable().getTable("STOCK").getField("ID_ARTICLE"));
414
 
415
                    return CollectionUtils.createSet(new FieldPath(p2, "QTE_REEL"));
416
                }
417
            };
418
            colStockGlobal.setRenderer(new NumberCellRenderer());
419
            source.getColumns().add(colStockGlobal);
420
        }
421
 
94 ilm 422
        if (getTable().getDBRoot().contains("ARTICLE_ELEMENT") && !getTable().getDBRoot().contains("TARIF_AGENCE")) {
423
            source.getColumns().add(new BaseSQLTableModelColumn("Type", String.class) {
424
 
425
                @Override
426
                protected Object show_(SQLRowAccessor r) {
427
 
428
                    Collection<? extends SQLRowAccessor> c = r.getReferentRows(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
429
                    if (c.size() == 0) {
430
                        // "Article simple"
431
                        return "Article simple";
432
                    } else {
433
                        // "Kit
434
                        return "Nomenclature";
435
                    }
436
                }
437
 
438
                @Override
439
                public Set<FieldPath> getPaths() {
440
                    Path p = new Path(getTable());
441
                    p = p.add(getTable().getTable("ARTICLE_ELEMENT").getField("ID_ARTICLE_PARENT"));
442
                    return CollectionUtils.createSet(new FieldPath(p, "QTE"));
443
                }
444
            });
445
        }
83 ilm 446
    }
447
 
182 ilm 448
    @Override
449
    public Set<String> getReadOnlyFields() {
450
        Set<String> s = new HashSet<>();
451
        s.add("ID_ARTICLE_VIRTUEL_PERE");
452
        return s;
453
    }
454
 
18 ilm 455
    protected List<String> getListFields() {
456
        final List<String> l = new ArrayList<String>();
457
 
458
        l.add("CODE");
93 ilm 459
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
460
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
461
            l.add("CODE_BARRE");
462
        }
18 ilm 463
        l.add("NOM");
464
        String articleAdvanced = DefaultNXProps.getInstance().getStringProperty("ArticleModeVenteAvance");
465
        Boolean bArticleAdvanced = Boolean.valueOf(articleAdvanced);
41 ilm 466
 
467
        if (bArticleAdvanced) {
18 ilm 468
            l.add("POIDS");
469
            l.add("PRIX_METRIQUE_HA_1");
470
            l.add("PRIX_METRIQUE_VT_1");
41 ilm 471
        }
18 ilm 472
        l.add("PA_HT");
473
        l.add("PV_HT");
182 ilm 474
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_TAXE, false)) {
18 ilm 475
            l.add("ID_TAXE");
182 ilm 476
        }
18 ilm 477
        l.add("PV_TTC");
182 ilm 478
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_COMPTE, false)) {
479
            l.add("ID_COMPTE_PCE");
480
            l.add("ID_COMPTE_PCE_ACHAT");
481
        }
482
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_FAMILLE, false)) {
483
            l.add("ID_FAMILLE_ARTICLE");
484
        }
485
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_LIST_FOURNISSEUR, false)) {
486
            l.add("ID_FOURNISSEUR");
487
        }
177 ilm 488
        l.add("POIDS");
93 ilm 489
        l.add("SKU");
156 ilm 490
 
491
        // if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_MULTI_DEPOT, false)) {
174 ilm 492
        l.add("GESTION_STOCK");
18 ilm 493
        l.add("ID_STOCK");
156 ilm 494
        // }
18 ilm 495
        String val = DefaultNXProps.getInstance().getStringProperty("ArticleService");
496
        Boolean b = Boolean.valueOf(val);
497
        if (b != null && b.booleanValue()) {
498
            l.add("SERVICE");
499
        }
180 ilm 500
 
18 ilm 501
        return l;
502
    }
503
 
83 ilm 504
    @Override
132 ilm 505
    public ListMap<String, String> getShowAs() {
506
        final ListMap<String, String> res = new ListMap<String, String>();
93 ilm 507
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
508
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
132 ilm 509
            res.add(null, "CODE_BARRE");
93 ilm 510
        }
182 ilm 511
        List<String> fieldDecl = new ArrayList<>();
512
 
513
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.ACTIVER_DECLINAISON, false)) {
514
 
515
            for (String fieldName : getTable().getFieldsName()) {
516
                if (fieldName.startsWith("ID_ARTICLE_DECLINAISON_")) {
517
                    fieldDecl.add(fieldName);
518
                }
519
            }
520
        }
521
        res.addAll(null, "CODE", "NOM", "ID_FAMILLE_ARTICLE", "ID_FOURNISSEUR");
522
        res.addAll(null, fieldDecl);
83 ilm 523
        return res;
524
    }
525
 
18 ilm 526
    protected List<String> getComboFields() {
527
        final List<String> l = new ArrayList<String>();
528
        l.add("CODE");
73 ilm 529
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
530
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.SHOW_PRODUCT_BAR_CODE, false)) {
531
            l.add("CODE_BARRE");
532
        }
533
 
18 ilm 534
        l.add("NOM");
182 ilm 535
        List<String> fieldDecl = new ArrayList<>();
536
        for (String fieldName : getTable().getFieldsName()) {
537
            if (fieldName.startsWith("ID_ARTICLE_DECLINAISON_")) {
538
                fieldDecl.add(fieldName);
539
            }
540
        }
541
        l.addAll(fieldDecl);
177 ilm 542
        l.add("PA_HT");
543
        l.add("PV_HT");
544
        l.add("DERNIER_DATE_ACHAT");
18 ilm 545
        return l;
546
    }
547
 
548
    /*
549
     * (non-Javadoc)
550
     *
551
     * @see org.openconcerto.devis.SQLElement#getComponent()
552
     */
553
    public SQLComponent createComponent() {
554
 
555
        return new ReferenceArticleSQLComponent(this);
556
    }
557
 
558
    /**
559
     * Calcul le prix d'HA total par rapport aux metriques
560
     *
561
     * @param rowVals
562
     * @return le prix d'achat en centimes
563
     */
67 ilm 564
    public static BigDecimal getPrixHAFromDetails(SQLRowValues rowVals) {
18 ilm 565
        return getValuePiece(rowVals, PRIX_HA);
566
    }
567
 
568
    /**
569
     * Calcul le prix de VT total par rapport aux metriques
570
     *
571
     * @param rowVals
572
     * @return le prix de vente en centimes
573
     */
67 ilm 574
    public static BigDecimal getPrixVTFromDetails(SQLRowValues rowVals) {
18 ilm 575
        return getValuePiece(rowVals, PRIX_VT);
576
    }
577
 
578
    /**
579
     * Calcul le poids total par rapport aux metriques
580
     *
581
     * @param rowVals
582
     * @return le poids total arrondi à trois chiffres apres la virgule
583
     */
584
    public static float getPoidsFromDetails(SQLRowValues rowVals) {
585
 
586
        // Valeur
587
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
588
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
589
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");
590
 
591
        final float produit = valMetrique1 * valMetrique2 * valMetrique3;
592
        if (produit > 0.0F) {
593
            return Math.round(produit * 1000.0F) / 1000.0F;
594
        }
595
        if (rowVals.getObject("POIDS") != null) {
596
            float p = rowVals.getFloat("POIDS");
597
            return p;
598
        }
599
        return 0.0F;
600
    }
601
 
67 ilm 602
    private static BigDecimal getValuePiece(SQLRowValues rowVals, int value) {
18 ilm 603
        if (rowVals.getObject("ID_MODE_VENTE_ARTICLE") == null) {
604
            throw new IllegalArgumentException("La SQLRowValues ne contient pas ID_MODE_VENTE_ARTICLE");
605
        }
606
        int mode = rowVals.getInt("ID_MODE_VENTE_ARTICLE");
607
        if (mode == 1) {
608
            mode = A_LA_PIECE;
609
        }
610
        // prix HA
67 ilm 611
        BigDecimal metrique1HA = rowVals.getObject("PRIX_METRIQUE_HA_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_HA_1"));
18 ilm 612
 
613
        // Prix VT
67 ilm 614
        BigDecimal metrique1VT = rowVals.getObject("PRIX_METRIQUE_VT_1") == null ? BigDecimal.ZERO : ((BigDecimal) rowVals.getObject("PRIX_METRIQUE_VT_1"));
18 ilm 615
 
616
        // Valeur
617
        float valMetrique1 = (rowVals.getObject("VALEUR_METRIQUE_1") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_1");
618
        float valMetrique2 = (rowVals.getObject("VALEUR_METRIQUE_2") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_2");
619
        float valMetrique3 = (rowVals.getObject("VALEUR_METRIQUE_3") == null) ? 0.0F : rowVals.getFloat("VALEUR_METRIQUE_3");
620
 
621
        // Mode de vente au metre carré
622
        if (mode == AU_METRE_CARRE) {
623
            float surface = valMetrique1 * valMetrique2;
624
            if (value == PRIX_HA) {
90 ilm 625
                return metrique1HA.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
18 ilm 626
            }
90 ilm 627
            return metrique1VT.multiply(BigDecimal.valueOf(surface), DecimalUtils.HIGH_PRECISION);
18 ilm 628
        }
629
        // Mode de vente au metre, largeur
630
        if (mode == AU_METRE_LARGEUR) {
631
            if (value == PRIX_HA) {
90 ilm 632
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
18 ilm 633
            }
90 ilm 634
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique2), DecimalUtils.HIGH_PRECISION);
18 ilm 635
        }
636
        // Mode de vente au metre, longueur
637
        if (mode == AU_METRE_LONGUEUR) {
638
            if (value == PRIX_HA) {
90 ilm 639
                return metrique1HA.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
18 ilm 640
            }
90 ilm 641
            return metrique1VT.multiply(BigDecimal.valueOf(valMetrique1), DecimalUtils.HIGH_PRECISION);
18 ilm 642
        }
643
        // Mode de vente au poids / m2
644
        if (mode == AU_POID_METRECARRE) {
645
            float surface = valMetrique1 * valMetrique2;
646
            float p = surface * valMetrique3;
647
            if (value == PRIX_HA) {
90 ilm 648
                return metrique1HA.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
18 ilm 649
            }
90 ilm 650
            return metrique1VT.multiply(BigDecimal.valueOf(p), DecimalUtils.HIGH_PRECISION);
18 ilm 651
        }
652
 
93 ilm 653
        // Mode de vente à la piece et autres
654
        if (value == PRIX_HA) {
655
            if (rowVals.getObject("PA_HT") != null) {
656
                return (BigDecimal) rowVals.getObject("PA_HT");
657
            }
658
            return BigDecimal.ZERO;
659
        }
660
        if (rowVals.getObject("PV_HT") != null) {
661
            return (BigDecimal) rowVals.getObject("PV_HT");
662
        }
663
        return BigDecimal.ZERO;
664
 
18 ilm 665
    }
666
 
667
    /**
668
     * retourne l'id d'un article ayant le meme Code, Nom et valeur Metrique, le cas échéant -1
669
     *
670
     * @param row
671
     * @param createIfNotExist
672
     * @return id de l'article correspondant
673
     */
674
    public static int getIdForCNM(SQLRowValues row, boolean createIfNotExist) {
675
        return getIdFor(row, true, createIfNotExist);
676
    }
677
 
678
    /**
679
     * retourne l'id d'un article ayant le meme Code, Nom le cas échéant -1
680
     *
681
     * @param row
682
     * @param createIfNotExist
683
     * @return id de l'article correspondant
684
     */
685
    public static int getIdForCN(SQLRowValues row, boolean createIfNotExist) {
686
 
687
        return getIdFor(row, false, createIfNotExist);
688
    }
689
 
93 ilm 690
    @SuppressWarnings("rawtypes")
18 ilm 691
    private static int getIdFor(SQLRowValues row, boolean includeMetrique, boolean createIfNotExist) {
692
 
693
        // On cherche l'article qui lui correspond
694
        SQLTable tableArt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
695
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(tableArt);
696
        String req = getMatchRequest(row, includeMetrique);
697
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());
698
 
699
        if (result != null && result.size() != 0) {
700
            Object[] tmp = (Object[]) result.get(0);
701
            return ((Number) tmp[0]).intValue();
702
        }
703
 
93 ilm 704
        if (createIfNotExist && row.getString("CODE") != null && row.getString("CODE").trim().length() > 0 && row.getString("NOM") != null && row.getString("NOM").trim().length() > 0) {
18 ilm 705
            SQLRowValues vals = new SQLRowValues(row);
83 ilm 706
            BigDecimal taux = BigDecimal.ONE.add(new BigDecimal(TaxeCache.getCache().getTauxFromId(row.getForeignID("ID_TAXE")) / 100f));
707
            vals.put("PV_TTC", vals.getBigDecimal("PV_HT").multiply(taux));
156 ilm 708
            vals.put("ID_DEPOT_STOCK", DepotStockSQLElement.DEFAULT_ID);
93 ilm 709
            int idArticle;
18 ilm 710
            try {
83 ilm 711
 
712
                // Liaison avec l'article fournisseur si il existe
713
                SQLSelect selMatchingCodeF = new SQLSelect();
714
                final SQLTable table = tableArt.getTable("ARTICLE_FOURNISSEUR");
715
                selMatchingCodeF.addSelect(table.getKey());
716
                selMatchingCodeF.addSelect(table.getField("ID_FOURNISSEUR"));
717
                selMatchingCodeF.addSelect(table.getField("CODE_BARRE"));
718
                Where wMatchingCodeF = new Where(table.getField("CODE"), "=", vals.getString("CODE"));
719
                wMatchingCodeF = wMatchingCodeF.and(new Where(table.getField("NOM"), "=", vals.getString("NOM")));
720
                selMatchingCodeF.setWhere(wMatchingCodeF);
721
 
93 ilm 722
                // FIXME utiliser une transaction bloquante sur la table
723
                List<SQLRow> l = SQLRowListRSH.execute(selMatchingCodeF, false, false);
83 ilm 724
                if (l.size() > 0) {
725
                    SQLRowValues rowVals = l.get(0).asRowValues();
726
                    vals.put("ID_FOURNISSEUR", rowVals.getObject("ID_FOURNISSEUR"));
727
                    vals.put("CODE_BARRE", rowVals.getObject("CODE_BARRE"));
90 ilm 728
                    vals.put("QTE_ACHAT", rowVals.getObject("QTE_ACHAT"));
93 ilm 729
                    SQLRow rowNew = vals.insert();
730
                    idArticle = rowNew.getID();
731
                    rowVals.put("ID_ARTICLE", idArticle);
83 ilm 732
                    rowVals.commit();
733
                } else {
93 ilm 734
                    SQLSelect selMatchingCodeArticle = new SQLSelect();
735
                    selMatchingCodeArticle.addSelect(tableArt.getKey());
736
                    Where wMatchingCode = new Where(tableArt.getField("CODE"), "=", vals.getString("CODE"));
737
                    wMatchingCode = wMatchingCode.and(new Where(tableArt.getField("NOM"), "=", vals.getString("NOM")));
738
                    selMatchingCodeArticle.setWhere(wMatchingCode);
739
                    List<SQLRow> matchingArticles = SQLRowListRSH.execute(selMatchingCodeArticle, false, false);
740
                    if (matchingArticles.size() > 0) {
741
                        idArticle = matchingArticles.get(0).getID();
742
                    } else {
182 ilm 743
                        Collection<SQLRowValues> refTarif = row.getReferentRows(row.getTable().getTable("ARTICLE_TARIF_FOURNISSEUR"));
744
                        if (!refTarif.isEmpty()) {
745
                            for (SQLRowValues sqlRowValues : refTarif) {
746
                                SQLRowValues rowValsTarif = new SQLRowValues(sqlRowValues);
747
                                rowValsTarif.put("ID_ARTICLE", vals);
748
                            }
749
                        }
750
 
93 ilm 751
                        SQLRow rowNew = vals.insert();
752
                        idArticle = rowNew.getID();
753
                    }
83 ilm 754
                }
93 ilm 755
                return idArticle;
18 ilm 756
            } catch (SQLException e) {
757
                e.printStackTrace();
758
            }
759
 
760
        }
761
        return -1;
762
 
763
    }
764
 
765
    /**
766
     * teste si un article ayant le meme nom et code existe
767
     *
768
     * @param row
769
     * @return true si au moins un article correspond
770
     */
771
    public static boolean isArticleForCNExist(SQLRowValues row) {
772
        return isArticleMatchExist(row, false);
773
    }
774
 
775
    /**
776
     * teste si un article ayant le meme nom, code et valeur metrique existe
777
     *
778
     * @param row
779
     * @return true si au moins un article correspond
780
     */
781
    public static boolean isArticleForCNMExist(SQLRowValues row) {
782
        return isArticleMatchExist(row, true);
783
    }
784
 
93 ilm 785
    @SuppressWarnings("rawtypes")
18 ilm 786
    private static boolean isArticleMatchExist(SQLRowValues row, boolean includeMetrique) {
787
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
788
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
789
        String req = getMatchRequest(row, includeMetrique);
790
        List result = (List) eltArticle.getTable().getBase().getDataSource().execute(req, new ArrayListHandler());
791
 
792
        return (result != null && result.size() != 0);
793
    }
794
 
795
    private static String getMatchRequest(SQLRowValues row, boolean includeMetrique) {
796
        // On cherche l'article qui lui correspond
797
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
798
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
799
        SQLSelect sel = new SQLSelect(eltArticle.getTable().getBase());
800
        sel.addSelect(eltArticle.getTable().getField("ID"));
801
 
90 ilm 802
        Where w = new Where(eltArticle.getTable().getField("CODE"), "=", row.getString("CODE").trim());
18 ilm 803
        if (includeMetrique) {
804
 
805
            float value1 = ((Number) row.getObject("VALEUR_METRIQUE_1")).floatValue();
806
            float value2 = ((Number) row.getObject("VALEUR_METRIQUE_2")).floatValue();
807
            float value3 = ((Number) row.getObject("VALEUR_METRIQUE_3")).floatValue();
808
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), "<=", new Float(value1 + 0.00001)));
809
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_1"), ">=", new Float(value1 - 0.00001)));
810
 
811
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), "<=", new Float(value2 + 0.00001)));
812
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_2"), ">=", new Float(value2 - 0.00001)));
813
 
814
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), "<=", new Float(value3 + 0.00001)));
815
            w = w.and(new Where(eltArticle.getTable().getField("VALEUR_METRIQUE_3"), ">=", new Float(value3 - 0.00001)));
816
 
817
        }
818
        sel.setWhere(w);
819
        return sel.asString();
820
    }
19 ilm 821
 
822
    public static boolean isReferenceEquals(SQLRowValues rowVals1, SQLRowValues rowVals2) {
823
        return (rowVals1.getObject("CODE").equals(rowVals2.getObject("CODE")) && rowVals1.getString("VALEUR_METRIQUE_1").equals(rowVals2.getString("VALEUR_METRIQUE_1"))
824
                && rowVals1.getString("VALEUR_METRIQUE_2").equals(rowVals2.getString("VALEUR_METRIQUE_2")) && rowVals1.getString("VALEUR_METRIQUE_3").equals(rowVals2.getString("VALEUR_METRIQUE_3")));
825
    }
57 ilm 826
 
156 ilm 827
    public void initStock(int id) {
828
        SQLRow row = getTable().getRow(id);
174 ilm 829
        Updater_1_5.initStock(row);
156 ilm 830
    }
831
 
57 ilm 832
    @Override
833
    protected String createCode() {
156 ilm 834
        return createCodeOfPackage() + ".ref";
57 ilm 835
    }
156 ilm 836
 
837
    @Override
838
    protected void _initComboRequest(ComboSQLRequest req) {
839
        super._initComboRequest(req);
840
        req.addToGraphToFetch("ID_DEPOT_STOCK");
182 ilm 841
        req.setWhere(new Where(getTable().getField("VIRTUEL"), "=", Boolean.FALSE));
842
 
156 ilm 843
    }
844
 
177 ilm 845
    static public void updateDateAchat(final SQLTable tableArticle, final SQLRow article) {
846
 
847
        assert article == null || article.getTable() == tableArticle;
848
        SQLTable tableTarifF = tableArticle.getTable("ARTICLE_TARIF_FOURNISSEUR");
849
        String up = "UPDATE " + tableArticle.getSQLName().quote() + " a SET " + tableArticle.getField("DERNIER_DATE_ACHAT").getQuotedName();
850
        up += " =(select MAX(" + tableTarifF.getField("DATE_PRIX").getQuotedName() + ")  ";
851
        up += " FROM " + tableTarifF.getSQLName().quote() + "  t" + " WHERE (t." + tableTarifF.getKey().getQuotedName() + " <> 1) ";
852
        up += " AND (t." + tableTarifF.getField("ARCHIVE").getQuotedName() + " = 0) ";
853
        up += "AND t." + tableTarifF.getField("ID_ARTICLE").getQuotedName() + " = " + (article == null ? "a." + tableArticle.getKey().getQuotedName() : article.getID()) + ")";
854
        if (article != null) {
855
            up += "WHERE " + tableArticle.getKey().getQuotedName() + " = " + article.getID();
856
        }
857
 
858
        tableArticle.getDBSystemRoot().getDataSource().execute(up);
859
    }
860
 
182 ilm 861
    /**
862
     * Création des déclinaisons tailles/couleurs à partir de l'article virtuel passé en parametre
863
     *
864
     * @param idArticlePere
865
     * @param tupleTailleCouleur
866
     * @throws SQLException
867
     */
868
    public void createDeclinaison(int idArticlePere, List<Tuple2<SQLRow, SQLRow>> tupleTailleCouleur) throws SQLException {
869
 
870
        final SQLRow row = getTable().getRow(idArticlePere);
871
        if (!row.getBoolean("VIRTUEL")) {
872
            throw new IllegalArgumentException("L'article n'est pas un article virtuel");
873
        }
874
        ListMap<SQLTable, SQLRow> children = ReferenceArticleSQLElement.this.getChildrenRows(row);
875
        for (Tuple2<SQLRow, SQLRow> t : tupleTailleCouleur) {
876
 
877
            SQLRowValues rowVals = ReferenceArticleSQLElement.this.createCopy(idArticlePere);
878
            for (SQLRow child : children.allValues()) {
879
                Configuration.getInstance().getDirectory().getElement(child.getTable()).createCopy(child, false, rowVals);
880
            }
881
            rowVals.put("ID_ARTICLE_VIRTUEL_PERE", idArticlePere);
882
            rowVals.put("VIRTUEL", Boolean.FALSE);
883
            rowVals.put("ID_ARTICLE_DECLINAISON_TAILLE", t.get0().getID());
884
            rowVals.put("ID_ARTICLE_DECLINAISON_COULEUR", t.get1().getID());
885
 
886
            rowVals.commit();
887
 
888
        }
889
 
890
    }
891
 
892
    public void transfert(final List<Tuple2<SQLRow, BigDecimal>> articles, final SQLRowAccessor selectedRowDepotDepart, final SQLRowAccessor selectedRowDepotArrivee, final String label,
893
            final Date dateValue) {
894
 
895
        final SQLTable mvtStockTable = getTable().getDBRoot().findTable("MOUVEMENT_STOCK");
896
 
897
        List<String> multipleRequestsHundred = new ArrayList<String>(100);
898
        boolean usePrice = mvtStockTable.contains("PRICE");
899
        List<StockItem> stockItems = new ArrayList<StockItem>();
900
 
901
        try {
902
            final DBSystemRoot dbSystemRoot = selectedRowDepotDepart.getTable().getDBSystemRoot();
903
            SQLUtils.executeAtomic(dbSystemRoot.getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() {
904
                @Override
905
                public Object handle(SQLDataSource ds) throws SQLException {
906
 
907
                    for (Tuple2<SQLRow, BigDecimal> t : articles) {
908
 
909
                        SQLRow selectedRowArticle = t.get0();
910
                        BigDecimal qteReel = t.get1();
911
                        {
912
                            // DEPART
913
                            final SQLRowAccessor rowStockDepart = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotDepart);
914
                            StockItem item = new StockItem(selectedRowArticle, rowStockDepart);
915
                            if (!item.isStockInit()) {
916
                                SQLRowValues rowVals = new SQLRowValues(mvtStockTable.getTable("STOCK"));
917
                                rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
918
                                rowVals.put("ID_DEPOT_STOCK", selectedRowDepotDepart.getID());
919
                                rowVals.commit();
920
                                selectedRowArticle.fetchValues();
921
                                item = new StockItem(selectedRowArticle, rowStockDepart);
922
                            }
923
                            stockItems.add(item);
924
                            double diff = -qteReel.doubleValue();
925
                            item.updateQty(diff, TypeStockMouvement.REEL);
926
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), true, usePrice));
927
                            item.updateQty(diff, TypeStockMouvement.THEORIQUE);
928
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), false, usePrice));
929
                            multipleRequestsHundred.add(item.getUpdateRequest());
930
                        }
931
                        // ARRIVEE
932
                        {
933
                            final SQLRowAccessor rowStockArrivee = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotArrivee);
934
                            StockItem item = new StockItem(selectedRowArticle, rowStockArrivee);
935
                            if (!item.isStockInit()) {
936
                                SQLRowValues rowVals = new SQLRowValues(mvtStockTable.getTable("STOCK"));
937
                                rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
938
                                rowVals.put("ID_DEPOT_STOCK", selectedRowDepotArrivee.getID());
939
                                rowVals.commit();
940
                                selectedRowArticle.fetchValues();
941
                                item = new StockItem(selectedRowArticle, rowStockArrivee);
942
                            }
943
                            stockItems.add(item);
944
                            double diff = qteReel.doubleValue();
945
                            item.updateQty(diff, TypeStockMouvement.REEL);
946
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), true, usePrice));
947
                            item.updateQty(diff, TypeStockMouvement.THEORIQUE);
948
                            multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(label, selectedRowDepotDepart, selectedRowDepotArrivee), false, usePrice));
949
                            multipleRequestsHundred.add(item.getUpdateRequest());
950
                        }
951
 
952
                        final int size = multipleRequestsHundred.size();
953
                        List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(size);
954
                        for (int i = 0; i < size; i++) {
955
                            handlers.add(null);
956
                        }
957
                        SQLUtils.executeMultiple(dbSystemRoot, multipleRequestsHundred, handlers);
958
 
959
                        final DBRoot root = mvtStockTable.getDBRoot();
960
                        if (root.contains("ARTICLE_ELEMENT")) {
961
                            // Mise à jour des stocks des nomenclatures
962
                            ComposedItemStockUpdater comp = new ComposedItemStockUpdater(root, stockItems);
963
                            comp.update();
964
                        }
965
                    }
966
                    return null;
967
                }
968
            });
969
        } catch (SQLException e1) {
970
            ExceptionHandler.handle("Stock update error", e1);
971
        }
972
    }
973
 
974
    private String getLabel(String label, SQLRowAccessor fromDepot, SQLRowAccessor toDepot) {
975
        return label + " de " + fromDepot.getString("NOM") + " vers " + toDepot.getString("NOM");
976
    }
977
 
978
    private String getMvtRequest(Date time, BigDecimal prc, double qteFinal, StockItem item, String label, boolean reel, boolean usePrice) {
979
        final SQLTable mvtStockTable = getTable().getDBRoot().findTable("MOUVEMENT_STOCK");
980
        final String mvtStockTableQuoted = mvtStockTable.getSQLName().quote();
981
 
982
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
983
        String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"NOM\",\"REEL\",\"ORDRE\"";
984
 
985
        if (usePrice && prc != null) {
986
            mvtStockQuery += ",\"PRICE\"";
987
        }
988
 
989
        mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + item.getArticle().getID() + "," + item.stock.getID() + ",'" + label + "'," + reel
990
                + ", (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
991
        if (usePrice && prc != null) {
992
            mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
993
        }
994
        mvtStockQuery += ")";
995
        return mvtStockQuery;
996
    }
997
 
18 ilm 998
}