OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Rev 182 | 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.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
 
180 ilm 395
                        tableBonItem.setClient(rowClient, !isFilling());
396
 
93 ilm 397
                    } else {
398
                        comboContact.getRequest().setWhere(Where.FALSE);
156 ilm 399
                        tableBonItem.setRowCatComptable(null);
174 ilm 400
                        if (!isFilling()) {
401
                            tableBonItem.setClient(null, true);
402
                        }
93 ilm 403
                        // DevisSQLComponent.this.table.setTarif(null, false);
404
                    }
405
                }
406
            });
407
 
174 ilm 408
            // Commercial
409
            JLabel labelCommercial = new JLabel(getLabelFor("ID_COMMERCIAL"));
410
            labelCommercial.setHorizontalAlignment(SwingConstants.RIGHT);
180 ilm 411
            c.fill = GridBagConstraints.HORIZONTAL;
174 ilm 412
            c.gridx++;
413
            c.weightx = 0;
414
            this.add(labelCommercial, c);
415
 
416
            this.comboCommercial = new ElementComboBox(false, 25);
417
            this.comboCommercial.setListIconVisible(false);
418
            c.gridx++;
419
            c.fill = GridBagConstraints.NONE;
420
            c.weightx = 1;
421
            this.add(this.comboCommercial, c);
422
            addRequiredSQLObject(this.comboCommercial, "ID_COMMERCIAL");
423
 
93 ilm 424
        }
425
 
19 ilm 426
        final ElementComboBox boxTarif = new ElementComboBox();
41 ilm 427
        this.comboClient.addValueListener(new PropertyChangeListener() {
428
            @Override
429
            public void propertyChange(PropertyChangeEvent evt) {
430
                if (comboClient.getElement().getTable().contains("ID_TARIF")) {
28 ilm 431
                    if (BonDeLivraisonSQLComponent.this.isFilling())
432
                        return;
433
                    final SQLRow row = ((SQLRequestComboBox) evt.getSource()).getSelectedRow();
434
                    if (row != null) {
435
                        // SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
436
                        // if (foreignRow.isUndefined() &&
437
                        // !row.getForeignRow("ID_DEVISE").isUndefined()) {
438
                        // SQLRowValues rowValsD = new SQLRowValues(foreignRow.getTable());
439
                        // rowValsD.put("ID_DEVISE", row.getObject("ID_DEVISE"));
440
                        // foreignRow = rowValsD;
441
                        //
442
                        // }
443
                        // tableBonItem.setTarif(foreignRow, true);
444
                        SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
445
                        if (!foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())
156 ilm 446
                                && JOptionPane.showConfirmDialog(null, TM.tr("deliveryForm.applyClientRates")) == JOptionPane.YES_OPTION) { //$NON-NLS-1$
28 ilm 447
                            boxTarif.setValue(foreignRow.getID());
448
                            // SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
449
                            // true);
450
                        } else {
451
                            boxTarif.setValue(foreignRow.getID());
19 ilm 452
                        }
453
                    }
454
                }
41 ilm 455
            }
456
        });
19 ilm 457
 
18 ilm 458
        // Bouton tout livrer
156 ilm 459
        JButton boutonAll = new JButton(TM.tr("deliveryForm.shipAll")); //$NON-NLS-1$
18 ilm 460
 
461
        boutonAll.addActionListener(new ActionListener() {
462
            public void actionPerformed(ActionEvent e) {
463
                RowValuesTableModel m = BonDeLivraisonSQLComponent.this.tableBonItem.getModel();
464
 
465
                // on livre tout les éléments
466
                for (int i = 0; i < m.getRowCount(); i++) {
467
                    SQLRowValues rowVals = m.getRowValuesAt(i);
468
                    Object o = rowVals.getObject("QTE");
469
                    int qte = o == null ? 0 : ((Number) o).intValue();
470
                    m.putValue(qte, i, "QTE_LIVREE");
471
                }
472
            }
473
        });
474
 
19 ilm 475
        // Tarif
476
        if (this.getTable().getFieldsName().contains("ID_TARIF")) {
477
            // TARIF
478
            c.gridy++;
479
            c.gridx = 0;
480
            c.weightx = 0;
481
            c.weighty = 0;
482
            c.gridwidth = 1;
93 ilm 483
            c.fill = GridBagConstraints.HORIZONTAL;
484
            this.add(new JLabel(getLabelFor("ID_TARIF"), SwingUtilities.RIGHT), c);
19 ilm 485
            c.gridx++;
41 ilm 486
            c.gridwidth = 1;
93 ilm 487
            c.fill = GridBagConstraints.NONE;
19 ilm 488
            c.weightx = 1;
489
            this.add(boxTarif, c);
490
            this.addView(boxTarif, "ID_TARIF");
73 ilm 491
            boxTarif.addModelListener("wantedID", new PropertyChangeListener() {
19 ilm 492
 
493
                @Override
494
                public void propertyChange(PropertyChangeEvent evt) {
73 ilm 495
                    SQLRow selectedRow = boxTarif.getRequest().getPrimaryTable().getRow(boxTarif.getWantedID());
496
                    tableBonItem.setTarif(selectedRow, !isFilling());
19 ilm 497
                }
498
            });
174 ilm 499
 
500
            if (getTable().contains("SERVI_PAR")) {
501
                // Commercial
502
                JLabel labelServi = new JLabel("Servi par");
503
                labelServi.setHorizontalAlignment(SwingConstants.RIGHT);
504
                c.gridx++;
505
                c.weightx = 0;
506
                this.add(labelServi, c);
507
 
508
                SQLTextCombo comboServiPar = new SQLTextCombo();
509
                c.gridx++;
510
                c.fill = GridBagConstraints.NONE;
511
                c.weightx = 1;
512
                this.add(comboServiPar, c);
513
                addRequiredSQLObject(comboServiPar, "SERVI_PAR");
514
            }
19 ilm 515
        }
41 ilm 516
 
517
        if (getTable().contains("A_ATTENTION")) {
518
            // Date livraison
519
            c.gridx++;
520
            c.fill = GridBagConstraints.HORIZONTAL;
521
            c.weightx = 0;
522
            this.add(new JLabel(getLabelFor("A_ATTENTION"), SwingConstants.RIGHT), c);
523
 
524
            JTextField specLivraison = new JTextField();
525
            c.gridx++;
526
            c.weightx = 0;
527
            c.weighty = 0;
528
            this.add(specLivraison, c);
529
            this.addView(specLivraison, "A_ATTENTION");
530
        }
531
 
18 ilm 532
        // Element du bon
533
        List<JButton> l = new ArrayList<JButton>();
534
        l.add(boutonAll);
535
        this.tableBonItem = new BonDeLivraisonItemTable(l);
536
 
537
        c.gridx = 0;
538
        c.gridy++;
539
        c.weightx = 1;
540
        c.weighty = 1;
541
        c.gridwidth = GridBagConstraints.REMAINDER;
542
        c.fill = GridBagConstraints.BOTH;
543
        this.add(this.tableBonItem, c);
544
        c.anchor = GridBagConstraints.EAST;
545
        // Totaux
546
        reconfigure(this.textTotalHT);
547
        reconfigure(this.textTotalTVA);
548
        reconfigure(this.textTotalTTC);
142 ilm 549
        DeviseField fieldEco = new DeviseField(5);
93 ilm 550
        DeviseField textPortHT = new DeviseField(5);
551
        DeviseField textRemiseHT = new DeviseField();
552
 
553
        // Total
554
        DeviseField fieldDevise = new DeviseField();
555
        DeviseField fieldService = new DeviseField();
556
        DeviseField fieldHA = new DeviseField();
557
        fieldHA.setOpaque(false);
558
        fieldService.setOpaque(false);
559
        if (getTable().contains("TOTAL_DEVISE")) {
560
            addSQLObject(fieldDevise, "TOTAL_DEVISE");
561
            addRequiredSQLObject(fieldService, "TOTAL_SERVICE");
562
        }
563
        if (getTable().contains("PREBILAN")) {
564
            addSQLObject(fieldHA, "PREBILAN");
565
        } else if (getTable().contains("T_HA")) {
566
            addSQLObject(fieldHA, "T_HA");
94 ilm 567
            this.allowEditable("T_HA", false);
93 ilm 568
        }
94 ilm 569
        // Disable
93 ilm 570
 
571
        SQLRequestComboBox boxTaxePort = new SQLRequestComboBox(false, 8);
572
 
18 ilm 573
        // Poids Total
574
        c.gridy++;
575
        c.gridx = 1;
576
        c.weightx = 0;
577
        c.weighty = 0;
578
        c.anchor = GridBagConstraints.EAST;
579
        c.gridwidth = 1;
580
        c.fill = GridBagConstraints.NONE;
73 ilm 581
        this.addSQLObject(this.textPoidsTotal, "TOTAL_POIDS");
142 ilm 582
        this.addSQLObject(fieldEco, "T_ECO_CONTRIBUTION");
73 ilm 583
        this.addRequiredSQLObject(this.textTotalHT, "TOTAL_HT");
584
        this.addRequiredSQLObject(this.textTotalTVA, "TOTAL_TVA");
585
        this.addRequiredSQLObject(this.textTotalTTC, "TOTAL_TTC");
142 ilm 586
        this.allowEditable("T_ECO_CONTRIBUTION", false);
94 ilm 587
        this.allowEditable("TOTAL_HT", false);
588
        this.allowEditable("TOTAL_TVA", false);
589
        this.allowEditable("TOTAL_TTC", false);
590
        this.allowEditable("TOTAL_POIDS", false);
142 ilm 591
        final TotalPanel panelTotal = new TotalPanel(tableBonItem, fieldEco, textTotalHT, textTotalTVA, textTotalTTC, textPortHT, textRemiseHT, fieldService, fieldHA, fieldDevise, this.textPoidsTotal,
592
                null, (getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
93 ilm 593
        // if (b) {
594
        JPanel panel = new JPanel(new GridBagLayout());
595
        GridBagConstraints cFrais = new DefaultGridBagConstraints();
596
        panel.add(new JLabel(getLabelFor("TOTAL_POIDS")), cFrais);
597
 
598
        this.textPoidsTotal.setEnabled(false);
599
        this.textPoidsTotal.setHorizontalAlignment(JTextField.RIGHT);
600
        this.textPoidsTotal.setDisabledTextColor(Color.BLACK);
601
        cFrais.gridx++;
602
        panel.add(this.textPoidsTotal, cFrais);
603
 
604
        panel.setOpaque(false);
605
        DefaultGridBagConstraints.lockMinimumSize(panel);
606
 
607
        DefaultGridBagConstraints.lockMinimumSize(textPortHT);
608
        addSQLObject(textPortHT, "PORT_HT");
609
        DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
610
        addSQLObject(textRemiseHT, "REMISE_HT");
611
 
612
        // Frais de port
613
 
614
        if (getTable().contains("ID_TAXE_PORT")) {
615
 
616
            JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
617
            labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
618
            cFrais.gridx = 0;
619
            cFrais.gridy++;
620
            panel.add(labelPortHT, cFrais);
621
            cFrais.gridx++;
622
            panel.add(textPortHT, cFrais);
623
 
624
            JLabel labelTaxeHT = new JLabel(getLabelFor("ID_TAXE_PORT"));
625
            labelTaxeHT.setHorizontalAlignment(SwingConstants.RIGHT);
626
            cFrais.gridx = 0;
627
            cFrais.gridy++;
628
            panel.add(labelTaxeHT, cFrais);
629
            cFrais.gridx++;
630
            panel.add(boxTaxePort, cFrais);
631
            this.addView(boxTaxePort, "ID_TAXE_PORT", REQ);
632
 
633
            boxTaxePort.addValueListener(new PropertyChangeListener() {
634
 
635
                @Override
636
                public void propertyChange(PropertyChangeEvent evt) {
637
                    panelTotal.updateTotal();
638
                }
639
            });
640
        }
641
 
642
        // Remise
643
        JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
644
        labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
645
        cFrais.gridy++;
646
        cFrais.gridx = 0;
647
        panel.add(labelRemiseHT, cFrais);
648
        cFrais.gridx++;
649
        panel.add(textRemiseHT, cFrais);
650
 
651
        c.gridx = 1;
652
        c.weightx = 0;
653
        c.weighty = 0;
654
        c.gridwidth = 1;
655
        c.fill = GridBagConstraints.NONE;
656
        c.anchor = GridBagConstraints.NORTHEAST;
657
        this.add(panel, c);
658
 
18 ilm 659
        c.gridx = 2;
660
        c.gridwidth = GridBagConstraints.REMAINDER;
661
        c.weightx = 0;
662
        c.weighty = 0;
663
        c.anchor = GridBagConstraints.EAST;
664
        c.fill = GridBagConstraints.HORIZONTAL;
73 ilm 665
        this.add(panelTotal, c);
18 ilm 666
 
667
        c.anchor = GridBagConstraints.WEST;
668
 
142 ilm 669
        if (getTable().getDBRoot().contains("RELIQUAT_BL")) {
670
 
671
            c.gridwidth = GridBagConstraints.REMAINDER;
672
            c.weightx = 1;
673
            c.fill = GridBagConstraints.HORIZONTAL;
674
            c.gridx = 0;
675
            c.gridy++;
676
            TitledSeparator sep = new TitledSeparator("Reliquat de kits");
677
            c.insets = new Insets(10, 2, 1, 2);
678
            this.add(sep, c);
679
            c.insets = new Insets(2, 2, 1, 2);
680
 
681
            // Reliquat du bon
682
            this.tableBonReliquatItem = new ReliquatRowValuesTable("RELIQUAT_BL");
683
            c.gridx = 0;
684
            c.gridy++;
685
            c.weightx = 1;
686
            c.weighty = 1;
687
            c.gridwidth = GridBagConstraints.REMAINDER;
688
            c.fill = GridBagConstraints.BOTH;
689
            this.add(this.tableBonReliquatItem, c);
690
            this.tableBonItem.setReliquatTable(tableBonReliquatItem);
691
        }
692
 
18 ilm 693
        /*******************************************************************************************
694
         * * INFORMATIONS COMPLEMENTAIRES
695
         ******************************************************************************************/
696
        c.gridwidth = GridBagConstraints.REMAINDER;
697
        c.weightx = 1;
698
        c.fill = GridBagConstraints.HORIZONTAL;
699
        c.gridx = 0;
700
        c.gridy++;
93 ilm 701
        TitledSeparator sep = new TitledSeparator(getLabelFor("INFOS"));
18 ilm 702
        c.insets = new Insets(10, 2, 1, 2);
703
        this.add(sep, c);
704
        c.insets = new Insets(2, 2, 1, 2);
705
 
706
        ITextArea textInfos = new ITextArea(4, 4);
707
 
708
        c.gridx = 0;
709
        c.gridy++;
710
        c.gridheight = 1;
711
        c.gridwidth = GridBagConstraints.REMAINDER;
712
        c.weightx = 1;
713
        c.weighty = 0;
714
        c.fill = GridBagConstraints.BOTH;
715
 
716
        final JScrollPane scrollPane = new JScrollPane(textInfos);
717
        this.add(scrollPane, c);
718
        textInfos.setBorder(null);
719
        DefaultGridBagConstraints.lockMinimumSize(scrollPane);
720
 
721
        c.gridx = 0;
722
        c.gridy++;
723
        c.gridheight = 1;
724
        c.gridwidth = 4;
725
        c.weightx = 0;
726
        c.weighty = 0;
727
        c.fill = GridBagConstraints.NONE;
728
        c.anchor = GridBagConstraints.EAST;
729
 
21 ilm 730
        this.panelOO = new PanelOOSQLComponent(this);
731
        this.add(this.panelOO, c);
732
 
18 ilm 733
        this.addRequiredSQLObject(date, "DATE");
734
        this.addSQLObject(textInfos, "INFOS");
735
        this.addSQLObject(this.textNom, "NOM");
736
        this.addSQLObject(this.selectCommande, "ID_COMMANDE_CLIENT");
737
        this.addRequiredSQLObject(this.textNumeroUnique, "NUMERO");
73 ilm 738
 
18 ilm 739
        // Doit etre locké a la fin
740
        DefaultGridBagConstraints.lockMinimumSize(comboClient);
741
 
93 ilm 742
        textPortHT.getDocument().addDocumentListener(new DocumentListener() {
743
            public void changedUpdate(DocumentEvent e) {
744
                panelTotal.updateTotal();
745
            }
746
 
747
            public void removeUpdate(DocumentEvent e) {
748
                panelTotal.updateTotal();
749
            }
750
 
751
            public void insertUpdate(DocumentEvent e) {
752
                panelTotal.updateTotal();
753
            }
754
        });
755
 
756
        textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
757
            public void changedUpdate(DocumentEvent e) {
758
                panelTotal.updateTotal();
759
            }
760
 
761
            public void removeUpdate(DocumentEvent e) {
762
                panelTotal.updateTotal();
763
            }
764
 
765
            public void insertUpdate(DocumentEvent e) {
766
                panelTotal.updateTotal();
767
            }
768
        });
769
 
18 ilm 770
    }
771
 
28 ilm 772
    public BonDeLivraisonItemTable getTableBonItem() {
773
        return this.tableBonItem;
774
    }
775
 
18 ilm 776
    private void reconfigure(JTextField field) {
777
        field.setEnabled(false);
778
        field.setHorizontalAlignment(JTextField.RIGHT);
779
        field.setDisabledTextColor(Color.BLACK);
780
        field.setBorder(null);
781
    }
782
 
783
    public int insert(SQLRow order) {
784
 
785
        int idBon = getSelectedID();
142 ilm 786
        int attempt = 0;
787
        // on verifie qu'un devis du meme numero n'a pas été inséré entre temps
788
        if (!this.textNumeroUnique.checkValidation(false)) {
789
            while (attempt < JUniqueTextField.RETRY_COUNT) {
790
                String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), date.getDate());
791
                this.textNumeroUnique.setText(num);
792
                attempt++;
793
                if (this.textNumeroUnique.checkValidation(false)) {
794
                    System.err.println("ATEMPT " + attempt + " SUCCESS WITH NUMERO " + num);
795
                    break;
796
                }
797
                try {
798
                    Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
799
                } catch (InterruptedException e) {
800
                    e.printStackTrace();
801
                }
802
            }
803
        }
804
        final String num = this.textNumeroUnique.getText();
805
        if (attempt == JUniqueTextField.RETRY_COUNT) {
806
            idBon = getSelectedID();
156 ilm 807
            ExceptionHandler.handle(TM.tr("deliveryForm.cannotAdd.existingNumber")); //$NON-NLS-1$
142 ilm 808
            final Object root = SwingUtilities.getRoot(this);
809
            if (root instanceof EditFrame) {
810
                final EditFrame frame = (EditFrame) root;
811
                frame.getPanel().setAlwaysVisible(true);
812
            }
813
        } else {
156 ilm 814
            if (getTable().getDBRoot().contains("TARIF_AGENCE")) {
815
                final List<ProductComponent> comps = checkStock();
816
                if (comps.size() > 0) {
817
                    String article = "";
818
                    for (ProductComponent comp : comps) {
819
                        article += "\n " + comp.getProduct().getString("CODE") + " --- " + comp.getProduct().getString("NOM");
820
                    }
821
                    JOptionPane.showMessageDialog(null, TM.tr("deliveryForm.cannotCreate.notInStock") + article); //$NON-NLS-1$
822
                    final Object root = SwingUtilities.getRoot(this);
823
                    if (root instanceof EditFrame) {
824
                        final EditFrame frame = (EditFrame) root;
825
                        frame.getPanel().setAlwaysVisible(true);
826
                    }
827
                    return -1;
828
                }
829
            }
18 ilm 830
            idBon = super.insert(order);
142 ilm 831
            if (this.tableBonReliquatItem != null) {
832
                this.tableBonReliquatItem.updateField("ID_BON_DE_LIVRAISON_ORIGINE", idBon);
833
            }
18 ilm 834
            this.tableBonItem.updateField("ID_BON_DE_LIVRAISON", idBon);
835
            this.tableBonItem.createArticle(idBon, this.getElement());
156 ilm 836
            final List<Object> cmdDourceTrRowsFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(idBon, "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
837
            ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(cmdDourceTrRowsFrom, "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
838
            final List<Object> devisSourceTrRowsFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(idBon, "DEVIS_ELEMENT", "DEVIS");
839
            ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(devisSourceTrRowsFrom, "DEVIS_ELEMENT", "DEVIS");
18 ilm 840
            // generation du document
841
            BonLivraisonXmlSheet bSheet = new BonLivraisonXmlSheet(getTable().getRow(idBon));
25 ilm 842
            bSheet.createDocumentAsynchronous();
843
            bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
18 ilm 844
 
845
            // incrémentation du numéro auto
93 ilm 846
            if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass()).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
18 ilm 847
                SQLRowValues rowVals = new SQLRowValues(this.tableNum);
848
                int val = this.tableNum.getRow(2).getInt("BON_L_START");
849
                val++;
850
                rowVals.put("BON_L_START", new Integer(val));
851
 
852
                try {
853
                    rowVals.update(2);
854
                } catch (SQLException e) {
855
                    e.printStackTrace();
856
                }
857
            }
858
 
61 ilm 859
            SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
860
 
861
            if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
862
 
73 ilm 863
                try {
864
                    updateStock(idBon);
865
                } catch (SQLException e) {
866
                    throw new IllegalStateException(e);
867
                }
61 ilm 868
            }
18 ilm 869
            // updateQte(idBon);
142 ilm 870
            if (attempt > 0) {
871
                SwingUtilities.invokeLater(new Runnable() {
872
                    public void run() {
156 ilm 873
                        JOptionPane.showMessageDialog(null, TM.tr("deliveryForm.numberRefreshed", num)); //$NON-NLS-1$
142 ilm 874
                    }
875
                });
18 ilm 876
            }
877
        }
878
 
879
        return idBon;
880
    }
881
 
156 ilm 882
    private List<ProductComponent> checkStock() {
883
        List<ProductComponent> comps = new ArrayList<ProductComponent>();
884
        final RowValuesTableModel rowValuesTableModel = this.tableBonItem.getRowValuesTable().getRowValuesTableModel();
885
 
886
        for (int i = 0; i < rowValuesTableModel.getRowCount(); i++) {
887
            final SQLRowValues rowValuesAt = rowValuesTableModel.getRowValuesAt(i);
888
            if (rowValuesAt.getInt("QTE_LIVREE") > 0 && rowValuesAt != null && rowValuesAt.getObject("ID_ARTICLE") != null && !rowValuesAt.isForeignEmpty("ID_ARTICLE")) {
889
                SQLRowAccessor article = rowValuesAt.getForeign("ID_ARTICLE");
890
                if (article.getBoolean("GESTION_STOCK")) {
891
                    ProductComponent comp = ProductComponent.createFrom(rowValuesAt);
892
                    if (comp.getStock() != null && !comp.getStock().isUndefined() && comp.getStock().getFloat("QTE_REEL") < 0) {
893
                        comps.add(comp);
894
                    }
895
                }
896
            }
897
        }
898
        return comps;
899
    }
900
 
18 ilm 901
    @Override
902
    public void select(SQLRowAccessor r) {
28 ilm 903
        if (r == null || r.getIDNumber() == null)
904
            super.select(r);
905
        else {
906
            System.err.println(r);
132 ilm 907
            final SQLRowValues rVals = r.asRowValues().deepCopy();
28 ilm 908
            final SQLRowValues vals = new SQLRowValues(r.getTable());
909
            vals.load(rVals, createSet("ID_CLIENT"));
910
            vals.setID(rVals.getID());
911
            System.err.println("Select CLIENT");
912
            super.select(vals);
913
            rVals.remove("ID_CLIENT");
914
            super.select(rVals);
915
        }
142 ilm 916
        if (this.tableBonReliquatItem != null) {
917
            this.tableBonReliquatItem.getRowValuesTable().clear();
918
            if (r != null) {
919
                this.tableBonReliquatItem.getRowValuesTable().insertFrom("ID_BON_LIVRAISON_ORIGINE", r.asRowValues());
920
            }
921
        }
18 ilm 922
    }
923
 
924
    @Override
925
    public void update() {
926
        if (!this.textNumeroUnique.checkValidation()) {
156 ilm 927
            ExceptionHandler.handle(TM.tr("deliveryForm.cannotAdd.existingNumber")); //$NON-NLS-1$
18 ilm 928
            Object root = SwingUtilities.getRoot(this);
929
            if (root instanceof EditFrame) {
930
                EditFrame frame = (EditFrame) root;
931
                frame.getPanel().setAlwaysVisible(true);
932
            }
933
            return;
934
        }
935
        super.update();
142 ilm 936
        if (tableBonReliquatItem != null) {
937
            this.tableBonReliquatItem.updateField("ID_BON_DE_LIVRAISON_ORIGINE", getSelectedID());
938
        }
156 ilm 939
        final List<Object> cmdClientFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(getSelectedID(), "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
940
        final List<Object> devisFrom = ((BonDeLivraisonSQLElement) getElement()).getSourceTrRowsFrom(getSelectedID(), "DEVIS_ELEMENT", "DEVIS");
18 ilm 941
        this.tableBonItem.updateField("ID_BON_DE_LIVRAISON", getSelectedID());
942
        this.tableBonItem.createArticle(getSelectedID(), this.getElement());
156 ilm 943
        ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(devisFrom, "DEVIS_ELEMENT", "DEVIS");
944
        ((BonDeLivraisonSQLElement) getElement()).updateQteLivree(cmdClientFrom, "COMMANDE_CLIENT_ELEMENT", "COMMANDE_CLIENT");
18 ilm 945
 
946
        // generation du document
947
        BonLivraisonXmlSheet bSheet = new BonLivraisonXmlSheet(getTable().getRow(getSelectedID()));
25 ilm 948
        bSheet.createDocumentAsynchronous();
949
        bSheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
950
 
61 ilm 951
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
952
        if (!prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
953
 
73 ilm 954
            try {
955
                updateStock(getSelectedID());
956
            } catch (SQLException e) {
957
                throw new IllegalStateException(e);
958
            }
61 ilm 959
        }
960
 
18 ilm 961
    }
962
 
132 ilm 963
    /**
964
     * Chargement des qtés restantes à livrer
965
     *
966
     * @param l
967
     */
156 ilm 968
    public void loadQuantity(List<SQLRowValues> l, final String fromTableElt) {
132 ilm 969
        Map<Integer, SQLRowValues> map = new HashMap<Integer, SQLRowValues>();
970
        for (SQLRowValues sqlRowValues : l) {
156 ilm 971
            // On ne prend en compte que les articles ou les lignes différentes de 0, autres lignes
972
            // considérées comme commentaires
973
            if (!sqlRowValues.isForeignEmpty("ID_ARTICLE") || sqlRowValues.getBigDecimal("PV_HT").signum() != 0) {
974
                if (!sqlRowValues.isForeignEmpty("ID_" + fromTableElt)) {
975
                    final int foreignID = sqlRowValues.getForeignID("ID_" + fromTableElt);
976
                    if (!map.containsKey(foreignID)) {
977
                        map.put(foreignID, sqlRowValues);
978
                    } else {
979
                        SQLRowValues vals = map.get(foreignID);
980
                        if (sqlRowValues.getInt("QTE_LIVREE") > 0) {
981
                            if (NumberUtils.areNumericallyEqual(sqlRowValues.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || sqlRowValues.getInt("QTE_LIVREE") > 1) {
982
                                vals.put("QTE_LIVREE", vals.getInt("QTE_LIVREE") + sqlRowValues.getInt("QTE_LIVREE"));
983
                            } else {
984
                                vals.put("QTE_UNITAIRE", vals.getBigDecimal("QTE_UNITAIRE").add(sqlRowValues.getBigDecimal("QTE_UNITAIRE")));
985
                            }
132 ilm 986
                        }
987
                    }
988
                }
989
            }
990
        }
991
        int count = this.tableBonItem.getModel().getRowCount();
992
        for (int i = 0; i < count; i++) {
993
            final SQLRowValues rowValuesAt = this.tableBonItem.getModel().getRowValuesAt(i);
994
            rowValuesAt.put("QTE_LIVREE", rowValuesAt.getObject("QTE"));
995
        }
996
 
997
        for (int i = 0; i < count; i++) {
998
            SQLRowValues r = this.tableBonItem.getModel().getRowValuesAt(i);
156 ilm 999
            SQLRowValues rowTR = map.get(r.getForeignID("ID_" + fromTableElt));
132 ilm 1000
            if (rowTR != null && !rowTR.isUndefined()) {
1001
                if (r.getInt("QTE_LIVREE") > 0 && rowTR.getInt("QTE_LIVREE") > 0) {
1002
                    if (NumberUtils.areNumericallyEqual(r.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || r.getInt("QTE_LIVREE") > 1) {
1003
                        this.tableBonItem.getModel().putValue(r.getInt("QTE_LIVREE") - rowTR.getInt("QTE_LIVREE"), i, "QTE_LIVREE");
1004
                    } else {
1005
                        this.tableBonItem.getModel().putValue(r.getBigDecimal("QTE_UNITAIRE").subtract(rowTR.getBigDecimal("QTE_UNITAIRE")), i, "QTE_UNITAIRE");
1006
                    }
1007
                }
1008
            } else {
1009
                this.tableBonItem.getModel().putValue(r.getObject("QTE"), i, "QTE_LIVREE");
1010
            }
1011
        }
1012
    }
1013
 
18 ilm 1014
    /***********************************************************************************************
1015
     * Mise à jour des quantités livrées dans les élements de facture
1016
     *
1017
     * @param idBon id du bon de livraison
73 ilm 1018
     * @throws SQLException
18 ilm 1019
     */
73 ilm 1020
    public void updateQte(int idBon) throws SQLException {
18 ilm 1021
 
156 ilm 1022
        SQLTable tableFactureElem = getDirectory().getElement(SaisieVenteFactureItemSQLElement.class).getTable();
1023
        SQLSelect selBonItem = new SQLSelect();
1024
        BonDeLivraisonItemSQLElement bonElt = getDirectory().getElement(BonDeLivraisonItemSQLElement.class);
18 ilm 1025
        selBonItem.addSelect(bonElt.getTable().getField("ID_SAISIE_VENTE_FACTURE_ELEMENT"));
1026
        selBonItem.addSelect(bonElt.getTable().getField("QTE_LIVREE"));
65 ilm 1027
        selBonItem.setWhere(bonElt.getTable().getField("ID_BON_DE_LIVRAISON"), "=", idBon);
18 ilm 1028
 
1029
        String reqBonItem = selBonItem.asString();
1030
        Object obBonItem = getTable().getBase().getDataSource().execute(reqBonItem, new ArrayListHandler());
1031
 
1032
        final List<Object[]> myListBonItem = (List<Object[]>) obBonItem;
1033
        final int size = myListBonItem.size();
73 ilm 1034
 
1035
        for (int i = 0; i < size; i++) {
1036
            final Object[] objTmp = myListBonItem.get(i);
1037
            final SQLRow rowFactElem = tableFactureElem.getRow(((Number) objTmp[0]).intValue());
1038
            final SQLRowValues rowVals = new SQLRowValues(tableFactureElem);
1039
            rowVals.put("QTE_LIVREE", Integer.valueOf(rowFactElem.getInt("QTE_LIVREE") + ((Number) objTmp[1]).intValue()));
1040
            rowVals.update(rowFactElem.getID());
18 ilm 1041
        }
1042
 
1043
    }
1044
 
1045
    /***********************************************************************************************
1046
     * Mise à jour des quantités livrées dans les élements de facture
1047
     *
1048
     * @param idBon id du bon de livraison
73 ilm 1049
     * @throws SQLException
18 ilm 1050
     */
73 ilm 1051
    public void cancelUpdateQte(int idBon) throws SQLException {
18 ilm 1052
 
156 ilm 1053
        SQLTable tableFactureElem = getDirectory().getElement(SaisieVenteFactureItemSQLElement.class).getTable();
1054
        SQLSelect selBonItem = new SQLSelect();
1055
        BonDeLivraisonItemSQLElement bonElt = getDirectory().getElement(BonDeLivraisonItemSQLElement.class);
18 ilm 1056
        selBonItem.addSelect(bonElt.getTable().getField("ID_SAISIE_VENTE_FACTURE_ELEMENT"));
1057
        selBonItem.addSelect(bonElt.getTable().getField("QTE_LIVREE"));
65 ilm 1058
        selBonItem.setWhere(bonElt.getTable().getField("ID_BON_DE_LIVRAISON"), "=", idBon);
18 ilm 1059
 
1060
        String reqBonItem = selBonItem.asString();
1061
        Object obBonItem = getTable().getBase().getDataSource().execute(reqBonItem, new ArrayListHandler());
1062
 
1063
        final List<Object[]> myListBonItem = (List<Object[]>) obBonItem;
1064
        final int size = myListBonItem.size();
73 ilm 1065
 
1066
        for (int i = 0; i < size; i++) {
1067
            final Object[] objTmp = myListBonItem.get(i);
1068
            final SQLRow rowFactElem = tableFactureElem.getRow(((Number) objTmp[0]).intValue());
1069
            final SQLRowValues rowVals = new SQLRowValues(tableFactureElem);
1070
            rowVals.put("QTE_LIVREE", Integer.valueOf(((Number) objTmp[1]).intValue() - rowFactElem.getInt("QTE_LIVREE")));
1071
            rowVals.update(rowFactElem.getID());
18 ilm 1072
        }
1073
 
1074
    }
1075
 
83 ilm 1076
    protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
61 ilm 1077
        return "BL N°" + row.getString("NUMERO");
1078
    }
1079
 
1080
    /**
1081
     * Mise à jour des stocks pour chaque article composant la facture
73 ilm 1082
     *
1083
     * @throws SQLException
61 ilm 1084
     */
73 ilm 1085
    private void updateStock(int id) throws SQLException {
61 ilm 1086
 
1087
        SQLPreferences prefs = new SQLPreferences(getTable().getDBRoot());
180 ilm 1088
        // Check if tr from bl or cmd pour DS
1089
        boolean stockWithBL = !prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true);
1090
        if (getTable().getForeignTable("ID_CLIENT").contains("NOTE_2018")) {
83 ilm 1091
            SQLRow row = getTable().getRow(id);
180 ilm 1092
            List<SQLRow> trCmd = row.getReferentRows(getTable().getTable("TR_COMMANDE_CLIENT"));
1093
            if (!trCmd.isEmpty()) {
1094
                stockWithBL = true;
1095
            }
1096
        }
1097
        if (stockWithBL) {
1098
            SQLRow row = getTable().getRow(id);
83 ilm 1099
            StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
61 ilm 1100
                @Override
83 ilm 1101
                public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
61 ilm 1102
                    return getLibelleStock(rowOrigin, rowElt);
1103
                }
93 ilm 1104
            }, row, row.getReferentRows(getTable().getTable("BON_DE_LIVRAISON_ELEMENT")),
1105
                    getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_DELIVER : TypeStockUpdate.REAL_DELIVER);
83 ilm 1106
 
142 ilm 1107
            if (getTable().getDBRoot().contains("RELIQUAT_BL")) {
1108
                List<SQLRow> l = row.getReferentRows(getTable().getTable("RELIQUAT_BL").getField("ID_BON_DE_LIVRAISON_ORIGINE"));
1109
                for (SQLRow sqlRow : l) {
1110
                    stockUpdater.addReliquat(sqlRow.getForeign("ID_ARTICLE"), sqlRow.getInt("QTE"), sqlRow.getBigDecimal("QTE_UNITAIRE"));
1111
                }
1112
            }
1113
 
83 ilm 1114
            stockUpdater.update();
61 ilm 1115
        }
1116
    }
1117
 
156 ilm 1118
    public void duplicate(final int idCmd) {
1119
 
1120
        final SQLElement cmd = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
1121
        final SQLElement cmdElt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON_ELEMENT");
1122
 
1123
        if (idCmd > 1) {
1124
            final SQLRow row = cmd.getTable().getRow(idCmd);
1125
            final SQLRowValues rowVals = new SQLRowValues(cmd.getTable());
1126
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
1127
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
1128
 
1129
            this.select(rowVals);
1130
        }
1131
 
1132
        final List<SQLRow> myListItem = cmd.getTable().getRow(idCmd).getReferentRows(cmdElt.getTable());
1133
 
1134
        if (myListItem.size() != 0) {
1135
            getRowValuesTable().getRowValuesTableModel().clearRows();
1136
 
1137
            for (final SQLRow rowElt : myListItem) {
1138
 
1139
                final SQLRowValues rowVals = rowElt.createUpdateRow();
1140
                rowVals.clearPrimaryKeys();
1141
                rowVals.putEmptyLink("ID_COMMANDE_CLIENT_ELEMENT");
1142
                getRowValuesTable().getRowValuesTableModel().addRow(rowVals);
1143
                final int rowIndex = getRowValuesTable().getRowValuesTableModel().getRowCount() - 1;
1144
                getRowValuesTable().getRowValuesTableModel().fireTableModelModified(rowIndex);
1145
            }
1146
        } else {
1147
            getRowValuesTable().getRowValuesTableModel().clearRows();
1148
        }
1149
        getRowValuesTable().getRowValuesTableModel().fireTableDataChanged();
1150
        getRowValuesTable().repaint();
1151
 
1152
    }
1153
 
142 ilm 1154
    public void loadFromReliquat(List<SQLRowValues> l) {
1155
        this.tableBonItem.insertFromReliquat(l);
1156
        this.tableBonItem.setEnabled(false);
1157
    }
1158
 
93 ilm 1159
    @Override
1160
    protected void refreshAfterSelect(SQLRowAccessor rSource) {
1161
 
1162
        tableBonItem.setDateDevise(date.getValue());
1163
    }
1164
 
18 ilm 1165
}