OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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
 *
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.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 {
182 ilm 589
                            ((BonReceptionSQLElement) getElement()).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
182 ilm 601
                final SQLRow row = getTable().getRow(idBonFinal);
602
                final BonReceptionXmlSheet sheet = new BonReceptionXmlSheet(row);
94 ilm 603
                sheet.createDocumentAsynchronous();
182 ilm 604
                sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true, getElement(), row);
94 ilm 605
 
73 ilm 606
            } catch (Exception e) {
607
                throw new IllegalStateException(e);
18 ilm 608
            }
609
        }
610
 
611
        return idBon;
612
    }
613
 
614
    @Override
73 ilm 615
    protected RowValuesTable getRowValuesTable() {
616
        return this.tableBonItem.getRowValuesTable();
617
    }
618
 
94 ilm 619
    public void loadFromReliquat(List<SQLRowValues> l) {
620
        this.tableBonItem.insertFromReliquat(l);
621
        this.tableBonItem.setEnabled(false);
622
    }
623
 
624
    public void loadQuantity(List<SQLRowValues> l) {
625
        Map<Integer, SQLRowValues> map = new HashMap<Integer, SQLRowValues>();
626
        for (SQLRowValues sqlRowValues : l) {
627
            if (!sqlRowValues.isForeignEmpty("ID_ARTICLE")) {
628
                final int foreignID = sqlRowValues.getForeignID("ID_ARTICLE");
629
                if (!map.containsKey(foreignID)) {
630
                    map.put(foreignID, sqlRowValues);
631
                } else {
632
                    SQLRowValues vals = map.get(foreignID);
633
                    if (sqlRowValues.getInt("QTE") > 0) {
132 ilm 634
                        if (NumberUtils.areNumericallyEqual(sqlRowValues.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || sqlRowValues.getInt("QTE") > 1) {
94 ilm 635
                            vals.put("QTE", vals.getInt("QTE") + sqlRowValues.getInt("QTE"));
636
                        } else {
637
                            vals.put("QTE_UNITAIRE", vals.getBigDecimal("QTE_UNITAIRE").add(sqlRowValues.getBigDecimal("QTE_UNITAIRE")));
638
                        }
639
                    }
640
                }
641
            }
642
        }
643
        int count = this.tableBonItem.getModel().getRowCount();
174 ilm 644
        int receipt = 0;
645
 
94 ilm 646
        for (int i = 0; i < count; i++) {
647
            SQLRowValues r = this.tableBonItem.getModel().getRowValuesAt(i);
648
            SQLRowValues rowTR = map.get(r.getForeignID("ID_ARTICLE"));
649
            if (rowTR != null && !rowTR.isUndefined()) {
650
                if (r.getInt("QTE") > 0) {
132 ilm 651
                    if (NumberUtils.areNumericallyEqual(r.getBigDecimal("QTE_UNITAIRE"), BigDecimal.ONE) || r.getInt("QTE") > 1) {
174 ilm 652
                        int value = r.getInt("QTE") - rowTR.getInt("QTE");
653
                        if ((value <= 0)) {
654
                            receipt++;
655
                        }
656
 
657
                        this.tableBonItem.getModel().putValue(Math.max(0, value), i, "QTE");
94 ilm 658
                    } else {
174 ilm 659
                        BigDecimal subtract = r.getBigDecimal("QTE_UNITAIRE").subtract(rowTR.getBigDecimal("QTE_UNITAIRE"));
660
                        if (subtract.signum() <= 0) {
661
                            receipt++;
662
                        }
663
                        this.tableBonItem.getModel().putValue(subtract.max(BigDecimal.ZERO), i, "QTE_UNITAIRE");
94 ilm 664
                    }
174 ilm 665
                } else {
666
                    receipt++;
94 ilm 667
                }
668
            }
669
        }
174 ilm 670
        if (receipt == count) {
671
            JOptionPane.showMessageDialog(null, "Attention tous les articles ont déjà été réceptionné!");
672
        }
94 ilm 673
    }
674
 
182 ilm 675
    public void removeZeroQtyLines() {
676
        int count = this.tableBonItem.getModel().getRowCount() - 1;
677
        for (int i = count; i >= 0; i--) {
678
            final SQLRowValues rowValuesAt = this.tableBonItem.getModel().getRowValuesAt(i);
679
            if (rowValuesAt.getInt("QTE") == 0) {
680
                this.tableBonItem.getModel().removeRowAt(i);
681
            }
682
        }
683
    }
684
 
73 ilm 685
    @Override
18 ilm 686
    public void update() {
687
 
688
        if (!this.textNumeroUnique.checkValidation()) {
689
            ExceptionHandler.handle("Impossible d'ajouter, numéro de bon de livraison existant.");
690
            Object root = SwingUtilities.getRoot(this);
691
            if (root instanceof EditFrame) {
692
                EditFrame frame = (EditFrame) root;
693
                frame.getPanel().setAlwaysVisible(true);
694
            }
695
            return;
696
        } else {
697
 
73 ilm 698
            // Mise à jour de l'élément
699
            super.update();
142 ilm 700
            final List<Object> cmdFrom = ((BonReceptionSQLElement) getElement()).getCmdFrom(getSelectedID());
73 ilm 701
            this.tableBonItem.updateField("ID_BON_RECEPTION", getSelectedID());
94 ilm 702
            if (tableBonReliquatItem != null) {
703
                this.tableBonReliquatItem.updateField("ID_BON_RECEPTION_ORIGINE", getSelectedID());
704
            }
83 ilm 705
            this.tableBonItem.createArticle(getSelectedID(), this.getElement());
73 ilm 706
            final int id = getSelectedID();
707
            ComptaPropsConfiguration.getInstanceCompta().getNonInteractiveSQLExecutor().execute(new Runnable() {
18 ilm 708
 
73 ilm 709
                @Override
710
                public void run() {
18 ilm 711
                    try {
73 ilm 712
 
713
                        // Mise à jour du stock
182 ilm 714
                        ((BonReceptionSQLElement) getElement()).updateStock(id);
144 ilm 715
                        ((BonReceptionSQLElement) getElement()).updateCmdElement(cmdFrom, id);
142 ilm 716
 
144 ilm 717
                        DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
718
                        elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), id);
719
 
73 ilm 720
                    } catch (Exception e) {
721
                        ExceptionHandler.handle("Update error", e);
18 ilm 722
                    }
723
                }
73 ilm 724
            });
144 ilm 725
 
149 ilm 726
            DemandeAchatItemSQLElement elt = getElement().getDirectory().getElement(DemandeAchatItemSQLElement.class);
727
            elt.updateStatus(getTable(), getTable().getTable("BON_RECEPTION_ELEMENT"), id);
728
 
94 ilm 729
            // generation du document
182 ilm 730
            final SQLRow row = getTable().getRow(id);
731
            final BonReceptionXmlSheet sheet = new BonReceptionXmlSheet(row);
94 ilm 732
            sheet.createDocumentAsynchronous();
182 ilm 733
            sheet.showPrintAndExportAsynchronous(this.panelOO.isVisualisationSelected(), this.panelOO.isImpressionSelected(), true, getElement(), row);
18 ilm 734
 
735
        }
736
    }
737
 
738
    /**
739
     * Calcul du prix d'achat pondéré pour chacun des articles du bon de reception
740
     *
741
     * @param id id du bon de reception
73 ilm 742
     * @throws SQLException
18 ilm 743
     */
73 ilm 744
    private void calculPHaPondere(int id) throws SQLException {
142 ilm 745
        // FIXME : unused !
18 ilm 746
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
747
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
748
        SQLElement eltStock = Configuration.getInstance().getDirectory().getElement("STOCK");
749
        SQLRow row = getTable().getRow(id);
750
 
751
        // On récupére les articles qui composent la facture
752
        SQLTable sqlTableBonElt = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("BON_RECEPTION_ELEMENT");
753
        List<SQLRow> elts = row.getReferentRows(sqlTableBonElt);
754
 
755
        for (SQLRow rowEltBon : elts) {
756
 
757
            SQLRowValues rowVals = rowEltBon.createUpdateRow();
758
 
759
            // recupere l'ancien prix d'achat
760
            int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowVals, false);
761
            if (idArticle > 1) {
762
                // Prix d'achat de l'article à l'origine
763
                SQLRow rowArticle = eltArticle.getTable().getRow(idArticle);
132 ilm 764
                if (rowArticle != null) {
765
                    BigDecimal prixHA = (BigDecimal) rowArticle.getObject("PRIX_METRIQUE_HA_1");
18 ilm 766
 
132 ilm 767
                    // Quantité en stock
768
                    int idStock = rowArticle.getInt("ID_STOCK");
769
                    SQLRow rowStock = eltStock.getTable().getRow(idStock);
770
                    BigDecimal qteStock = new BigDecimal(rowStock.getInt("QTE_REEL"));
771
                    if (prixHA != null && qteStock.compareTo(BigDecimal.ZERO) > 0) {
772
                        BigDecimal qteRecue = new BigDecimal(rowEltBon.getInt("QTE"));
773
                        BigDecimal prixHACmd = (BigDecimal) rowEltBon.getObject("PRIX_METRIQUE_HA_1");
774
                        if (qteRecue.compareTo(BigDecimal.ZERO) > 0 && prixHACmd != null) {
775
                            BigDecimal totalHARecue = qteRecue.multiply(prixHACmd, DecimalUtils.HIGH_PRECISION);
776
                            BigDecimal totalHAStock = qteStock.multiply(prixHA, DecimalUtils.HIGH_PRECISION);
777
                            BigDecimal totalQte = qteRecue.add(qteStock);
778
                            BigDecimal prixHaPond = totalHARecue.add(totalHAStock).divide(totalQte, DecimalUtils.HIGH_PRECISION);
779
                            SQLRowValues rowValsArticle = rowArticle.createEmptyUpdateRow();
780
                            rowValsArticle.put("PRIX_METRIQUE_HA_1", prixHaPond);
781
                            rowValsArticle.commit();
782
                        }
18 ilm 783
                    }
784
                }
785
            }
786
 
787
        }
788
    }
789
 
93 ilm 790
    @Override
94 ilm 791
    public void select(SQLRowAccessor r) {
792
        super.select(r);
793
        if (this.tableBonReliquatItem != null) {
794
            this.tableBonReliquatItem.getRowValuesTable().clear();
795
            if (r != null) {
796
                this.tableBonReliquatItem.getRowValuesTable().insertFrom("ID_BON_RECEPTION_ORIGINE", r.asRowValues());
797
            }
798
        }
799
    }
800
 
801
    @Override
93 ilm 802
    protected void refreshAfterSelect(SQLRowAccessor rSource) {
803
        if (this.date.getValue() != null) {
804
            this.tableBonItem.setDateDevise(this.date.getValue());
805
        }
806
 
807
    }
18 ilm 808
}