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.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;
19
import org.openconcerto.erp.core.supplychain.order.component.CommandeSQLComponent;
156 ilm 20
import org.openconcerto.erp.core.supplychain.order.ui.CommandeItemTable;
41 ilm 21
import org.openconcerto.erp.core.supplychain.supplier.component.MouvementStockSQLComponent;
142 ilm 22
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
18 ilm 23
import org.openconcerto.sql.Configuration;
24
import org.openconcerto.sql.element.SQLComponent;
25
import org.openconcerto.sql.element.SQLElement;
73 ilm 26
import org.openconcerto.sql.element.TreesOfSQLRows;
19 ilm 27
import org.openconcerto.sql.model.SQLBackgroundTableCache;
18 ilm 28
import org.openconcerto.sql.model.SQLBase;
19 ilm 29
import org.openconcerto.sql.model.SQLInjector;
18 ilm 30
import org.openconcerto.sql.model.SQLRow;
19 ilm 31
import org.openconcerto.sql.model.SQLRowListRSH;
18 ilm 32
import org.openconcerto.sql.model.SQLRowValues;
19 ilm 33
import org.openconcerto.sql.model.SQLSelect;
18 ilm 34
import org.openconcerto.sql.model.SQLTable;
19 ilm 35
import org.openconcerto.sql.model.Where;
61 ilm 36
import org.openconcerto.sql.preferences.SQLPreferences;
132 ilm 37
import org.openconcerto.sql.request.ListSQLRequest;
19 ilm 38
import org.openconcerto.sql.users.UserManager;
18 ilm 39
import org.openconcerto.sql.view.EditFrame;
40
import org.openconcerto.sql.view.EditPanel;
19 ilm 41
import org.openconcerto.sql.view.EditPanel.EditMode;
42
import org.openconcerto.sql.view.list.RowValuesTableModel;
73 ilm 43
import org.openconcerto.ui.FrameUtil;
83 ilm 44
import org.openconcerto.utils.ListMap;
18 ilm 45
 
73 ilm 46
import java.math.BigDecimal;
18 ilm 47
import java.sql.SQLException;
48
import java.util.ArrayList;
83 ilm 49
import java.util.Collection;
18 ilm 50
import java.util.List;
83 ilm 51
import java.util.Map.Entry;
18 ilm 52
 
19 ilm 53
import javax.swing.SwingUtilities;
18 ilm 54
 
55
public class MouvementStockSQLElement extends ComptaSQLConfElement {
56
 
57
    public MouvementStockSQLElement() {
58
        super("MOUVEMENT_STOCK", "un mouvement de stock", "mouvements de stock");
59
    }
60
 
156 ilm 61
    @Override
62
    public ListMap<String, String> getShowAs() {
63
        ListMap<String, String> map = new ListMap<String, String>();
64
        map.putCollection("ID_STOCK", "ID_DEPOT_STOCK");
65
        return map;
66
    }
67
 
18 ilm 68
    protected List<String> getListFields() {
69
        final List<String> l = new ArrayList<String>();
156 ilm 70
        l.add("ID_STOCK");
18 ilm 71
        l.add("DATE");
72
        l.add("NOM");
73
        l.add("ID_ARTICLE");
74
        l.add("QTE");
83 ilm 75
        l.add("REEL");
18 ilm 76
        return l;
77
    }
78
 
79
    protected List<String> getComboFields() {
80
        final List<String> l = new ArrayList<String>();
81
        l.add("NOM");
82
        l.add("QTE");
83
        return l;
84
    }
85
 
86
    /*
87
     * (non-Javadoc)
88
     *
89
     * @see org.openconcerto.devis.SQLElement#getComponent()
90
     */
91
    public SQLComponent createComponent() {
41 ilm 92
        return new MouvementStockSQLComponent(this);
18 ilm 93
    }
94
 
95
    @Override
73 ilm 96
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
97
        super.archive(trees, cutLinks);
83 ilm 98
        updateStock(trees.getRows(), true);
99
 
73 ilm 100
    }
101
 
61 ilm 102
    /**
18 ilm 103
     * Mise à jour des stocks ajoute la quantité si archive est à false
104
     *
105
     * @param id mouvement stock
106
     * @param archive
156 ilm 107
     * @throws SQLException
18 ilm 108
     */
156 ilm 109
    public ListMap<SQLRow, SQLRowValues> updateStock(Collection<SQLRow> rowsMvt, boolean archive) throws SQLException {
73 ilm 110
        // FIXME: if (SwingUtilities.isEventDispatchThread()) {
111
        // throw new IllegalStateException("This method must be called outside of EDT");
112
        // }
83 ilm 113
        // Stock Reel : inc/dec QTE_REEL, inc/dec QTE_LIV_ATTENTE/inc/dec
114
        // QTE_RECEPT_ATTENTE
115
        // Stock Th : inc/dec QTE_TH, inc/dec QTE_LIV_ATTENTE/inc/dec
116
        // QTE_RECEPT_ATTENTE
117
 
156 ilm 118
        final ListMap<SQLRow, SQLRowValues> map = new ListMap<>();
119
        final SQLTable tableCommandeElement = Configuration.getInstance().getBase().getTable("COMMANDE_ELEMENT");
120
        final SQLElement elementStock = Configuration.getInstance().getDirectory().getElement("STOCK");
121
 
83 ilm 122
        for (SQLRow rowMvtStock : rowsMvt) {
18 ilm 123
 
132 ilm 124
            boolean retour = rowMvtStock.getString("SOURCE") == null || rowMvtStock.getString("SOURCE").startsWith("AVOIR_CLIENT");
19 ilm 125
            // Mise à jour des stocks
156 ilm 126
 
19 ilm 127
            final SQLRow rowArticle = rowMvtStock.getForeignRow("ID_ARTICLE");
73 ilm 128
 
156 ilm 129
            SQLRow rowStock = rowMvtStock.getForeignRow(("ID_STOCK"));
130
            if (rowStock == null || rowStock.isUndefined()) {
131
                rowStock = rowArticle.getForeign("ID_STOCK");
132
            }
133
 
83 ilm 134
            if (rowMvtStock.getBoolean("REEL")) {
135
                float qte = rowStock.getFloat("QTE_REEL");
136
                float qteMvt = rowMvtStock.getFloat("QTE");
18 ilm 137
 
156 ilm 138
                SQLRowValues rowVals = new SQLRowValues(elementStock.getTable());
18 ilm 139
 
83 ilm 140
                float qteNvlle;
141
                float qteNvlleEnAttenteRecept = rowStock.getFloat("QTE_RECEPT_ATTENTE");
142
                float qteNvlleEnAttenteExp = rowStock.getFloat("QTE_LIV_ATTENTE");
143
                if (archive) {
144
                    qteNvlle = qte - qteMvt;
132 ilm 145
                    if (!retour) {
146
                        // Réception
147
                        if (qteMvt > 0) {
148
                            qteNvlleEnAttenteRecept += qteMvt;
149
                        } else {
150
                            // Livraison
151
                            qteNvlleEnAttenteExp -= qteMvt;
152
                        }
83 ilm 153
                    }
154
                } else {
155
                    qteNvlle = qte + qteMvt;
132 ilm 156
                    if (!retour) {
157
                        // Réception
158
                        if (qteMvt > 0) {
159
                            qteNvlleEnAttenteRecept -= qteMvt;
160
                        } else {
161
                            // Livraison
162
                            qteNvlleEnAttenteExp += qteMvt;
163
                        }
83 ilm 164
                    }
165
                }
166
                rowVals.put("QTE_REEL", qteNvlle);
167
                rowVals.put("QTE_RECEPT_ATTENTE", qteNvlleEnAttenteRecept);
168
                rowVals.put("QTE_LIV_ATTENTE", qteNvlleEnAttenteExp);
18 ilm 169
 
83 ilm 170
                try {
156 ilm 171
                    rowVals.update(rowStock.getID());
18 ilm 172
 
156 ilm 173
                    SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
174
                    boolean gestionStockMin = prefs.getBoolean(GestionArticleGlobalPreferencePanel.WARNING_STOCK_MIN, true);
175
 
176
                    if (!archive && gestionStockMin && rowStock.getObject("QTE_MIN") != null && qteNvlle < rowStock.getFloat("QTE_MIN")) {
177
                        // final float qteShow = qteNvlle;
178
                        SQLInjector inj = SQLInjector.getInjector(rowArticle.getTable(), tableCommandeElement);
179
                        SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(rowArticle));
180
                        rowValsElt.put("ID_STYLE", 2);
181
                        final SQLRow unite = rowArticle.getForeign("ID_UNITE_VENTE");
182
                        final float qteElt = rowStock.getFloat("QTE_MIN") - qteNvlle;
183
                        if (unite.isUndefined() || unite.getBoolean("A_LA_PIECE")) {
184
                            rowValsElt.put("QTE", Math.round(qteElt));
185
                            rowValsElt.put("QTE_UNITAIRE", BigDecimal.ONE);
186
                        } else {
187
                            rowValsElt.put("QTE", 1);
188
                            rowValsElt.put("QTE_UNITAIRE", new BigDecimal(qteElt));
83 ilm 189
                        }
156 ilm 190
                        rowValsElt.put("ID_TAXE", rowValsElt.getObject("ID_TAXE"));
191
                        rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * qteElt);
192
                        rowValsElt.put("T_PA_HT", rowValsElt.getLong("PA_HT") * qteElt);
193
                        rowValsElt.put("T_PA_TTC", rowValsElt.getLong("T_PA_HT") * (rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0));
194
                        map.add(rowArticle.getForeignRow("ID_FOURNISSEUR"), rowValsElt);
83 ilm 195
                    }
196
                } catch (SQLException e) {
156 ilm 197
                    throw new SQLException("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"), e);
83 ilm 198
                }
199
            } else {
200
                float qte = rowStock.getFloat("QTE_TH");
201
                float qteMvt = rowMvtStock.getFloat("QTE");
19 ilm 202
 
156 ilm 203
                SQLRowValues rowVals = new SQLRowValues(elementStock.getTable());
18 ilm 204
 
83 ilm 205
                float qteNvlle;
206
                float qteNvlleEnAttenteRecept = rowStock.getFloat("QTE_RECEPT_ATTENTE");
207
                float qteNvlleEnAttenteExp = rowStock.getFloat("QTE_LIV_ATTENTE");
208
 
209
                if (archive) {
210
                    qteNvlle = qte - qteMvt;
132 ilm 211
                    if (!retour) {
212
 
213
                        // CommandeF
214
                        if (qteMvt > 0) {
215
                            qteNvlleEnAttenteRecept -= qteMvt;
216
                        } else {
217
                            // CommanceC
218
                            qteNvlleEnAttenteExp += qteMvt;
219
                        }
83 ilm 220
                    }
73 ilm 221
                } else {
83 ilm 222
                    qteNvlle = qte + qteMvt;
132 ilm 223
                    if (!retour) {
224
 
225
                        // CommandeF
226
                        if (qteMvt > 0) {
227
                            qteNvlleEnAttenteRecept += qteMvt;
228
                        } else {
229
                            // CommanceC
230
                            qteNvlleEnAttenteExp -= qteMvt;
231
                        }
83 ilm 232
                    }
73 ilm 233
                }
83 ilm 234
                rowVals.put("QTE_TH", qteNvlle);
235
                rowVals.put("QTE_RECEPT_ATTENTE", qteNvlleEnAttenteRecept);
236
                rowVals.put("QTE_LIV_ATTENTE", qteNvlleEnAttenteExp);
237
                try {
156 ilm 238
                    rowVals.update(rowStock.getID());
83 ilm 239
                } catch (SQLException e) {
156 ilm 240
                    throw new SQLException("Erreur lors de la mise à jour du stock pour l'article " + rowArticle.getString("CODE"), e);
83 ilm 241
                }
19 ilm 242
            }
73 ilm 243
 
18 ilm 244
        }
19 ilm 245
        return map;
18 ilm 246
    }
247
 
83 ilm 248
    public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise) {
142 ilm 249
        createCommandeF(col, rowDevise, "", true);
67 ilm 250
    }
19 ilm 251
 
142 ilm 252
    public static void createCommandeF(final ListMap<SQLRow, SQLRowValues> col, final SQLRow rowDevise, final String ref, final boolean useCommandeEnCours) {
73 ilm 253
        if (SwingUtilities.isEventDispatchThread()) {
254
            throw new IllegalStateException("This method must be called outside of EDT");
255
        }
83 ilm 256
        if (col.size() > 0) {
19 ilm 257
 
73 ilm 258
            final SQLElement commande = Configuration.getInstance().getDirectory().getElement("COMMANDE");
83 ilm 259
            for (final Entry<SQLRow, List<SQLRowValues>> e : col.entrySet()) {
260
                final SQLRow fournisseur = e.getKey();
73 ilm 261
                // On regarde si il existe une commande en cours existante
262
                final SQLSelect sel = new SQLSelect();
263
                sel.addSelectStar(commande.getTable());
264
                Where w = new Where(commande.getTable().getField("EN_COURS"), "=", Boolean.TRUE);
265
                w = w.and(new Where(commande.getTable().getField("ID_FOURNISSEUR"), "=", fournisseur.getID()));
266
                sel.setWhere(w);
19 ilm 267
 
142 ilm 268
                final List<SQLRow> rowsCmd = !useCommandeEnCours ? null
269
                        : (List<SQLRow>) Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), SQLRowListRSH.createFromSelect(sel));
19 ilm 270
 
73 ilm 271
                SwingUtilities.invokeLater(new Runnable() {
272
 
273
                    @Override
274
                    public void run() {
19 ilm 275
                        SQLRow commandeExistante = null;
276
                        if (rowsCmd != null && rowsCmd.size() > 0) {
277
                            commandeExistante = rowsCmd.get(0);
278
                        }
279
                        EditFrame frame;
280
                        CommandeSQLComponent cmp;
281
 
282
                        if (commandeExistante != null) {
283
                            frame = new EditFrame(commande, EditMode.MODIFICATION);
284
                            cmp = (CommandeSQLComponent) frame.getSQLComponent();
285
                            cmp.select(commandeExistante);
286
                        } else {
287
                            frame = new EditFrame(commande);
288
                            cmp = (CommandeSQLComponent) frame.getSQLComponent();
41 ilm 289
                            final SQLRowValues rowVals = new SQLRowValues(commande.getTable());
290
                            final SQLElement eltComm = Configuration.getInstance().getDirectory().getElement("COMMERCIAL");
19 ilm 291
                            int idUser = UserManager.getInstance().getCurrentUser().getId();
292
                            SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
293
 
294
                            if (rowsComm != null) {
295
                                rowVals.put("ID_COMMERCIAL", rowsComm.getID());
296
                            }
132 ilm 297
                            if (fournisseur != null && !fournisseur.isUndefined()) {
298
                                rowVals.put("ID_FOURNISSEUR", fournisseur.getID());
299
                            }
19 ilm 300
                            if (rowDevise != null) {
301
                                rowVals.put("ID_DEVISE", rowDevise.getID());
302
                            }
67 ilm 303
                            if (commande.getTable().contains("ID_ADRESSE")) {
304
                                rowVals.put("ID_ADRESSE", null);
305
                            }
306
                            rowVals.put("NOM", ref);
19 ilm 307
                            cmp.select(rowVals);
73 ilm 308
                            cmp.getRowValuesTable().getRowValuesTableModel().clearRows();
19 ilm 309
                        }
310
 
156 ilm 311
                        CommandeItemTable itemTable = cmp.getRowValuesTablePanel();
312
 
73 ilm 313
                        final RowValuesTableModel model = cmp.getRowValuesTable().getRowValuesTableModel();
83 ilm 314
                        for (SQLRowValues rowValsElt : e.getValue()) {
19 ilm 315
                            SQLRowValues rowValsMatch = null;
316
                            int index = 0;
317
 
318
                            for (int i = 0; i < model.getRowCount(); i++) {
41 ilm 319
                                final SQLRowValues rowValsCmdElt = model.getRowValuesAt(i);
19 ilm 320
                                if (ReferenceArticleSQLElement.isReferenceEquals(rowValsCmdElt, rowValsElt)) {
321
                                    rowValsMatch = rowValsCmdElt;
322
                                    index = i;
323
                                    break;
324
                                }
325
                            }
326
                            if (rowValsMatch != null) {
41 ilm 327
                                final int qte = rowValsMatch.getInt("QTE");
19 ilm 328
                                model.putValue(qte + rowValsElt.getInt("QTE"), index, "QTE");
329
                            } else {
330
                                model.addRow(rowValsElt);
156 ilm 331
                                if (rowValsElt.getObject("ID_ARTICLE") != null && !rowValsElt.isForeignEmpty("ID_ARTICLE")) {
332
                                    Object o = itemTable.tarifCompletion(rowValsElt.getForeign("ID_ARTICLE").asRow(), "PRIX_METRIQUE_HA_1");
333
                                    if (o != null) {
334
                                        model.putValue(o, model.getRowCount() - 1, "PRIX_METRIQUE_HA_1");
335
                                    }
336
                                }
19 ilm 337
                            }
338
                        }
339
 
340
                        frame.pack();
73 ilm 341
                        FrameUtil.show(frame);
342
 
19 ilm 343
                    }
73 ilm 344
                });
345
 
346
            }
347
 
19 ilm 348
        }
349
 
350
    }
351
 
132 ilm 352
    @Override
353
    protected void _initListRequest(ListSQLRequest req) {
354
        super._initListRequest(req);
355
        req.addToGraphToFetch("SOURCE", "IDSOURCE");
356
    }
357
 
73 ilm 358
    public static final void showSource(final int id) {
359
        if (!SwingUtilities.isEventDispatchThread()) {
360
            throw new IllegalStateException("This method must be called from EDT");
361
        }
18 ilm 362
        if (id != 1) {
73 ilm 363
            final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
364
            final SQLTable tableMvt = base.getTable("MOUVEMENT_STOCK");
365
            final String stringTableSource = tableMvt.getRow(id).getString("SOURCE");
366
            SwingUtilities.invokeLater(new Runnable() {
367
                public void run() {
368
 
369
                    final EditFrame f;
370
                    // Si une source est associée on l'affiche en readonly
371
                    if (stringTableSource.trim().length() != 0 && tableMvt.getRow(id).getInt("IDSOURCE") != 1) {
372
                        f = new EditFrame(Configuration.getInstance().getDirectory().getElement(stringTableSource), EditPanel.READONLY);
373
                        f.selectionId(tableMvt.getRow(id).getInt("IDSOURCE"));
374
                    } else {
375
                        // Sinon on affiche le mouvement de stock
376
                        f = new EditFrame(Configuration.getInstance().getDirectory().getElement(tableMvt), EditPanel.READONLY);
377
                        f.selectionId(id);
378
                    }
379
                    f.pack();
380
                    FrameUtil.show(f);
381
 
382
                }
383
            });
18 ilm 384
        } else {
385
            System.err.println("Aucun mouvement associé, impossible de modifier ou d'accéder à la source de cette ecriture!");
386
        }
387
    }
57 ilm 388
 
389
    @Override
390
    protected String createCode() {
156 ilm 391
        return createCodeOfPackage() + ".transaction";
57 ilm 392
    }
18 ilm 393
}