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