OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 177 | Rev 182 | 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.sales.invoice.component;
15
 
16
import static org.openconcerto.utils.CollectionUtils.createSet;
142 ilm 17
 
18 ilm 18
import org.openconcerto.erp.config.ComptaPropsConfiguration;
19
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
83 ilm 20
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
63 ilm 21
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18 ilm 22
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
23
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
24
import org.openconcerto.erp.core.common.ui.DeviseField;
25
import org.openconcerto.erp.core.common.ui.TotalPanel;
93 ilm 26
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
174 ilm 27
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
18 ilm 28
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
29
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
30
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent;
65 ilm 31
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
18 ilm 32
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
90 ilm 33
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement.DoWithRow;
18 ilm 34
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
35
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
83 ilm 36
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
93 ilm 37
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
61 ilm 38
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
18 ilm 39
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
40
import org.openconcerto.erp.model.BanqueModifiedListener;
41
import org.openconcerto.erp.model.ISQLCompteSelector;
21 ilm 42
import org.openconcerto.erp.panel.PanelOOSQLComponent;
18 ilm 43
import org.openconcerto.erp.preferences.DefaultNXProps;
61 ilm 44
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
93 ilm 45
import org.openconcerto.erp.preferences.GestionClientPreferencePanel;
94 ilm 46
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
18 ilm 47
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
48
import org.openconcerto.sql.Configuration;
49
import org.openconcerto.sql.element.ElementSQLObject;
83 ilm 50
import org.openconcerto.sql.element.SQLComponent;
18 ilm 51
import org.openconcerto.sql.element.SQLElement;
52
import org.openconcerto.sql.model.SQLBackgroundTableCache;
53
import org.openconcerto.sql.model.SQLBase;
54
import org.openconcerto.sql.model.SQLInjector;
55
import org.openconcerto.sql.model.SQLRow;
56
import org.openconcerto.sql.model.SQLRowAccessor;
57
import org.openconcerto.sql.model.SQLRowValues;
58
import org.openconcerto.sql.model.SQLSelect;
59
import org.openconcerto.sql.model.SQLTable;
60
import org.openconcerto.sql.model.UndefinedRowValuesCache;
61
import org.openconcerto.sql.model.Where;
61 ilm 62
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 63
import org.openconcerto.sql.sqlobject.ElementComboBox;
64
import org.openconcerto.sql.sqlobject.JUniqueTextField;
28 ilm 65
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
18 ilm 66
import org.openconcerto.sql.sqlobject.SQLTextCombo;
67
import org.openconcerto.sql.users.UserManager;
156 ilm 68
import org.openconcerto.sql.users.rights.UserRightsManager;
18 ilm 69
import org.openconcerto.sql.view.EditFrame;
142 ilm 70
import org.openconcerto.sql.view.EditPanel.EditMode;
73 ilm 71
import org.openconcerto.sql.view.list.RowValuesTable;
18 ilm 72
import org.openconcerto.sql.view.list.RowValuesTableModel;
73
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 74
import org.openconcerto.ui.FormLayouter;
18 ilm 75
import org.openconcerto.ui.JDate;
76
import org.openconcerto.ui.TitledSeparator;
77
import org.openconcerto.ui.component.ITextArea;
156 ilm 78
import org.openconcerto.ui.component.InteractionMode;
18 ilm 79
import org.openconcerto.utils.ExceptionHandler;
80
import org.openconcerto.utils.GestionDevise;
142 ilm 81
import org.openconcerto.utils.cc.IFactory;
18 ilm 82
import org.openconcerto.utils.text.SimpleDocumentListener;
83
 
84
import java.awt.GridBagConstraints;
85
import java.awt.GridBagLayout;
86
import java.awt.event.ActionEvent;
87
import java.awt.event.ActionListener;
88
import java.beans.PropertyChangeEvent;
89
import java.beans.PropertyChangeListener;
19 ilm 90
import java.math.BigDecimal;
94 ilm 91
import java.math.RoundingMode;
18 ilm 92
import java.sql.SQLException;
19 ilm 93
import java.util.ArrayList;
28 ilm 94
import java.util.Date;
18 ilm 95
import java.util.List;
96
import java.util.Map;
97
 
98
import javax.swing.JCheckBox;
99
import javax.swing.JLabel;
100
import javax.swing.JOptionPane;
101
import javax.swing.JPanel;
102
import javax.swing.JScrollPane;
61 ilm 103
import javax.swing.JTabbedPane;
18 ilm 104
import javax.swing.JTextField;
105
import javax.swing.SwingConstants;
106
import javax.swing.SwingUtilities;
107
import javax.swing.event.DocumentEvent;
108
 
109
public class SaisieVenteFactureSQLComponent extends TransfertBaseSQLComponent {
110
    private AbstractArticleItemTable tableFacture;
111
    private JLabel labelAffaire = new JLabel("Affaire");
93 ilm 112
    private final JDate dateSaisie = new JDate(true);
149 ilm 113
    private DeviseField textPortHT, textAcompte, textAvoirTTC, textRemiseHT, fieldTTC, textNetAPayer;
94 ilm 114
    private DeviseField totalTimbre, netPayer;
115
    private JTextField tauxTimbre;
116
 
18 ilm 117
    private SQLElement factureElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
118
    private SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
119
    public static final SQLTable TABLE_ADRESSE = Configuration.getInstance().getDirectory().getElement("ADRESSE").getTable();
120
    private SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
121
    private final SQLElement client = Configuration.getInstance().getDirectory().getElement(this.tableClient);
122
    private JUniqueTextField textNumeroUnique;
93 ilm 123
    private ElementComboBox comboClient;
18 ilm 124
    private ISQLCompteSelector compteSel;
125
    private final SQLTable tableNum = this.factureElt.getTable().getBase().getTable("NUMEROTATION_AUTO");
21 ilm 126
    private JCheckBox checkCompteServiceAuto, checkPrevisionnelle, checkComplement, checkAcompte, checkCT;
90 ilm 127
 
128
    protected PanelOOSQLComponent panelOO;
18 ilm 129
    private ElementComboBox selAvoir, selAffaire;
130
    private ElementSQLObject eltModeRegl;
131
    private static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
132
    private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
133
    private static final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
83 ilm 134
    private ElementComboBox contact;
18 ilm 135
    private SQLRowAccessor rowSelected;
136
    private SQLElement eltContact = Configuration.getInstance().getDirectory().getElement("CONTACT");
137
    private JTextField refClient = new JTextField();
142 ilm 138
 
18 ilm 139
    protected TotalPanel totalTTC;
93 ilm 140
    private final boolean displayDpt;
141
    private final ElementComboBox comboDpt = new ElementComboBox();
94 ilm 142
    private final boolean gestionTimbre;
93 ilm 143
 
18 ilm 144
    // Type intervention
145
    private SQLTextCombo textTypeMission = new SQLTextCombo();
146
 
147
    private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
148
        public void propertyChange(PropertyChangeEvent arg0) {
83 ilm 149
            int idCli = SaisieVenteFactureSQLComponent.this.comboClient.getWantedID();
18 ilm 150
            if (idCli > 1) {
151
                SQLRow rowCli = SaisieVenteFactureSQLComponent.this.client.getTable().getRow(idCli);
156 ilm 152
                if (!isFilling() && !rowCli.isForeignEmpty("ID_COMMERCIAL")) {
94 ilm 153
                    comboCommercial.setValue(rowCli.getForeignID("ID_COMMERCIAL"));
154
                }
149 ilm 155
 
156 ilm 156
                if (rowCli.getFields().contains("ID_CATEGORIE_COMPTABLE") && rowCli.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowCli.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
157
                    totalTTC.setCategorieComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
158
                    tableFacture.setRowCatComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
159
                } else {
160
                    totalTTC.setCategorieComptable(null);
161
                    tableFacture.setRowCatComptable(null);
162
                }
163
 
180 ilm 164
                SaisieVenteFactureSQLComponent.this.tableFacture.setClient(rowCli, !isFilling());
174 ilm 165
 
83 ilm 166
                if (getMode() == SQLComponent.Mode.INSERTION || !isFilling()) {
18 ilm 167
                    SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
168
                    int idModeRegl = rowCli.getInt("ID_MODE_REGLEMENT");
169
                    if (idModeRegl > 1) {
170
                        SQLRow rowModeRegl = sqleltModeRegl.getTable().getRow(idModeRegl);
171
                        SQLRowValues rowValsModeRegl = rowModeRegl.createUpdateRow();
172
                        rowValsModeRegl.clearPrimaryKeys();
173
                        SaisieVenteFactureSQLComponent.this.eltModeRegl.setValue(rowValsModeRegl);
174
                    }
175
                }
156 ilm 176
            } else {
177
                totalTTC.setCategorieComptable(null);
178
                tableFacture.setRowCatComptable(null);
18 ilm 179
            }
93 ilm 180
 
18 ilm 181
            Where w = new Where(SaisieVenteFactureSQLComponent.this.tableAvoir.getField("SOLDE"), "=", Boolean.FALSE);
182
            if (SaisieVenteFactureSQLComponent.this.comboClient.isEmpty()) {
183
                w = w.and(new Where(getTable().getBase().getTable("AVOIR_CLIENT").getField("ID_CLIENT"), "=", -1));
184
            } else {
83 ilm 185
                w = w.and(new Where(getTable().getBase().getTable("AVOIR_CLIENT").getField("ID_CLIENT"), "=", idCli));
18 ilm 186
            }
187
            if (getSelectedID() > 1) {
188
                SQLRow row = getTable().getRow(getSelectedID());
189
                w = w.or(new Where(SaisieVenteFactureSQLComponent.this.tableAvoir.getKey(), "=", row.getInt("ID_AVOIR_CLIENT")));
190
            }
191
 
192
            SaisieVenteFactureSQLComponent.this.selAvoir.getRequest().setWhere(w);
193
            SaisieVenteFactureSQLComponent.this.selAvoir.fillCombo();
194
        }
195
    };
196
 
197
    private PropertyChangeListener changeCompteListener;
198
    private PropertyChangeListener changeClientListener;
199
    private ISQLCompteSelector compteSelService;
200
    private JLabel labelCompteServ;
156 ilm 201
    private ElementComboBox comboCommercial, comboPoleProduit;
18 ilm 202
    private ElementComboBox comboVerificateur = new ElementComboBox();;
83 ilm 203
    private SQLTable tableBanque = getTable().getTable(BanqueSQLElement.TABLENAME);
18 ilm 204
 
93 ilm 205
    private final SQLRowAccessor defaultNum;
206
 
207
    public SaisieVenteFactureSQLComponent(int defaultNum) {
18 ilm 208
        super(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE"));
93 ilm 209
        this.defaultNum = this.tableNum.getRow(defaultNum);
210
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
211
        this.displayDpt = prefs.getBoolean(GestionClientPreferencePanel.DISPLAY_CLIENT_DPT, false);
94 ilm 212
        this.gestionTimbre = prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.GESTION_TIMBRE_FISCAL, false);
93 ilm 213
    }
83 ilm 214
 
93 ilm 215
    public SaisieVenteFactureSQLComponent() {
216
        this(2);
217
 
18 ilm 218
    }
219
 
220
 
221
    private int previousClient = -1;
93 ilm 222
    private ElementComboBox comboNumAuto = null;
18 ilm 223
 
224
    public void addViews() {
225
        this.setLayout(new GridBagLayout());
93 ilm 226
 
227
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
228
            this.addView(new JCheckBox(), "CREATE_VIRTUAL_STOCK");
229
        }
18 ilm 230
        final GridBagConstraints c = new DefaultGridBagConstraints();
231
 
93 ilm 232
        if (getTable().contains("ID_NUMEROTATION_AUTO")) {
233
            this.comboNumAuto = new ElementComboBox();
234
            this.addView(this.comboNumAuto, "ID_NUMEROTATION_AUTO");
235
        }
236
 
18 ilm 237
        this.checkPrevisionnelle = new JCheckBox();
238
        this.checkComplement = new JCheckBox();
239
        this.fieldTTC = new DeviseField();
240
 
241
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
242
 
243
        this.textAvoirTTC = new DeviseField();
149 ilm 244
        this.textAcompte = new DeviseField();
18 ilm 245
 
25 ilm 246
        // Champ Module
247
        c.gridx = 0;
248
        c.gridy++;
249
        c.gridwidth = GridBagConstraints.REMAINDER;
63 ilm 250
        final JPanel addP = ComptaSQLConfElement.createAdditionalPanel();
25 ilm 251
        this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
252
        this.add(addP, c);
253
 
254
        c.gridy++;
255
        c.gridwidth = 1;
256
 
18 ilm 257
        /*******************************************************************************************
258
         * * RENSEIGNEMENTS
259
         ******************************************************************************************/
260
        // Ligne 1 : Numero de facture
261
        JLabel labelNum = new JLabel(getLabelFor("NUMERO"));
262
        labelNum.setHorizontalAlignment(SwingConstants.RIGHT);
263
        c.gridx = 0;
264
        c.gridy++;
265
        c.weightx = 0;
266
        this.add(labelNum, c);
267
 
149 ilm 268
        this.textNumeroUnique = new JUniqueTextField(16) {
269
            @Override
270
            public String getAutoRefreshNumber() {
271
                if (getMode() == Mode.INSERTION) {
272
                    return NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate(), defaultNum);
273
                } else {
274
                    return null;
142 ilm 275
                }
149 ilm 276
            }
277
        };
18 ilm 278
        c.gridx++;
279
        c.weightx = 0;
280
        c.fill = GridBagConstraints.NONE;
281
        DefaultGridBagConstraints.lockMinimumSize(this.textNumeroUnique);
282
            this.add(textNumeroUnique, c);
283
 
284
        // Date
285
        c.gridx++;
286
        c.weightx = 0;
287
        c.fill = GridBagConstraints.HORIZONTAL;
288
        this.add(new JLabel(getLabelFor("DATE"), SwingConstants.RIGHT), c);
289
 
290
        c.gridx++;
291
        c.weightx = 1;
292
        c.fill = GridBagConstraints.NONE;
73 ilm 293
 
294
        // listener permettant la mise à jour du numéro de facture en fonction de la date
295
        // sélectionnée
296
        dateSaisie.addValueListener(new PropertyChangeListener() {
297
 
298
            @Override
299
            public void propertyChange(PropertyChangeEvent evt) {
300
                if (!isFilling() && dateSaisie.getValue() != null) {
301
 
180 ilm 302
                    final String nextNumero = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getValue(), defaultNum);
73 ilm 303
 
304
                    if (textNumeroUnique.getText().trim().length() > 0 && !nextNumero.equalsIgnoreCase(textNumeroUnique.getText())) {
305
 
306
                        int answer = JOptionPane.showConfirmDialog(SaisieVenteFactureSQLComponent.this, "Voulez vous actualiser le numéro de la facture?", "Changement du numéro de facture",
307
                                JOptionPane.YES_NO_OPTION);
308
                        if (answer == JOptionPane.NO_OPTION) {
309
                            return;
310
                        }
311
                    }
312
 
313
                    textNumeroUnique.setText(nextNumero);
93 ilm 314
                    tableFacture.setDateDevise(dateSaisie.getValue());
73 ilm 315
                }
316
            }
317
        });
18 ilm 318
        this.add(dateSaisie, c);
319
 
320
        // Ligne 2 : reference
321
        c.gridx = 0;
322
        c.gridwidth = 1;
323
        c.gridy++;
324
        c.weightx = 0;
325
        c.fill = GridBagConstraints.HORIZONTAL;
142 ilm 326
 
18 ilm 327
        JLabel labelLibelle = new JLabel(getLabelFor("NOM"));
328
        labelLibelle.setHorizontalAlignment(SwingConstants.RIGHT);
329
        this.add(labelLibelle, c);
330
 
331
        SQLTextCombo textLibelle = new SQLTextCombo();
332
        c.gridx++;
333
        c.weightx = 1;
334
        c.fill = GridBagConstraints.BOTH;
335
        this.add(textLibelle, c);
336
 
337
        this.addSQLObject(textLibelle, "NOM");
338
        c.fill = GridBagConstraints.HORIZONTAL;
339
        this.comboCommercial = new ElementComboBox(false);
61 ilm 340
        // Commercial
156 ilm 341
            this.addRequiredSQLObject(this.comboCommercial, "ID_COMMERCIAL");
61 ilm 342
        c.gridx++;
343
        c.weightx = 0;
344
        c.fill = GridBagConstraints.HORIZONTAL;
156 ilm 345
        this.add(new JLabel(getLabelFor("ID_COMMERCIAL"), SwingConstants.RIGHT), c);
18 ilm 346
 
61 ilm 347
        c.gridx++;
348
        c.weightx = 1;
349
        c.fill = GridBagConstraints.NONE;
18 ilm 350
 
61 ilm 351
        this.add(this.comboCommercial, c);
156 ilm 352
 
18 ilm 353
        // Client
354
        c.gridx = 0;
355
        c.gridy++;
356
        c.weightx = 0;
357
        c.fill = GridBagConstraints.HORIZONTAL;
358
        this.add(new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT), c);
359
 
360
        c.gridx++;
361
        c.weightx = 1;
362
        c.fill = GridBagConstraints.NONE;
363
        this.comboClient = new ElementComboBox();
364
 
365
        this.add(this.comboClient, c);
93 ilm 366
        this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
18 ilm 367
 
93 ilm 368
        if (this.displayDpt) {
369
            c.gridx++;
370
            c.gridwidth = 1;
371
            final JLabel labelDpt = new JLabel(getLabelFor("ID_CLIENT_DEPARTEMENT"));
372
            labelDpt.setHorizontalAlignment(SwingConstants.RIGHT);
373
            c.weightx = 0;
374
            c.gridwidth = 1;
375
            c.fill = GridBagConstraints.HORIZONTAL;
376
            this.add(labelDpt, c);
377
 
378
            c.gridx++;
379
            c.gridwidth = 1;
380
            c.weightx = 0;
381
            c.weighty = 0;
382
            c.fill = GridBagConstraints.NONE;
383
            this.add(this.comboDpt, c);
384
            DefaultGridBagConstraints.lockMinimumSize(this.comboDpt);
385
            addSQLObject(this.comboDpt, "ID_CLIENT_DEPARTEMENT");
386
 
387
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
388
 
389
                @Override
390
                public void propertyChange(PropertyChangeEvent evt) {
391
                    int wantedID = comboClient.getWantedID();
392
 
393
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
394
                        final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
395
                        comboDpt.getRequest().setWhere(new Where(comboDpt.getRequest().getPrimaryTable().getField("ID_CLIENT"), "=", rowClient.getID()));
396
                    } else {
397
                        comboDpt.getRequest().setWhere(null);
398
                    }
399
                }
400
            });
401
 
402
        }
403
 
156 ilm 404
        if (getTable().contains("ID_POLE_PRODUIT")) {
405
            JLabel labelPole = new JLabel(getLabelFor("ID_POLE_PRODUIT"));
406
            labelPole.setHorizontalAlignment(SwingConstants.RIGHT);
407
            c.gridx++;
408
            this.add(labelPole, c);
409
 
410
            c.gridx++;
411
            this.comboPoleProduit = new ElementComboBox();
412
            this.add(this.comboPoleProduit, c);
413
            this.addSQLObject(this.comboPoleProduit, "ID_POLE_PRODUIT");
414
            DefaultGridBagConstraints.lockMinimumSize(this.comboPoleProduit);
415
        }
416
 
142 ilm 417
        if (
418
 
419
        getTable().contains("ID_ECHEANCIER_CCI")) {
61 ilm 420
            // Echeancier
93 ilm 421
            c.gridy++;
422
            c.gridx = 0;
61 ilm 423
            c.weightx = 0;
424
            c.fill = GridBagConstraints.HORIZONTAL;
425
            this.add(new JLabel(getLabelFor("ID_ECHEANCIER_CCI"), SwingConstants.RIGHT), c);
426
 
427
            c.gridx++;
428
            c.weightx = 1;
429
            c.fill = GridBagConstraints.NONE;
430
            final ElementComboBox echeancier = new ElementComboBox();
431
            final SQLElement contactElement = Configuration.getInstance().getDirectory().getElement("ECHEANCIER_CCI");
65 ilm 432
            echeancier.init(contactElement, contactElement.getComboRequest(true));
61 ilm 433
            DefaultGridBagConstraints.lockMinimumSize(echeancier);
434
            this.addView(echeancier, "ID_ECHEANCIER_CCI");
435
 
436
            selAffaire.addValueListener(new PropertyChangeListener() {
437
 
438
                @Override
439
                public void propertyChange(PropertyChangeEvent arg0) {
440
                    // TODO Raccord de méthode auto-généré
441
                    if (selAffaire.getSelectedRow() != null) {
442
                        echeancier.getRequest().setWhere(new Where(contactElement.getTable().getField("ID_AFFAIRE"), "=", selAffaire.getSelectedRow().getID()));
443
 
444
                        if (!isFilling()) {
445
                            SQLRow rowPole = selAffaire.getSelectedRow().getForeignRow("ID_POLE_PRODUIT");
156 ilm 446
                            comboPoleProduit.setValue(rowPole);
61 ilm 447
                        }
448
                    } else {
449
                        echeancier.getRequest().setWhere(null);
450
                    }
451
                }
452
            });
453
            this.add(echeancier, c);
454
 
455
        }
456
 
18 ilm 457
        this.comboClient.addValueListener(this.changeClientListener);
458
 
94 ilm 459
        // SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
460
        // if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.ADDRESS_SPEC, true)) {
461
 
93 ilm 462
        final SQLElement adrElement = getElement().getForeignElement("ID_ADRESSE");
463
        final org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI addressUI = new org.openconcerto.erp.core.customerrelationship.customer.ui.AddressChoiceUI();
464
 
465
            addressUI.addToUI(this, c);
466
 
467
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
468
 
469
                @Override
470
                public void propertyChange(PropertyChangeEvent evt) {
471
                    int wantedID = comboClient.getWantedID();
472
                    System.err.println("SET WHERE ID_CLIENT = " + wantedID);
473
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
474
 
132 ilm 475
                        addressUI.getComboAdrF().getRequest().setWhere(
476
                                new Where(adrElement.getTable().getField("ID_CLIENT"), "=", wantedID).and(new Where(adrElement.getTable().getField("TYPE"), "=", AdresseType.Invoice.getId())));
477
                        addressUI.getComboAdrL().getRequest().setWhere(
478
                                new Where(adrElement.getTable().getField("ID_CLIENT"), "=", wantedID).and(new Where(adrElement.getTable().getField("TYPE"), "=", AdresseType.Delivery.getId())));
93 ilm 479
                    } else {
480
                        addressUI.getComboAdrF().getRequest().setWhere(Where.FALSE);
481
                        addressUI.getComboAdrL().getRequest().setWhere(Where.FALSE);
482
                    }
483
                }
484
            });
94 ilm 485
        // }
174 ilm 486
 
487
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
488
        if (prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.CATEGORIE_COMPTABLE_SPEC, false)) {
489
            // cat spe
490
            final CategorieComptableChoiceUI catUI = new CategorieComptableChoiceUI();
491
            catUI.addToUI(this, c);
492
            catUI.getCombo().addModelListener("wantedID", new PropertyChangeListener() {
493
 
494
                @Override
495
                public void propertyChange(PropertyChangeEvent evt) {
496
                    int wantedID = catUI.getCombo().getWantedID();
497
                    if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
498
                        tableFacture.setRowCatComptable(catUI.getCombo().getElement().getTable().getRow(wantedID));
499
                    } else {
500
                        tableFacture.setRowCatComptable(null);
501
                    }
502
                }
503
            });
504
        }
505
 
93 ilm 506
        // Contact
142 ilm 507
        this.contact = new ElementComboBox() {
508
            @Override
509
            protected SQLComponent createSQLComponent(EditMode mode) {
510
                final SQLComponent c = super.createSQLComponent(mode);
511
                if (mode.equals(EditMode.CREATION)) {
512
                    c.setDefaultsFactory(new IFactory<SQLRowValues>() {
93 ilm 513
 
142 ilm 514
                        @Override
515
                        public SQLRowValues createChecked() {
516
                            final SQLRowValues defaultContactRowValues = new SQLRowValues(eltContact.getTable());
517
                            final SQLRow row = SaisieVenteFactureSQLComponent.this.comboClient.getSelectedRow();
518
                                defaultContactRowValues.putForeignID("ID_CLIENT", row);
519
 
520
                            return defaultContactRowValues;
521
                        }
522
                    });
523
                }
524
                return c;
525
            }
526
        };
527
 
93 ilm 528
        JLabel labelContact = new JLabel(getLabelFor("ID_CONTACT"));
529
        c.gridy++;
530
        c.gridx = 0;
531
        c.gridwidth = 1;
532
        c.weightx = 0;
533
        c.fill = GridBagConstraints.HORIZONTAL;
534
        labelContact.setHorizontalAlignment(SwingConstants.RIGHT);
535
        this.add(labelContact, c);
536
 
537
        c.gridx++;
538
        c.gridwidth = 1;
539
        c.weightx = 1;
540
        this.add(this.contact, c);
541
        SQLElement contactElement = getElement().getForeignElement("ID_CONTACT");
542
        this.contact.init(contactElement, contactElement.getComboRequest(true));
543
        this.contact.getRequest().setWhere(Where.FALSE);
544
        this.addSQLObject(this.contact, "ID_CONTACT");
545
        // }
546
 
142 ilm 547
        if (
548
 
549
        getTable().contains("DATE_LIVRAISON")) {
93 ilm 550
            JLabel labelDateLiv = new JLabel("Livraison le");
551
            c.gridx++;
18 ilm 552
            c.gridwidth = 1;
553
            c.weightx = 0;
80 ilm 554
            c.fill = GridBagConstraints.HORIZONTAL;
93 ilm 555
            labelDateLiv.setHorizontalAlignment(SwingConstants.RIGHT);
556
            this.add(labelDateLiv, c);
18 ilm 557
 
558
            c.gridx++;
93 ilm 559
            c.gridwidth = 1;
560
            c.weightx = 0;
80 ilm 561
            c.fill = GridBagConstraints.NONE;
93 ilm 562
            JDate dateLiv = new JDate();
563
            this.add(dateLiv, c);
564
            c.fill = GridBagConstraints.HORIZONTAL;
565
            this.addSQLObject(dateLiv, "DATE_LIVRAISON");
566
        }
18 ilm 567
 
61 ilm 568
        // Acompte
569
        this.checkAcompte = new JCheckBox(getLabelFor("ACOMPTE"));
570
        c.gridx++;
571
        c.gridwidth = GridBagConstraints.REMAINDER;
572
        // this.add(this.checkAcompte, c);
573
        c.gridwidth = 1;
574
        this.addView(this.checkAcompte, "ACOMPTE");
575
 
18 ilm 576
        // Compte Service
577
        this.checkCompteServiceAuto = new JCheckBox(getLabelFor("COMPTE_SERVICE_AUTO"));
578
        this.addSQLObject(this.checkCompteServiceAuto, "COMPTE_SERVICE_AUTO");
579
        this.compteSelService = new ISQLCompteSelector();
580
 
581
        this.labelCompteServ = new JLabel("Compte Service");
582
        c.gridy++;
583
        c.gridx = 0;
584
        c.gridwidth = 1;
585
        c.weightx = 0;
586
        this.labelCompteServ.setHorizontalAlignment(SwingConstants.RIGHT);
587
        this.add(this.labelCompteServ, c);
588
 
589
        c.gridx++;
590
        c.gridwidth = GridBagConstraints.REMAINDER;
591
        c.weightx = 1;
592
        this.add(this.compteSelService, c);
593
 
594
        String valServ = DefaultNXProps.getInstance().getStringProperty("ArticleService");
595
        Boolean bServ = Boolean.valueOf(valServ);
596
 
597
        this.checkCompteServiceAuto.addActionListener(new ActionListener() {
598
            @Override
599
            public void actionPerformed(ActionEvent e) {
600
                setCompteServiceVisible(!SaisieVenteFactureSQLComponent.this.checkCompteServiceAuto.isSelected());
601
            }
602
        });
603
 
83 ilm 604
        // FIXME A checker si utile pour Preventec ou KD
605
        setCompteServiceVisible(false);
93 ilm 606
        setCompteServiceVisible(!(bServ != null && !bServ.booleanValue()));
18 ilm 607
 
608
 
609
        final JPanel pAcompte = new JPanel();
610
        final DeviseField textAcompteHT = new DeviseField();
611
        pAcompte.add(new JLabel("Acompte HT"));
612
        pAcompte.add(textAcompteHT);
613
 
614
        pAcompte.add(new JLabel("soit"));
615
        final JTextField textAcompte = new JTextField(5);
616
        pAcompte.add(textAcompte);
617
        pAcompte.add(new JLabel("%"));
618
        c.gridx = 0;
619
        c.gridy++;
620
        c.anchor = GridBagConstraints.EAST;
621
        c.fill = GridBagConstraints.NONE;
622
        this.add(pAcompte, c);
623
        c.anchor = GridBagConstraints.WEST;
624
        this.addView(textAcompte, "POURCENT_ACOMPTE");
625
 
626
        pAcompte.setVisible(false);
627
 
628
        /*******************************************************************************************
629
         * * DETAILS
630
         ******************************************************************************************/
631
            this.tableFacture = new SaisieVenteFactureItemTable();
19 ilm 632
 
633
        final ElementComboBox boxTarif = new ElementComboBox();
634
        if (this.getTable().getFieldsName().contains("ID_TARIF")) {
635
            // TARIF
636
            c.gridy++;
637
            c.gridx = 0;
638
            c.weightx = 0;
639
            c.weighty = 0;
640
            c.gridwidth = 1;
80 ilm 641
            c.fill = GridBagConstraints.HORIZONTAL;
93 ilm 642
            this.add(new JLabel(getLabelFor("ID_TARIF"), SwingConstants.RIGHT), c);
19 ilm 643
            c.gridx++;
644
            c.gridwidth = GridBagConstraints.REMAINDER;
80 ilm 645
            c.fill = GridBagConstraints.NONE;
19 ilm 646
            c.weightx = 1;
83 ilm 647
            DefaultGridBagConstraints.lockMinimumSize(boxTarif);
19 ilm 648
            this.add(boxTarif, c);
649
            this.addView(boxTarif, "ID_TARIF");
73 ilm 650
            boxTarif.addModelListener("wantedID", new PropertyChangeListener() {
19 ilm 651
 
652
                @Override
653
                public void propertyChange(PropertyChangeEvent evt) {
73 ilm 654
                    SQLRow selectedRow = boxTarif.getRequest().getPrimaryTable().getRow(boxTarif.getWantedID());
93 ilm 655
                    tableFacture.setTarif(selectedRow, !isFilling());
19 ilm 656
                }
657
            });
658
        }
142 ilm 659
        if (this.getTable().getFieldsName().contains("ACOMPTE_COMMANDE")) {
660
            // ACOMPTE
661
            c.gridy += (this.getTable().getFieldsName().contains("ID_TARIF") ? 0 : 1);
662
            c.gridx += (this.getTable().getFieldsName().contains("ID_TARIF") ? 1 : 2);
663
            c.weightx = 0;
664
            c.weighty = 0;
665
            c.gridwidth = 1;
666
            c.fill = GridBagConstraints.HORIZONTAL;
667
            this.add(new JLabel(getLabelFor("ACOMPTE_COMMANDE"), SwingConstants.RIGHT), c);
668
            c.gridx++;
669
            c.gridwidth = GridBagConstraints.REMAINDER;
670
            c.fill = GridBagConstraints.NONE;
671
            c.weightx = 1;
672
            JTextField acompteCmd = new JTextField(15);
673
            DefaultGridBagConstraints.lockMinimumSize(acompteCmd);
674
            this.add(acompteCmd, c);
675
            this.addView(acompteCmd, "ACOMPTE_COMMANDE");
676
        }
677
 
18 ilm 678
        c.gridy++;
679
        c.gridx = 0;
680
        c.weightx = 1;
681
        c.weighty = 1;
682
        c.gridwidth = GridBagConstraints.REMAINDER;
683
        c.fill = GridBagConstraints.BOTH;
684
 
61 ilm 685
        ITextArea infos = new ITextArea(4, 4);
686
            this.add(this.tableFacture, c);
687
 
18 ilm 688
        // FIXME
689
        this.addView(this.tableFacture.getRowValuesTable(), "");
690
 
691
        /*******************************************************************************************
692
         * * MODE DE REGLEMENT
693
         ******************************************************************************************/
694
        JPanel panelBottom = new JPanel(new GridBagLayout());
695
        GridBagConstraints cBottom = new DefaultGridBagConstraints();
696
        cBottom.weightx = 1;
697
        cBottom.anchor = GridBagConstraints.NORTHWEST;
698
        // Mode de règlement
699
        this.addView("ID_MODE_REGLEMENT", REQ + ";" + DEC + ";" + SEP);
700
        this.eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");
701
        panelBottom.add(this.eltModeRegl, cBottom);
702
 
703
        /*******************************************************************************************
704
         * * FRAIS DE PORT ET REMISE
705
         ******************************************************************************************/
706
        JPanel panelFrais = new JPanel();
707
        panelFrais.setLayout(new GridBagLayout());
708
 
709
        final GridBagConstraints cFrais = new DefaultGridBagConstraints();
710
 
711
        this.textPortHT = new DeviseField(5);
712
        DefaultGridBagConstraints.lockMinimumSize(textPortHT);
713
        addSQLObject(this.textPortHT, "PORT_HT");
714
        this.textRemiseHT = new DeviseField(5);
715
        DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
716
        addSQLObject(this.textRemiseHT, "REMISE_HT");
717
 
718
        // Frais de port
719
        cFrais.gridheight = 1;
720
        cFrais.gridx = 1;
65 ilm 721
        SQLRequestComboBox boxTaxePort = new SQLRequestComboBox(false, 8);
722
        if (getTable().contains("ID_TAXE_PORT")) {
18 ilm 723
 
65 ilm 724
            JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
725
            labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
726
            cFrais.gridy++;
727
            panelFrais.add(labelPortHT, cFrais);
728
            cFrais.gridx++;
729
            panelFrais.add(this.textPortHT, cFrais);
18 ilm 730
 
65 ilm 731
            JLabel labelTaxeHT = new JLabel(getLabelFor("ID_TAXE_PORT"));
732
            labelTaxeHT.setHorizontalAlignment(SwingConstants.RIGHT);
733
            cFrais.gridx = 1;
734
            cFrais.gridy++;
735
            panelFrais.add(labelTaxeHT, cFrais);
736
            cFrais.gridx++;
737
            panelFrais.add(boxTaxePort, cFrais);
738
            this.addView(boxTaxePort, "ID_TAXE_PORT", REQ);
739
 
740
            boxTaxePort.addValueListener(new PropertyChangeListener() {
741
 
742
                @Override
743
                public void propertyChange(PropertyChangeEvent evt) {
744
                    // TODO Raccord de méthode auto-généré
745
                    totalTTC.updateTotal();
746
                }
747
            });
748
        }
156 ilm 749
        final DeviseField textFraisDocHT = new DeviseField();
750
        final SQLRequestComboBox boxTaxeFraisDoc = new SQLRequestComboBox(false, 8);
65 ilm 751
 
156 ilm 752
        final boolean showFrais = prefs.getBoolean(GestionCommercialeGlobalPreferencePanel.FRAIS_DOCUMENT, false);
753
        if (showFrais) {
754
 
755
            JLabel labelFraisDocHT = new JLabel(getLabelFor("FRAIS_DOCUMENT_HT"));
756
            labelFraisDocHT.setHorizontalAlignment(SwingConstants.RIGHT);
757
            cFrais.gridx = 1;
758
            cFrais.gridy++;
759
            panelFrais.add(labelFraisDocHT, cFrais);
760
            cFrais.gridx++;
761
            panelFrais.add(textFraisDocHT, cFrais);
762
            addView(textFraisDocHT, "FRAIS_DOCUMENT_HT");
763
 
764
            JLabel labelTaxeFraisDocHT = new JLabel(getLabelFor("ID_TAXE_FRAIS_DOCUMENT"));
765
            labelTaxeFraisDocHT.setHorizontalAlignment(SwingConstants.RIGHT);
766
            cFrais.gridx = 1;
767
            cFrais.gridy++;
768
            panelFrais.add(labelTaxeFraisDocHT, cFrais);
769
            cFrais.gridx++;
770
            panelFrais.add(boxTaxeFraisDoc, cFrais);
771
            this.addView(boxTaxeFraisDoc, "ID_TAXE_FRAIS_DOCUMENT", REQ);
772
 
773
            boxTaxeFraisDoc.addValueListener(new PropertyChangeListener() {
774
 
775
                @Override
776
                public void propertyChange(PropertyChangeEvent evt) {
777
                    totalTTC.updateTotal();
778
                }
779
            });
780
 
781
            textFraisDocHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
782
 
783
                @Override
784
                public void update(final DocumentEvent e) {
785
                    totalTTC.updateTotal();
786
                }
787
            });
788
 
789
            comboClient.addModelListener("wantedID", new PropertyChangeListener() {
790
 
791
                @Override
792
                public void propertyChange(PropertyChangeEvent evt) {
793
                    if (!isFilling()) {
794
                        final int wantedID = comboClient.getWantedID();
795
                        long l = 0;
796
                        if (wantedID != SQLRow.NONEXISTANT_ID && wantedID >= SQLRow.MIN_VALID_ID) {
797
 
798
                            final SQLRow rowClient = getTable().getForeignTable("ID_CLIENT").getRow(wantedID);
799
                            SQLRow rowFrais = rowClient.getForeign("ID_FRAIS_DOCUMENT");
800
                            if (rowFrais != null && !rowFrais.isUndefined()) {
801
                                l = rowFrais.getLong("MONTANT_HT");
802
                                boxTaxeFraisDoc.setValue(rowFrais.getForeignID("ID_TAXE"));
803
                            }
804
                            textFraisDocHT.setValue(l);
805
                        }
806
                    }
807
                }
808
            });
809
        }
810
 
18 ilm 811
        // Remise
812
        JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
813
        labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
814
        cFrais.gridy++;
815
        cFrais.gridx = 1;
816
        panelFrais.add(labelRemiseHT, cFrais);
817
        cFrais.gridx++;
818
        panelFrais.add(this.textRemiseHT, cFrais);
819
        cFrais.gridy++;
820
 
821
        cBottom.gridx++;
822
        cBottom.weightx = 1;
823
        cBottom.anchor = GridBagConstraints.NORTHEAST;
824
        cBottom.fill = GridBagConstraints.NONE;
825
        panelBottom.add(panelFrais, cBottom);
826
 
827
        /*******************************************************************************************
828
         * * CALCUL DES TOTAUX
829
         ******************************************************************************************/
830
        DeviseField fieldHT = new DeviseField();
831
        final DeviseField fieldTVA = new DeviseField();
832
        DeviseField fieldService = new DeviseField();
833
        DeviseField fieldTHA = new DeviseField();
142 ilm 834
        DeviseField fieldTEco = new DeviseField();
19 ilm 835
 
836
        DeviseField fieldDevise = null;
837
        if (getTable().getFieldsName().contains("T_DEVISE")) {
838
            fieldDevise = new DeviseField();
839
            addSQLObject(fieldDevise, "T_DEVISE");
840
        }
18 ilm 841
        // FIXME was required but not displayed for KD
842
        addSQLObject(fieldTHA, "T_HA");
142 ilm 843
        addSQLObject(fieldTEco, "T_ECO_CONTRIBUTION");
18 ilm 844
        addRequiredSQLObject(fieldHT, "T_HT");
845
        addRequiredSQLObject(fieldTVA, "T_TVA");
846
        addRequiredSQLObject(this.fieldTTC, "T_TTC");
847
        addRequiredSQLObject(fieldService, "T_SERVICE");
19 ilm 848
        JTextField poids = new JTextField();
849
        addSQLObject(poids, "T_POIDS");
80 ilm 850
 
94 ilm 851
        // Disable
852
        this.allowEditable("T_HA", false);
142 ilm 853
        this.allowEditable("T_ECO_CONTRIBUTION", false);
94 ilm 854
        this.allowEditable("T_HT", false);
855
        this.allowEditable("T_TVA", false);
856
        this.allowEditable("T_TTC", false);
857
        this.allowEditable("T_SERVICE", false);
858
        this.allowEditable("T_POIDS", false);
859
 
142 ilm 860
        totalTTC = new TotalPanel(this.tableFacture, fieldTEco, fieldHT, fieldTVA, this.fieldTTC, this.textPortHT, this.textRemiseHT, fieldService, fieldTHA, fieldDevise, poids, null,
861
                (getTable().contains("ID_TAXE_PORT") ? boxTaxePort : null), null);
156 ilm 862
        totalTTC.setTextFraisDoc(textFraisDocHT, boxTaxeFraisDoc);
18 ilm 863
        DefaultGridBagConstraints.lockMinimumSize(totalTTC);
864
        cBottom.gridx++;
865
        cBottom.weightx = 1;
866
        cBottom.anchor = GridBagConstraints.EAST;
867
        cBottom.fill = GridBagConstraints.HORIZONTAL;
868
        panelBottom.add(totalTTC, cBottom);
869
 
870
        c.anchor = GridBagConstraints.WEST;
871
        c.gridwidth = GridBagConstraints.REMAINDER;
872
        c.fill = GridBagConstraints.HORIZONTAL;
873
        c.gridx = 0;
874
        c.gridy++;
875
        c.weighty = 0;
876
        this.add(panelBottom, c);
877
 
94 ilm 878
        // Ligne : Timbre
879
        c.gridy++;
880
        c.gridx = 0;
881
        c.weightx = 1;
882
        c.weighty = 0;
883
        c.gridwidth = GridBagConstraints.REMAINDER;
884
        c.anchor = GridBagConstraints.EAST;
885
        c.fill = GridBagConstraints.HORIZONTAL;
886
        final JPanel timbrePanel = createTimbrePanel();
887
        this.add(timbrePanel, c);
888
 
889
        timbrePanel.setVisible(this.gestionTimbre);
890
 
18 ilm 891
        // Ligne : Avoir
892
        c.gridy++;
893
        c.gridx = 0;
894
        c.weightx = 1;
895
        c.weighty = 0;
896
        c.gridwidth = GridBagConstraints.REMAINDER;
897
        c.anchor = GridBagConstraints.EAST;
898
        c.fill = GridBagConstraints.HORIZONTAL;
899
        this.add(createPanelAvoir(), c);
900
 
901
        // Infos
61 ilm 902
            c.gridy++;
903
            c.gridx = 0;
904
            c.gridwidth = 4;
905
            c.fill = GridBagConstraints.BOTH;
906
            this.add(new TitledSeparator(getLabelFor("INFOS")), c);
18 ilm 907
 
61 ilm 908
            c.gridy++;
18 ilm 909
 
61 ilm 910
            final JScrollPane comp = new JScrollPane(infos);
911
            infos.setBorder(null);
912
            DefaultGridBagConstraints.lockMinimumSize(comp);
913
            this.add(comp, c);
18 ilm 914
 
21 ilm 915
        this.panelOO = new PanelOOSQLComponent(this);
18 ilm 916
        c.gridy++;
917
        c.gridx = 0;
918
        c.weightx = 1;
919
        c.fill = GridBagConstraints.NONE;
920
        c.anchor = GridBagConstraints.NORTHEAST;
21 ilm 921
        this.add(this.panelOO, c);
18 ilm 922
 
923
        this.addSQLObject(this.textAvoirTTC, "T_AVOIR_TTC");
149 ilm 924
        this.addSQLObject(this.textAcompte, "T_ACOMPTE");
18 ilm 925
 
926
        this.addRequiredSQLObject(dateSaisie, "DATE");
927
        this.addRequiredSQLObject(this.textNumeroUnique, "NUMERO");
928
        this.addSQLObject(infos, "INFOS");
929
        this.addSQLObject(this.checkPrevisionnelle, "PREVISIONNELLE");
930
        this.addSQLObject(this.checkComplement, "COMPLEMENT");
931
        this.addSQLObject(this.selAvoir, "ID_AVOIR_CLIENT");
932
        this.addSQLObject(this.compteSelService, "ID_COMPTE_PCE_SERVICE");
19 ilm 933
        ModeDeReglementSQLComponent modeReglComp;
83 ilm 934
 
19 ilm 935
        modeReglComp = (ModeDeReglementSQLComponent) this.eltModeRegl.getSQLChild();
177 ilm 936
        modeReglComp.addDateCompListener(this.dateSaisie);
18 ilm 937
        this.selAvoir.getRequest().setWhere(new Where(this.tableAvoir.getField("SOLDE"), "=", Boolean.FALSE));
938
        this.selAvoir.fillCombo();
939
 
940
        // Selection du compte de service
941
        int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
942
        if (idCompteVenteService <= 1) {
943
            try {
944
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
945
            } catch (Exception e) {
946
                e.printStackTrace();
947
            }
948
        }
949
        this.compteSelService.setValue(idCompteVenteService);
950
 
951
        // Lock
952
 
953
        DefaultGridBagConstraints.lockMinimumSize(this.comboClient);
954
        DefaultGridBagConstraints.lockMinimumSize(this.comboCommercial);
955
 
956
        // Listeners
957
 
958
        this.comboClient.addValueListener(this.listenerModeReglDefaut);
959
        this.fieldTTC.getDocument().addDocumentListener(new SimpleDocumentListener() {
960
            @Override
961
            public void update(DocumentEvent e) {
94 ilm 962
                calculTimbre();
18 ilm 963
                refreshText();
964
            }
965
 
966
        });
967
 
94 ilm 968
        if (this.checkTaux != null) {
969
            this.checkTaux.addActionListener(new ActionListener() {
970
                @Override
971
                public void actionPerformed(ActionEvent e) {
972
                    calculTimbre();
973
                    refreshText();
974
                }
975
 
976
            });
977
        }
978
        this.tauxTimbre.getDocument().addDocumentListener(new SimpleDocumentListener() {
979
            @Override
980
            public void update(DocumentEvent e) {
981
                calculTimbre();
982
                refreshText();
983
            }
984
 
985
        });
986
 
987
        this.totalTimbre.getDocument().addDocumentListener(new SimpleDocumentListener() {
988
            @Override
989
            public void update(DocumentEvent e) {
990
                refreshText();
991
            }
992
 
993
        });
994
 
18 ilm 995
        this.selAvoir.addValueListener(new PropertyChangeListener() {
996
 
997
            public void propertyChange(PropertyChangeEvent evt) {
998
                refreshText();
999
            }
1000
 
1001
        });
1002
 
1003
        this.checkAcompte.addPropertyChangeListener(new PropertyChangeListener() {
1004
 
1005
            public void propertyChange(PropertyChangeEvent evt) {
1006
 
1007
                pAcompte.setVisible(SaisieVenteFactureSQLComponent.this.checkAcompte.isSelected());
1008
            }
1009
        });
1010
 
1011
        this.changeClientListener = new PropertyChangeListener() {
1012
 
1013
            public void propertyChange(PropertyChangeEvent evt) {
1014
 
93 ilm 1015
                if (SaisieVenteFactureSQLComponent.this.comboClient.getSelectedRow() != null) {
83 ilm 1016
                    final SQLRow row = SaisieVenteFactureSQLComponent.this.comboClient.getSelectedRow();
142 ilm 1017
                    final int id = (row == null) ? SQLRow.NONEXISTANT_ID : row.getID();
1018
                        if (row != null) {
1019
                            if (row.getFields().contains("ID_COMPTE_PCE_SERVICE") && compteSelService != null && !row.isForeignEmpty("ID_COMPTE_PCE_SERVICE")) {
1020
                                compteSelService.setValue(row.getForeignID("ID_COMPTE_PCE_SERVICE"));
1021
                            }
1022
                            if (row.getFields().contains("ID_COMPTE_PCE_PRODUIT") && !row.isForeignEmpty("ID_COMPTE_PCE_PRODUIT")) {
1023
                                totalTTC.setDefaultCompteProduit(row.getForeign("ID_COMPTE_PCE_PRODUIT"));
1024
                            }
93 ilm 1025
                        }
83 ilm 1026
                    if (row != null) {
18 ilm 1027
                        if (SaisieVenteFactureSQLComponent.this.contact != null) {
1028
                            Where w = new Where(SaisieVenteFactureSQLComponent.this.eltContact.getTable().getField("ID_CLIENT"), "=", SQLRow.NONEXISTANT_ID);
1029
                                w = w.or(new Where(SaisieVenteFactureSQLComponent.this.eltContact.getTable().getField("ID_CLIENT"), "=", id));
83 ilm 1030
                            SaisieVenteFactureSQLComponent.this.contact.getRequest().setWhere(w);
18 ilm 1031
                        }
1032
 
93 ilm 1033
                    } else {
18 ilm 1034
 
1035
                    }
1036
                    SaisieVenteFactureSQLComponent.this.previousClient = id;
1037
                }
73 ilm 1038
 
18 ilm 1039
            }
1040
        };
1041
 
1042
        this.changeCompteListener = new PropertyChangeListener() {
1043
            public void propertyChange(PropertyChangeEvent evt) {
1044
                SQLSelect sel = new SQLSelect(getTable().getBase());
1045
                sel.addSelect(SaisieVenteFactureSQLComponent.this.client.getTable().getKey());
1046
                Where where = new Where(SaisieVenteFactureSQLComponent.this.client.getTable().getField("ID_COMPTE_PCE"), "=", SaisieVenteFactureSQLComponent.this.compteSel.getValue());
1047
                sel.setWhere(where);
1048
 
1049
                String req = sel.asString();
1050
                List l = getTable().getBase().getDataSource().execute(req);
1051
                if (l != null) {
1052
                    if (l.size() == 1) {
1053
                        Map<String, Object> m = (Map<String, Object>) l.get(0);
1054
                        Object o = m.get(SaisieVenteFactureSQLComponent.this.client.getTable().getKey().getName());
1055
                        System.err.println("Only one value match :: " + o);
1056
                        if (o != null) {
1057
                            SaisieVenteFactureSQLComponent.this.comboClient.setValue(Integer.valueOf(((Number) o).intValue()));
1058
                        }
1059
                    }
1060
                }
1061
            }
1062
        };
83 ilm 1063
 
18 ilm 1064
        this.textPortHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
1065
            @Override
1066
            public void update(DocumentEvent e) {
1067
                totalTTC.updateTotal();
1068
            }
1069
        });
1070
 
1071
        this.textRemiseHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
1072
            @Override
1073
            public void update(DocumentEvent e) {
1074
                totalTTC.updateTotal();
1075
            }
1076
        });
28 ilm 1077
        this.comboClient.addValueListener(new PropertyChangeListener() {
1078
            @Override
1079
            public void propertyChange(PropertyChangeEvent evt) {
1080
                if (SaisieVenteFactureSQLComponent.this.isFilling())
1081
                    return;
1082
                final SQLRow row = ((SQLRequestComboBox) evt.getSource()).getSelectedRow();
1083
                if (row != null) {
1084
                    if (SaisieVenteFactureSQLComponent.this.client.getTable().contains("ID_TARIF")) {
1085
                        SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
93 ilm 1086
                        if (foreignRow != null && !foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())) {
28 ilm 1087
                            boxTarif.setValue(foreignRow.getID());
1088
                        } else {
80 ilm 1089
                            boxTarif.setValue(foreignRow);
28 ilm 1090
                        }
73 ilm 1091
 
28 ilm 1092
                    }
1093
 
1094
                    int idCpt = row.getInt("ID_COMPTE_PCE");
1095
 
1096
                    if (idCpt <= 1) {
1097
                        // Select Compte client par defaut
1098
                        idCpt = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
1099
                        if (idCpt <= 1) {
1100
                            try {
1101
                                idCpt = ComptePCESQLElement.getIdComptePceDefault("Clients");
1102
                            } catch (Exception e) {
1103
                                e.printStackTrace();
1104
                            }
1105
                        }
1106
                    }
1107
                    if (SaisieVenteFactureSQLComponent.this.compteSel != null) {
1108
                        Integer i = SaisieVenteFactureSQLComponent.this.compteSel.getValue();
1109
                        if (i == null || i.intValue() != idCpt) {
1110
                            SaisieVenteFactureSQLComponent.this.compteSel.setValue(idCpt);
1111
                        }
1112
                    }
1113
                }
1114
 
1115
            }
1116
        });
83 ilm 1117
 
18 ilm 1118
    }
1119
 
94 ilm 1120
    private void calculTimbre() {
1121
        totalTimbre.setValue(0L);
1122
        if (gestionTimbre && this.checkTaux != null && this.checkTaux.isSelected()) {
1123
            if (tauxTimbre.getText().trim().length() != 0) {
1124
                BigDecimal taux = new BigDecimal(tauxTimbre.getText());
1125
                Long ttc = fieldTTC.getValue();
1126
                if (ttc != null) {
1127
                    long timbreValue = taux.multiply(new BigDecimal(ttc)).movePointLeft(2).setScale(0, RoundingMode.HALF_UP).longValue();
1128
                    totalTimbre.setValue(timbreValue);
1129
                }
1130
            }
1131
        }
1132
    }
1133
 
18 ilm 1134
    private JPanel createPanelAvoir() {
1135
        JPanel panelAvoir = new JPanel(new GridBagLayout());
1136
        panelAvoir.setOpaque(false);
1137
        GridBagConstraints cA = new DefaultGridBagConstraints();
1138
        JLabel labelAvoir = new JLabel(getLabelFor("ID_AVOIR_CLIENT"));
1139
        labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
1140
        cA.weightx = 1;
1141
        labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
1142
        panelAvoir.add(labelAvoir, cA);
1143
        cA.weightx = 0;
1144
        cA.gridx++;
1145
        this.selAvoir = new ElementComboBox();
1146
        this.selAvoir.setAddIconVisible(false);
1147
        panelAvoir.add(this.selAvoir, cA);
1148
        final JLabel labelTotalAvoir = new JLabel("Total à régler");
94 ilm 1149
        this.textNetAPayer = new DeviseField();
1150
        this.textNetAPayer.setEditable(false);
18 ilm 1151
        cA.gridx++;
1152
        cA.weightx = 0;
1153
        panelAvoir.add(labelTotalAvoir, cA);
1154
        cA.gridx++;
1155
        cA.weightx = 0;
94 ilm 1156
        panelAvoir.add(this.textNetAPayer, cA);
1157
        addView(textNetAPayer, "NET_A_PAYER");
1158
        this.textNetAPayer.setHorizontalAlignment(SwingConstants.RIGHT);
18 ilm 1159
 
1160
        return panelAvoir;
1161
    }
1162
 
94 ilm 1163
    private JCheckBox checkTaux;
1164
 
1165
    private JPanel createTimbrePanel() {
1166
        JPanel panelTimbre = new JPanel(new GridBagLayout());
1167
        panelTimbre.setOpaque(false);
1168
        GridBagConstraints cA = new DefaultGridBagConstraints();
1169
        this.checkTaux = new JCheckBox(getLabelFor("SOUMIS_TIMBRE_FISCAL") + " " + getLabelFor("TAUX_TIMBRE_FISCAL"));
1170
        checkTaux.setHorizontalAlignment(SwingConstants.RIGHT);
1171
        cA.weightx = 1;
1172
        checkTaux.setHorizontalAlignment(SwingConstants.RIGHT);
1173
        panelTimbre.add(checkTaux, cA);
1174
        cA.weightx = 0;
1175
        cA.gridx++;
1176
        this.tauxTimbre = new JTextField(8);
1177
        panelTimbre.add(this.tauxTimbre, cA);
1178
        final JLabel labelTotalTimbre = new JLabel(getLabelFor("TOTAL_TIMBRE_FISCAL"));
1179
        this.totalTimbre = new DeviseField();
1180
        this.totalTimbre.setEditable(false);
1181
        cA.gridx++;
1182
        cA.weightx = 0;
1183
        panelTimbre.add(labelTotalTimbre, cA);
1184
        cA.gridx++;
1185
        cA.weightx = 0;
1186
        panelTimbre.add(this.totalTimbre, cA);
1187
        this.totalTimbre.setHorizontalAlignment(SwingConstants.RIGHT);
1188
 
1189
        this.addView(checkTaux, "SOUMIS_TIMBRE_FISCAL");
1190
        this.addView(tauxTimbre, "TAUX_TIMBRE_FISCAL");
1191
        this.addView(totalTimbre, "TOTAL_TIMBRE_FISCAL");
1192
        return panelTimbre;
1193
    }
1194
 
18 ilm 1195
    private void setCompteServiceVisible(boolean b) {
1196
        this.compteSelService.setVisible(b);
1197
        this.labelCompteServ.setVisible(b);
1198
    }
1199
 
1200
    private void refreshText() {
73 ilm 1201
        Number n = this.fieldTTC.getValue();
94 ilm 1202
        long totalAvoirTTC = 0;
1203
        long netAPayer = 0;
1204
        long ttc = 0;
1205
        if (n != null) {
1206
            netAPayer = n.longValue();
1207
            ttc = n.longValue();
1208
        }
1209
 
18 ilm 1210
        if (this.selAvoir.getSelectedId() > 1) {
1211
            SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
1212
            if (n != null) {
1213
                SQLRow rowAvoir = tableAvoir.getRow(this.selAvoir.getSelectedId());
1214
                long totalAvoir = ((Number) rowAvoir.getObject("MONTANT_TTC")).longValue();
1215
                totalAvoir -= ((Number) rowAvoir.getObject("MONTANT_SOLDE")).longValue();
1216
                if (getSelectedID() > 1) {
1217
                    SQLRow row = getTable().getRow(getSelectedID());
1218
                    int idAvoirOld = row.getInt("ID_AVOIR_CLIENT");
1219
                    if (idAvoirOld == rowAvoir.getID()) {
1220
                        totalAvoir += Long.valueOf(row.getObject("T_AVOIR_TTC").toString());
1221
                    }
1222
                }
1223
 
1224
                long l = ttc - totalAvoir;
1225
                if (l < 0) {
1226
                    l = 0;
94 ilm 1227
                    totalAvoirTTC = ttc;
18 ilm 1228
                } else {
94 ilm 1229
                    totalAvoirTTC = totalAvoir;
18 ilm 1230
                }
94 ilm 1231
                netAPayer = l;
18 ilm 1232
            }
94 ilm 1233
        }
1234
        if (this.gestionTimbre) {
1235
            Long timbre = this.totalTimbre.getValue();
1236
            if (timbre != null) {
1237
                netAPayer += timbre;
18 ilm 1238
            }
1239
        }
149 ilm 1240
        Long acompte = this.textAcompte.getValue();
1241
        if (acompte != null) {
1242
            netAPayer -= acompte;
1243
        }
94 ilm 1244
        this.textNetAPayer.setValue(netAPayer);
1245
        this.textAvoirTTC.setValue(totalAvoirTTC);
18 ilm 1246
    }
1247
 
1248
    public int insert(SQLRow order) {
1249
        return commit(order);
1250
    }
1251
 
80 ilm 1252
    private void createCompteServiceAuto(int id) throws SQLException {
156 ilm 1253
        SQLRow rowPole = this.comboPoleProduit.getSelectedRow();
18 ilm 1254
        SQLRow rowVerif = this.comboVerificateur.getSelectedRow();
1255
        String verifInitiale = getInitialesFromVerif(rowVerif);
1256
        int idCpt = ComptePCESQLElement.getId("706" + rowPole.getString("CODE") + verifInitiale, "Service " + rowPole.getString("NOM") + " " + rowVerif.getString("NOM"));
1257
        SQLRowValues rowVals = this.getTable().getRow(id).createEmptyUpdateRow();
1258
        rowVals.put("ID_COMPTE_PCE_SERVICE", idCpt);
80 ilm 1259
        rowVals.update();
18 ilm 1260
    }
1261
 
1262
    @Override
1263
    public void select(SQLRowAccessor r) {
80 ilm 1264
 
90 ilm 1265
        this.panelOO.getCheckAbo().setSelected(false);
1266
 
80 ilm 1267
        boolean isPartial = false;
1268
        if (r != null && r.getBoolean("PARTIAL") != null) {
1269
            isPartial = r.getBoolean("PARTIAL").booleanValue();
1270
        }
1271
 
1272
        boolean isSolde = false;
1273
        if (r != null && r.getBoolean("SOLDE") != null) {
1274
            isSolde = r.getBoolean("SOLDE").booleanValue();
1275
        }
1276
 
144 ilm 1277
        if (getMode() == Mode.MODIFICATION && r != null && !r.isUndefined() && (isPartial || isSolde)) {
80 ilm 1278
            throw new IllegalArgumentException("Impossible de modifier une facturation intermédiaire");
1279
        }
1280
 
18 ilm 1281
        if (compteSel != null) {
1282
            this.compteSel.rmValueListener(this.changeCompteListener);
1283
        }
90 ilm 1284
 
18 ilm 1285
        this.rowSelected = r;
1286
        if (r != null) {
83 ilm 1287
            // FIXME Mettre un droit pour autoriser la modification d'une facture lettrée ou pointée
80 ilm 1288
            if (!r.isUndefined() && r.getObject("ID_MOUVEMENT") != null && !r.isForeignEmpty("ID_MOUVEMENT")) {
1289
                SQLTable tableEcr = getTable().getTable("ECRITURE");
1290
                SQLTable tableMvt = getTable().getTable("MOUVEMENT");
1291
                SQLTable tablePiece = getTable().getTable("PIECE");
83 ilm 1292
                {
1293
                    SQLSelect sel = new SQLSelect();
1294
                    sel.addSelect(tableEcr.getKey(), "COUNT");
1295
                    int idPiece = r.getForeign("ID_MOUVEMENT").getInt("ID_PIECE");
1296
                    Where w = new Where(tableMvt.getKey(), "=", tableEcr.getField("ID_MOUVEMENT"));
1297
                    w = w.and(new Where(tablePiece.getKey(), "=", tableMvt.getField("ID_PIECE")));
1298
                    w = w.and(new Where(tablePiece.getKey(), "=", idPiece));
1299
                    w = w.and(new Where(tableEcr.getField("POINTEE"), "!=", "").or(new Where(tableEcr.getField("LETTRAGE"), "!=", "")));
1300
                    sel.setWhere(w);
1301
                    Object o = Configuration.getInstance().getRoot().getBase().getDataSource().executeScalar(sel.asString());
1302
                    if (o != null && ((Number) o).longValue() > 0) {
1303
                        SwingUtilities.invokeLater(new Runnable() {
18 ilm 1304
 
83 ilm 1305
                            @Override
1306
                            public void run() {
1307
                                JOptionPane.showMessageDialog(null, "Attention cette facture est pointée ou lettrée en comptabilité. \nToute modification écrasera ces informations comptables.");
1308
                            }
1309
                        });
1310
                    }
80 ilm 1311
                }
83 ilm 1312
                {
1313
                    SQLSelect sel = new SQLSelect();
1314
                    SQLTable tableAssoc = getTable().getTable("ASSOCIATION_ANALYTIQUE");
1315
                    sel.addSelect(tableAssoc.getKey(), "COUNT");
1316
                    int idPiece = r.getForeign("ID_MOUVEMENT").getInt("ID_PIECE");
1317
                    Where w = new Where(tableMvt.getKey(), "=", tableEcr.getField("ID_MOUVEMENT"));
1318
                    w = w.and(new Where(tableAssoc.getField("ID_ECRITURE"), "=", tableEcr.getKey()));
1319
                    w = w.and(new Where(tablePiece.getKey(), "=", tableMvt.getField("ID_PIECE")));
1320
                    w = w.and(new Where(tablePiece.getKey(), "=", idPiece));
1321
                    w = w.and(new Where(tableAssoc.getField("GESTION_AUTO"), "=", Boolean.FALSE));
1322
                    sel.setWhere(w);
1323
                    System.err.println(sel.asString());
1324
                    Object o = Configuration.getInstance().getRoot().getBase().getDataSource().executeScalar(sel.asString());
1325
                    if (o != null && ((Number) o).longValue() > 0) {
1326
                        SwingUtilities.invokeLater(new Runnable() {
80 ilm 1327
 
83 ilm 1328
                            @Override
1329
                            public void run() {
1330
                                JOptionPane.showMessageDialog(null,
1331
                                        "Attention la répartition analytique a été modifié manuellement sur cette facture. \nToute modification écrasera ces informations comptables.");
1332
                            }
1333
                        });
1334
                    }
1335
                }
80 ilm 1336
            }
18 ilm 1337
        }
1338
            super.select(r);
1339
 
142 ilm 1340
        if (r != null)
1341
 
1342
        {
73 ilm 1343
            // this.tableFacture.getModel().clearRows();
1344
            // this.tableFacture.insertFrom("ID_SAISIE_VENTE_FACTURE", r.getID());
18 ilm 1345
            Boolean b = (Boolean) r.getObject("ACOMPTE");
1346
            if (b != null) {
1347
                setAcompte(b);
1348
            } else {
1349
                setAcompte(false);
1350
            }
1351
        }
90 ilm 1352
 
61 ilm 1353
        if (this.comboClient != null) {
93 ilm 1354
 
61 ilm 1355
            this.comboClient.addValueListener(this.changeClientListener);
1356
        }
18 ilm 1357
        if (this.compteSel != null) {
1358
            this.compteSel.addValueListener(this.changeCompteListener);
1359
        } // nomClient.addValueListener(changeClientListener);
1360
    }
1361
 
1362
    private String getInitialesFromVerif(SQLRow row) {
1363
        String s = "";
1364
 
1365
        if (row != null) {
1366
            String prenom = row.getString("PRENOM");
1367
            if (prenom != null && prenom.length() > 0) {
1368
                s += prenom.toUpperCase().charAt(0);
1369
            }
1370
            String nom = row.getString("NOM");
1371
            if (nom != null && nom.length() > 0) {
1372
                s += nom.toUpperCase().charAt(0);
1373
            }
1374
        }
1375
 
1376
        return s;
1377
    }
1378
 
1379
    public int commit(SQLRow order) {
1380
 
1381
        int idSaisieVF = -1;
1382
        long lFactureOld = 0;
1383
        SQLRow rowFactureOld = null;
1384
        SQLRow rowFacture = null;
142 ilm 1385
        int attempt = 0;
144 ilm 1386
        // on vérifie qu'une facture de même numero n'a pas été insérée entre temps
1387
        boolean validated = this.textNumeroUnique.checkValidation(false);
1388
        while (!validated && attempt < JUniqueTextField.RETRY_COUNT) {
1389
            try {
1390
                Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
1391
            } catch (InterruptedException e) {
1392
                e.printStackTrace();
142 ilm 1393
            }
149 ilm 1394
            String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate(), defaultNum);
144 ilm 1395
            this.textNumeroUnique.setText(num);
1396
            validated = this.textNumeroUnique.checkValidation(false);
1397
            System.err.println("ATTEMPT " + attempt + " WITH NUMERO " + num + " validated : " + validated);
1398
            attempt++;
142 ilm 1399
        }
1400
        final String num = this.textNumeroUnique.getText();
144 ilm 1401
        if (!validated) {
142 ilm 1402
            idSaisieVF = getSelectedID();
1403
            ExceptionHandler.handle("Impossible d'ajouter, numéro de facture existant.");
1404
            final Object root = SwingUtilities.getRoot(this);
1405
            if (root instanceof EditFrame) {
1406
                final EditFrame frame = (EditFrame) root;
1407
                frame.getPanel().setAlwaysVisible(true);
1408
            }
1409
        } else {
73 ilm 1410
            try {
1411
                if (getMode() == Mode.INSERTION) {
1412
                    idSaisieVF = super.insert(order);
1413
                    rowFacture = getTable().getRow(idSaisieVF);
1414
                    // incrémentation du numéro auto
93 ilm 1415
                    final SQLRow rowNum = comboNumAuto == null ? this.tableNum.getRow(2) : comboNumAuto.getSelectedRow();
180 ilm 1416
                    if (NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), rowFacture.getDate("DATE").getTime(), rowNum).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
93 ilm 1417
                        SQLRowValues rowVals = rowNum.createEmptyUpdateRow();
18 ilm 1418
 
180 ilm 1419
                        String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(getElement().getClass());
93 ilm 1420
                        int val = rowNum.getInt(labelNumberFor);
73 ilm 1421
                        val++;
1422
                        rowVals.put(labelNumberFor, Integer.valueOf(val));
93 ilm 1423
                        rowVals.update();
18 ilm 1424
                    }
73 ilm 1425
                } else {
1426
                    if (JOptionPane.showConfirmDialog(this, "Attention en modifiant cette facture, vous supprimerez les chéques et les échéances associés. Continuer?", "Modification de facture",
1427
                            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
1428
                        // On recupere l'ancien total HT
1429
                        rowFactureOld = this.getTable().getRow(getSelectedID());
1430
                        lFactureOld = ((Number) rowFactureOld.getObject("T_HT")).longValue();
18 ilm 1431
 
73 ilm 1432
                        super.update();
18 ilm 1433
 
73 ilm 1434
                        idSaisieVF = getSelectedID();
1435
                    } else {
1436
                        // Annulation par l'utilisateur
1437
                        return idSaisieVF;
1438
                    }
18 ilm 1439
                }
1440
 
73 ilm 1441
                rowFacture = getTable().getRow(idSaisieVF);
1442
                final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
18 ilm 1443
 
73 ilm 1444
                // Mise à jour des tables liées
1445
                this.tableFacture.updateField("ID_SAISIE_VENTE_FACTURE", idSaisieVF);
18 ilm 1446
 
90 ilm 1447
                this.tableFacture.createArticle(idSaisieVF, this.getElement());
18 ilm 1448
 
90 ilm 1449
 
73 ilm 1450
                int idMvt = -1;
83 ilm 1451
                if (!this.checkPrevisionnelle.isSelected()) {
1452
                    if (getMode() == Mode.MODIFICATION) {
1453
                        idMvt = rowFacture.getInt("ID_MOUVEMENT");
1454
                        // on supprime tout ce qui est lié à la facture
1455
                        System.err.println("Archivage des fils");
1456
                        EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
1457
                        eltEcr.archiveMouvementProfondeur(idMvt, false);
1458
                    }
18 ilm 1459
 
73 ilm 1460
                    System.err.println("Regeneration des ecritures");
1461
                    if (idMvt > 1) {
1462
                        new GenerationMvtSaisieVenteFacture(idSaisieVF, idMvt);
1463
                    } else {
1464
                        new GenerationMvtSaisieVenteFacture(idSaisieVF);
1465
                    }
1466
                    System.err.println("Fin regeneration");
61 ilm 1467
 
73 ilm 1468
                    // Mise à jour des stocks
18 ilm 1469
 
73 ilm 1470
                    updateStock(idSaisieVF);
18 ilm 1471
 
73 ilm 1472
                    // On retire l'avoir
1473
                    if (rowFactureOld != null && rowFactureOld.getInt("ID_AVOIR_CLIENT") > 1) {
18 ilm 1474
 
73 ilm 1475
                        SQLRow rowAvoir = rowFactureOld.getForeignRow("ID_AVOIR_CLIENT");
18 ilm 1476
 
73 ilm 1477
                        Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
1478
                        Long avoirTTC = (Long) rowFactureOld.getObject("T_AVOIR_TTC");
18 ilm 1479
 
73 ilm 1480
                        long montant = montantSolde - avoirTTC;
1481
                        if (montant < 0) {
1482
                            montant = 0;
1483
                        }
18 ilm 1484
 
73 ilm 1485
                        SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
1486
 
1487
                        // Soldé
1488
                        rowVals.put("SOLDE", Boolean.FALSE);
1489
                        rowVals.put("MONTANT_SOLDE", montant);
1490
                        Long restant = (Long) rowAvoir.getObject("MONTANT_TTC") - montantSolde;
1491
                        rowVals.put("MONTANT_RESTANT", restant);
1492
 
18 ilm 1493
                        rowVals.update();
73 ilm 1494
 
18 ilm 1495
                    }
1496
 
73 ilm 1497
                    final int idAvoir = rowFacture.getInt("ID_AVOIR_CLIENT");
1498
                    // on solde l'avoir
1499
                    if (idAvoir > 1) {
18 ilm 1500
 
73 ilm 1501
                        SQLRow rowAvoir = rowFacture.getForeignRow("ID_AVOIR_CLIENT");
18 ilm 1502
 
73 ilm 1503
                        Long montantTTC = (Long) rowAvoir.getObject("MONTANT_TTC");
1504
                        Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
1505
                        Long factTTC = (Long) rowFacture.getObject("T_TTC");
18 ilm 1506
 
73 ilm 1507
                        long restant = montantTTC - montantSolde;
18 ilm 1508
 
73 ilm 1509
                        SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
1510
                        final long l2 = factTTC - restant;
1511
                        // Soldé
1512
                        if (l2 >= 0) {
1513
                            rowVals.put("SOLDE", Boolean.TRUE);
1514
                            rowVals.put("MONTANT_SOLDE", montantTTC);
1515
                            rowVals.put("MONTANT_RESTANT", 0);
1516
                        } else {
1517
                            // Il reste encore de l'argent pour l'avoir
1518
                            final long m = montantSolde + factTTC;
1519
                            rowVals.put("MONTANT_SOLDE", m);
1520
                            rowVals.put("MONTANT_RESTANT", montantTTC - m);
1521
                        }
1522
 
18 ilm 1523
                        rowVals.update();
73 ilm 1524
 
18 ilm 1525
                    }
1526
 
1527
 
90 ilm 1528
                    if (getTable().getDBRoot().contains("ABONNEMENT") && panelOO.isCheckAboSelected()) {
1529
                        DoWithRow doWithRow = ((SaisieVenteFactureSQLElement) getElement()).getSpecialAction("subscription.autocreate");
1530
                        if (doWithRow != null) {
1531
                            doWithRow.process(rowFacture);
1532
                        }
1533
                    }
94 ilm 1534
                    createDocument(rowFacture);
90 ilm 1535
 
73 ilm 1536
                }
142 ilm 1537
                if (attempt > 0) {
1538
                    SwingUtilities.invokeLater(new Runnable() {
1539
                        public void run() {
1540
                            JOptionPane.showMessageDialog(null, "Le numéro a été actualisé en " + num);
1541
                        }
1542
                    });
1543
                }
73 ilm 1544
            } catch (Exception e) {
1545
                ExceptionHandler.handle("", e);
18 ilm 1546
            }
1547
        }
1548
        return idSaisieVF;
1549
    }
1550
 
63 ilm 1551
    public void createDocument(SQLRow row) {
1552
        // generation du document
1553
        final VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(row);
1554
 
1555
        try {
1556
            sheet.createDocumentAsynchronous();
1557
            sheet.showPrintAndExportAsynchronous(panelOO.isVisualisationSelected(), panelOO.isImpressionSelected(), true);
1558
        } catch (Exception e) {
1559
            ExceptionHandler.handle("Impossible de générer la facture", e);
1560
        }
1561
    }
1562
 
18 ilm 1563
    @Override
1564
    public void update() {
1565
        commit(null);
1566
    }
1567
 
1568
    /**
1569
     * Création d'une facture à partir d'un devis
1570
     *
1571
     * @param idDevis
1572
     *
1573
     */
1574
    public void loadDevis(int idDevis) {
1575
 
1576
        SQLElement devis = Configuration.getInstance().getDirectory().getElement("DEVIS");
1577
        SQLElement devisElt = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT");
1578
 
1579
        if (idDevis > 1) {
1580
            SQLInjector injector = SQLInjector.getInjector(devis.getTable(), this.getTable());
19 ilm 1581
            SQLRow rowDevis = devis.getTable().getRow(idDevis);
1582
            SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(idDevis);
1583
            String string = rowDevis.getString("OBJET");
1584
            createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ",") + rowDevis.getString("NUMERO"));
1585
            this.select(createRowValuesFrom);
18 ilm 1586
        }
1587
 
1588
            loadItem(this.tableFacture, devis, idDevis, devisElt);
1589
    }
1590
 
1591
    /**
1592
     * Création d'une facture à partir d'une facture existante
1593
     *
1594
     * @param idFacture
1595
     *
1596
     */
1597
    public void loadFactureExistante(int idFacture) {
1598
 
1599
        SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
1600
        SQLElement factElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1601
 
1602
        // On duplique la facture
1603
        if (idFacture > 1) {
1604
            SQLRow row = fact.getTable().getRow(idFacture);
1605
            SQLRowValues rowVals = new SQLRowValues(fact.getTable());
1606
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
93 ilm 1607
            if (getTable().contains("ID_NUMEROTATION_AUTO")) {
180 ilm 1608
                rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date(), row.getForeign("ID_NUMEROTATION_AUTO")));
93 ilm 1609
            } else {
180 ilm 1610
                rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()));
93 ilm 1611
            }
65 ilm 1612
            rowVals.put("NOM", row.getObject("NOM"));
18 ilm 1613
            this.select(rowVals);
1614
        }
1615
 
1616
        // On duplique les elements de facture
1617
        List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
1618
 
1619
        if (myListItem.size() != 0) {
1620
            this.tableFacture.getModel().clearRows();
1621
 
1622
            for (SQLRow rowElt : myListItem) {
1623
 
1624
                SQLRowValues rowVals = rowElt.createUpdateRow();
1625
                rowVals.clearPrimaryKeys();
1626
                this.tableFacture.getModel().addRow(rowVals);
1627
                int rowIndex = this.tableFacture.getModel().getRowCount() - 1;
1628
                this.tableFacture.getModel().fireTableModelModified(rowIndex);
1629
            }
1630
        } else {
1631
            this.tableFacture.getModel().clearRows();
1632
        }
1633
        this.tableFacture.getModel().fireTableDataChanged();
1634
        this.tableFacture.repaint();
1635
    }
1636
 
19 ilm 1637
    public List<SQLRowValues> createFactureAcompte(int idFacture, long acompte) {
1638
 
1639
        SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
1640
        SQLElement factElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1641
 
1642
        // On duplique la facture
1643
        if (idFacture > 1) {
1644
            SQLRow row = fact.getTable().getRow(idFacture);
1645
            SQLRowValues rowVals = new SQLRowValues(fact.getTable());
1646
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
1647
            rowVals.put("ID_AFFAIRE", row.getInt("ID_AFFAIRE"));
180 ilm 1648
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()));
19 ilm 1649
            rowVals.put("NOM", "Acompte de " + GestionDevise.currencyToString(acompte) + "€");
1650
            this.select(rowVals);
1651
        }
1652
 
1653
        // On duplique les elements de facture
1654
        List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
1655
        List<SQLRowValues> result = new ArrayList<SQLRowValues>(myListItem.size());
1656
        if (myListItem.size() != 0) {
1657
            this.tableFacture.getModel().clearRows();
1658
 
1659
            double acc = ((double) acompte / (double) myListItem.size());
1660
            long toAdd = 0;
1661
            SQLTable tablePourcentCCIP = Configuration.getInstance().getRoot().findTable("POURCENT_CCIP");
1662
            for (SQLRow rowElt : myListItem) {
1663
 
1664
                SQLRowValues rowValsUp = rowElt.createUpdateRow();
1665
                SQLRowValues rowVals = rowElt.createUpdateRow();
1666
                rowVals.clearPrimaryKeys();
1667
 
1668
                long val = rowVals.getLong("T_PV_HT");
1669
                double value = (acc + toAdd) / val * 100.0;
1670
                // Si l'acompte est supérieur au montant
1671
                if (value > 100) {
1672
                    value = 100;
1673
                    toAdd += (acc - val);
1674
                } else {
1675
                    toAdd = 0;
1676
                }
1677
                BigDecimal pourcentAcompte = new BigDecimal(rowValsUp.getLong("POURCENT_ACOMPTE") - value);
1678
                rowValsUp.put("POURCENT_ACOMPTE", pourcentAcompte);
1679
                BigDecimal pourcentCurrentAcompte = new BigDecimal(value);
1680
                rowVals.put("POURCENT_ACOMPTE", pourcentCurrentAcompte);
1681
                List<SQLRow> rowsCCIP = rowElt.getReferentRows(tablePourcentCCIP);
1682
                if (rowsCCIP.size() > 0) {
1683
                    SQLRowValues rowValsCCIP = rowsCCIP.get(0).createUpdateRow();
1684
                    rowValsCCIP.clearPrimaryKeys();
1685
                    rowValsCCIP.put("ID_SAISIE_VENTE_FACTURE_ELEMENT", rowVals);
1686
                    rowValsCCIP.put("NOM", "Acompte");
1687
                    rowValsCCIP.put("POURCENT", pourcentCurrentAcompte);
1688
                }
1689
                System.err.println(value);
1690
                this.tableFacture.getModel().addRow(rowVals);
1691
                int rowIndex = this.tableFacture.getModel().getRowCount() - 1;
1692
                this.tableFacture.getModel().fireTableModelModified(rowIndex);
1693
            }
1694
            if (toAdd > 0) {
1695
                for (int i = 0; i < this.tableFacture.getModel().getRowCount() && toAdd > 0; i++) {
1696
                    SQLRowValues rowVals = this.tableFacture.getModel().getRowValuesAt(i);
1697
                    if (rowVals.getFloat("POURCENT_ACOMPTE") < 100) {
1698
                        long val = rowVals.getLong("T_PV_HT");
1699
                        double value = (acc + toAdd) / val * 100.0;
1700
                        // Si l'acompte est supérieur au montant
1701
                        if (value > 100) {
1702
                            value = 100;
1703
                            toAdd += (acc - val);
1704
                        } else {
1705
                            toAdd = 0;
1706
                        }
1707
                        rowVals.put("POURCENT_ACOMPTE", new BigDecimal(value));
1708
                        this.tableFacture.getModel().fireTableModelModified(i);
1709
                    }
1710
                }
1711
            }
1712
 
1713
            // FIXME Check total if pb with round
1714
        } else {
1715
            this.tableFacture.getModel().clearRows();
1716
        }
1717
        this.tableFacture.getModel().fireTableDataChanged();
1718
        this.tableFacture.repaint();
1719
        return result;
1720
    }
1721
 
18 ilm 1722
    /**
1723
     * Création d'une facture à partir d'une commande
1724
     *
1725
     * @param idCmd
1726
     *
1727
     */
1728
    public void loadCommande(int idCmd) {
1729
 
1730
        SQLElement cmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
1731
        SQLElement cmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
1732
 
1733
        if (idCmd > 1) {
1734
            SQLInjector injector = SQLInjector.getInjector(cmd.getTable(), this.getTable());
19 ilm 1735
            SQLRow rowCmd = cmd.getTable().getRow(idCmd);
1736
            SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(idCmd);
1737
            String string = rowCmd.getString("NOM");
1738
            createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ",") + rowCmd.getString("NUMERO"));
1739
            this.select(createRowValuesFrom);
18 ilm 1740
            this.listenerModeReglDefaut.propertyChange(null);
1741
        }
1742
        loadItem(this.tableFacture, cmd, idCmd, cmdElt);
1743
    }
1744
 
1745
    /**
1746
     * Création d'une facture à partir d'un bon de livraison
1747
     *
1748
     * @param idBl
1749
     *
1750
     */
67 ilm 1751
    public void loadBonItems(SQLRowAccessor rowBL, boolean clear) {
18 ilm 1752
 
1753
        SQLElement bon = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
1754
        SQLElement bonElt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON_ELEMENT");
67 ilm 1755
 
1756
        loadItem(this.tableFacture, bon, rowBL.getID(), bonElt, clear);
18 ilm 1757
    }
1758
 
1759
    public void addRowItem(SQLRowValues row) {
1760
        this.tableFacture.getModel().addRow(row);
1761
    }
1762
 
1763
    private static final SQLElement eltModeReglement = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
1764
 
1765
    @Override
1766
    protected SQLRowValues createDefaults() {
1767
        SQLRowValues vals = new SQLRowValues(this.getTable());
1768
        SQLRow r;
1769
 
1770
        try {
1771
            r = ModeReglementDefautPrefPanel.getDefaultRow(true);
1772
            if (r.getID() > 1) {
1773
                SQLRowValues rowVals = eltModeReglement.createCopy(r, null);
1774
                System.err.println(rowVals.getInt("ID_TYPE_REGLEMENT"));
1775
                vals.put("ID_MODE_REGLEMENT", rowVals);
1776
            }
1777
        } catch (SQLException e) {
1778
            System.err.println("Impossible de sélectionner le mode de règlement par défaut du client.");
1779
            e.printStackTrace();
1780
        }
1781
        this.tableFacture.getModel().clearRows();
1782
 
1783
        // User
1784
        // SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
1785
        SQLElement eltComm = Configuration.getInstance().getDirectory().getElement("COMMERCIAL");
1786
        int idUser = UserManager.getInstance().getCurrentUser().getId();
1787
 
1788
        // sel.addSelect(eltComm.getTable().getKey());
1789
        // sel.setWhere(new Where(eltComm.getTable().getField("ID_USER_COMMON"), "=", idUser));
1790
        // List<SQLRow> rowsComm = (List<SQLRow>)
1791
        // Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), new
1792
        // SQLRowListRSH(eltComm.getTable()));
1793
 
1794
        SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
1795
 
1796
        if (rowsComm != null) {
1797
            vals.put("ID_COMMERCIAL", rowsComm.getID());
1798
        }
1799
 
94 ilm 1800
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
1801
        Double d = prefs.getDouble(GestionCommercialeGlobalPreferencePanel.TAUX_TIMBRE_FISCAL, Double.valueOf(1));
1802
        vals.put("TAUX_TIMBRE_FISCAL", new BigDecimal(d));
1803
        vals.put("TOTAL_TIMBRE_FISCAL", 0L);
18 ilm 1804
        // User
1805
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
93 ilm 1806
        if (getTable().contains("ID_NUMEROTATION_AUTO")) {
1807
            vals.put("ID_NUMEROTATION_AUTO", this.defaultNum.getID());
180 ilm 1808
            vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date(), vals.getForeign("ID_NUMEROTATION_AUTO")));
93 ilm 1809
        } else {
180 ilm 1810
            vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()));
93 ilm 1811
        }
18 ilm 1812
        int idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
1813
        if (idCompteVenteProduit <= 1) {
1814
            try {
1815
                idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
1816
            } catch (Exception e) {
1817
                e.printStackTrace();
1818
            }
1819
        }
1820
 
1821
        vals.put("ID_COMPTE_PCE_VENTE", idCompteVenteProduit);
1822
        if (this.checkCT != null) {
1823
            vals.put("CONTROLE_TECHNIQUE", this.checkCT.isSelected());
1824
        }
93 ilm 1825
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
1826
            vals.put("CREATE_VIRTUAL_STOCK", Boolean.TRUE);
1827
        }
19 ilm 1828
        int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
1829
        if (idCompteVenteService <= 1) {
1830
            try {
1831
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
1832
            } catch (Exception e) {
1833
                e.printStackTrace();
1834
            }
1835
        }
65 ilm 1836
        if (getTable().contains("ID_TAXE_PORT")) {
80 ilm 1837
            SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
1838
            vals.put("ID_TAXE_PORT", taxeDefault.getID());
65 ilm 1839
        }
156 ilm 1840
        if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
1841
            SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
1842
            vals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
1843
        }
19 ilm 1844
        vals.put("ID_COMPTE_PCE_SERVICE", idCompteVenteService);
18 ilm 1845
        System.err.println("Defaults " + vals);
1846
        return vals;
1847
    }
1848
 
1849
    public void setDefaults() {
1850
        this.resetValue();
21 ilm 1851
 
180 ilm 1852
        this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new java.util.Date(), defaultNum));
18 ilm 1853
        this.tableFacture.getModel().clearRows();
1854
    }
1855
 
1856
    public RowValuesTableModel getRowValuesTableModel() {
1857
        return this.tableFacture.getModel();
1858
    }
1859
 
1860
    /**
1861
     * Définir la facture comme prévisionnelle. Pas de génération comptable, ni de mode de règlement
1862
     *
19 ilm 1863
     * @deprecated mettre les valeurs dans une RowValues
18 ilm 1864
     * @param b
1865
     */
19 ilm 1866
    @Deprecated
18 ilm 1867
    public void setPrevisonnelle(boolean b) {
1868
        this.checkPrevisionnelle.setSelected(b);
1869
        if (!b) {
180 ilm 1870
            this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), new Date()));
18 ilm 1871
        }
1872
    }
1873
 
1874
    /**
1875
     * Définir la facture comme complémentaire. Règlement supérieur au montant de la facture
1876
     * initiale
1877
     *
1878
     * @param b
1879
     */
1880
    public void setComplement(boolean b) {
1881
        this.checkComplement.setSelected(b);
1882
    }
1883
 
1884
    /**
1885
     * Définir la facture comme acompte.
1886
     *
1887
     * @param b
1888
     */
1889
    public void setAcompte(boolean b) {
1890
        this.checkAcompte.setSelected(b);
1891
        this.checkAcompte.firePropertyChange("ValueChanged", !b, b);
1892
    }
1893
 
1894
    public void setTypeInterventionText(String text) {
1895
        this.textTypeMission.setValue(text);
1896
    }
1897
 
1898
    public void setReferenceClientText(String text) {
1899
        this.refClient.setText(text);
1900
    }
1901
 
83 ilm 1902
    protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
61 ilm 1903
        return "Saisie vente facture N°" + row.getString("NUMERO");
1904
    }
1905
 
18 ilm 1906
    /**
1907
     * Mise à jour des stocks pour chaque article composant la facture
73 ilm 1908
     *
1909
     * @throws SQLException
18 ilm 1910
     */
73 ilm 1911
    private void updateStock(int id) throws SQLException {
18 ilm 1912
 
67 ilm 1913
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
61 ilm 1914
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
83 ilm 1915
            SQLRow row = getTable().getRow(id);
180 ilm 1916
 
1917
            // Check if tr from bl or cmd pour DS
1918
            if (getTable().getForeignTable("ID_CLIENT").contains("NOTE_2018")) {
1919
                List<SQLRow> trCmd = row.getReferentRows(getTable().getTable("TR_COMMANDE_CLIENT"));
1920
                if (!trCmd.isEmpty()) {
1921
                    return;
1922
                }
1923
            }
1924
 
83 ilm 1925
            StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
18 ilm 1926
 
61 ilm 1927
                @Override
83 ilm 1928
                public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
61 ilm 1929
                    return getLibelleStock(rowOrigin, rowElt);
18 ilm 1930
                }
93 ilm 1931
            }, row, row.getReferentRows(getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT")),
1932
                    getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_DELIVER : TypeStockUpdate.REAL_DELIVER);
18 ilm 1933
 
83 ilm 1934
            stockUpdater.update();
1935
 
18 ilm 1936
        }
1937
    }
73 ilm 1938
 
1939
    @Override
1940
    protected RowValuesTable getRowValuesTable() {
1941
        return this.tableFacture.getRowValuesTable();
1942
    }
1943
 
93 ilm 1944
    @Override
1945
    protected void refreshAfterSelect(SQLRowAccessor r) {
1946
        this.tableFacture.setDateDevise(this.dateSaisie.getValue());
1947
    }
1948
 
174 ilm 1949
    @Override
1950
    protected void initDone() {
1951
 
1952
        super.initDone();
1953
 
1954
        // FIXME listener pour le module project à déplacer dans le module quand l'interface passera
1955
        // en group
177 ilm 1956
        if (getTable().contains("ID_AFFAIRE") && getView("ID_AFFAIRE") != null && getView("ID_AFFAIRE") instanceof SQLRequestComboBox) {
1957
 
174 ilm 1958
            final SQLRequestComboBox viewClient = (SQLRequestComboBox) getView("ID_CLIENT").getComp();
1959
            final SQLRequestComboBox viewAffaire = (SQLRequestComboBox) getView("ID_AFFAIRE").getComp();
1960
            final SQLRequestComboBox viewComm = (SQLRequestComboBox) getView("ID_COMMERCIAL").getComp();
1961
            final SQLRequestComboBox viewAgence;
177 ilm 1962
            if (getTable().contains("ID_POLE_PRODUIT") && (SQLRequestComboBox) getView("ID_POLE_PRODUIT") != null) {
174 ilm 1963
                viewAgence = (SQLRequestComboBox) getView("ID_POLE_PRODUIT").getComp();
1964
            } else {
1965
                viewAgence = null;
1966
            }
1967
 
1968
            viewAffaire.addModelListener("wantedID", new PropertyChangeListener() {
1969
 
1970
                @Override
1971
                public void propertyChange(PropertyChangeEvent evt) {
1972
                    if (!isFilling()) {
1973
                        SQLRowAccessor selAffaire = viewAffaire.getSelectedRow();
1974
                        if (selAffaire != null && !selAffaire.isUndefined()) {
1975
                            viewClient.setValue(selAffaire.getForeignID("ID_CLIENT"));
1976
                            if (selAffaire.getTable().contains("ID_COMMERCIAL")) {
1977
                                viewComm.setValue(selAffaire.getForeignID("ID_COMMERCIAL"));
1978
                            }
1979
                        }
1980
                    }
1981
                }
1982
            });
1983
 
1984
            if (viewAgence != null) {
1985
 
1986
                viewComm.addModelListener("wantedID", new PropertyChangeListener() {
1987
 
1988
                    @Override
1989
                    public void propertyChange(PropertyChangeEvent evt) {
1990
                        if (!isFilling()) {
1991
                            SQLRowAccessor selComm = viewComm.getSelectedRow();
1992
                            if (selComm != null && !selComm.isUndefined() && selComm.getTable().contains("ID_POLE_PRODUIT")) {
1993
                                viewAgence.setValue(selComm.getForeignID("ID_POLE_PRODUIT"));
1994
                            }
1995
                        }
1996
                    }
1997
                });
1998
            }
1999
        }
2000
 
2001
    }
2002
 
18 ilm 2003
}