OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.supplychain.receipt.component;
15
 
16
import org.openconcerto.erp.config.ComptaPropsConfiguration;
17
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
63 ilm 18
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18 ilm 19
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
20
import org.openconcerto.erp.core.common.ui.DeviseField;
132 ilm 21
import org.openconcerto.erp.core.common.ui.TotalPanel;
149 ilm 22
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
18 ilm 23
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
94 ilm 24
import org.openconcerto.erp.core.sales.product.ui.ReliquatRowValuesTable;
144 ilm 25
import org.openconcerto.erp.core.supplychain.order.element.DemandeAchatItemSQLElement;
142 ilm 26
import org.openconcerto.erp.core.supplychain.receipt.element.BonReceptionSQLElement;
18 ilm 27
import org.openconcerto.erp.core.supplychain.receipt.ui.BonReceptionItemTable;
83 ilm 28
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
93 ilm 29
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
61 ilm 30
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
94 ilm 31
import org.openconcerto.erp.generationDoc.gestcomm.BonReceptionXmlSheet;
32
import org.openconcerto.erp.panel.PanelOOSQLComponent;
149 ilm 33
import org.openconcerto.erp.preferences.DefaultNXProps;
18 ilm 34
import org.openconcerto.sql.Configuration;
35
import org.openconcerto.sql.element.SQLElement;
36
import org.openconcerto.sql.model.SQLRow;
37
import org.openconcerto.sql.model.SQLRowAccessor;
38
import org.openconcerto.sql.model.SQLRowValues;
39
import org.openconcerto.sql.model.SQLTable;
40
import org.openconcerto.sql.sqlobject.ElementComboBox;
41
import org.openconcerto.sql.sqlobject.JUniqueTextField;
42
import org.openconcerto.sql.view.EditFrame;
73 ilm 43
import org.openconcerto.sql.view.list.RowValuesTable;
18 ilm 44
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 45
import org.openconcerto.ui.FormLayouter;
18 ilm 46
import org.openconcerto.ui.JDate;
47
import org.openconcerto.ui.TitledSeparator;
57 ilm 48
import org.openconcerto.ui.component.ITextArea;
149 ilm 49
import org.openconcerto.ui.preferences.DefaultProps;
90 ilm 50
import org.openconcerto.utils.DecimalUtils;
18 ilm 51
import org.openconcerto.utils.ExceptionHandler;
132 ilm 52
import org.openconcerto.utils.NumberUtils;
18 ilm 53
 
149 ilm 54
import java.awt.Color;
132 ilm 55
import java.awt.GridBagConstraints;
56
import java.awt.GridBagLayout;
57
import java.awt.Insets;
58
import java.beans.PropertyChangeEvent;
59
import java.beans.PropertyChangeListener;
60
import java.math.BigDecimal;
61
import java.sql.SQLException;
62
import java.util.HashMap;
63
import java.util.List;
64
import java.util.Map;
65
 
66
import javax.swing.JCheckBox;
67
import javax.swing.JLabel;
68
import javax.swing.JPanel;
69
import javax.swing.JScrollPane;
70
import javax.swing.JTextField;
71
import javax.swing.SwingConstants;
72
import javax.swing.SwingUtilities;
149 ilm 73
import javax.swing.event.DocumentEvent;
74
import javax.swing.event.DocumentListener;
75
import javax.swing.event.TableModelEvent;
76
import javax.swing.event.TableModelListener;
132 ilm 77
 
18 ilm 78
public class BonReceptionSQLComponent extends TransfertBaseSQLComponent {
79
    private BonReceptionItemTable tableBonItem;
94 ilm 80
    private ReliquatRowValuesTable tableBonReliquatItem;
18 ilm 81
    private ElementComboBox selectCommande;
82
    private ElementComboBox fournisseur;
83
    private JUniqueTextField textNumeroUnique;
84
    private final SQLTable tableNum = getTable().getBase().getTable("NUMEROTATION_AUTO");
85
    private final JTextField textReference = new JTextField(25);
94 ilm 86
    private PanelOOSQLComponent panelOO;
93 ilm 87
    private JDate date = new JDate(true);
18 ilm 88
 
89
    public BonReceptionSQLComponent() {
90
        super(Configuration.getInstance().getDirectory().getElement("BON_RECEPTION"));
91
    }
92
 
93
    @Override
94
    protected SQLRowValues createDefaults() {
95
        this.tableBonItem.getModel().clearRows();
93 ilm 96
        this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
97
        SQLRowValues rowVals = new SQLRowValues(getTable());
132 ilm 98
        rowVals.put("T_DEVISE", 0L);
93 ilm 99
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
100
            rowVals.put("CREATE_VIRTUAL_STOCK", Boolean.TRUE);
101
        }
149 ilm 102
        if (getTable().contains("ID_TAXE_PORT")) {
103
            rowVals.put("ID_TAXE_PORT", TaxeCache.getCache().getFirstTaxe().getID());
104
        }
93 ilm 105
        return rowVals;
18 ilm 106
    }
107
 
108
    public void addViews() {
109
        this.setLayout(new GridBagLayout());
110
        final GridBagConstraints c = new DefaultGridBagConstraints();
111
 
93 ilm 112
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
113
            this.addView(new JCheckBox(), "CREATE_VIRTUAL_STOCK");
114
        }
115
 
25 ilm 116
        // Champ Module
117
        c.gridx = 0;
118
        c.gridy++;
119
        c.gridwidth = GridBagConstraints.REMAINDER;
63 ilm 120
        final JPanel addP = ComptaSQLConfElement.createAdditionalPanel();
25 ilm 121
        this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
122
        this.add(addP, c);
123
 
124
        c.gridy++;
125
        c.gridwidth = 1;
126
 
18 ilm 127
        this.selectCommande = new ElementComboBox();
128
        // Numero
129
        JLabel labelNum = new JLabel(getLabelFor("NUMERO"));
130
        labelNum.setHorizontalAlignment(SwingConstants.RIGHT);
131
        this.add(labelNum, c);
132
 
142 ilm 133
        this.textNumeroUnique = new JUniqueTextField(16) {
134
            @Override
135
            public String getAutoRefreshNumber() {
136
                if (getMode() == Mode.INSERTION) {
137
                    return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), date.getDate());
138
                } else {
139
                    return null;
140
                }
141
            }
142
        };
18 ilm 143
        c.gridx++;
144
        c.weightx = 1;
145
        c.weighty = 0;
146
        c.fill = GridBagConstraints.NONE;
147
        DefaultGridBagConstraints.lockMinimumSize(this.textNumeroUnique);
148
        this.add(this.textNumeroUnique, c);
149
 
150
        // Date
151
        JLabel labelDate = new JLabel(getLabelFor("DATE"));
152
        labelDate.setHorizontalAlignment(SwingConstants.RIGHT);
153
        c.fill = GridBagConstraints.HORIZONTAL;
154
        c.gridx++;
155
        c.weightx = 0;
156
        this.add(labelDate, c);
157
 
158
        c.gridx++;
159
        c.weightx = 0;
160
        c.weighty = 0;
161
        this.add(date, c);
93 ilm 162
 
163
        this.date.addValueListener(new PropertyChangeListener() {
164
 
165
            @Override
166
            public void propertyChange(PropertyChangeEvent evt) {
167
                if (!isFilling() && date.getValue() != null) {
168
                    tableBonItem.setDateDevise(date.getValue());
169
                }
170
            }
171
        });
172
 
18 ilm 173
        // Reference
174
        c.gridy++;
175
        c.gridx = 0;
176
        final JLabel labelNom = new JLabel(getLabelFor("NOM"));
177
        labelNom.setHorizontalAlignment(SwingConstants.RIGHT);
178
        this.add(labelNom, c);
179
        c.gridx++;
180
        c.fill = GridBagConstraints.HORIZONTAL;
181
        DefaultGridBagConstraints.lockMinimumSize(this.textReference);
182
        this.add(this.textReference, c);
183
        // Fournisseur
184
        JLabel labelFournisseur = new JLabel(getLabelFor("ID_FOURNISSEUR"));
185
        labelFournisseur.setHorizontalAlignment(SwingConstants.RIGHT);
186
        c.gridx = 0;
187
        c.gridy++;
188
        c.weightx = 0;
189
        c.weighty = 0;
190
        this.add(labelFournisseur, c);
191
 
192
        this.fournisseur = new ElementComboBox();
193
        c.gridx++;
194
        c.weightx = 0;
195
        c.weighty = 0;
196
        c.fill = GridBagConstraints.NONE;
197
        this.add(this.fournisseur, c);
198
 
149 ilm 199
        this.tableBonItem = new BonReceptionItemTable();
200
        this.addRequiredSQLObject(this.fournisseur, "ID_FOURNISSEUR");
201
 
156 ilm 202
        fournisseur.addModelListener("wantedID", new PropertyChangeListener() {
203
 
204
            @Override
205
            public void propertyChange(PropertyChangeEvent evt) {
206
                int wantedID = fournisseur.getWantedID();
207
                if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
208
 
209
                    final SQLRow rowF = getTable().getForeignTable("ID_FOURNISSEUR").getRow(wantedID);
210
 
211
                    if (rowF.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowF.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
212
                        tableBonItem.setRowCatComptable(rowF.getForeign("ID_CATEGORIE_COMPTABLE"));
213
                    } else {
214
                        tableBonItem.setRowCatComptable(null);
215
                    }
216
 
217
                } else {
218
                    tableBonItem.setRowCatComptable(null);
219
                }
220
            }
221
        });
222
 
19 ilm 223
        // Devise
224
        c.gridx = 0;
225
        c.gridy++;
226
        c.weightx = 0;
227
        c.fill = GridBagConstraints.HORIZONTAL;
228
        this.add(new JLabel(getLabelFor("ID_DEVISE"), SwingConstants.RIGHT), c);
229
 
230
        final ElementComboBox boxDevise = new ElementComboBox();
231
        c.gridx = GridBagConstraints.RELATIVE;
232
        c.gridwidth = 1;
233
        c.weightx = 1;
234
        c.weighty = 0;
235
        c.fill = GridBagConstraints.NONE;
93 ilm 236
        DefaultGridBagConstraints.lockMinimumSize(boxDevise);
19 ilm 237
        this.add(boxDevise, c);
238
        this.addView(boxDevise, "ID_DEVISE");
93 ilm 239
        fournisseur.addValueListener(new PropertyChangeListener() {
19 ilm 240
 
93 ilm 241
            @Override
242
            public void propertyChange(PropertyChangeEvent arg0) {
142 ilm 243
                if (fournisseur.getSelectedRow() != null && fournisseur.getSelectedRow().getFields().contains("ID_DEVISE")) {
244
                    boxDevise.setValue(fournisseur.getSelectedRow().asRow().getForeignID("ID_DEVISE"));
93 ilm 245
                } else {
246
                    boxDevise.setValue((SQLRowAccessor) null);
247
                }
248
            }
249
        });
250
 
18 ilm 251
        // Element du bon
149 ilm 252
 
93 ilm 253
        boxDevise.addValueListener(new PropertyChangeListener() {
254
 
255
            @Override
256
            public void propertyChange(PropertyChangeEvent evt) {
257
                tableBonItem.setDevise(boxDevise.getSelectedRow());
258
 
259
            }
260
        });
18 ilm 261
        c.gridx = 0;
262
        c.gridy++;
263
        c.weightx = 1;
264
        c.weighty = 1;
265
        c.gridwidth = GridBagConstraints.REMAINDER;
266
        c.fill = GridBagConstraints.BOTH;
267
        this.add(this.tableBonItem, c);
67 ilm 268
        this.fournisseur.addValueListener(new PropertyChangeListener() {
269
 
270
            @Override
271
            public void propertyChange(PropertyChangeEvent evt) {
272
                tableBonItem.setFournisseur(fournisseur.getSelectedRow());
273
            }
274
        });
275
 
18 ilm 276
        c.anchor = GridBagConstraints.EAST;
277
 
149 ilm 278
        c.gridx = 0;
18 ilm 279
        c.gridy++;
280
        c.gridwidth = GridBagConstraints.REMAINDER;
132 ilm 281
        c.gridheight = 2;
282
        c.anchor = GridBagConstraints.NORTHEAST;
283
        c.fill = GridBagConstraints.BOTH;
284
        c.weighty = 0;
18 ilm 285
 
149 ilm 286
        this.add(getBottomPanel(), c);
18 ilm 287
        c.gridy++;
132 ilm 288
        c.gridheight = 1;
18 ilm 289
        c.anchor = GridBagConstraints.WEST;
290
 
94 ilm 291
        if (getTable().getDBRoot().contains("RELIQUAT_BR")) {
292
 
293
            c.gridwidth = GridBagConstraints.REMAINDER;
294
            c.weightx = 1;
295
            c.fill = GridBagConstraints.HORIZONTAL;
296
            c.gridx = 0;
297
            c.gridy++;
298
            TitledSeparator sep = new TitledSeparator("Reliquat de kits");
299
            c.insets = new Insets(10, 2, 1, 2);
300
            this.add(sep, c);
301
            c.insets = new Insets(2, 2, 1, 2);
302
 
303
            // Reliquat du bon
304
            this.tableBonReliquatItem = new ReliquatRowValuesTable("RELIQUAT_BR");
305
            c.gridx = 0;
306
            c.gridy++;
307
            c.weightx = 1;
308
            c.weighty = 1;
309
            c.gridwidth = GridBagConstraints.REMAINDER;
310
            c.fill = GridBagConstraints.BOTH;
311
            this.add(this.tableBonReliquatItem, c);
312
            this.tableBonItem.setReliquatTable(tableBonReliquatItem);
313
        }
314
 
18 ilm 315
        c.gridx = 0;
316
        c.gridy++;
94 ilm 317
        c.fill = GridBagConstraints.NONE;
318
        c.anchor = GridBagConstraints.SOUTHEAST;
319
        c.gridwidth = GridBagConstraints.REMAINDER;
320
 
321
        this.panelOO = new PanelOOSQLComponent(this);
322
        this.add(this.panelOO, c);
323
 
18 ilm 324
        this.addRequiredSQLObject(date, "DATE");
325
        this.addSQLObject(this.textReference, "NOM");
326
        this.addSQLObject(this.selectCommande, "ID_COMMANDE");
327
        this.addRequiredSQLObject(this.textNumeroUnique, "NUMERO");
328
 
93 ilm 329
        this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass()));
18 ilm 330
 
331
        // Lock UI
332
        DefaultGridBagConstraints.lockMinimumSize(this.fournisseur);
333
 
334
    }
335
 
149 ilm 336
    private JPanel getBottomPanel() {
337
        final JPanel panel = new JPanel(new GridBagLayout());
338
        final GridBagConstraints c = new DefaultGridBagConstraints();
339
        ITextArea infos = new ITextArea(3, 3);
340
        addView(infos, "INFOS");
341
        // Colonne 1 : Infos
342
        c.gridx = 0;
343
        c.weightx = 1;
344
        c.anchor = GridBagConstraints.WEST;
345
        c.fill = GridBagConstraints.HORIZONTAL;
346
 
347
        panel.add(new TitledSeparator(getLabelFor("INFOS")), c);
348
 
349
        c.gridy++;
350
        c.weighty = 0;
351
        c.weightx = 1;
352
        c.fill = GridBagConstraints.BOTH;
353
        final JScrollPane scrollPane = new JScrollPane(infos);
354
        scrollPane.setBorder(null);
355
        panel.add(scrollPane, c);
356
 
357
        // Colonne 2 : Poids & autres
358
        DefaultProps props = DefaultNXProps.getInstance();
359
        Boolean b = props.getBooleanValue("ArticleShowPoids");
360
        final JTextField textPoidsTotal = new JTextField(8);
361
        JTextField poids = new JTextField();
362
        if (b) {
363
            final JPanel panelPoids = new JPanel(new GridBagLayout());
364
            GridBagConstraints cPoids = new DefaultGridBagConstraints();
365
            cPoids.weightx = 0;
366
            panelPoids.add(new JLabel(getLabelFor("TOTAL_POIDS")), cPoids);
367
            cPoids.weightx = 1;
368
            textPoidsTotal.setEnabled(false);
369
            textPoidsTotal.setHorizontalAlignment(JTextField.RIGHT);
370
            textPoidsTotal.setDisabledTextColor(Color.BLACK);
371
            cPoids.gridx++;
372
            panelPoids.add(textPoidsTotal, cPoids);
373
 
374
            c.gridx++;
375
            c.gridy = 0;
376
            c.weightx = 0;
377
            c.weighty = 0;
378
            c.gridwidth = 1;
379
            c.gridheight = 2;
380
            c.fill = GridBagConstraints.NONE;
381
            c.anchor = GridBagConstraints.NORTHEAST;
382
            panel.add(panelPoids, c);
383
            DefaultGridBagConstraints.lockMinimumSize(panelPoids);
384
            addSQLObject(textPoidsTotal, "TOTAL_POIDS");
385
        } else {
386
            addSQLObject(poids, "TOTAL_POIDS");
387
        }
388
 
389
        DeviseField textPortHT = new DeviseField();
390
        DeviseField textRemiseHT = new DeviseField();
391
        ElementComboBox comboTaxePort = new ElementComboBox(false, 10);
392
 
393
        if (getTable().contains("PORT_HT")) {
394
 
395
            addSQLObject(textPortHT, "PORT_HT");
396
            final JPanel panelPoids = new JPanel(new GridBagLayout());
397
            GridBagConstraints cPort = new DefaultGridBagConstraints();
398
            cPort.gridx = 0;
399
            cPort.fill = GridBagConstraints.NONE;
400
            cPort.weightx = 0;
401
            panelPoids.add(new JLabel(getLabelFor("PORT_HT")), cPort);
402
            textPortHT.setHorizontalAlignment(JTextField.RIGHT);
403
            cPort.gridx++;
404
            cPort.weightx = 1;
405
            panelPoids.add(textPortHT, cPort);
406
 
407
            cPort.gridy++;
408
            cPort.gridx = 0;
409
            cPort.weightx = 0;
410
            addRequiredSQLObject(comboTaxePort, "ID_TAXE_PORT");
411
            panelPoids.add(new JLabel(getLabelFor("ID_TAXE_PORT")), cPort);
412
            cPort.gridx++;
413
            cPort.weightx = 1;
414
            panelPoids.add(comboTaxePort, cPort);
415
 
416
            addSQLObject(textRemiseHT, "REMISE_HT");
417
            cPort.gridy++;
418
            cPort.gridx = 0;
419
            cPort.fill = GridBagConstraints.NONE;
420
            cPort.weightx = 0;
421
            panelPoids.add(new JLabel(getLabelFor("REMISE_HT")), cPort);
422
            textRemiseHT.setHorizontalAlignment(JTextField.RIGHT);
423
            cPort.gridx++;
424
            cPort.weightx = 1;
425
            panelPoids.add(textRemiseHT, cPort);
426
 
427
            c.gridx++;
428
            c.gridy = 0;
429
            c.weightx = 0;
430
            c.weighty = 0;
431
            c.gridwidth = 1;
432
            c.gridheight = 2;
433
            c.fill = GridBagConstraints.NONE;
434
            c.anchor = GridBagConstraints.NORTHEAST;
435
            panel.add(panelPoids, c);
436
            DefaultGridBagConstraints.lockMinimumSize(panelPoids);
437
        }
438
        // Total
439
 
440
        DeviseField fieldHT = new DeviseField();
441
        DeviseField fieldEco = new DeviseField();
442
        DeviseField fieldTVA = new DeviseField();
443
        DeviseField fieldTTC = new DeviseField();
444
        DeviseField fieldDevise = new DeviseField();
445
        DeviseField fieldService = new DeviseField();
446
        fieldHT.setOpaque(false);
447
        fieldTVA.setOpaque(false);
448
        fieldTTC.setOpaque(false);
449
        fieldService.setOpaque(false);
450
        addRequiredSQLObject(fieldEco, "T_ECO_CONTRIBUTION");
451
        addRequiredSQLObject(fieldDevise, "T_DEVISE");
452
        addRequiredSQLObject(fieldHT, "TOTAL_HT");
453
        addRequiredSQLObject(fieldTVA, "TOTAL_TVA");
454
        addRequiredSQLObject(fieldTTC, "TOTAL_TTC");
455
 
456
        // Disable
457
        this.allowEditable("T_ECO_CONTRIBUTION", false);
458
        this.allowEditable("TOTAL_HT", false);
459
        this.allowEditable("TOTAL_TVA", false);
460
        this.allowEditable("TOTAL_TTC", false);
461
 
156 ilm 462
        final TotalPanel totalTTC = new TotalPanel(this.tableBonItem, fieldEco, fieldHT, fieldTVA, fieldTTC, textPortHT, textRemiseHT, fieldService, null, fieldDevise, textPoidsTotal, null,
149 ilm 463
                (getTable().contains("ID_TAXE_PORT") ? comboTaxePort : null), null);
464
 
465
        c.gridx++;
466
        c.gridy--;
467
        c.gridwidth = GridBagConstraints.REMAINDER;
468
        c.gridheight = 2;
469
        c.anchor = GridBagConstraints.NORTHEAST;
470
        c.fill = GridBagConstraints.BOTH;
471
        c.weighty = 0;
472
        c.weightx = 0;
473
        DefaultGridBagConstraints.lockMinimumSize(totalTTC);
474
 
475
        panel.add(totalTTC, c);
476
        tableBonItem.getModel().addTableModelListener(new TableModelListener() {
477
 
478
            public void tableChanged(TableModelEvent e) {
479
                textPoidsTotal.setText(String.valueOf(tableBonItem.getPoidsTotal()));
480
            }
481
        });
482
 
483
        textPortHT.getDocument().addDocumentListener(new DocumentListener() {
484
            public void changedUpdate(DocumentEvent e) {
485
                totalTTC.updateTotal();
486
            }
487
 
488
            public void removeUpdate(DocumentEvent e) {
489
                totalTTC.updateTotal();
490
            }
491
 
492
            public void insertUpdate(DocumentEvent e) {
493
                totalTTC.updateTotal();
494
            }
495
        });
496
 
497
        comboTaxePort.addValueListener(new PropertyChangeListener() {
498
 
499
            @Override
500
            public void propertyChange(PropertyChangeEvent evt) {
501
                totalTTC.updateTotal();
502
            }
503
        });
504
 
505
        textRemiseHT.getDocument().addDocumentListener(new DocumentListener() {
506
            public void changedUpdate(DocumentEvent e) {
507
                totalTTC.updateTotal();
508
            }
509
 
510
            public void removeUpdate(DocumentEvent e) {
511
                totalTTC.updateTotal();
512
            }
513
 
514
            public void insertUpdate(DocumentEvent e) {
515
                totalTTC.updateTotal();
516
            }
517
        });
518
        return panel;
519
    }
520
 
18 ilm 521
    public int insert(SQLRow order) {
522
 
73 ilm 523
        int idBon = SQLRow.NONEXISTANT_ID;
142 ilm 524
        // on verifie qu'un devis du meme numero n'a pas été inséré entre temps
525
        int attempt = 0;
526
        if (!this.textNumeroUnique.checkValidation(false)) {
527
            while (attempt < JUniqueTextField.RETRY_COUNT) {
528
                String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), date.getDate());
529
                this.textNumeroUnique.setText(num);
530
                attempt++;
531
                if (this.textNumeroUnique.checkValidation(false)) {
532
                    System.err.println("ATEMPT " + attempt + " SUCCESS WITH NUMERO " + num);
533
                    break;
534
                }
535
                try {
536
                    Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
537
                } catch (InterruptedException e) {
538
                    e.printStackTrace();
539
                }
540
            }
541
        }
542
        final String num = this.textNumeroUnique.getText();
543
        if (attempt == JUniqueTextField.RETRY_COUNT) {
544
            idBon = getSelectedID();
545
            ExceptionHandler.handle("Impossible d'ajouter, numéro de bon existant.");
546
            final Object root = SwingUtilities.getRoot(this);
547
            if (root instanceof EditFrame) {
548
                final EditFrame frame = (EditFrame) root;
549
                frame.getPanel().setAlwaysVisible(true);
550
            }
551
        } else {
18 ilm 552
            idBon = super.insert(order);
73 ilm 553
            try {
554
                this.tableBonItem.updateField("ID_BON_RECEPTION", idBon);
94 ilm 555
                if (this.tableBonReliquatItem != null) {
556
                    this.tableBonReliquatItem.updateField("ID_BON_RECEPTION_ORIGINE", idBon);
557
                }
83 ilm 558
                this.tableBonItem.createArticle(idBon, this.getElement());
559
 
73 ilm 560
                // incrémentation du numéro auto
93 ilm 561
                if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass()).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
73 ilm 562
                    SQLRowValues rowVals = new SQLRowValues(this.tableNum);
563
                    int val = this.tableNum.getRow(2).getInt("BON_R_START");
564
                    val++;
565
                    rowVals.put("BON_R_START", new Integer(val));
566
                    rowVals.update(2);
567
                }
132 ilm 568
                // FIXME USE A PREF
569
                // calculPHaPondere(idBon);
18 ilm 570
 
73 ilm 571
                final int idBonFinal = idBon;
572
                ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
18 ilm 573
 
73 ilm 574
                    @Override
575
                    public void run() {
576
                        try {
577
                            updateStock(idBonFinal);
142 ilm 578
                            ((BonReceptionSQLElement) getElement()).updateCmdElement(((BonReceptionSQLElement) getElement()).getCmdFrom(idBonFinal), idBonFinal);
73 ilm 579
                        } catch (Exception e) {
580
                            ExceptionHandler.handle("Update error", e);
581
                        }
582
                    }
583
                });
142 ilm 584
 
144 ilm 585
                DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
586
                elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), idBon);
587
 
94 ilm 588
                // generation du document
589
                final BonReceptionXmlSheet sheet = new BonReceptionXmlSheet(getTable().getRow(idBonFinal));
590
                sheet.createDocumentAsynchronous();
591
                sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
592
 
73 ilm 593
            } catch (Exception e) {
594
                throw new IllegalStateException(e);
18 ilm 595
            }
596
        }
597
 
598
        return idBon;
599
    }
600
 
601
    @Override
73 ilm 602
    protected RowValuesTable getRowValuesTable() {
603
        return this.tableBonItem.getRowValuesTable();
604
    }
605
 
94 ilm 606
    public void loadFromReliquat(List<SQLRowValues> l) {
607
        this.tableBonItem.insertFromReliquat(l);
608
        this.tableBonItem.setEnabled(false);
609
    }
610
 
611
    public void loadQuantity(List<SQLRowValues> l) {
612
        Map<Integer, SQLRowValues> map = new HashMap<Integer, SQLRowValues>();
613
        for (SQLRowValues sqlRowValues : l) {
614
            if (!sqlRowValues.isForeignEmpty("ID_ARTICLE")) {
615
                final int foreignID = sqlRowValues.getForeignID("ID_ARTICLE");
616
                if (!map.containsKey(foreignID)) {
617
                    map.put(foreignID, sqlRowValues);
618
                } else {
619
                    SQLRowValues vals = map.get(foreignID);
620
                    if (sqlRowValues.getInt("QTE") > 0) {
132 ilm 621
                        if (NumberUtils.areNumericallyEqual(sqlRowValues.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || sqlRowValues.getInt("QTE") > 1) {
94 ilm 622
                            vals.put("QTE", vals.getInt("QTE") + sqlRowValues.getInt("QTE"));
623
                        } else {
624
                            vals.put("QTE_UNITAIRE", vals.getBigDecimal("QTE_UNITAIRE").add(sqlRowValues.getBigDecimal("QTE_UNITAIRE")));
625
                        }
626
                    }
627
                }
628
            }
629
        }
630
        int count = this.tableBonItem.getModel().getRowCount();
631
        for (int i = 0; i < count; i++) {
632
            SQLRowValues r = this.tableBonItem.getModel().getRowValuesAt(i);
633
            SQLRowValues rowTR = map.get(r.getForeignID("ID_ARTICLE"));
634
            if (rowTR != null && !rowTR.isUndefined()) {
635
                if (r.getInt("QTE") > 0) {
132 ilm 636
                    if (NumberUtils.areNumericallyEqual(r.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || r.getInt("QTE") > 1) {
94 ilm 637
                        this.tableBonItem.getModel().putValue(r.getInt("QTE") - rowTR.getInt("QTE"), i, "QTE");
638
                    } else {
639
                        this.tableBonItem.getModel().putValue(r.getBigDecimal("QTE_UNITAIRE").subtract(rowTR.getBigDecimal("QTE_UNITAIRE")), i, "QTE_UNITAIRE");
640
                    }
641
                }
642
            }
643
        }
644
    }
645
 
73 ilm 646
    @Override
18 ilm 647
    public void update() {
648
 
649
        if (!this.textNumeroUnique.checkValidation()) {
650
            ExceptionHandler.handle("Impossible d'ajouter, numéro de bon de livraison existant.");
651
            Object root = SwingUtilities.getRoot(this);
652
            if (root instanceof EditFrame) {
653
                EditFrame frame = (EditFrame) root;
654
                frame.getPanel().setAlwaysVisible(true);
655
            }
656
            return;
657
        } else {
658
 
73 ilm 659
            // Mise à jour de l'élément
660
            super.update();
142 ilm 661
            final List<Object> cmdFrom = ((BonReceptionSQLElement) getElement()).getCmdFrom(getSelectedID());
73 ilm 662
            this.tableBonItem.updateField("ID_BON_RECEPTION", getSelectedID());
94 ilm 663
            if (tableBonReliquatItem != null) {
664
                this.tableBonReliquatItem.updateField("ID_BON_RECEPTION_ORIGINE", getSelectedID());
665
            }
83 ilm 666
            this.tableBonItem.createArticle(getSelectedID(), this.getElement());
73 ilm 667
            final int id = getSelectedID();
668
            ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
18 ilm 669
 
73 ilm 670
                @Override
671
                public void run() {
18 ilm 672
                    try {
73 ilm 673
 
674
                        // Mise à jour du stock
675
                        updateStock(id);
144 ilm 676
                        ((BonReceptionSQLElement) getElement()).updateCmdElement(cmdFrom, id);
142 ilm 677
 
144 ilm 678
                        DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
679
                        elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), id);
680
 
73 ilm 681
                    } catch (Exception e) {
682
                        ExceptionHandler.handle("Update error", e);
18 ilm 683
                    }
684
                }
73 ilm 685
            });
144 ilm 686
 
149 ilm 687
            DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
688
            elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), id);
689
 
94 ilm 690
            // generation du document
691
            final BonReceptionXmlSheet sheet = new BonReceptionXmlSheet(getTable().getRow(id));
692
            sheet.createDocumentAsynchronous();
693
            sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true);
18 ilm 694
 
695
        }
696
    }
697
 
698
    /**
699
     * Calcul du prix d'achat pondéré pour chacun des articles du bon de reception
700
     *
701
     * @param id id du bon de reception
73 ilm 702
     * @throws SQLException
18 ilm 703
     */
73 ilm 704
    private void calculPHaPondere(int id) throws SQLException {
142 ilm 705
        // FIXME : unused !
18 ilm 706
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
707
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
708
        SQLElement eltStock = Configuration.getInstance().getDirectory().getElement("STOCK");
709
        SQLRow row = getTable().getRow(id);
710
 
711
        // On récupére les articles qui composent la facture
712
        SQLTable sqlTableBonElt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("BON_RECEPTION_ELEMENT");
713
        List<SQLRow> elts = row.getReferentRows(sqlTableBonElt);
714
 
715
        for (SQLRow rowEltBon : elts) {
716
 
717
            SQLRowValues rowVals = rowEltBon.createUpdateRow();
718
 
719
            // recupere l'ancien prix d'achat
720
            int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowVals, false);
721
            if (idArticle > 1) {
722
                // Prix d'achat de l'article à l'origine
723
                SQLRow rowArticle = eltArticle.getTable().getRow(idArticle);
132 ilm 724
                if (rowArticle != null) {
725
                    BigDecimal prixHA = (BigDecimal) rowArticle.getObject("PRIX_METRIQUE_HA_1");
18 ilm 726
 
132 ilm 727
                    // Quantité en stock
728
                    int idStock = rowArticle.getInt("ID_STOCK");
729
                    SQLRow rowStock = eltStock.getTable().getRow(idStock);
730
                    BigDecimal qteStock = new BigDecimal(rowStock.getInt("QTE_REEL"));
731
                    if (prixHA != null && qteStock.compareTo(BigDecimal.ZERO) > 0) {
732
                        BigDecimal qteRecue = new BigDecimal(rowEltBon.getInt("QTE"));
733
                        BigDecimal prixHACmd = (BigDecimal) rowEltBon.getObject("PRIX_METRIQUE_HA_1");
734
                        if (qteRecue.compareTo(BigDecimal.ZERO) > 0 && prixHACmd != null) {
735
                            BigDecimal totalHARecue = qteRecue.multiply(prixHACmd, DecimalUtils.HIGH_PRECISION);
736
                            BigDecimal totalHAStock = qteStock.multiply(prixHA, DecimalUtils.HIGH_PRECISION);
737
                            BigDecimal totalQte = qteRecue.add(qteStock);
738
                            BigDecimal prixHaPond = totalHARecue.add(totalHAStock).divide(totalQte, DecimalUtils.HIGH_PRECISION);
739
                            SQLRowValues rowValsArticle = rowArticle.createEmptyUpdateRow();
740
                            rowValsArticle.put("PRIX_METRIQUE_HA_1", prixHaPond);
741
                            rowValsArticle.commit();
742
                        }
18 ilm 743
                    }
744
                }
745
            }
746
 
747
        }
748
    }
749
 
83 ilm 750
    protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
61 ilm 751
        return "Bon de réception N°" + row.getString("NUMERO");
752
    }
753
 
18 ilm 754
    /**
755
     * Mise à jour des stocks pour chaque article composant du bon
73 ilm 756
     *
757
     * @throws SQLException
18 ilm 758
     */
73 ilm 759
    private void updateStock(int id) throws SQLException {
83 ilm 760
 
761
        SQLRow row = getTable().getRow(id);
762
        StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
763
 
61 ilm 764
            @Override
83 ilm 765
            public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
766
 
61 ilm 767
                return getLibelleStock(rowOrigin, rowElt);
18 ilm 768
            }
93 ilm 769
        }, row, row.getReferentRows(getTable().getTable("BON_RECEPTION_ELEMENT")),
770
                getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_RECEPT : TypeStockUpdate.REAL_RECEPT);
18 ilm 771
 
94 ilm 772
        if (getTable().getDBRoot().contains("RELIQUAT_BR")) {
142 ilm 773
            List<SQLRow> l = row.getReferentRows(getTable().getTable("RELIQUAT_BR").getField("ID_BON_RECEPTION_ORIGINE"));
94 ilm 774
            for (SQLRow sqlRow : l) {
775
                stockUpdater.addReliquat(sqlRow.getForeign("ID_ARTICLE"), sqlRow.getInt("QTE"), sqlRow.getBigDecimal("QTE_UNITAIRE"));
776
            }
777
        }
778
 
83 ilm 779
        stockUpdater.update();
93 ilm 780
 
18 ilm 781
    }
93 ilm 782
 
783
    @Override
94 ilm 784
    public void select(SQLRowAccessor r) {
785
        super.select(r);
786
        if (this.tableBonReliquatItem != null) {
787
            this.tableBonReliquatItem.getRowValuesTable().clear();
788
            if (r != null) {
789
                this.tableBonReliquatItem.getRowValuesTable().insertFrom("ID_BON_RECEPTION_ORIGINE", r.asRowValues());
790
            }
791
        }
792
    }
793
 
794
    @Override
93 ilm 795
    protected void refreshAfterSelect(SQLRowAccessor rSource) {
796
        if (this.date.getValue() != null) {
797
            this.tableBonItem.setDateDevise(this.date.getValue());
798
        }
799
 
800
    }
18 ilm 801
}