OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

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