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.shipment.component;
15
 
28 ilm 16
import static org.openconcerto.utils.CollectionUtils.createSet;
142 ilm 17
 
18 ilm 18
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
63 ilm 19
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18 ilm 20
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
21
import org.openconcerto.erp.core.common.ui.DeviseField;
73 ilm 22
import org.openconcerto.erp.core.common.ui.TotalPanel;
93 ilm 23
import org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI;
24
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
174 ilm 25
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
93 ilm 26
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
18 ilm 27
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureItemSQLElement;
156 ilm 28
import org.openconcerto.erp.core.sales.product.model.ProductComponent;
142 ilm 29
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable;
18 ilm 30
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonItemSQLElement;
142 ilm 31
import org.openconcerto.erp.core.sales.shipment.element.BonDeLivraisonSQLElement;
18 ilm 32
import org.openconcerto.erp.core.sales.shipment.report.BonLivraisonXmlSheet;
33
import org.openconcerto.erp.core.sales.shipment.ui.BonDeLivraisonItemTable;
83 ilm 34
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
93 ilm 35
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
61 ilm 36
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
21 ilm 37
import org.openconcerto.erp.panel.PanelOOSQLComponent;
61 ilm 38
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
93 ilm 39
import org.openconcerto.erp.preferences.GestionClientPreferencePanel;
94 ilm 40
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
156 ilm 41
import org.openconcerto.erp.utils.TM;
18 ilm 42
import org.openconcerto.sql.Configuration;
43
import org.openconcerto.sql.element.SQLElement;
174 ilm 44
import org.openconcerto.sql.model.SQLBackgroundTableCache;
18 ilm 45
import org.openconcerto.sql.model.SQLRow;
46
import org.openconcerto.sql.model.SQLRowAccessor;
47
import org.openconcerto.sql.model.SQLRowValues;
48
import org.openconcerto.sql.model.SQLSelect;
49
import org.openconcerto.sql.model.SQLTable;
61 ilm 50
import org.openconcerto.sql.model.Where;
51
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 52
import org.openconcerto.sql.sqlobject.ElementComboBox;
53
import org.openconcerto.sql.sqlobject.JUniqueTextField;
28 ilm 54
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
174 ilm 55
import org.openconcerto.sql.sqlobject.SQLTextCombo;
56
import org.openconcerto.sql.users.UserManager;
18 ilm 57
import org.openconcerto.sql.view.EditFrame;
73 ilm 58
import org.openconcerto.sql.view.list.RowValuesTable;
18 ilm 59
import org.openconcerto.sql.view.list.RowValuesTableModel;
60
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 61
import org.openconcerto.ui.FormLayouter;
18 ilm 62
import org.openconcerto.ui.JDate;
63
import org.openconcerto.ui.TitledSeparator;
64
import org.openconcerto.ui.component.ITextArea;
65
import org.openconcerto.utils.ExceptionHandler;
132 ilm 66
import org.openconcerto.utils.NumberUtils;
18 ilm 67
 
68
import java.awt.Color;
69
import java.awt.GridBagConstraints;
70
import java.awt.GridBagLayout;
71
import java.awt.Insets;
72
import java.awt.event.ActionEvent;
73
import java.awt.event.ActionListener;
19 ilm 74
import java.beans.PropertyChangeEvent;
75
import java.beans.PropertyChangeListener;
132 ilm 76
import java.math.BigDecimal;
18 ilm 77
import java.sql.SQLException;
78
import java.util.ArrayList;
132 ilm 79
import java.util.HashMap;
18 ilm 80
import java.util.List;
132 ilm 81
import java.util.Map;
18 ilm 82
 
83
import javax.swing.JButton;
93 ilm 84
import javax.swing.JCheckBox;
18 ilm 85
import javax.swing.JLabel;
19 ilm 86
import javax.swing.JOptionPane;
18 ilm 87
import javax.swing.JPanel;
88
import javax.swing.JScrollPane;
89
import javax.swing.JTextField;
90
import javax.swing.SwingConstants;
91
import javax.swing.SwingUtilities;
93 ilm 92
import javax.swing.event.DocumentEvent;
93
import javax.swing.event.DocumentListener;
18 ilm 94
 
95
import org.apache.commons.dbutils.handlers.ArrayListHandler;
96
 
97
public class BonDeLivraisonSQLComponent extends TransfertBaseSQLComponent {
98
    private BonDeLivraisonItemTable tableBonItem;
142 ilm 99
    private ReliquatRowValuesTable tableBonReliquatItem;
18 ilm 100
    private ElementComboBox selectCommande, comboClient;
21 ilm 101
    private PanelOOSQLComponent panelOO;
18 ilm 102
    private JUniqueTextField textNumeroUnique;
103
    private final SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
104
    private final DeviseField textTotalHT = new DeviseField(6);
105
    private final DeviseField textTotalTVA = new DeviseField(6);
106
    private final DeviseField textTotalTTC = new DeviseField(6);
107
    private final JTextField textPoidsTotal = new JTextField(6);
108
    private final JTextField textNom = new JTextField(25);
93 ilm 109
    private final JDate date = new JDate(true);
110
    private final boolean displayDpt;
111
    private final ElementComboBox comboDpt = new ElementComboBox();
174 ilm 112
    private ElementComboBox comboCommercial;
18 ilm 113
 
114
    public BonDeLivraisonSQLComponent() {
115
        super(Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON"));
93 ilm 116
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
117
        this.displayDpt = prefs.getBoolean(GestionClientPreferencePanel.DISPLAY_CLIENT_DPT, false);
18 ilm 118
    }
119
 
120
    @Override
73 ilm 121
    protected RowValuesTable getRowValuesTable() {
122
        return this.tableBonItem.getRowValuesTable();
123
    }
124
 
125
    @Override
18 ilm 126
    protected SQLRowValues createDefaults() {
90 ilm 127
        this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
18 ilm 128
        this.tableBonItem.getModel().clearRows();
93 ilm 129
        SQLRowValues rowVals = super.createDefaults();
130
        if (rowVals == null) {
131
            rowVals = new SQLRowValues(getTable());
132
        }
174 ilm 133
        SQLElement eltComm = getElement().getForeignElement("ID_COMMERCIAL");
134
        int idUser = UserManager.getInstance().getCurrentUser().getId();
135
        SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
136
 
137
        if (rowsComm != null) {
138
            rowVals.put("ID_COMMERCIAL", rowsComm.getID());
139
        }
93 ilm 140
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
141
            rowVals.put("CREATE_VIRTUAL_STOCK", Boolean.TRUE);
142
        }
143
        if (getTable().contains("ID_TAXE_PORT")) {
144
            SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
145
            rowVals.put("ID_TAXE_PORT", taxeDefault.getID());
146
        }
156 ilm 147
        if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
148
            SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
149
            rowVals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
150
        }
93 ilm 151
        return rowVals;
18 ilm 152
    }
153
 
154
    public void addViews() {
155
        this.textTotalHT.setOpaque(false);
156
        this.textTotalTVA.setOpaque(false);
157
        this.textTotalTTC.setOpaque(false);
93 ilm 158
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
159
            this.addView(new JCheckBox(), "CREATE_VIRTUAL_STOCK");
160
        }
18 ilm 161
        this.selectCommande = new ElementComboBox();
162
 
163
        this.setLayout(new GridBagLayout());
164
 
165
        final GridBagConstraints c = new DefaultGridBagConstraints();
166
 
25 ilm 167
        // Champ Module
168
        c.gridx = 0;
169
        c.gridy++;
170
        c.gridwidth = GridBagConstraints.REMAINDER;
63 ilm 171
        final JPanel addP = ComptaSQLConfElement.createAdditionalPanel();
41 ilm 172
        this.setAdditionalFieldsPanel(new FormLayouter(addP, 2));
25 ilm 173
        this.add(addP, c);
174
 
175
        c.gridy++;
176
        c.gridwidth = 1;
177
 
18 ilm 178
        // Numero
179
        JLabel labelNum = new JLabel(getLabelFor("NUMERO"));
180
        labelNum.setHorizontalAlignment(SwingConstants.RIGHT);
181
        this.add(labelNum, c);
182
 
142 ilm 183
        this.textNumeroUnique = new JUniqueTextField(16) {
184
            @Override
185
            public String getAutoRefreshNumber() {
186
                if (getMode() == Mode.INSERTION) {
187
                    return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), date.getDate());
188
                } else {
189
                    return null;
190
                }
191
            }
192
        };
18 ilm 193
        c.gridx++;
194
        c.weightx = 1;
195
        c.weighty = 0;
196
        c.fill = GridBagConstraints.NONE;
197
        DefaultGridBagConstraints.lockMinimumSize(textNumeroUnique);
198
        this.add(this.textNumeroUnique, c);
199
 
200
        // Date
201
        c.gridx++;
202
        c.fill = GridBagConstraints.HORIZONTAL;
203
        c.weightx = 0;
204
        this.add(new JLabel(getLabelFor("DATE"), SwingConstants.RIGHT), c);
205
 
206
        c.gridx++;
207
        c.weightx = 0;
208
        c.weighty = 0;
209
        c.fill = GridBagConstraints.NONE;
210
        this.add(date, c);
211
 
93 ilm 212
        this.date.addValueListener(new PropertyChangeListener() {
213
 
214
            @Override
215
            public void propertyChange(PropertyChangeEvent evt) {
216
                if (!isFilling() && date.getValue() != null) {
217
                    tableBonItem.setDateDevise(date.getValue());
218
                }
219
            }
220
        });
221
 
18 ilm 222
        // Reference
223
        c.gridy++;
224
        c.gridx = 0;
225
        c.fill = GridBagConstraints.HORIZONTAL;
226
        this.add(new JLabel(getLabelFor("NOM"), SwingConstants.RIGHT), c);
227
        c.gridx++;
228
        c.weightx = 1;
229
        this.add(this.textNom, c);
41 ilm 230
        if (getTable().contains("DATE_LIVRAISON")) {
231
            // Date livraison
232
            c.gridx++;
233
            c.fill = GridBagConstraints.HORIZONTAL;
234
            c.weightx = 0;
235
            this.add(new JLabel(getLabelFor("DATE_LIVRAISON"), SwingConstants.RIGHT), c);
18 ilm 236
 
41 ilm 237
            JDate dateLivraison = new JDate(true);
238
            c.gridx++;
239
            c.weightx = 0;
240
            c.weighty = 0;
241
            c.fill = GridBagConstraints.NONE;
242
            this.add(dateLivraison, c);
243
            this.addView(dateLivraison, "DATE_LIVRAISON");
244
        }
18 ilm 245
        // Client
61 ilm 246
        JLabel labelClient = new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT);
18 ilm 247
        c.gridx = 0;
248
        c.gridy++;
249
        c.weightx = 0;
61 ilm 250
        c.fill = GridBagConstraints.HORIZONTAL;
18 ilm 251
        c.weighty = 0;
252
        this.add(labelClient, c);
253
 
254
        c.gridx++;
255
        c.weightx = 0;
256
        c.weighty = 0;
257
        c.fill = GridBagConstraints.NONE;
258
        this.comboClient = new ElementComboBox();
41 ilm 259
        this.add(this.comboClient, c);
93 ilm 260
        this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
261
 
262
        if (this.displayDpt) {
263
            c.gridx++;
264
            c.gridwidth = 1;
265
            final JLabel labelDpt = new JLabel(getLabelFor("ID_CLIENT_DEPARTEMENT"));
266
            labelDpt.setHorizontalAlignment(SwingConstants.RIGHT);
267
            c.weightx = 0;
268
            c.gridwidth = 1;
269
            c.fill = GridBagConstraints.HORIZONTAL;
270
            this.add(labelDpt, c);
271
 
272
            c.gridx++;
273
            c.gridwidth = 1;
274
            c.weightx = 0;
275
            c.weighty = 0;
276
            c.fill = GridBagConstraints.NONE;
277
            this.add(this.comboDpt, c);
278
            DefaultGridBagConstraints.lockMinimumSize(this.comboDpt);
279
            addSQLObject(this.comboDpt, "ID_CLIENT_DEPARTEMENT");
280
 
281
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
282
 
283
                @Override
284
                public void propertyChange(PropertyChangeEvent evt) {
285
                    int wantedID = comboClient.getWantedID();
286
 
287
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
288
                        final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
289
                        comboDpt.getRequest().setWhere(new Where(comboDpt.getRequest().getPrimaryTable().getField("ID_CLIENT"), "=", rowClient.getID()));
290
                    } else {
291
                        comboDpt.getRequest().setWhere(null);
292
                    }
293
                }
294
            });
295
 
296
        }
94 ilm 297
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
298
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ADDRESS_SPEC, true)) {
93 ilm 299
 
94 ilm 300
            final SQLElement adrElement = getElement().getForeignElement("ID_ADRESSE");
301
            final AddressChoiceUI addressUI = new AddressChoiceUI();
302
            addressUI.addToUI(this, c);
303
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
93 ilm 304
 
94 ilm 305
                @Override
306
                public void propertyChange(PropertyChangeEvent evt) {
307
                    int wantedID = comboClient.getWantedID();
308
                    System.err.println("SET WHERE ID_CLIENT = " + wantedID);
309
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
93 ilm 310
 
94 ilm 311
                        addressUI.getComboAdrF().getRequest().setWhere(
312
                                new Where(adrElement.getTable().getField("ID_CLIENT"), "=", wantedID).and(new Where(adrElement.getTable().getField("TYPE"), "=", AdresseType.Invoice.getId())));
313
                        addressUI.getComboAdrL().getRequest().setWhere(
314
                                new Where(adrElement.getTable().getField("ID_CLIENT"), "=", wantedID).and(new Where(adrElement.getTable().getField("TYPE"), "=", AdresseType.Delivery.getId())));
315
                    } else {
316
                        addressUI.getComboAdrF().getRequest().setWhere(Where.FALSE);
317
                        addressUI.getComboAdrL().getRequest().setWhere(Where.FALSE);
318
                    }
93 ilm 319
                }
94 ilm 320
            });
321
        }
174 ilm 322
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CATEGORIE_COMPTABLE_SPEC, false)) {
323
            // cat spe
324
            final CategorieComptableChoiceUI catUI = new CategorieComptableChoiceUI();
325
            catUI.addToUI(this, c);
326
            catUI.getCombo().addModelListener("wantedID", new PropertyChangeListener() {
327
 
328
                @Override
329
                public void propertyChange(PropertyChangeEvent evt) {
330
                    int wantedID = catUI.getCombo().getWantedID();
331
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
332
                        tableBonItem.setRowCatComptable(catUI.getCombo().getElement().getTable().getRow(wantedID));
333
                    } else {
334
                        tableBonItem.setRowCatComptable(null);
335
                    }
336
                }
337
            });
338
        }
41 ilm 339
        if (getTable().contains("SPEC_LIVRAISON")) {
340
            // Date livraison
341
            c.gridx++;
342
            c.fill = GridBagConstraints.HORIZONTAL;
343
            c.weightx = 0;
344
            this.add(new JLabel(getLabelFor("SPEC_LIVRAISON"), SwingConstants.RIGHT), c);
18 ilm 345
 
41 ilm 346
            JTextField specLivraison = new JTextField();
347
            c.gridx++;
348
            c.weightx = 0;
349
            c.weighty = 0;
350
            this.add(specLivraison, c);
351
            this.addView(specLivraison, "SPEC_LIVRAISON");
352
        }
353
 
93 ilm 354
        if (getTable().contains("ID_CONTACT")) {
355
            // Contact Client
356
            c.gridx = 0;
357
            c.gridy++;
358
            c.gridwidth = 1;
359
            final JLabel labelContact = new JLabel(getLabelFor("ID_CONTACT"));
360
            labelContact.setHorizontalAlignment(SwingConstants.RIGHT);
361
            c.weightx = 0;
362
            c.gridwidth = 1;
363
            c.fill = GridBagConstraints.HORIZONTAL;
364
            this.add(labelContact, c);
365
 
366
            final ElementComboBox comboContact = new ElementComboBox();
367
            c.gridx++;
368
            c.gridwidth = 1;
369
            c.weightx = 0;
370
            c.weighty = 0;
371
            c.fill = GridBagConstraints.NONE;
372
            this.add(comboContact, c);
373
            final SQLElement contactElement = getElement().getForeignElement("ID_CONTACT");
374
            comboContact.init(contactElement, contactElement.getComboRequest(true));
375
            comboContact.getRequest().setWhere(Where.FALSE);
376
            DefaultGridBagConstraints.lockMinimumSize(comboContact);
377
            this.addView(comboContact, "ID_CONTACT");
378
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
379
 
380
                @Override
381
                public void propertyChange(PropertyChangeEvent evt) {
382
                    int wantedID = comboClient.getWantedID();
383
                    System.err.println("SET WHERE ID_CLIENT = " + wantedID);
384
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
385
 
386
                        final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
387
                        int idClient = rowClient.getID();
388
                        comboContact.getRequest().setWhere(new Where(contactElement.getTable().getField("ID_CLIENT"), "=", idClient));
156 ilm 389
                        if (rowClient.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowClient.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
390
                            tableBonItem.setRowCatComptable(rowClient.getForeign("ID_CATEGORIE_COMPTABLE"));
391
                        } else {
392
                            tableBonItem.setRowCatComptable(null);
393
                        }
174 ilm 394
                        if (!isFilling()) {
395
                            tableBonItem.setClient(rowClient, true);
396
                        }
397
 
93 ilm 398
                    } else {
399
                        comboContact.getRequest().setWhere(Where.FALSE);
156 ilm 400
                        tableBonItem.setRowCatComptable(null);
174 ilm 401
                        if (!isFilling()) {
402
                            tableBonItem.setClient(null, true);
403
                        }
93 ilm 404
                        // DevisSQLComponent.this.table.setTarif(null, false);
405
                    }
406
                }
407
            });
408
 
174 ilm 409
            // Commercial
410
            JLabel labelCommercial = new JLabel(getLabelFor("ID_COMMERCIAL"));
411
            labelCommercial.setHorizontalAlignment(SwingConstants.RIGHT);
412
 
413
            c.gridx++;
414
            c.weightx = 0;
415
            this.add(labelCommercial, c);
416
 
417
            this.comboCommercial = new ElementComboBox(false, 25);
418
            this.comboCommercial.setListIconVisible(false);
419
            c.gridx++;
420
            c.fill = GridBagConstraints.NONE;
421
            c.weightx = 1;
422
            this.add(this.comboCommercial, c);
423
            addRequiredSQLObject(this.comboCommercial, "ID_COMMERCIAL");
424
 
93 ilm 425
        }
426
 
19 ilm 427
        final ElementComboBox boxTarif = new ElementComboBox();
41 ilm 428
        this.comboClient.addValueListener(new PropertyChangeListener() {
429
            @Override
430
            public void propertyChange(PropertyChangeEvent evt) {
431
                if (comboClient.getElement().getTable().contains("ID_TARIF")) {
28 ilm 432
                    if (BonDeLivraisonSQLComponent.this.isFilling())
433
                        return;
434
                    final SQLRow row = ((SQLRequestComboBox) evt.getSource()).getSelectedRow();
435
                    if (row != null) {
436
                        // SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
437
                        // if (foreignRow.isUndefined() &&
438
                        // !row.getForeignRow("ID_DEVISE").isUndefined()) {
439
                        // SQLRowValues rowValsD = new SQLRowValues(foreignRow.getTable());
440
                        // rowValsD.put("ID_DEVISE", row.getObject("ID_DEVISE"));
441
                        // foreignRow = rowValsD;
442
                        //
443
                        // }
444
                        // tableBonItem.setTarif(foreignRow, true);
445
                        SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
446
                        if (!foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())
156 ilm 447
                                && JOptionPane.showConfirmDialog(null, TM.tr("deliveryForm.applyClientRates")) == JOptionPane.YES_OPTION) { //$NON-NLS-1$
28 ilm 448
                            boxTarif.setValue(foreignRow.getID());
449
                            // SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
450
                            // true);
451
                        } else {
452
                            boxTarif.setValue(foreignRow.getID());
19 ilm 453
                        }
454
                    }
455
                }
41 ilm 456
            }
457
        });
19 ilm 458
 
18 ilm 459
        // Bouton tout livrer
156 ilm 460
        JButton boutonAll = new JButton(TM.tr("deliveryForm.shipAll")); //$NON-NLS-1$
18 ilm 461
 
462
        boutonAll.addActionListener(new ActionListener() {
463
            public void actionPerformed(ActionEvent e) {
464
                RowValuesTableModel m = BonDeLivraisonSQLComponent.this.tableBonItem.getModel();
465
 
466
                // on livre tout les éléments
467
                for (int i = 0; i < m.getRowCount(); i++) {
468
                    SQLRowValues rowVals = m.getRowValuesAt(i);
469
                    Object o = rowVals.getObject("QTE");
470
                    int qte = o == null ? 0 : ((Number) o).intValue();
471
                    m.putValue(qte, i, "QTE_LIVREE");
472
                }
473
            }
474
        });
475
 
19 ilm 476
        // Tarif
477
        if (this.getTable().getFieldsName().contains("ID_TARIF")) {
478
            // TARIF
479
            c.gridy++;
480
            c.gridx = 0;
481
            c.weightx = 0;
482
            c.weighty = 0;
483
            c.gridwidth = 1;
93 ilm 484
            c.fill = GridBagConstraints.HORIZONTAL;
485
            this.add(new JLabel(getLabelFor("ID_TARIF"), SwingUtilities.RIGHT), c);
19 ilm 486
            c.gridx++;
41 ilm 487
            c.gridwidth = 1;
93 ilm 488
            c.fill = GridBagConstraints.NONE;
19 ilm 489
            c.weightx = 1;
490
            this.add(boxTarif, c);
491
            this.addView(boxTarif, "ID_TARIF");
73 ilm 492
            boxTarif.addModelListener("wantedID", new PropertyChangeListener() {
19 ilm 493
 
494
                @Override
495
                public void propertyChange(PropertyChangeEvent evt) {
73 ilm 496
                    SQLRow selectedRow = boxTarif.getRequest().getPrimaryTable().getRow(boxTarif.getWantedID());
497
                    tableBonItem.setTarif(selectedRow, !isFilling());
19 ilm 498
                }
499
            });
174 ilm 500
 
501
            if (getTable().contains("SERVI_PAR")) {
502
                // Commercial
503
                JLabel labelServi = new JLabel("Servi par");
504
                labelServi.setHorizontalAlignment(SwingConstants.RIGHT);
505
                c.gridx++;
506
                c.weightx = 0;
507
                this.add(labelServi, c);
508
 
509
                SQLTextCombo comboServiPar = new SQLTextCombo();
510
                c.gridx++;
511
                c.fill = GridBagConstraints.NONE;
512
                c.weightx = 1;
513
                this.add(comboServiPar, c);
514
                addRequiredSQLObject(comboServiPar, "SERVI_PAR");
515
            }
19 ilm 516
        }
41 ilm 517
 
518
        if (getTable().contains("A_ATTENTION")) {
519
            // Date livraison
520
            c.gridx++;
521
            c.fill = GridBagConstraints.HORIZONTAL;
522
            c.weightx = 0;
523
            this.add(new JLabel(getLabelFor("A_ATTENTION"), SwingConstants.RIGHT), c);
524
 
525
            JTextField specLivraison = new JTextField();
526
            c.gridx++;
527
            c.weightx = 0;
528
            c.weighty = 0;
529
            this.add(specLivraison, c);
530
            this.addView(specLivraison, "A_ATTENTION");
531
        }
532
 
18 ilm 533
        // Element du bon
534
        List<JButton> l = new ArrayList<JButton>();
535
        l.add(boutonAll);
536
        this.tableBonItem = new BonDeLivraisonItemTable(l);
537
 
538
        c.gridx = 0;
539
        c.gridy++;
540
        c.weightx = 1;
541
        c.weighty = 1;
542
        c.gridwidth = GridBagConstraints.REMAINDER;
543
        c.fill = GridBagConstraints.BOTH;
544
        this.add(this.tableBonItem, c);
545
        c.anchor = GridBagConstraints.EAST;
546
        // Totaux
547
        reconfigure(this.textTotalHT);
548
        reconfigure(this.textTotalTVA);
549
        reconfigure(this.textTotalTTC);
142 ilm 550
        DeviseField fieldEco = new DeviseField(5);
93 ilm 551
        DeviseField textPortHT = new DeviseField(5);
552
        DeviseField textRemiseHT = new DeviseField();
553
 
554
        // Total
555
        DeviseField fieldDevise = new DeviseField();
556
        DeviseField fieldService = new DeviseField();
557
        DeviseField fieldHA = new DeviseField();
558
        fieldHA.setOpaque(false);
559
        fieldService.setOpaque(false);
560
        if (getTable().contains("TOTAL_DEVISE")) {
561
            addSQLObject(fieldDevise, "TOTAL_DEVISE");
562
            addRequiredSQLObject(fieldService, "TOTAL_SERVICE");
563
        }
564
        if (getTable().contains("PREBILAN")) {
565
            addSQLObject(fieldHA, "PREBILAN");
566
        } else if (getTable().contains("T_HA")) {
567
            addSQLObject(fieldHA, "T_HA");
94 ilm 568
            this.allowEditable("T_HA", false);
93 ilm 569
        }
94 ilm 570
        // Disable
93 ilm 571
 
572
        SQLRequestComboBox boxTaxePort = new SQLRequestComboBox(false, 8);
573
 
18 ilm 574
        // Poids Total
575
        c.gridy++;
576
        c.gridx = 1;
577
        c.weightx = 0;
578
        c.weighty = 0;
579
        c.anchor = GridBagConstraints.EAST;
580
        c.gridwidth = 1;
581
        c.fill = GridBagConstraints.NONE;
73 ilm 582
        this.addSQLObject(this.textPoidsTotal, "TOTAL_POIDS");
142 ilm 583
        this.addSQLObject(fieldEco, "T_ECO_CONTRIBUTION");
73 ilm 584
        this.addRequiredSQLObject(this.textTotalHT, "TOTAL_HT");
585
        this.addRequiredSQLObject(this.textTotalTVA, "TOTAL_TVA");
586
        this.addRequiredSQLObject(this.textTotalTTC, "TOTAL_TTC");
142 ilm 587
        this.allowEditable("T_ECO_CONTRIBUTION", false);
94 ilm 588
        this.allowEditable("TOTAL_HT", false);
589
        this.allowEditable("TOTAL_TVA", false);
590
        this.allowEditable("TOTAL_TTC", false);
591
        this.allowEditable("TOTAL_POIDS", false);
142 ilm 592
        final TotalPanel panelTotal = new TotalPanel(tableBonItem, fieldEco, textTotalHT, textTotalTVA, textTotalTTC, textPortHT, textRemiseHT, fieldService, fieldHA, fieldDevise, this.textPoidsTotal,
593
                null, (getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
93 ilm 594
        // if (b) {
595
        JPanel panel = new JPanel(new GridBagLayout());
596
        GridBagConstraints cFrais = new DefaultGridBagConstraints();
597
        panel.add(new JLabel(getLabelFor("TOTAL_POIDS")), cFrais);
598
 
599
        this.textPoidsTotal.setEnabled(false);
600
        this.textPoidsTotal.setHorizontalAlignment(JTextField.RIGHT);
601
        this.textPoidsTotal.setDisabledTextColor(Color.BLACK);
602
        cFrais.gridx++;
603
        panel.add(this.textPoidsTotal, cFrais);
604
 
605
        panel.setOpaque(false);
606
        DefaultGridBagConstraints.lockMinimumSize(panel);
607
 
608
        DefaultGridBagConstraints.lockMinimumSize(textPortHT);
609
        addSQLObject(textPortHT, "PORT_HT");
610
        DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
611
        addSQLObject(textRemiseHT, "REMISE_HT");
612
 
613
        // Frais de port
614
 
615
        if (getTable().contains("ID_TAXE_PORT")) {
616
 
617
            JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
618
            labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
619
            cFrais.gridx = 0;
620
            cFrais.gridy++;
621
            panel.add(labelPortHT, cFrais);
622
            cFrais.gridx++;
623
            panel.add(textPortHT, cFrais);
624
 
625
            JLabel labelTaxeHT = new JLabel(getLabelFor("ID_TAXE_PORT"));
626
            labelTaxeHT.setHorizontalAlignment(SwingConstants.RIGHT);
627
            cFrais.gridx = 0;
628
            cFrais.gridy++;
629
            panel.add(labelTaxeHT, cFrais);
630
            cFrais.gridx++;
631
            panel.add(boxTaxePort, cFrais);
632
            this.addView(boxTaxePort, "ID_TAXE_PORT", REQ);
633
 
634
            boxTaxePort.addValueListener(new PropertyChangeListener() {
635
 
636
                @Override
637
                public void propertyChange(PropertyChangeEvent evt) {
638
                    panelTotal.updateTotal();
639
                }
640
            });
641
        }
642
 
643
        // Remise
644
        JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
645
        labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
646
        cFrais.gridy++;
647
        cFrais.gridx = 0;
648
        panel.add(labelRemiseHT, cFrais);
649
        cFrais.gridx++;
650
        panel.add(textRemiseHT, cFrais);
651
 
652
        c.gridx = 1;
653
        c.weightx = 0;
654
        c.weighty = 0;
655
        c.gridwidth = 1;
656
        c.fill = GridBagConstraints.NONE;
657
        c.anchor = GridBagConstraints.NORTHEAST;
658
        this.add(panel, c);
659
 
18 ilm 660
        c.gridx = 2;
661
        c.gridwidth = GridBagConstraints.REMAINDER;
662
        c.weightx = 0;
663
        c.weighty = 0;
664
        c.anchor = GridBagConstraints.EAST;
665
        c.fill = GridBagConstraints.HORIZONTAL;
73 ilm 666
        this.add(panelTotal, c);
18 ilm 667
 
668
        c.anchor = GridBagConstraints.WEST;
669
 
142 ilm 670
        if (getTable().getDBRoot().contains("RELIQUAT_BL")) {
671
 
672
            c.gridwidth = GridBagConstraints.REMAINDER;
673
            c.weightx = 1;
674
            c.fill = GridBagConstraints.HORIZONTAL;
675
            c.gridx = 0;
676
            c.gridy++;
677
            TitledSeparator sep = new TitledSeparator("Reliquat de kits");
678
            c.insets = new Insets(10, 2, 1, 2);
679
            this.add(sep, c);
680
            c.insets = new Insets(2, 2, 1, 2);
681
 
682
            // Reliquat du bon
683
            this.tableBonReliquatItem = new ReliquatRowValuesTable("RELIQUAT_BL");
684
            c.gridx = 0;
685
            c.gridy++;
686
            c.weightx = 1;
687
            c.weighty = 1;
688
            c.gridwidth = GridBagConstraints.REMAINDER;
689
            c.fill = GridBagConstraints.BOTH;
690
            this.add(this.tableBonReliquatItem, c);
691
            this.tableBonItem.setReliquatTable(tableBonReliquatItem);
692
        }
693
 
18 ilm 694
        /*******************************************************************************************
695
         * * INFORMATIONS COMPLEMENTAIRES
696
         ******************************************************************************************/
697
        c.gridwidth = GridBagConstraints.REMAINDER;
698
        c.weightx = 1;
699
        c.fill = GridBagConstraints.HORIZONTAL;
700
        c.gridx = 0;
701
        c.gridy++;
93 ilm 702
        TitledSeparator sep = new TitledSeparator(getLabelFor("INFOS"));
18 ilm 703
        c.insets = new Insets(10, 2, 1, 2);
704
        this.add(sep, c);
705
        c.insets = new Insets(2, 2, 1, 2);
706
 
707
        ITextArea textInfos = new ITextArea(4, 4);
708
 
709
        c.gridx = 0;
710
        c.gridy++;
711
        c.gridheight = 1;
712
        c.gridwidth = GridBagConstraints.REMAINDER;
713
        c.weightx = 1;
714
        c.weighty = 0;
715
        c.fill = GridBagConstraints.BOTH;
716
 
717
        final JScrollPane scrollPane = new JScrollPane(textInfos);
718
        this.add(scrollPane, c);
719
        textInfos.setBorder(null);
720
        DefaultGridBagConstraints.lockMinimumSize(scrollPane);
721
 
722
        c.gridx = 0;
723
        c.gridy++;
724
        c.gridheight = 1;
725
        c.gridwidth = 4;
726
        c.weightx = 0;
727
        c.weighty = 0;
728
        c.fill = GridBagConstraints.NONE;
729
        c.anchor = GridBagConstraints.EAST;
730
 
21 ilm 731
        this.panelOO = new PanelOOSQLComponent(this);
732
        this.add(this.panelOO, c);
733
 
18 ilm 734
        this.addRequiredSQLObject(date, "DATE");
735
        this.addSQLObject(textInfos, "INFOS");
736
        this.addSQLObject(this.textNom, "NOM");
737
        this.addSQLObject(this.selectCommande, "ID_COMMANDE_CLIENT");
738
        this.addRequiredSQLObject(this.textNumeroUnique, "NUMERO");
73 ilm 739
 
18 ilm 740
        // Doit etre locké a la fin
741
        DefaultGridBagConstraints.lockMinimumSize(comboClient);
742
 
93 ilm 743
        textPortHT.getDocument().addDocumentListener(new DocumentListener() {
744
            public void changedUpdate(DocumentEvent e) {
745
                panelTotal.updateTotal();
746
            }
747
 
748
            public void removeUpdate(DocumentEvent e) {
749
                panelTotal.updateTotal();
750
            }
751
 
752
            public void insertUpdate(DocumentEvent e) {
753
                panelTotal.updateTotal();
754
            }
755
        });
756
 
757
        textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
758
            public void changedUpdate(DocumentEvent e) {
759
                panelTotal.updateTotal();
760
            }
761
 
762
            public void removeUpdate(DocumentEvent e) {
763
                panelTotal.updateTotal();
764
            }
765
 
766
            public void insertUpdate(DocumentEvent e) {
767
                panelTotal.updateTotal();
768
            }
769
        });
770
 
18 ilm 771
    }
772
 
28 ilm 773
    public BonDeLivraisonItemTable getTableBonItem() {
774
        return this.tableBonItem;
775
    }
776
 
18 ilm 777
    private void reconfigure(JTextField field) {
778
        field.setEnabled(false);
779
        field.setHorizontalAlignment(JTextField.RIGHT);
780
        field.setDisabledTextColor(Color.BLACK);
781
        field.setBorder(null);
782
    }
783
 
784
    public int insert(SQLRow order) {
785
 
786
        int idBon = getSelectedID();
142 ilm 787
        int attempt = 0;
788
        // on verifie qu'un devis du meme numero n'a pas été inséré entre temps
789
        if (!this.textNumeroUnique.checkValidation(false)) {
790
            while (attempt < JUniqueTextField.RETRY_COUNT) {
791
                String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), date.getDate());
792
                this.textNumeroUnique.setText(num);
793
                attempt++;
794
                if (this.textNumeroUnique.checkValidation(false)) {
795
                    System.err.println("ATEMPT " + attempt + " SUCCESS WITH NUMERO " + num);
796
                    break;
797
                }
798
                try {
799
                    Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
800
                } catch (InterruptedException e) {
801
                    e.printStackTrace();
802
                }
803
            }
804
        }
805
        final String num = this.textNumeroUnique.getText();
806
        if (attempt == JUniqueTextField.RETRY_COUNT) {
807
            idBon = getSelectedID();
156 ilm 808
            ExceptionHandler.handle(TM.tr("deliveryForm.cannotAdd.existingNumber")); //$NON-NLS-1$
142 ilm 809
            final Object root = SwingUtilities.getRoot(this);
810
            if (root instanceof EditFrame) {
811
                final EditFrame frame = (EditFrame) root;
812
                frame.getPanel().setAlwaysVisible(true);
813
            }
814
        } else {
156 ilm 815
            if (getTable().getDBRoot().contains("TARIF_AGENCE")) {
816
                final List<ProductComponent> comps = checkStock();
817
                if (comps.size() > 0) {
818
                    String article = "";
819
                    for (ProductComponent comp : comps) {
820
                        article += "\n " + comp.getProduct().getString("CODE") + " --- " + comp.getProduct().getString("NOM");
821
                    }
822
                    JOptionPane.showMessageDialog(null, TM.tr("deliveryForm.cannotCreate.notInStock") + article); //$NON-NLS-1$
823
                    final Object root = SwingUtilities.getRoot(this);
824
                    if (root instanceof EditFrame) {
825
                        final EditFrame frame = (EditFrame) root;
826
                        frame.getPanel().setAlwaysVisible(true);
827
                    }
828
                    return -1;
829
                }
830
            }
18 ilm 831
            idBon = super.insert(order);
142 ilm 832
            if (this.tableBonReliquatItem != null) {
833
                this.tableBonReliquatItem.updateField("ID_BON_DE_LIVRAISON_ORIGINE", idBon);
834
            }
18 ilm 835
            this.tableBonItem.updateField("ID_BON_DE_LIVRAISON", idBon);
836
            this.tableBonItem.createArticle(idBon, this.getElement());
156 ilm 837
            final List<Object> cmdDourceTrRowsFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(idBon, "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
838
            ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(cmdDourceTrRowsFrom, "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
839
            final List<Object> devisSourceTrRowsFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(idBon, "DEVIS_ELEMENT", "DEVIS");
840
            ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(devisSourceTrRowsFrom, "DEVIS_ELEMENT", "DEVIS");
18 ilm 841
            // generation du document
842
            BonLivraisonXmlSheet bSheet = new BonLivraisonXmlSheet(getTable().getRow(idBon));
25 ilm 843
            bSheet.createDocumentAsynchronous();
844
            bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
18 ilm 845
 
846
            // incrémentation du numéro auto
93 ilm 847
            if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass()).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
18 ilm 848
                SQLRowValues rowVals = new SQLRowValues(this.tableNum);
849
                int val = this.tableNum.getRow(2).getInt("BON_L_START");
850
                val++;
851
                rowVals.put("BON_L_START", new Integer(val));
852
 
853
                try {
854
                    rowVals.update(2);
855
                } catch (SQLException e) {
856
                    e.printStackTrace();
857
                }
858
            }
859
 
61 ilm 860
            SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
861
 
862
            if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
863
 
73 ilm 864
                try {
865
                    updateStock(idBon);
866
                } catch (SQLException e) {
867
                    throw new IllegalStateException(e);
868
                }
61 ilm 869
            }
18 ilm 870
            // updateQte(idBon);
142 ilm 871
            if (attempt > 0) {
872
                SwingUtilities.invokeLater(new Runnable() {
873
                    public void run() {
156 ilm 874
                        JOptionPane.showMessageDialog(null, TM.tr("deliveryForm.numberRefreshed", num)); //$NON-NLS-1$
142 ilm 875
                    }
876
                });
18 ilm 877
            }
878
        }
879
 
880
        return idBon;
881
    }
882
 
156 ilm 883
    private List<ProductComponent> checkStock() {
884
        List<ProductComponent> comps = new ArrayList<ProductComponent>();
885
        final RowValuesTableModel rowValuesTableModel = this.tableBonItem.getRowValuesTable().getRowValuesTableModel();
886
 
887
        for (int i = 0; i < rowValuesTableModel.getRowCount(); i++) {
888
            final SQLRowValues rowValuesAt = rowValuesTableModel.getRowValuesAt(i);
889
            if (rowValuesAt.getInt("QTE_LIVREE") > 0 && rowValuesAt != null && rowValuesAt.getObject("ID_ARTICLE") != null && !rowValuesAt.isForeignEmpty("ID_ARTICLE")) {
890
                SQLRowAccessor article = rowValuesAt.getForeign("ID_ARTICLE");
891
                if (article.getBoolean("GESTION_STOCK")) {
892
                    ProductComponent comp = ProductComponent.createFrom(rowValuesAt);
893
                    if (comp.getStock() != null && !comp.getStock().isUndefined() && comp.getStock().getFloat("QTE_REEL") < 0) {
894
                        comps.add(comp);
895
                    }
896
                }
897
            }
898
        }
899
        return comps;
900
    }
901
 
18 ilm 902
    @Override
903
    public void select(SQLRowAccessor r) {
28 ilm 904
        if (r == null || r.getIDNumber() == null)
905
            super.select(r);
906
        else {
907
            System.err.println(r);
132 ilm 908
            final SQLRowValues rVals = r.asRowValues().deepCopy();
28 ilm 909
            final SQLRowValues vals = new SQLRowValues(r.getTable());
910
            vals.load(rVals, createSet("ID_CLIENT"));
911
            vals.setID(rVals.getID());
912
            System.err.println("Select CLIENT");
913
            super.select(vals);
914
            rVals.remove("ID_CLIENT");
915
            super.select(rVals);
916
        }
142 ilm 917
        if (this.tableBonReliquatItem != null) {
918
            this.tableBonReliquatItem.getRowValuesTable().clear();
919
            if (r != null) {
920
                this.tableBonReliquatItem.getRowValuesTable().insertFrom("ID_BON_LIVRAISON_ORIGINE", r.asRowValues());
921
            }
922
        }
18 ilm 923
    }
924
 
925
    @Override
926
    public void update() {
927
        if (!this.textNumeroUnique.checkValidation()) {
156 ilm 928
            ExceptionHandler.handle(TM.tr("deliveryForm.cannotAdd.existingNumber")); //$NON-NLS-1$
18 ilm 929
            Object root = SwingUtilities.getRoot(this);
930
            if (root instanceof EditFrame) {
931
                EditFrame frame = (EditFrame) root;
932
                frame.getPanel().setAlwaysVisible(true);
933
            }
934
            return;
935
        }
936
        super.update();
142 ilm 937
        if (tableBonReliquatItem != null) {
938
            this.tableBonReliquatItem.updateField("ID_BON_DE_LIVRAISON_ORIGINE", getSelectedID());
939
        }
156 ilm 940
        final List<Object> cmdClientFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(getSelectedID(), "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
941
        final List<Object> devisFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(getSelectedID(), "DEVIS_ELEMENT", "DEVIS");
18 ilm 942
        this.tableBonItem.updateField("ID_BON_DE_LIVRAISON", getSelectedID());
943
        this.tableBonItem.createArticle(getSelectedID(), this.getElement());
156 ilm 944
        ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(devisFrom, "DEVIS_ELEMENT", "DEVIS");
945
        ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(cmdClientFrom, "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
18 ilm 946
 
947
        // generation du document
948
        BonLivraisonXmlSheet bSheet = new BonLivraisonXmlSheet(getTable().getRow(getSelectedID()));
25 ilm 949
        bSheet.createDocumentAsynchronous();
950
        bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
951
 
61 ilm 952
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
953
        if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
954
 
73 ilm 955
            try {
956
                updateStock(getSelectedID());
957
            } catch (SQLException e) {
958
                throw new IllegalStateException(e);
959
            }
61 ilm 960
        }
961
 
18 ilm 962
    }
963
 
132 ilm 964
    /**
965
     * Chargement des qtés restantes à livrer
966
     *
967
     * @param l
968
     */
156 ilm 969
    public void loadQuantity(List<SQLRowValues> l, final String fromTableElt) {
132 ilm 970
        Map<Integer, SQLRowValues> map = new HashMap<Integer, SQLRowValues>();
971
        for (SQLRowValues sqlRowValues : l) {
156 ilm 972
            // On ne prend en compte que les articles ou les lignes différentes de 0, autres lignes
973
            // considérées comme commentaires
974
            if (!sqlRowValues.isForeignEmpty("ID_ARTICLE") || sqlRowValues.getBigDecimal("PV_HT").signum() != 0) {
975
                if (!sqlRowValues.isForeignEmpty("ID_" + fromTableElt)) {
976
                    final int foreignID = sqlRowValues.getForeignID("ID_" + fromTableElt);
977
                    if (!map.containsKey(foreignID)) {
978
                        map.put(foreignID, sqlRowValues);
979
                    } else {
980
                        SQLRowValues vals = map.get(foreignID);
981
                        if (sqlRowValues.getInt("QTE_LIVREE") > 0) {
982
                            if (NumberUtils.areNumericallyEqual(sqlRowValues.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || sqlRowValues.getInt("QTE_LIVREE") > 1) {
983
                                vals.put("QTE_LIVREE", vals.getInt("QTE_LIVREE") + sqlRowValues.getInt("QTE_LIVREE"));
984
                            } else {
985
                                vals.put("QTE_UNITAIRE", vals.getBigDecimal("QTE_UNITAIRE").add(sqlRowValues.getBigDecimal("QTE_UNITAIRE")));
986
                            }
132 ilm 987
                        }
988
                    }
989
                }
990
            }
991
        }
992
        int count = this.tableBonItem.getModel().getRowCount();
993
        for (int i = 0; i < count; i++) {
994
            final SQLRowValues rowValuesAt = this.tableBonItem.getModel().getRowValuesAt(i);
995
            rowValuesAt.put("QTE_LIVREE", rowValuesAt.getObject("QTE"));
996
        }
997
 
998
        for (int i = 0; i < count; i++) {
999
            SQLRowValues r = this.tableBonItem.getModel().getRowValuesAt(i);
156 ilm 1000
            SQLRowValues rowTR = map.get(r.getForeignID("ID_" + fromTableElt));
132 ilm 1001
            if (rowTR != null && !rowTR.isUndefined()) {
1002
                if (r.getInt("QTE_LIVREE") > 0 && rowTR.getInt("QTE_LIVREE") > 0) {
1003
                    if (NumberUtils.areNumericallyEqual(r.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || r.getInt("QTE_LIVREE") > 1) {
1004
                        this.tableBonItem.getModel().putValue(r.getInt("QTE_LIVREE") - rowTR.getInt("QTE_LIVREE"), i, "QTE_LIVREE");
1005
                    } else {
1006
                        this.tableBonItem.getModel().putValue(r.getBigDecimal("QTE_UNITAIRE").subtract(rowTR.getBigDecimal("QTE_UNITAIRE")), i, "QTE_UNITAIRE");
1007
                    }
1008
                }
1009
            } else {
1010
                this.tableBonItem.getModel().putValue(r.getObject("QTE"), i, "QTE_LIVREE");
1011
            }
1012
        }
1013
    }
1014
 
18 ilm 1015
    /***********************************************************************************************
1016
     * Mise à jour des quantités livrées dans les élements de facture
1017
     *
1018
     * @param idBon id du bon de livraison
73 ilm 1019
     * @throws SQLException
18 ilm 1020
     */
73 ilm 1021
    public void updateQte(int idBon) throws SQLException {
18 ilm 1022
 
156 ilm 1023
        SQLTable tableFactureElem = getDirectory().getElement(SaisieVenteFactureItemSQLElement.class).getTable();
1024
        SQLSelect selBonItem = new SQLSelect();
1025
        BonDeLivraisonItemSQLElement bonElt = getDirectory().getElement(BonDeLivraisonItemSQLElement.class);
18 ilm 1026
        selBonItem.addSelect(bonElt.getTable().getField("ID_SAISIE_VENTE_FACTURE_ELEMENT"));
1027
        selBonItem.addSelect(bonElt.getTable().getField("QTE_LIVREE"));
65 ilm 1028
        selBonItem.setWhere(bonElt.getTable().getField("ID_BON_DE_LIVRAISON"), "=", idBon);
18 ilm 1029
 
1030
        String reqBonItem = selBonItem.asString();
1031
        Object obBonItem = getTable().getBase().getDataSource().execute(reqBonItem, new ArrayListHandler());
1032
 
1033
        final List<Object[]> myListBonItem = (List<Object[]>) obBonItem;
1034
        final int size = myListBonItem.size();
73 ilm 1035
 
1036
        for (int i = 0; i < size; i++) {
1037
            final Object[] objTmp = myListBonItem.get(i);
1038
            final SQLRow rowFactElem = tableFactureElem.getRow(((Number) objTmp[0]).intValue());
1039
            final SQLRowValues rowVals = new SQLRowValues(tableFactureElem);
1040
            rowVals.put("QTE_LIVREE", Integer.valueOf(rowFactElem.getInt("QTE_LIVREE") + ((Number) objTmp[1]).intValue()));
1041
            rowVals.update(rowFactElem.getID());
18 ilm 1042
        }
1043
 
1044
    }
1045
 
1046
    /***********************************************************************************************
1047
     * Mise à jour des quantités livrées dans les élements de facture
1048
     *
1049
     * @param idBon id du bon de livraison
73 ilm 1050
     * @throws SQLException
18 ilm 1051
     */
73 ilm 1052
    public void cancelUpdateQte(int idBon) throws SQLException {
18 ilm 1053
 
156 ilm 1054
        SQLTable tableFactureElem = getDirectory().getElement(SaisieVenteFactureItemSQLElement.class).getTable();
1055
        SQLSelect selBonItem = new SQLSelect();
1056
        BonDeLivraisonItemSQLElement bonElt = getDirectory().getElement(BonDeLivraisonItemSQLElement.class);
18 ilm 1057
        selBonItem.addSelect(bonElt.getTable().getField("ID_SAISIE_VENTE_FACTURE_ELEMENT"));
1058
        selBonItem.addSelect(bonElt.getTable().getField("QTE_LIVREE"));
65 ilm 1059
        selBonItem.setWhere(bonElt.getTable().getField("ID_BON_DE_LIVRAISON"), "=", idBon);
18 ilm 1060
 
1061
        String reqBonItem = selBonItem.asString();
1062
        Object obBonItem = getTable().getBase().getDataSource().execute(reqBonItem, new ArrayListHandler());
1063
 
1064
        final List<Object[]> myListBonItem = (List<Object[]>) obBonItem;
1065
        final int size = myListBonItem.size();
73 ilm 1066
 
1067
        for (int i = 0; i < size; i++) {
1068
            final Object[] objTmp = myListBonItem.get(i);
1069
            final SQLRow rowFactElem = tableFactureElem.getRow(((Number) objTmp[0]).intValue());
1070
            final SQLRowValues rowVals = new SQLRowValues(tableFactureElem);
1071
            rowVals.put("QTE_LIVREE", Integer.valueOf(((Number) objTmp[1]).intValue() - rowFactElem.getInt("QTE_LIVREE")));
1072
            rowVals.update(rowFactElem.getID());
18 ilm 1073
        }
1074
 
1075
    }
1076
 
83 ilm 1077
    protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
61 ilm 1078
        return "BL N°" + row.getString("NUMERO");
1079
    }
1080
 
1081
    /**
1082
     * Mise à jour des stocks pour chaque article composant la facture
73 ilm 1083
     *
1084
     * @throws SQLException
61 ilm 1085
     */
73 ilm 1086
    private void updateStock(int id) throws SQLException {
61 ilm 1087
 
1088
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
1089
        if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
1090
 
83 ilm 1091
            SQLRow row = getTable().getRow(id);
1092
            StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
61 ilm 1093
                @Override
83 ilm 1094
                public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
61 ilm 1095
                    return getLibelleStock(rowOrigin, rowElt);
1096
                }
93 ilm 1097
            }, row, row.getReferentRows(getTable().getTable("BON_DE_LIVRAISON_ELEMENT")),
1098
                    getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_DELIVER : TypeStockUpdate.REAL_DELIVER);
83 ilm 1099
 
142 ilm 1100
            if (getTable().getDBRoot().contains("RELIQUAT_BL")) {
1101
                List<SQLRow> l = row.getReferentRows(getTable().getTable("RELIQUAT_BL").getField("ID_BON_DE_LIVRAISON_ORIGINE"));
1102
                for (SQLRow sqlRow : l) {
1103
                    stockUpdater.addReliquat(sqlRow.getForeign("ID_ARTICLE"), sqlRow.getInt("QTE"), sqlRow.getBigDecimal("QTE_UNITAIRE"));
1104
                }
1105
            }
1106
 
83 ilm 1107
            stockUpdater.update();
61 ilm 1108
        }
1109
    }
1110
 
156 ilm 1111
    public void duplicate(final int idCmd) {
1112
 
1113
        final SQLElement cmd = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
1114
        final SQLElement cmdElt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON_ELEMENT");
1115
 
1116
        if (idCmd > 1) {
1117
            final SQLRow row = cmd.getTable().getRow(idCmd);
1118
            final SQLRowValues rowVals = new SQLRowValues(cmd.getTable());
1119
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
1120
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
1121
 
1122
            this.select(rowVals);
1123
        }
1124
 
1125
        final List<SQLRow> myListItem = cmd.getTable().getRow(idCmd).getReferentRows(cmdElt.getTable());
1126
 
1127
        if (myListItem.size() != 0) {
1128
            getRowValuesTable().getRowValuesTableModel().clearRows();
1129
 
1130
            for (final SQLRow rowElt : myListItem) {
1131
 
1132
                final SQLRowValues rowVals = rowElt.createUpdateRow();
1133
                rowVals.clearPrimaryKeys();
1134
                rowVals.putEmptyLink("ID_COMMANDE_CLIENT_ELEMENT");
1135
                getRowValuesTable().getRowValuesTableModel().addRow(rowVals);
1136
                final int rowIndex = getRowValuesTable().getRowValuesTableModel().getRowCount() - 1;
1137
                getRowValuesTable().getRowValuesTableModel().fireTableModelModified(rowIndex);
1138
            }
1139
        } else {
1140
            getRowValuesTable().getRowValuesTableModel().clearRows();
1141
        }
1142
        getRowValuesTable().getRowValuesTableModel().fireTableDataChanged();
1143
        getRowValuesTable().repaint();
1144
 
1145
    }
1146
 
142 ilm 1147
    public void loadFromReliquat(List<SQLRowValues> l) {
1148
        this.tableBonItem.insertFromReliquat(l);
1149
        this.tableBonItem.setEnabled(false);
1150
    }
1151
 
93 ilm 1152
    @Override
1153
    protected void refreshAfterSelect(SQLRowAccessor rSource) {
1154
 
1155
        tableBonItem.setDateDevise(date.getValue());
1156
    }
1157
 
18 ilm 1158
}