OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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