OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.sales.order.element;
15
 
94 ilm 16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
18
import org.openconcerto.erp.core.common.component.TransfertGroupSQLComponent;
18 ilm 19
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
94 ilm 20
import org.openconcerto.erp.core.sales.account.VenteFactureSituationSQLComponent;
21
import org.openconcerto.erp.core.sales.account.VenteFactureSoldeSQLComponent;
18 ilm 22
import org.openconcerto.erp.core.sales.order.component.CommandeClientSQLComponent;
94 ilm 23
import org.openconcerto.erp.core.sales.order.report.CommandeClientXmlSheet;
93 ilm 24
import org.openconcerto.erp.core.sales.order.ui.EtatCommandeClient;
174 ilm 25
import org.openconcerto.erp.core.sales.product.element.UniteVenteArticleSQLElement;
26
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
27
import org.openconcerto.erp.core.sales.product.model.ProductHelper;
142 ilm 28
import org.openconcerto.erp.core.sales.shipment.component.BonDeLivraisonSQLComponent;
19 ilm 29
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
156 ilm 30
import org.openconcerto.erp.core.supplychain.stock.element.StockSQLElement;
94 ilm 31
import org.openconcerto.erp.model.MouseSheetXmlListeListener;
93 ilm 32
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
18 ilm 33
import org.openconcerto.sql.Configuration;
34
import org.openconcerto.sql.element.SQLComponent;
35
import org.openconcerto.sql.element.SQLElement;
142 ilm 36
import org.openconcerto.sql.element.SQLElementLink.LinkType;
132 ilm 37
import org.openconcerto.sql.element.SQLElementLinksSetup;
90 ilm 38
import org.openconcerto.sql.element.TreesOfSQLRows;
93 ilm 39
import org.openconcerto.sql.model.ConnectionHandlerNoSetup;
40
import org.openconcerto.sql.model.SQLDataSource;
19 ilm 41
import org.openconcerto.sql.model.SQLInjector;
42
import org.openconcerto.sql.model.SQLRow;
94 ilm 43
import org.openconcerto.sql.model.SQLRowAccessor;
93 ilm 44
import org.openconcerto.sql.model.SQLRowListRSH;
19 ilm 45
import org.openconcerto.sql.model.SQLRowValues;
93 ilm 46
import org.openconcerto.sql.model.SQLRowValuesListFetcher;
83 ilm 47
import org.openconcerto.sql.model.SQLSelect;
142 ilm 48
import org.openconcerto.sql.model.SQLSelectJoin;
19 ilm 49
import org.openconcerto.sql.model.SQLTable;
83 ilm 50
import org.openconcerto.sql.model.Where;
93 ilm 51
import org.openconcerto.sql.preferences.SQLPreferences;
52
import org.openconcerto.sql.request.UpdateBuilder;
53
import org.openconcerto.sql.utils.SQLUtils;
144 ilm 54
import org.openconcerto.sql.view.EditFrame;
93 ilm 55
import org.openconcerto.sql.view.list.IListe;
56
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
94 ilm 57
import org.openconcerto.sql.view.list.RowAction;
93 ilm 58
import org.openconcerto.sql.view.list.RowAction.PredicateRowAction;
59
import org.openconcerto.sql.view.list.SQLTableModelColumn;
142 ilm 60
import org.openconcerto.sql.view.list.SQLTableModelSource;
93 ilm 61
import org.openconcerto.utils.CompareUtils;
90 ilm 62
import org.openconcerto.utils.DecimalUtils;
93 ilm 63
import org.openconcerto.utils.ExceptionHandler;
83 ilm 64
import org.openconcerto.utils.ListMap;
94 ilm 65
import org.openconcerto.utils.NumberUtils;
93 ilm 66
import org.openconcerto.utils.cc.ITransformer;
18 ilm 67
 
142 ilm 68
import java.awt.Component;
69
import java.awt.event.ActionEvent;
70
import java.io.IOException;
71
import java.math.BigDecimal;
72
import java.math.RoundingMode;
73
import java.sql.SQLException;
74
import java.util.ArrayList;
75
import java.util.Arrays;
76
import java.util.Collection;
77
import java.util.HashSet;
78
import java.util.List;
79
import java.util.Map;
80
import java.util.Set;
81
 
82
import javax.swing.AbstractAction;
83
import javax.swing.JLabel;
84
import javax.swing.JTable;
85
import javax.swing.SwingUtilities;
86
import javax.swing.table.DefaultTableCellRenderer;
87
 
88
import org.apache.commons.dbutils.ResultSetHandler;
89
import org.apache.commons.dbutils.handlers.ArrayListHandler;
90
 
18 ilm 91
public class CommandeClientSQLElement extends ComptaSQLConfElement {
92
 
93
    public CommandeClientSQLElement() {
94
        super("COMMANDE_CLIENT", "une commande client", "commandes clients");
93 ilm 95
 
96
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
97
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ORDER_PACKAGING_MANAGEMENT, true)) {
98
 
99
            for (final EtatCommandeClient etat : EtatCommandeClient.values()) {
100
 
101
                PredicateRowAction action = new PredicateRowAction(new AbstractAction(etat.getTranslation()) {
102
 
103
                    @Override
104
                    public void actionPerformed(ActionEvent e) {
105
                        changeStateOfRows(IListe.get(e).getSelectedRows(), etat);
106
                    }
107
                }, false);
108
                action.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
109
                action.setPath(Arrays.asList("Etat", "Etat", "Etat"));
110
                getRowActions().add(action);
111
            }
112
 
113
            PredicateRowAction actionTransfertBL = new PredicateRowAction(new AbstractAction("Transfert automatique vers BL") {
114
 
115
                @Override
116
                public void actionPerformed(ActionEvent e) {
117
                    TransfertCommandeAutoUtils transfert = new TransfertCommandeAutoUtils(getTable());
118
                    transfert.transfertMultiBL(IListe.get(e).getSelectedRows());
119
                }
120
            }, false);
121
            actionTransfertBL.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
122
            getRowActions().add(actionTransfertBL);
123
 
124
            PredicateRowAction actionStock = new PredicateRowAction(new AbstractAction("Vérification des stocks") {
125
 
126
                @Override
127
                public void actionPerformed(ActionEvent e) {
128
                    new Thread("Check Commande To Ship") {
129
                        public void run() {
130
                            try {
131
                                checkCommandeToShip();
132
                            } catch (Exception e) {
133
                                ExceptionHandler.handle("Erreur pendant la vérification du statut des commandes", e);
134
                            }
135
                        }
136
                    }.start();
137
                }
138
 
139
            }, false);
140
            actionStock.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
141
            getRowActions().add(actionStock);
142
 
143
            PredicateRowAction actionFacture = new PredicateRowAction(new AbstractAction("Transfert automatique en facture") {
144
 
145
                @Override
146
                public void actionPerformed(ActionEvent e) {
147
                    TransfertCommandeAutoUtils transfert = new TransfertCommandeAutoUtils(getTable());
148
                    transfert.transfertFacture(IListe.get(e).getSelectedRows());
149
                }
150
            }, false);
151
            actionFacture.setPredicate(IListeEvent.getNonEmptySelectionPredicate());
152
            getRowActions().add(actionFacture);
153
 
154
        }
94 ilm 155
 
156
        final List<RowAction> allowedActions = new ArrayList<RowAction>();
157
        // Transfert vers facture
158
        PredicateRowAction bonAction = new PredicateRowAction(new AbstractAction() {
159
            public void actionPerformed(ActionEvent e) {
160
                transfertBonLivraisonClient(IListe.get(e).getSelectedRows());
161
            }
151 ilm 162
        }, true, "sales.order.create.deliverynote");
94 ilm 163
 
164
        // Transfert vers facture
165
        RowAction factureAction = new RowAction(new AbstractAction() {
166
            public void actionPerformed(ActionEvent e) {
167
                transfertFactureClient(IListe.get(e).getSelectedRows());
168
            }
151 ilm 169
        }, true, "sales.order.create.invoice") {
94 ilm 170
 
171
            @Override
172
            public boolean enabledFor(List<SQLRowValues> selection) {
173
                if (selection.isEmpty()) {
174
                    return false;
175
                } else if (selection.size() > 1) {
176
                    return true;
177
                } else {
178
                    BigDecimal d = getAvancement(selection.get(0));
179
                    return d.signum() == 0;
180
                }
181
            }
182
        };
183
 
184
        // Transfert vers facture intermédiaire
185
        RowAction acompteAction = new RowAction(new AbstractAction("Créer une facture intermédiaire") {
186
            public void actionPerformed(ActionEvent e) {
187
                transfertAcompteClient(IListe.get(e).getSelectedRows());
188
            }
189
        }, false, "sales.order.create.account") {
190
            BigDecimal cent = BigDecimal.ONE.movePointRight(2);
191
 
192
            @Override
193
            public boolean enabledFor(List<SQLRowValues> selection) {
194
                if (selection.isEmpty() || selection.size() > 1) {
195
                    return false;
196
                } else {
197
                    BigDecimal d = getAvancement(selection.get(0));
198
                    return NumberUtils.compare(d, cent) != 0;
199
                }
200
            }
201
        };
202
 
203
        // Transfert vers facture solde
204
        RowAction soldeAction = new RowAction(new AbstractAction("Facturer le solde") {
205
            public void actionPerformed(ActionEvent e) {
206
                transfertSoldeClient(IListe.get(e).getSelectedRows());
207
            }
208
        }, false, "sales.order.create.account.solde") {
209
            BigDecimal cent = BigDecimal.ONE.movePointRight(2);
210
 
211
            @Override
212
            public boolean enabledFor(List<SQLRowValues> selection) {
213
                if (selection.isEmpty() || selection.size() > 1) {
214
                    return false;
215
                } else {
216
                    BigDecimal d = getAvancement(selection.get(0));
217
                    return NumberUtils.compare(d, cent) != 0 && NumberUtils.compare(d, BigDecimal.ZERO) != 0;
218
                }
219
            }
220
        };
221
 
222
        // Transfert vers commande
223
        PredicateRowAction cmdAction = new PredicateRowAction(new AbstractAction() {
224
            public void actionPerformed(ActionEvent e) {
225
                final int selectedId = IListe.get(e).getSelectedId();
226
                ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
227
 
228
                    @Override
229
                    public void run() {
230
                        final CommandeClientSQLElement elt = (CommandeClientSQLElement) Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
142 ilm 231
                        elt.transfertCommande(selectedId, true);
94 ilm 232
 
233
                    }
234
                });
235
 
236
            }
237
 
238
        }, false, "sales.order.create.supplier.order");
239
 
240
        cmdAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
241
 
242
        bonAction.setPredicate(IListeEvent.getSingleSelectionPredicate());
243
 
244
        MouseSheetXmlListeListener mouseSheetXmlListeListener = new MouseSheetXmlListeListener(CommandeClientXmlSheet.class);
245
        mouseSheetXmlListeListener.setGenerateHeader(true);
246
        mouseSheetXmlListeListener.setShowHeader(true);
247
 
248
        allowedActions.add(bonAction);
249
        allowedActions.add(factureAction);
250
        allowedActions.add(acompteAction);
251
        allowedActions.add(soldeAction);
252
        allowedActions.add(cmdAction);
253
        allowedActions.addAll(mouseSheetXmlListeListener.getRowActions());
254
        getRowActions().addAll(allowedActions);
18 ilm 255
    }
256
 
132 ilm 257
    @Override
258
    protected void setupLinks(SQLElementLinksSetup links) {
259
        super.setupLinks(links);
260
        if (getTable().contains("ID_ADRESSE")) {
261
            links.get("ID_ADRESSE").setType(LinkType.ASSOCIATION);
262
        }
142 ilm 263
        if (getTable().contains("ID_ADRESSE_FACT")) {
264
            links.get("ID_ADRESSE_FACT").setType(LinkType.ASSOCIATION);
265
        }
132 ilm 266
        if (getTable().contains("ID_ADRESSE_LIVRAISON")) {
267
            links.get("ID_ADRESSE_LIVRAISON").setType(LinkType.ASSOCIATION);
268
        }
269
    }
270
 
93 ilm 271
    public SQLRow getNextCommandeToPrepare() {
272
        final SQLTable tableCmd = getTable();
273
        SQLSelect sel = new SQLSelect();
274
        sel.addSelect(tableCmd.getKey());
275
        sel.addSelect(tableCmd.getField("NUMERO"));
276
        sel.addSelect(tableCmd.getField("DATE"));
277
        sel.addSelect(tableCmd.getField("T_HT"));
278
        sel.addSelect(tableCmd.getField("T_TVA"));
279
        sel.addSelect(tableCmd.getField("T_TTC"));
280
        sel.addSelect(tableCmd.getField("PORT_HT"));
281
        sel.addSelect(tableCmd.getField("REMISE_HT"));
282
        sel.addSelect(tableCmd.getField("ID_TAXE_PORT"));
283
        sel.addSelect(tableCmd.getField("ID_CLIENT"));
284
        Where w = new Where(tableCmd.getField("ETAT_COMMANDE"), "=", EtatCommandeClient.A_PREPARER.getId());
285
        sel.setWhere(w);
286
        sel.clearOrder();
287
        sel.addFieldOrder(sel.getAlias(tableCmd.getField("DATE")));
288
        sel.addFieldOrder(sel.getAlias(tableCmd.getField("T_HT")));
289
 
290
        List<SQLRow> result = SQLRowListRSH.execute(sel);
291
        if (result == null || result.size() == 0) {
292
            return null;
293
        } else {
294
            return result.get(0);
295
        }
296
    }
297
 
298
    public int getNbCommandeAPreparer() {
299
        final SQLTable tableCmd = getTable();
300
        SQLSelect sel = new SQLSelect();
301
        sel.addSelect(tableCmd.getKey(), "COUNT");
302
        Where w = new Where(tableCmd.getField("ETAT_COMMANDE"), "=", EtatCommandeClient.A_PREPARER.getId());
303
        sel.setWhere(w);
304
 
305
        Object r = getTable().getDBSystemRoot().getDataSource().executeScalar(sel.asString());
306
        int nb = 0;
307
        if (r != null) {
308
            nb = ((Number) r).intValue();
309
        }
310
        return nb;
311
    }
312
 
313
    public void checkCommandeToShip() throws Exception {
314
        assert !SwingUtilities.isEventDispatchThread();
315
 
316
        SQLUtils.executeAtomic(getTable().getDBSystemRoot().getDataSource(), new ConnectionHandlerNoSetup<Object, IOException>() {
317
            @Override
318
            public Object handle(final SQLDataSource ds) throws SQLException, IOException {
319
                final SQLTable tableCmd = getTable();
320
 
321
                SQLRowValues rowVals = new SQLRowValues(tableCmd);
322
                rowVals.put(tableCmd.getKey().getName(), null);
323
                rowVals.put("NUMERO", null);
324
 
325
                final SQLTable tableCmdElt = tableCmd.getTable("COMMANDE_CLIENT_ELEMENT");
326
                SQLRowValues rowValsElt = new SQLRowValues(tableCmdElt);
327
                rowValsElt.put("QTE", null);
156 ilm 328
                rowValsElt.put("ID_DEPOT_STOCK", null);
93 ilm 329
                rowValsElt.put("QTE_UNITAIRE", null);
330
                rowValsElt.put("ID_COMMANDE_CLIENT", rowVals);
331
 
332
                SQLRowValues rowValsArt = new SQLRowValues(tableCmd.getTable("ARTICLE"));
156 ilm 333
                SQLRowValues rowValsStock = new SQLRowValues(tableCmd.getTable("STOCK"));
334
                rowValsStock.putNulls("QTE_REEL", "QTE_TH");
335
                rowValsStock.put("ID_DEPOT_STOCK", null);
336
                rowValsStock.put("ID_ARTICLE", rowValsArt);
337
                rowValsArt.put("ID_DEPOT_STOCK", null);
93 ilm 338
                rowValsElt.put("ID_ARTICLE", rowValsArt);
339
 
340
                SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
341
                fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
342
 
343
                    @Override
344
                    public SQLSelect transformChecked(SQLSelect input) {
345
                        Where w = new Where(input.getAlias(tableCmd).getField("ETAT_COMMANDE"), "=", EtatCommandeClient.A_PREPARER.getId());
346
                        w = w.or(new Where(input.getAlias(tableCmd).getField("ETAT_COMMANDE"), "=", EtatCommandeClient.RUPTURE.getId()));
347
                        input.setWhere(w);
348
                        // ORDER BY ETAT COMMANDE et T_HT pour mettre en priorité les ruptures de
349
                        // stock et les commandes les plus chers
350
                        input.clearOrder();
351
                        input.addFieldOrder(input.getAlias(tableCmd.getField("ETAT_COMMANDE")));
352
                        input.addFieldOrder(input.getAlias(tableCmd.getField("T_HT")));
353
                        System.err.println(input.asString());
354
                        return input;
355
                    }
356
                });
357
 
358
                List<SQLRowValues> result = fetcher.fetch();
359
                List<Integer> cmdStockOK = new ArrayList<Integer>();
360
                List<Integer> cmdNoStock = new ArrayList<Integer>();
361
 
362
                // Stock utilisé par les commandes à préparer
363
                StockCommande stockGlobalUsed = new StockCommande();
364
                for (int i = result.size() - 1; i >= 0; i--) {
365
                    SQLRowValues sqlRowValues = result.get(i);
366
                    boolean inStock = true;
367
 
368
                    // Stock utilisé par la commande actuelle
369
                    StockCommande stockCmd = new StockCommande();
370
                    for (SQLRowValues item : sqlRowValues.getReferentRows(tableCmdElt)) {
371
 
156 ilm 372
                        if (item.getObject("ID_ARTICLE") != null && !item.isForeignEmpty("ID_ARTICLE")) {
373
                            final int foreignID = item.getForeignID("ID_ARTICLE");
93 ilm 374
 
156 ilm 375
                            // Stock = stock actuel dans la base - stock utilisé par les commandes
376
                            // déja testées -
377
                            // stock utilisé par la commande en cours (si 2 fois le meme article)
378
                            BigDecimal stock = BigDecimal.ZERO;
379
                            SQLRowAccessor rowStock = StockSQLElement.getStockFetched(item);
380
                            if (rowStock != null) {
381
                                stock = new BigDecimal(rowStock.getFloat("QTE_REEL"));
382
                            }
383
                            stock = stock.subtract(stockCmd.getQty(foreignID)).subtract(stockGlobalUsed.getQty(foreignID));
93 ilm 384
 
156 ilm 385
                            BigDecimal needQty = item.getBigDecimal("QTE_UNITAIRE").multiply(new BigDecimal(item.getInt("QTE")), DecimalUtils.HIGH_PRECISION);
93 ilm 386
 
156 ilm 387
                            stockCmd.addQty(foreignID, needQty);
93 ilm 388
 
156 ilm 389
                            inStock = CompareUtils.compare(stock, needQty) >= 0;
390
 
391
                            if (!inStock) {
392
                                break;
393
                            }
93 ilm 394
                        }
395
                    }
396
 
397
                    if (inStock) {
398
                        Map<Integer, BigDecimal> m = stockCmd.getMap();
399
                        for (Integer id : m.keySet()) {
400
                            stockGlobalUsed.addQty(id, m.get(id));
401
                        }
402
 
403
                        cmdStockOK.add(sqlRowValues.getID());
404
                    } else {
405
                        cmdNoStock.add(sqlRowValues.getID());
406
                    }
407
                }
408
 
409
                List<String> reqs = new ArrayList<String>(2);
410
 
411
                if (cmdStockOK.size() > 0) {
412
                    UpdateBuilder builderStockOK = new UpdateBuilder(tableCmd);
413
                    builderStockOK.setObject("ETAT_COMMANDE", EtatCommandeClient.A_PREPARER.getId());
414
                    builderStockOK.setWhere(new Where(getTable().getKey(), cmdStockOK));
415
                    reqs.add(builderStockOK.asString());
416
                }
417
 
418
                if (cmdNoStock.size() > 0) {
419
                    UpdateBuilder builderNoStock = new UpdateBuilder(tableCmd);
420
                    builderNoStock.setObject("ETAT_COMMANDE", EtatCommandeClient.RUPTURE.getId());
421
                    builderNoStock.setWhere(new Where(getTable().getKey(), cmdNoStock));
422
                    reqs.add(builderNoStock.asString());
423
                }
424
 
425
                if (reqs.size() > 0) {
426
                    List<? extends ResultSetHandler> handlers = new ArrayList<ResultSetHandler>(reqs.size());
427
                    for (String s : reqs) {
428
                        handlers.add(null);
429
                    }
430
                    SQLUtils.executeMultiple(tableCmd.getDBSystemRoot(), reqs, handlers);
431
                    tableCmd.fireTableModified(-1);
432
                }
433
                return null;
434
            }
435
        });
436
 
437
    }
438
 
439
    private void changeStateOfRows(List<SQLRowValues> l, EtatCommandeClient etat) {
440
 
441
        List<Integer> ids = new ArrayList<Integer>(l.size());
442
        for (SQLRowValues sqlRowValues : l) {
443
            ids.add(sqlRowValues.getID());
444
        }
445
 
446
        UpdateBuilder builder = new UpdateBuilder(getTable());
447
        builder.setObject("ETAT_COMMANDE", etat.getId());
448
        builder.setWhere(new Where(getTable().getKey(), ids));
449
 
450
        getTable().getDBSystemRoot().getDataSource().execute(builder.asString());
451
        getTable().fireTableModified(-1);
452
    }
453
 
18 ilm 454
    /*
455
     * (non-Javadoc)
456
     *
457
     * @see org.openconcerto.devis.BaseSQLElement#getComboFields()
458
     */
459
    protected List<String> getComboFields() {
73 ilm 460
        final List<String> l = new ArrayList<String>();
18 ilm 461
        l.add("NUMERO");
462
        return l;
463
    }
464
 
465
    /*
466
     * (non-Javadoc)
467
     *
468
     * @see org.openconcerto.devis.BaseSQLElement#getListFields()
469
     */
470
    protected List<String> getListFields() {
73 ilm 471
        final List<String> l = new ArrayList<String>();
18 ilm 472
        l.add("NUMERO");
473
        l.add("DATE");
142 ilm 474
        if (getTable().contains("DATE_LIVRAISON_PREV")) {
475
            l.add("DATE_LIVRAISON_PREV");
476
        }
18 ilm 477
        l.add("ID_CLIENT");
41 ilm 478
        l.add("ID_COMMERCIAL");
18 ilm 479
        l.add("T_HT");
480
        l.add("T_TTC");
156 ilm 481
        if (getTable().getFieldsName().contains("ACOMPTE_COMMANDE")) {
482
            l.add("ACOMPTE_COMMANDE");
483
        }
18 ilm 484
        l.add("NOM");
485
        l.add("INFOS");
93 ilm 486
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
487
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ORDER_PACKAGING_MANAGEMENT, true)) {
488
            l.add("NUMERO_EXPEDITION");
489
            l.add("ETAT_COMMANDE");
490
        }
18 ilm 491
        return l;
492
    }
493
 
494
    @Override
28 ilm 495
    public Set<String> getReadOnlyFields() {
73 ilm 496
        final Set<String> s = new HashSet<String>();
28 ilm 497
        s.add("ID_DEVIS");
498
        return s;
499
    }
500
 
67 ilm 501
    @Override
90 ilm 502
    protected void archive(TreesOfSQLRows trees, boolean cutLinks) throws SQLException {
83 ilm 503
 
90 ilm 504
        for (SQLRow row : trees.getRows()) {
505
 
506
            // Mise à jour des stocks
507
            SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
508
            SQLSelect sel = new SQLSelect();
509
            sel.addSelect(eltMvtStock.getTable().getField("ID"));
510
            Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", row.getID());
511
            Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
512
            sel.setWhere(w.and(w2));
513
 
514
            @SuppressWarnings("rawtypes")
515
            List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
516
            if (l != null) {
517
                for (int i = 0; i < l.size(); i++) {
518
                    Object[] tmp = (Object[]) l.get(i);
519
                    eltMvtStock.archive(((Number) tmp[0]).intValue());
520
                }
83 ilm 521
            }
522
        }
90 ilm 523
        super.archive(trees, cutLinks);
83 ilm 524
    }
525
 
526
    @Override
142 ilm 527
    protected synchronized void _initTableSource(final SQLTableModelSource source) {
528
        super._initTableSource(source);
73 ilm 529
        // TODO: refaire un renderer pour les commandes transférées en BL
530
        // final CommandeClientRenderer rend = CommandeClientRenderer.getInstance();
531
        // final SQLTableModelColumn col = source.getColumn(getTable().getField("T_HT"));
532
        // col.setColumnInstaller(new IClosure<TableColumn>() {
533
        // @Override
534
        // public void executeChecked(TableColumn input) {
535
        // input.setCellRenderer(rend);
536
        // }
537
        // });
93 ilm 538
        source.init();
539
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
540
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ORDER_PACKAGING_MANAGEMENT, true)) {
541
 
542
            SQLTableModelColumn col = source.getColumn(getTable().getField("ETAT_COMMANDE"));
543
            if (col != null) {
544
                col.setRenderer(new DefaultTableCellRenderer() {
545
 
546
                    @Override
547
                    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
548
 
549
                        JLabel comp = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
550
                        if (value != null) {
551
                            final EtatCommandeClient fromID = EtatCommandeClient.fromID((Integer) value);
552
                            if (fromID != null) {
553
                                comp.setText(fromID.getTranslation());
554
                            } else {
555
                                comp.setText("");
556
                            }
557
                        }
558
                        return comp;
559
                    }
560
                });
561
 
562
            }
563
        }
67 ilm 564
    }
565
 
18 ilm 566
    /*
567
     * (non-Javadoc)
568
     *
569
     * @see org.openconcerto.devis.SQLElement#getComponent()
570
     */
571
    public SQLComponent createComponent() {
572
        return new CommandeClientSQLComponent();
573
    }
574
 
575
    /**
19 ilm 576
     * Transfert d'une commande en commande fournisseur
577
     *
578
     * @param commandeID
579
     */
142 ilm 580
    public void transfertCommande(int commandeID, boolean useCommandeEnCours) {
19 ilm 581
 
582
        SQLElement elt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
583
        SQLRow rowCmd = getTable().getRow(commandeID);
584
        List<SQLRow> rows = rowCmd.getReferentRows(elt.getTable());
174 ilm 585
        transfertEltToCommandeF(rows);
586
    }
73 ilm 587
 
174 ilm 588
    public void transfertEltToCommandeF(List<? extends SQLRowAccessor> rowsItems) {
589
        ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
590
 
591
            @Override
592
            public void run() {
593
                ProductHelper helper = new ProductHelper(getTable().getDBRoot());
594
                List<ProductComponent> productComp = new ArrayList<>();
595
                helper.fillProductComponent(rowsItems, productComp, 1, 0, 1);
596
 
597
                List<ProductComponent> leafItems = helper.getChildWithQtyFrom(productComp);
598
 
599
                final ListMap<SQLRow, SQLRowValues> map = new ListMap<SQLRow, SQLRowValues>();
600
                final Set<Integer> stockChecked = new HashSet<Integer>();
601
                for (ProductComponent comp : leafItems) {
602
                    SQLRowAccessor rowArticleFind = comp.getProduct();
603
 
604
                    SQLRow row = rowArticleFind.asRow();
605
                    SQLRowAccessor rowStock = comp.getStock();
606
                    int value = 0;
607
                    if (row.getBoolean("GESTION_STOCK") && !stockChecked.contains(rowStock.getID())) {
608
                        stockChecked.add(rowStock.getID());
609
 
610
                        value = -Math.round(rowStock.getFloat("QTE_TH") - rowStock.getFloat("QTE_MIN"));
611
                    } else if (!row.getBoolean("GESTION_STOCK")) {
612
                        value = comp.getQty().intValue();
613
                    }
614
                    if (value > 0) {
615
 
616
                        SQLInjector inj = SQLInjector.getInjector(row.getTable(), row.getTable().getTable("COMMANDE_ELEMENT"));
617
                        SQLRowValues rowValsElt = new SQLRowValues(inj.createRowValuesFrom(row));
618
 
619
                        int qte = 1;
620
                        BigDecimal qteUV = BigDecimal.ONE;
621
 
622
                        if (row.getObject("ID_UNITE_VENTE") != null && row.getForeignID("ID_UNITE_VENTE") != UniteVenteArticleSQLElement.A_LA_PIECE) {
623
                            qteUV = comp.getQty();
624
                        } else {
625
                            qte = comp.getQty().setScale(0, RoundingMode.HALF_UP).intValue();
626
                        }
627
 
628
                        rowValsElt.put("QTE", qte);
629
                        rowValsElt.put("QTE_UNITAIRE", qteUV);
630
 
631
                        rowValsElt.put("T_POIDS", rowValsElt.getLong("POIDS") * rowValsElt.getInt("QTE"));
632
                        rowValsElt.put("T_PA_HT", ((BigDecimal) rowValsElt.getObject("PA_HT")).multiply(new BigDecimal(rowValsElt.getInt("QTE")), DecimalUtils.HIGH_PRECISION));
633
                        rowValsElt.put("T_PA_TTC", ((BigDecimal) rowValsElt.getObject("T_PA_HT")).multiply(new BigDecimal((rowValsElt.getForeign("ID_TAXE").getFloat("TAUX") / 100.0 + 1.0)),
634
                                DecimalUtils.HIGH_PRECISION));
635
                        // rowValsElt.put("ID_DEVISE",
636
                        // rowCmd.getForeignRow("ID_TARIF").getForeignID("ID_DEVISE"));
637
                        map.add(rowArticleFind.getForeign("ID_FOURNISSEUR").asRow(), rowValsElt);
638
                    }
639
 
156 ilm 640
                }
174 ilm 641
                MouvementStockSQLElement.createCommandeF(map, null, "");
132 ilm 642
            }
174 ilm 643
        });
19 ilm 644
    }
94 ilm 645
 
646
    /**
647
     * Transfert en BL
648
     *
649
     * @param row
650
     */
142 ilm 651
    public void transfertBonLivraisonClient(final List<SQLRowValues> rows) {
652
        BonDeLivraisonSQLComponent comp = (BonDeLivraisonSQLComponent) TransfertBaseSQLComponent.openTransfertFrame(rows, "BON_DE_LIVRAISON").getSQLComponent();
653
        final SQLTable tableElt = comp.getElement().getTable().getTable("BON_DE_LIVRAISON_ELEMENT");
654
        SQLRowValues rowVals = new SQLRowValues(tableElt);
655
        rowVals.put("QTE_UNITAIRE", null);
656
        rowVals.put("QTE", null);
657
        rowVals.put("QTE_LIVREE", null);
658
        rowVals.put("ID_ARTICLE", null);
156 ilm 659
        rowVals.put("PV_HT", null);
660
        rowVals.put("ID_COMMANDE_CLIENT_ELEMENT", null);
142 ilm 661
 
662
        SQLRowValuesListFetcher fetcher = SQLRowValuesListFetcher.create(rowVals);
663
        fetcher.setSelTransf(new ITransformer<SQLSelect, SQLSelect>() {
664
 
665
            @Override
666
            public SQLSelect transformChecked(SQLSelect input) {
667
                List<Integer> ids = new ArrayList<Integer>(rows.size());
668
                for (SQLRowValues sqlRowValues : rows) {
669
                    ids.add(sqlRowValues.getID());
670
                }
671
                SQLSelectJoin joinBR = input.addJoin("RIGHT", tableElt.getTable("BON_DE_LIVRAISON_ELEMENT").getField("ID_BON_DE_LIVRAISON"));
672
                SQLSelectJoin joinTR = input.addBackwardJoin("RIGHT", tableElt.getTable("TR_COMMANDE_CLIENT").getField("ID_BON_DE_LIVRAISON"), joinBR.getJoinedTable().getAlias());
673
                joinTR.setWhere(new Where(joinTR.getJoinedTable().getField("ID_COMMANDE_CLIENT"), ids));
674
                System.err.println(input.asString());
675
                return input;
676
            }
677
        });
156 ilm 678
        comp.loadQuantity(fetcher.fetch(), "COMMANDE_CLIENT_ELEMENT");
142 ilm 679
 
94 ilm 680
    }
681
 
682
    /**
683
     * Transfert en Facture
684
     *
685
     * @param row
686
     */
144 ilm 687
    public EditFrame transfertFactureClient(List<SQLRowValues> rows) {
688
        return TransfertBaseSQLComponent.openTransfertFrame(rows, "SAISIE_VENTE_FACTURE");
94 ilm 689
 
690
    }
691
 
692
    /**
693
     * Transfert en Facture
694
     *
695
     * @param row
696
     */
144 ilm 697
    public EditFrame transfertAcompteClient(List<SQLRowValues> rows) {
698
        return TransfertGroupSQLComponent.openTransfertFrame(rows, "SAISIE_VENTE_FACTURE", VenteFactureSituationSQLComponent.ID);
94 ilm 699
    }
700
 
701
    /**
702
     * Transfert en Facture
703
     *
704
     * @param row
705
     */
144 ilm 706
    public EditFrame transfertSoldeClient(List<SQLRowValues> rows) {
707
        return TransfertGroupSQLComponent.openTransfertFrame(rows, "SAISIE_VENTE_FACTURE", VenteFactureSoldeSQLComponent.ID);
94 ilm 708
    }
709
 
151 ilm 710
    public BigDecimal getAvancement(SQLRowAccessor r) {
94 ilm 711
        Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("TR_COMMANDE_CLIENT"));
712
        long totalFact = 0;
713
        long total = r.getLong("T_HT");
714
        for (SQLRowAccessor row : rows) {
715
            if (!row.isForeignEmpty("ID_SAISIE_VENTE_FACTURE")) {
716
                SQLRowAccessor rowFact = row.getForeign("ID_SAISIE_VENTE_FACTURE");
717
                Long l = rowFact.getLong("T_HT");
718
                totalFact += l;
719
            }
720
        }
721
        if (total > 0) {
722
            return new BigDecimal(totalFact).divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION).movePointRight(2).setScale(2, RoundingMode.HALF_UP);
723
        } else {
724
            return BigDecimal.ONE.movePointRight(2);
725
        }
726
    }
156 ilm 727
 
728
    @Override
729
    protected String createCode() {
730
        return "sales.order";
731
    }
732
 
18 ilm 733
}