OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

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