OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 151 | Rev 174 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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