OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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
 *
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.supplychain.stock.element;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
19 ilm 18
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
174 ilm 19
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
182 ilm 20
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
19 ilm 21
import org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent;
156 ilm 22
import org.openconcerto.erp.core.supplychain.order.ui.CommandeItemTable;
182 ilm 23
import org.openconcerto.erp.core.supplychain.stock.element.StockItem.TypeStockMouvement;
41 ilm 24
import org.openconcerto.erp.core.supplychain.supplier.component.MouvementStockSQLComponent;
142 ilm 25
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
174 ilm 26
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
18 ilm 27
import org.openconcerto.sql.Configuration;
28
import org.openconcerto.sql.element.SQLComponent;
29
import org.openconcerto.sql.element.SQLElement;
73 ilm 30
import org.openconcerto.sql.element.TreesOfSQLRows;
182 ilm 31
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
32
import org.openconcerto.sql.model.DBRoot;
19 ilm 33
import org.openconcerto.sql.model.SQLBackgroundTableCache;
18 ilm 34
import org.openconcerto.sql.model.SQLBase;
182 ilm 35
import org.openconcerto.sql.model.SQLDataSource;
19 ilm 36
import org.openconcerto.sql.model.SQLInjector;
18 ilm 37
import org.openconcerto.sql.model.SQLRow;
182 ilm 38
import org.openconcerto.sql.model.SQLRowAccessor;
19 ilm 39
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 40
import org.openconcerto.sql.model.SQLRowValues;
19 ilm 41
import org.openconcerto.sql.model.SQLSelect;
18 ilm 42
import org.openconcerto.sql.model.SQLTable;
19 ilm 43
import org.openconcerto.sql.model.Where;
61 ilm 44
import org.openconcerto.sql.preferences.SQLPreferences;
132 ilm 45
import org.openconcerto.sql.request.ListSQLRequest;
19 ilm 46
import org.openconcerto.sql.users.UserManager;
182 ilm 47
import org.openconcerto.sql.utils.SQLUtils;
18 ilm 48
import org.openconcerto.sql.view.EditFrame;
49
import org.openconcerto.sql.view.EditPanel;
19 ilm 50
import org.openconcerto.sql.view.EditPanel.EditMode;
51
import org.openconcerto.sql.view.list.RowValuesTableModel;
73 ilm 52
import org.openconcerto.ui.FrameUtil;
182 ilm 53
import org.openconcerto.utils.ExceptionHandler;
83 ilm 54
import org.openconcerto.utils.ListMap;
18 ilm 55
 
73 ilm 56
import java.math.BigDecimal;
182 ilm 57
import java.math.RoundingMode;
18 ilm 58
import java.sql.SQLException;
182 ilm 59
import java.text.SimpleDateFormat;
18 ilm 60
import java.util.ArrayList;
83 ilm 61
import java.util.Collection;
182 ilm 62
import java.util.Date;
18 ilm 63
import java.util.List;
83 ilm 64
import java.util.Map.Entry;
18 ilm 65
 
174 ilm 66
import javax.swing.JOptionPane;
19 ilm 67
import javax.swing.SwingUtilities;
18 ilm 68
 
182 ilm 69
import org.apache.commons.dbutils.ResultSetHandler;
70
 
18 ilm 71
public class MouvementStockSQLElement extends ComptaSQLConfElement {
72
 
73
    public MouvementStockSQLElement() {
74
        super("MOUVEMENT_STOCK", "un mouvement de stock", "mouvements de stock");
75
    }
76
 
156 ilm 77
    @Override
78
    public ListMap<String, String> getShowAs() {
79
        ListMap<String, String> map = new ListMap<String, String>();
80
        map.putCollection("ID_STOCK", "ID_DEPOT_STOCK");
81
        return map;
82
    }
83
 
18 ilm 84
    protected List<String> getListFields() {
85
        final List<String> l = new ArrayList<String>();
156 ilm 86
        l.add("ID_STOCK");
18 ilm 87
        l.add("DATE");
88
        l.add("NOM");
89
        l.add("ID_ARTICLE");
90
        l.add("QTE");
83 ilm 91
        l.add("REEL");
18 ilm 92
        return l;
93
    }
94
 
95
    protected List<String> getComboFields() {
96
        final List<String> l = new ArrayList<String>();
97
        l.add("NOM");
98
        l.add("QTE");
99
        return l;
100
    }
101
 
102
    /*
103
     * (non-Javadoc)
104
     *
105
     * @see org.openconcerto.devis.SQLElement#getComponent()
106
     */
107
    public SQLComponent createComponent() {
41 ilm 108
        return new MouvementStockSQLComponent(this);
18 ilm 109
    }
110
 
111
    @Override
73 ilm 112
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
113
        super.archive(trees, cutLinks);
83 ilm 114
        updateStock(trees.getRows(), true);
115
 
73 ilm 116
    }
117
 
61 ilm 118
    /**
18 ilm 119
     * Mise à jour des stocks ajoute la quantité si archive est à false
120
     *
121
     * @param id mouvement stock
122
     * @param archive
156 ilm 123
     * @throws SQLException
18 ilm 124
     */
156 ilm 125
    public ListMap<SQLRow, SQLRowValues> updateStock(Collection<SQLRow> rowsMvt, boolean archive) throws SQLException {
73 ilm 126
        // FIXME: if (SwingUtilities.isEventDispatchThread()) {
127
        // throw new IllegalStateException("This method must be called outside of EDT");
128
        // }
83 ilm 129
        // Stock Reel : inc/dec QTE_REEL, inc/dec QTE_LIV_ATTENTE/inc/dec
130
        // QTE_RECEPT_ATTENTE
131
        // Stock Th : inc/dec QTE_TH, inc/dec QTE_LIV_ATTENTE/inc/dec
132
        // QTE_RECEPT_ATTENTE
133
 
156 ilm 134
        final ListMap<SQLRow, SQLRowValues> map = new ListMap<>();
135
 
182 ilm 136
        if (rowsMvt == null || rowsMvt.isEmpty()) {
137
            return map;
138
        }
139
 
140
        final DBRoot root = rowsMvt.iterator().next().getTable().getDBRoot();
141
 
142
        final SQLTable tableCommandeElement = root.getTable("COMMANDE_ELEMENT");
143
        final SQLTable tableStock = root.getTable("STOCK");
144
 
83 ilm 145
        for (SQLRow rowMvtStock : rowsMvt) {
18 ilm 146
 
132 ilm 147
            boolean retour = rowMvtStock.getString("SOURCE") == null || rowMvtStock.getString("SOURCE").startsWith("AVOIR_CLIENT");
19 ilm 148
            // Mise à jour des stocks
156 ilm 149
 
19 ilm 150
            final SQLRow rowArticle = rowMvtStock.getForeignRow("ID_ARTICLE");
73 ilm 151
 
156 ilm 152
            SQLRow rowStock = rowMvtStock.getForeignRow(("ID_STOCK"));
153
            if (rowStock == null || rowStock.isUndefined()) {
154
                rowStock = rowArticle.getForeign("ID_STOCK");
155
            }
156
 
83 ilm 157
            if (rowMvtStock.getBoolean("REEL")) {
158
                float qte = rowStock.getFloat("QTE_REEL");
159
                float qteMvt = rowMvtStock.getFloat("QTE");
18 ilm 160
 
182 ilm 161
                SQLRowValues rowVals = new SQLRowValues(tableStock);
18 ilm 162
 
83 ilm 163
                float qteNvlle;
164
                float qteNvlleEnAttenteRecept = rowStock.getFloat("QTE_RECEPT_ATTENTE");
165
                float qteNvlleEnAttenteExp = rowStock.getFloat("QTE_LIV_ATTENTE");
166
                if (archive) {
167
                    qteNvlle = qte - qteMvt;
132 ilm 168
                    if (!retour) {
169
                        // Réception
170
                        if (qteMvt > 0) {
171
                            qteNvlleEnAttenteRecept += qteMvt;
172
                        } else {
173
                            // Livraison
174
                            qteNvlleEnAttenteExp -= qteMvt;
175
                        }
83 ilm 176
                    }
177
                } else {
178
                    qteNvlle = qte + qteMvt;
132 ilm 179
                    if (!retour) {
180
                        // Réception
181
                        if (qteMvt > 0) {
182
                            qteNvlleEnAttenteRecept -= qteMvt;
183
                        } else {
184
                            // Livraison
185
                            qteNvlleEnAttenteExp += qteMvt;
186
                        }
83 ilm 187
                    }
188
                }
189
                rowVals.put("QTE_REEL", qteNvlle);
190
                rowVals.put("QTE_RECEPT_ATTENTE", qteNvlleEnAttenteRecept);
191
                rowVals.put("QTE_LIV_ATTENTE", qteNvlleEnAttenteExp);
18 ilm 192
 
83 ilm 193
                try {
156 ilm 194
                    rowVals.update(rowStock.getID());
18 ilm 195
 
182 ilm 196
                    SQLPreferences prefs = new SQLPreferences(root);
156 ilm 197
                    boolean gestionStockMin = prefs.getBoolean(GestionArticleGlobalPreferencePanel.WARNING_STOCK_MIN, true);
198
 
199
                    if (!archive && gestionStockMin && rowStock.getObject("QTE_MIN") != null && qteNvlle < rowStock.getFloat("QTE_MIN")) {
200
                        // final float qteShow = qteNvlle;
201
                        SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCommandeElement);
202
                        SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticle));
203
                        rowValsElt.put("ID_STYLE", 2);
204
                        final SQLRow unite = rowArticle.getForeign("ID_UNITE_VENTE");
205
                        final float qteElt = rowStock.getFloat("QTE_MIN") - qteNvlle;
206
                        if (unite.isUndefined() || unite.getBoolean("A_LA_PIECE")) {
207
                            rowValsElt.put("QTE", Math.round(qteElt));
208
                            rowValsElt.put("QTE_UNITAIRE", BigDecimal.ONE);
209
                        } else {
210
                            rowValsElt.put("QTE", 1);
211
                            rowValsElt.put("QTE_UNITAIRE", new BigDecimal(qteElt));
83 ilm 212
                        }
156 ilm 213
                        rowValsElt.put("ID_TAXE", rowValsElt.getObject("ID_TAXE"));
214
                        rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * qteElt);
215
                        rowValsElt.put("T_PA_HT", rowValsElt.getLong("PA_HT") * qteElt);
216
                        rowValsElt.put("T_PA_TTC", rowValsElt.getLong("T_PA_HT") * (rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0));
217
                        map.add(rowArticle.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
83 ilm 218
                    }
219
                } catch (SQLException e) {
156 ilm 220
                    throw new SQLException("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"), e);
83 ilm 221
                }
222
            } else {
223
                float qte = rowStock.getFloat("QTE_TH");
224
                float qteMvt = rowMvtStock.getFloat("QTE");
19 ilm 225
 
182 ilm 226
                SQLRowValues rowVals = new SQLRowValues(tableStock);
18 ilm 227
 
83 ilm 228
                float qteNvlle;
229
                float qteNvlleEnAttenteRecept = rowStock.getFloat("QTE_RECEPT_ATTENTE");
230
                float qteNvlleEnAttenteExp = rowStock.getFloat("QTE_LIV_ATTENTE");
231
 
232
                if (archive) {
233
                    qteNvlle = qte - qteMvt;
132 ilm 234
                    if (!retour) {
235
 
236
                        // CommandeF
237
                        if (qteMvt > 0) {
238
                            qteNvlleEnAttenteRecept -= qteMvt;
239
                        } else {
240
                            // CommanceC
241
                            qteNvlleEnAttenteExp += qteMvt;
242
                        }
83 ilm 243
                    }
73 ilm 244
                } else {
83 ilm 245
                    qteNvlle = qte + qteMvt;
132 ilm 246
                    if (!retour) {
247
 
248
                        // CommandeF
249
                        if (qteMvt > 0) {
250
                            qteNvlleEnAttenteRecept += qteMvt;
251
                        } else {
252
                            // CommanceC
253
                            qteNvlleEnAttenteExp -= qteMvt;
254
                        }
83 ilm 255
                    }
73 ilm 256
                }
83 ilm 257
                rowVals.put("QTE_TH", qteNvlle);
258
                rowVals.put("QTE_RECEPT_ATTENTE", qteNvlleEnAttenteRecept);
259
                rowVals.put("QTE_LIV_ATTENTE", qteNvlleEnAttenteExp);
260
                try {
156 ilm 261
                    rowVals.update(rowStock.getID());
83 ilm 262
                } catch (SQLException e) {
156 ilm 263
                    throw new SQLException("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"), e);
83 ilm 264
                }
19 ilm 265
            }
73 ilm 266
 
18 ilm 267
        }
19 ilm 268
        return map;
18 ilm 269
    }
270
 
83 ilm 271
    public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise) {
174 ilm 272
        createCommandeF(col, rowDevise, "");
67 ilm 273
    }
19 ilm 274
 
174 ilm 275
    public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise, final String ref) {
73 ilm 276
        if (SwingUtilities.isEventDispatchThread()) {
277
            throw new IllegalStateException("This method must be called outside of EDT");
278
        }
83 ilm 279
        if (col.size() > 0) {
19 ilm 280
 
73 ilm 281
            final SQLElement commande = Configuration.getInstance().getDirectory().getElement("COMMANDE");
174 ilm 282
            Boolean useCommandeEnCours = SQLPreferences.getMemCached(commande.getTable().getDBRoot()).getBoolean(GestionCommercialeGlobalPreferencePanel.COMMANDE_FOURNISSEUR_EN_COURS, false);
83 ilm 283
            for (final Entry<SQLRow, List<SQLRowValues>> e : col.entrySet()) {
284
                final SQLRow fournisseur = e.getKey();
73 ilm 285
                // On regarde si il existe une commande en cours existante
286
                final SQLSelect sel = new SQLSelect();
287
                sel.addSelectStar(commande.getTable());
288
                Where w = new Where(commande.getTable().getField("EN_COURS"), "=", Boolean.TRUE);
289
                w = w.and(new Where(commande.getTable().getField("ID_FOURNISSEUR"), "=", fournisseur.getID()));
290
                sel.setWhere(w);
19 ilm 291
 
142 ilm 292
                final List<SQLRow> rowsCmd = !useCommandeEnCours ? null
293
                        : (List<SQLRow>) Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
19 ilm 294
 
73 ilm 295
                SwingUtilities.invokeLater(new Runnable() {
296
 
297
                    @Override
298
                    public void run() {
19 ilm 299
                        SQLRow commandeExistante = null;
300
                        if (rowsCmd != null && rowsCmd.size() > 0) {
301
                            commandeExistante = rowsCmd.get(0);
302
                        }
303
                        EditFrame frame;
304
                        CommandeSQLComponent cmp;
305
 
306
                        if (commandeExistante != null) {
307
                            frame = new EditFrame(commande, EditMode.MODIFICATION);
308
                            cmp = (CommandeSQLComponent) frame.getSQLComponent();
309
                            cmp.select(commandeExistante);
310
                        } else {
311
                            frame = new EditFrame(commande);
312
                            cmp = (CommandeSQLComponent) frame.getSQLComponent();
41 ilm 313
                            final SQLRowValues rowVals = new SQLRowValues(commande.getTable());
314
                            final SQLElement eltComm = Configuration.getInstance().getDirectory().getElement("COMMERCIAL");
19 ilm 315
                            int idUser = UserManager.getInstance().getCurrentUser().getId();
316
                            SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
317
 
318
                            if (rowsComm != null) {
319
                                rowVals.put("ID_COMMERCIAL", rowsComm.getID());
320
                            }
132 ilm 321
                            if (fournisseur != null && !fournisseur.isUndefined()) {
322
                                rowVals.put("ID_FOURNISSEUR", fournisseur.getID());
323
                            }
19 ilm 324
                            if (rowDevise != null) {
325
                                rowVals.put("ID_DEVISE", rowDevise.getID());
326
                            }
67 ilm 327
                            if (commande.getTable().contains("ID_ADRESSE")) {
328
                                rowVals.put("ID_ADRESSE", null);
329
                            }
330
                            rowVals.put("NOM", ref);
19 ilm 331
                            cmp.select(rowVals);
73 ilm 332
                            cmp.getRowValuesTable().getRowValuesTableModel().clearRows();
19 ilm 333
                        }
334
 
156 ilm 335
                        CommandeItemTable itemTable = cmp.getRowValuesTablePanel();
336
 
73 ilm 337
                        final RowValuesTableModel model = cmp.getRowValuesTable().getRowValuesTableModel();
83 ilm 338
                        for (SQLRowValues rowValsElt : e.getValue()) {
19 ilm 339
                            SQLRowValues rowValsMatch = null;
340
                            int index = 0;
341
 
342
                            for (int i = 0; i < model.getRowCount(); i++) {
41 ilm 343
                                final SQLRowValues rowValsCmdElt = model.getRowValuesAt(i);
182 ilm 344
                                Number lineArticleNumber = rowValsCmdElt.contains("ID_ARTICLE") ? rowValsCmdElt.getNonEmptyForeignIDNumber("ID_ARTICLE") : null;
345
                                Number lineToAddArticleNumber = rowValsElt.contains("ID_ARTICLE") ? rowValsElt.getNonEmptyForeignIDNumber("ID_ARTICLE") : null;
346
                                if (lineToAddArticleNumber == null || lineArticleNumber == null || lineArticleNumber.equals(lineToAddArticleNumber)) {
347
                                    if (ReferenceArticleSQLElement.isReferenceEquals(rowValsCmdElt, rowValsElt)) {
348
                                        rowValsMatch = rowValsCmdElt;
349
                                        index = i;
350
                                        break;
351
                                    }
19 ilm 352
                                }
353
                            }
354
                            if (rowValsMatch != null) {
174 ilm 355
 
356
                                int qte = rowValsMatch.getInt("QTE");
357
                                BigDecimal qteUV = rowValsMatch.getBigDecimal("QTE_UNITAIRE");
358
 
359
                                if (rowValsMatch.getObject("ID_UNITE_VENTE") != null && rowValsMatch.getForeignID("ID_UNITE_VENTE") != UniteVenteArticleSQLElement.A_LA_PIECE) {
360
                                    qteUV = qteUV.multiply(new BigDecimal(qte));
361
                                    int qteElt = rowValsElt.getInt("QTE");
362
                                    BigDecimal qteUVElt = rowValsElt.getBigDecimal("QTE_UNITAIRE");
363
                                    qteUV = qteUV.add(qteUVElt.multiply(new BigDecimal(qteElt)));
364
                                    qte = 1;
365
                                } else {
366
                                    qte += rowValsElt.getInt("QTE");
367
                                }
368
 
369
                                model.putValue(qte, index, "QTE");
370
                                model.putValue(qteUV, index, "QTE_UNITAIRE");
19 ilm 371
                            } else {
372
                                model.addRow(rowValsElt);
156 ilm 373
                                if (rowValsElt.getObject("ID_ARTICLE") != null && !rowValsElt.isForeignEmpty("ID_ARTICLE")) {
374
                                    Object o = itemTable.tarifCompletion(rowValsElt.getForeign("ID_ARTICLE").asRow(), "PRIX_METRIQUE_HA_1");
375
                                    if (o != null) {
376
                                        model.putValue(o, model.getRowCount() - 1, "PRIX_METRIQUE_HA_1");
377
                                    }
378
                                }
19 ilm 379
                            }
380
                        }
381
 
382
                        frame.pack();
73 ilm 383
                        FrameUtil.show(frame);
384
 
19 ilm 385
                    }
73 ilm 386
                });
387
            }
174 ilm 388
        } else {
389
            SwingUtilities.invokeLater(new Runnable() {
73 ilm 390
 
174 ilm 391
                @Override
392
                public void run() {
393
                    JOptionPane.showMessageDialog(null, "Aucune commande à passer", "Commande fournisseur", JOptionPane.INFORMATION_MESSAGE);
394
                }
395
 
396
            });
19 ilm 397
        }
398
 
399
    }
400
 
132 ilm 401
    @Override
402
    protected void _initListRequest(ListSQLRequest req) {
403
        super._initListRequest(req);
404
        req.addToGraphToFetch("SOURCE", "IDSOURCE");
405
    }
406
 
73 ilm 407
    public static final void showSource(final int id) {
408
        if (!SwingUtilities.isEventDispatchThread()) {
409
            throw new IllegalStateException("This method must be called from EDT");
410
        }
18 ilm 411
        if (id != 1) {
73 ilm 412
            final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
413
            final SQLTable tableMvt = base.getTable("MOUVEMENT_STOCK");
414
            final String stringTableSource = tableMvt.getRow(id).getString("SOURCE");
415
            SwingUtilities.invokeLater(new Runnable() {
416
                public void run() {
417
 
418
                    final EditFrame f;
419
                    // Si une source est associée on l'affiche en readonly
420
                    if (stringTableSource.trim().length() != 0 && tableMvt.getRow(id).getInt("IDSOURCE") != 1) {
421
                        f = new EditFrame(Configuration.getInstance().getDirectory().getElement(stringTableSource), EditPanel.READONLY);
422
                        f.selectionId(tableMvt.getRow(id).getInt("IDSOURCE"));
423
                    } else {
424
                        // Sinon on affiche le mouvement de stock
425
                        f = new EditFrame(Configuration.getInstance().getDirectory().getElement(tableMvt), EditPanel.READONLY);
426
                        f.selectionId(id);
427
                    }
428
                    f.pack();
429
                    FrameUtil.show(f);
430
 
431
                }
432
            });
18 ilm 433
        } else {
434
            System.err.println("Aucun mouvement associé, impossible de modifier ou d'accéder à la source de cette ecriture!");
435
        }
436
    }
57 ilm 437
 
182 ilm 438
    public void transfertStock(BigDecimal qteReel, final Date dateValue, final SQLRow selectedRowArticle, final SQLRow selectedRowDepotDepart, final SQLRow selectedRowDepotArrivee,
439
            final String labelTrStock) {
440
        final boolean usePrice = getTable().contains("PRICE");
441
        try {
442
            SQLUtils.executeAtomic(selectedRowDepotDepart.getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, SQLException>() {
443
                @Override
444
                public Object handle(SQLDataSource ds) throws SQLException {
445
                    List<StockItem> stockItems = new ArrayList<StockItem>();
446
                    List<String> multipleRequestsHundred = new ArrayList<String>(100);
447
                    {
448
                        // DEPART
449
                        final SQLRowAccessor rowStockDepart = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotDepart);
450
                        StockItem item = new StockItem(selectedRowArticle, rowStockDepart);
451
                        if (!item.isStockInit()) {
452
                            SQLRowValues rowVals = new SQLRowValues(getTable().getTable("STOCK"));
453
                            rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
454
                            rowVals.put("ID_DEPOT_STOCK", selectedRowDepotDepart.getID());
455
                            rowVals.commit();
456
                            selectedRowArticle.fetchValues();
457
                            item = new StockItem(selectedRowArticle, rowStockDepart);
458
                        }
459
                        stockItems.add(item);
460
                        double diff = -qteReel.doubleValue();
461
                        item.updateQty(diff, TypeStockMouvement.REEL);
462
                        multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(labelTrStock, selectedRowDepotDepart, selectedRowDepotArrivee), true, usePrice));
463
                        item.updateQty(diff, TypeStockMouvement.THEORIQUE);
464
                        multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(labelTrStock, selectedRowDepotDepart, selectedRowDepotArrivee), false, usePrice));
465
                        multipleRequestsHundred.add(item.getUpdateRequest());
466
                    }
467
                    // ARRIVEE
468
                    {
469
                        final SQLRowAccessor rowStockArrivee = ProductComponent.findOrCreateStock(selectedRowArticle, selectedRowDepotArrivee);
470
                        StockItem item = new StockItem(selectedRowArticle, rowStockArrivee);
471
                        if (!item.isStockInit()) {
472
                            SQLRowValues rowVals = new SQLRowValues(getTable().getTable("STOCK"));
473
                            rowVals.put("ID_ARTICLE", selectedRowArticle.getID());
474
                            rowVals.put("ID_DEPOT_STOCK", selectedRowDepotArrivee.getID());
475
                            rowVals.commit();
476
                            selectedRowArticle.fetchValues();
477
                            item = new StockItem(selectedRowArticle, rowStockArrivee);
478
                        }
479
                        stockItems.add(item);
480
                        double diff = qteReel.doubleValue();
481
                        item.updateQty(diff, TypeStockMouvement.REEL);
482
                        multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(labelTrStock, selectedRowDepotDepart, selectedRowDepotArrivee), true, usePrice));
483
                        item.updateQty(diff, TypeStockMouvement.THEORIQUE);
484
                        multipleRequestsHundred.add(getMvtRequest(dateValue, BigDecimal.ZERO, diff, item, getLabel(labelTrStock, selectedRowDepotDepart, selectedRowDepotArrivee), false, usePrice));
485
                        multipleRequestsHundred.add(item.getUpdateRequest());
486
                    }
487
 
488
                    final int size = multipleRequestsHundred.size();
489
                    List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(size);
490
                    for (int i = 0; i < size; i++) {
491
                        handlers.add(null);
492
                    }
493
                    SQLUtils.executeMultiple(selectedRowArticle.getTable().getDBSystemRoot(), multipleRequestsHundred, handlers);
494
 
495
                    final DBRoot root = getTable().getDBRoot();
496
                    if (root.contains("ARTICLE_ELEMENT")) {
497
                        // Mise à jour des stocks des nomenclatures
498
                        ComposedItemStockUpdater comp = new ComposedItemStockUpdater(root, stockItems);
499
                        comp.update();
500
                    }
501
                    return null;
502
                }
503
            });
504
        } catch (SQLException e1) {
505
            ExceptionHandler.handle("Stock update error", e1);
506
        }
507
    }
508
 
509
    private String getLabel(String label, SQLRowAccessor fromDepot, SQLRowAccessor toDepot) {
510
        return label + " de " + fromDepot.getString("NOM") + " vers " + toDepot.getString("NOM");
511
    }
512
 
513
    private String getMvtRequest(Date time, BigDecimal prc, double qteFinal, StockItem item, String label, boolean reel, boolean usePrice) {
514
        String mvtStockTableQuoted = getTable().getSQLName().quote();
515
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
516
        String mvtStockQuery = "INSERT INTO " + mvtStockTableQuoted + " (\"QTE\",\"DATE\",\"ID_ARTICLE\",\"ID_STOCK\",\"NOM\",\"REEL\",\"ORDRE\"";
517
 
518
        if (usePrice && prc != null) {
519
            mvtStockQuery += ",\"PRICE\"";
520
        }
521
 
522
        mvtStockQuery += ") VALUES(" + qteFinal + ",'" + dateFormat.format(time) + "'," + item.getArticle().getID() + "," + item.stock.getID() + ",'" + label + "'," + reel
523
                + ", (SELECT (MAX(\"ORDRE\")+1) FROM " + mvtStockTableQuoted + ")";
524
        if (usePrice && prc != null) {
525
            mvtStockQuery += "," + prc.setScale(6, RoundingMode.HALF_UP).toString();
526
        }
527
        mvtStockQuery += ")";
528
        return mvtStockQuery;
529
    }
530
 
57 ilm 531
    @Override
532
    protected String createCode() {
156 ilm 533
        return createCodeOfPackage() + ".transaction";
57 ilm 534
    }
18 ilm 535
}