OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | Details | Compare with Previous | Last modification | View Log | RSS feed

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