OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.sales.invoice.component;
15
 
16
import static org.openconcerto.utils.CollectionUtils.createSet;
142 ilm 17
 
18 ilm 18
import org.openconcerto.erp.config.ComptaPropsConfiguration;
19
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
83 ilm 20
import org.openconcerto.erp.core.common.element.BanqueSQLElement;
63 ilm 21
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
18 ilm 22
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
23
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
24
import org.openconcerto.erp.core.common.ui.DeviseField;
25
import org.openconcerto.erp.core.common.ui.TotalPanel;
93 ilm 26
import org.openconcerto.erp.core.customerrelationship.customer.ui.AdresseType;
174 ilm 27
import org.openconcerto.erp.core.customerrelationship.customer.ui.CategorieComptableChoiceUI;
18 ilm 28
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
29
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
30
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent;
65 ilm 31
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
18 ilm 32
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
90 ilm 33
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement.DoWithRow;
18 ilm 34
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
35
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
83 ilm 36
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater;
93 ilm 37
import org.openconcerto.erp.core.supplychain.stock.element.StockItemsUpdater.TypeStockUpdate;
61 ilm 38
import org.openconcerto.erp.core.supplychain.stock.element.StockLabel;
18 ilm 39
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
40
import org.openconcerto.erp.model.BanqueModifiedListener;
41
import org.openconcerto.erp.model.ISQLCompteSelector;
21 ilm 42
import org.openconcerto.erp.panel.PanelOOSQLComponent;
18 ilm 43
import org.openconcerto.erp.preferences.DefaultNXProps;
61 ilm 44
import org.openconcerto.erp.preferences.GestionArticleGlobalPreferencePanel;
93 ilm 45
import org.openconcerto.erp.preferences.GestionClientPreferencePanel;
94 ilm 46
import org.openconcerto.erp.preferences.GestionCommercialeGlobalPreferencePanel;
18 ilm 47
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
48
import org.openconcerto.sql.Configuration;
49
import org.openconcerto.sql.element.ElementSQLObject;
83 ilm 50
import org.openconcerto.sql.element.SQLComponent;
18 ilm 51
import org.openconcerto.sql.element.SQLElement;
52
import org.openconcerto.sql.model.SQLBackgroundTableCache;
53
import org.openconcerto.sql.model.SQLBase;
54
import org.openconcerto.sql.model.SQLInjector;
55
import org.openconcerto.sql.model.SQLRow;
56
import org.openconcerto.sql.model.SQLRowAccessor;
57
import org.openconcerto.sql.model.SQLRowValues;
58
import org.openconcerto.sql.model.SQLSelect;
59
import org.openconcerto.sql.model.SQLTable;
60
import org.openconcerto.sql.model.UndefinedRowValuesCache;
61
import org.openconcerto.sql.model.Where;
61 ilm 62
import org.openconcerto.sql.preferences.SQLPreferences;
18 ilm 63
import org.openconcerto.sql.sqlobject.ElementComboBox;
64
import org.openconcerto.sql.sqlobject.JUniqueTextField;
28 ilm 65
import org.openconcerto.sql.sqlobject.SQLRequestComboBox;
18 ilm 66
import org.openconcerto.sql.sqlobject.SQLTextCombo;
67
import org.openconcerto.sql.users.UserManager;
156 ilm 68
import org.openconcerto.sql.users.rights.UserRightsManager;
18 ilm 69
import org.openconcerto.sql.view.EditFrame;
142 ilm 70
import org.openconcerto.sql.view.EditPanel.EditMode;
73 ilm 71
import org.openconcerto.sql.view.list.RowValuesTable;
18 ilm 72
import org.openconcerto.sql.view.list.RowValuesTableModel;
73
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 74
import org.openconcerto.ui.FormLayouter;
18 ilm 75
import org.openconcerto.ui.JDate;
76
import org.openconcerto.ui.TitledSeparator;
77
import org.openconcerto.ui.component.ITextArea;
156 ilm 78
import org.openconcerto.ui.component.InteractionMode;
18 ilm 79
import org.openconcerto.utils.ExceptionHandler;
80
import org.openconcerto.utils.GestionDevise;
142 ilm 81
import org.openconcerto.utils.cc.IFactory;
18 ilm 82
import org.openconcerto.utils.text.SimpleDocumentListener;
83
 
84
import java.awt.GridBagConstraints;
85
import java.awt.GridBagLayout;
86
import java.awt.event.ActionEvent;
87
import java.awt.event.ActionListener;
88
import java.beans.PropertyChangeEvent;
89
import java.beans.PropertyChangeListener;
19 ilm 90
import java.math.BigDecimal;
94 ilm 91
import java.math.RoundingMode;
18 ilm 92
import java.sql.SQLException;
19 ilm 93
import java.util.ArrayList;
28 ilm 94
import java.util.Date;
18 ilm 95
import java.util.List;
96
import java.util.Map;
97
 
98
import javax.swing.JCheckBox;
99
import javax.swing.JLabel;
100
import javax.swing.JOptionPane;
101
import javax.swing.JPanel;
102
import javax.swing.JScrollPane;
61 ilm 103
import javax.swing.JTabbedPane;
18 ilm 104
import javax.swing.JTextField;
105
import javax.swing.SwingConstants;
106
import javax.swing.SwingUtilities;
107
import javax.swing.event.DocumentEvent;
108
 
109
public class SaisieVenteFactureSQLComponent extends TransfertBaseSQLComponent {
110
    private AbstractArticleItemTable tableFacture;
111
    private JLabel labelAffaire = new JLabel("Affaire");
93 ilm 112
    private final JDate dateSaisie = new JDate(true);
149 ilm 113
    private DeviseField textPortHT, textAcompte, textAvoirTTC, textRemiseHT, fieldTTC, textNetAPayer;
94 ilm 114
    private DeviseField totalTimbre, netPayer;
115
    private JTextField tauxTimbre;
116
 
18 ilm 117
    private SQLElement factureElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
118
    private SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
119
    public static final SQLTable TABLE_ADRESSE = Configuration.getInstance().getDirectory().getElement("ADRESSE").getTable();
120
    private SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
121
    private final SQLElement client = Configuration.getInstance().getDirectory().getElement(this.tableClient);
122
    private JUniqueTextField textNumeroUnique;
93 ilm 123
    private ElementComboBox comboClient;
18 ilm 124
    private ISQLCompteSelector compteSel;
125
    private final SQLTable tableNum = this.factureElt.getTable().getBase().getTable("NUMEROTATION_AUTO");
21 ilm 126
    private JCheckBox checkCompteServiceAuto, checkPrevisionnelle, checkComplement, checkAcompte, checkCT;
90 ilm 127
 
128
    protected PanelOOSQLComponent panelOO;
18 ilm 129
    private ElementComboBox selAvoir, selAffaire;
130
    private ElementSQLObject eltModeRegl;
131
    private static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
132
    private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
133
    private static final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
83 ilm 134
    private ElementComboBox contact;
18 ilm 135
    private SQLRowAccessor rowSelected;
136
    private SQLElement eltContact = Configuration.getInstance().getDirectory().getElement("CONTACT");
137
    private JTextField refClient = new JTextField();
142 ilm 138
 
18 ilm 139
    protected TotalPanel totalTTC;
93 ilm 140
    private final boolean displayDpt;
141
    private final ElementComboBox comboDpt = new ElementComboBox();
94 ilm 142
    private final boolean gestionTimbre;
93 ilm 143
 
18 ilm 144
    // Type intervention
145
    private SQLTextCombo textTypeMission = new SQLTextCombo();
146
 
147
    private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
148
        public void propertyChange(PropertyChangeEvent arg0) {
83 ilm 149
            int idCli = SaisieVenteFactureSQLComponent.this.comboClient.getWantedID();
18 ilm 150
            if (idCli > 1) {
151
                SQLRow rowCli = SaisieVenteFactureSQLComponent.this.client.getTable().getRow(idCli);
156 ilm 152
                if (!isFilling() && !rowCli.isForeignEmpty("ID_COMMERCIAL")) {
94 ilm 153
                    comboCommercial.setValue(rowCli.getForeignID("ID_COMMERCIAL"));
154
                }
149 ilm 155
 
156 ilm 156
                if (rowCli.getFields().contains("ID_CATEGORIE_COMPTABLE") && rowCli.getObject("ID_CATEGORIE_COMPTABLE") != null && !rowCli.isForeignEmpty("ID_CATEGORIE_COMPTABLE")) {
157
                    totalTTC.setCategorieComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
158
                    tableFacture.setRowCatComptable(rowCli.getForeign("ID_CATEGORIE_COMPTABLE"));
159
                } else {
160
                    totalTTC.setCategorieComptable(null);
161
                    tableFacture.setRowCatComptable(null);
162
                }
163
 
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();
18 ilm 938
        this.selAvoir.getRequest().setWhere(new Where(this.tableAvoir.getField("SOLDE"), "=", Boolean.FALSE));
939
        this.selAvoir.fillCombo();
940
 
941
        // Selection du compte de service
942
        int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
943
        if (idCompteVenteService <= 1) {
944
            try {
945
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
946
            } catch (Exception e) {
947
                e.printStackTrace();
948
            }
949
        }
950
        this.compteSelService.setValue(idCompteVenteService);
951
 
952
        // Lock
953
 
954
        DefaultGridBagConstraints.lockMinimumSize(this.comboClient);
955
        DefaultGridBagConstraints.lockMinimumSize(this.comboCommercial);
956
 
957
        // Listeners
958
 
959
        this.comboClient.addValueListener(this.listenerModeReglDefaut);
960
        this.fieldTTC.getDocument().addDocumentListener(new SimpleDocumentListener() {
961
            @Override
962
            public void update(DocumentEvent e) {
94 ilm 963
                calculTimbre();
18 ilm 964
                refreshText();
965
            }
966
 
967
        });
968
 
94 ilm 969
        if (this.checkTaux != null) {
970
            this.checkTaux.addActionListener(new ActionListener() {
971
                @Override
972
                public void actionPerformed(ActionEvent e) {
973
                    calculTimbre();
974
                    refreshText();
975
                }
976
 
977
            });
978
        }
979
        this.tauxTimbre.getDocument().addDocumentListener(new SimpleDocumentListener() {
980
            @Override
981
            public void update(DocumentEvent e) {
982
                calculTimbre();
983
                refreshText();
984
            }
985
 
986
        });
987
 
988
        this.totalTimbre.getDocument().addDocumentListener(new SimpleDocumentListener() {
989
            @Override
990
            public void update(DocumentEvent e) {
991
                refreshText();
992
            }
993
 
994
        });
995
 
18 ilm 996
        this.selAvoir.addValueListener(new PropertyChangeListener() {
997
 
998
            public void propertyChange(PropertyChangeEvent evt) {
999
                refreshText();
1000
            }
1001
 
1002
        });
1003
 
1004
        this.checkAcompte.addPropertyChangeListener(new PropertyChangeListener() {
1005
 
1006
            public void propertyChange(PropertyChangeEvent evt) {
1007
 
1008
                pAcompte.setVisible(SaisieVenteFactureSQLComponent.this.checkAcompte.isSelected());
1009
            }
1010
        });
1011
 
1012
        this.changeClientListener = new PropertyChangeListener() {
1013
 
1014
            public void propertyChange(PropertyChangeEvent evt) {
1015
 
93 ilm 1016
                if (SaisieVenteFactureSQLComponent.this.comboClient.getSelectedRow() != null) {
83 ilm 1017
                    final SQLRow row = SaisieVenteFactureSQLComponent.this.comboClient.getSelectedRow();
142 ilm 1018
                    final int id = (row == null) ? SQLRow.NONEXISTANT_ID : row.getID();
1019
                        if (row != null) {
1020
                            if (row.getFields().contains("ID_COMPTE_PCE_SERVICE") && compteSelService != null && !row.isForeignEmpty("ID_COMPTE_PCE_SERVICE")) {
1021
                                compteSelService.setValue(row.getForeignID("ID_COMPTE_PCE_SERVICE"));
1022
                            }
1023
                            if (row.getFields().contains("ID_COMPTE_PCE_PRODUIT") && !row.isForeignEmpty("ID_COMPTE_PCE_PRODUIT")) {
1024
                                totalTTC.setDefaultCompteProduit(row.getForeign("ID_COMPTE_PCE_PRODUIT"));
1025
                            }
93 ilm 1026
                        }
83 ilm 1027
                    if (row != null) {
18 ilm 1028
                        if (SaisieVenteFactureSQLComponent.this.contact != null) {
1029
                            Where w = new Where(SaisieVenteFactureSQLComponent.this.eltContact.getTable().getField("ID_CLIENT"), "=", SQLRow.NONEXISTANT_ID);
1030
                                w = w.or(new Where(SaisieVenteFactureSQLComponent.this.eltContact.getTable().getField("ID_CLIENT"), "=", id));
83 ilm 1031
                            SaisieVenteFactureSQLComponent.this.contact.getRequest().setWhere(w);
18 ilm 1032
                        }
1033
 
93 ilm 1034
                    } else {
18 ilm 1035
 
1036
                    }
1037
                    SaisieVenteFactureSQLComponent.this.previousClient = id;
1038
                }
73 ilm 1039
 
18 ilm 1040
            }
1041
        };
1042
 
1043
        this.changeCompteListener = new PropertyChangeListener() {
1044
            public void propertyChange(PropertyChangeEvent evt) {
1045
                SQLSelect sel = new SQLSelect(getTable().getBase());
1046
                sel.addSelect(SaisieVenteFactureSQLComponent.this.client.getTable().getKey());
1047
                Where where = new Where(SaisieVenteFactureSQLComponent.this.client.getTable().getField("ID_COMPTE_PCE"), "=", SaisieVenteFactureSQLComponent.this.compteSel.getValue());
1048
                sel.setWhere(where);
1049
 
1050
                String req = sel.asString();
1051
                List l = getTable().getBase().getDataSource().execute(req);
1052
                if (l != null) {
1053
                    if (l.size() == 1) {
1054
                        Map<String, Object> m = (Map<String, Object>) l.get(0);
1055
                        Object o = m.get(SaisieVenteFactureSQLComponent.this.client.getTable().getKey().getName());
1056
                        System.err.println("Only one value match :: " + o);
1057
                        if (o != null) {
1058
                            SaisieVenteFactureSQLComponent.this.comboClient.setValue(Integer.valueOf(((Number) o).intValue()));
1059
                        }
1060
                    }
1061
                }
1062
            }
1063
        };
83 ilm 1064
 
18 ilm 1065
        this.textPortHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
1066
            @Override
1067
            public void update(DocumentEvent e) {
1068
                totalTTC.updateTotal();
1069
            }
1070
        });
1071
 
1072
        this.textRemiseHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
1073
            @Override
1074
            public void update(DocumentEvent e) {
1075
                totalTTC.updateTotal();
1076
            }
1077
        });
28 ilm 1078
        this.comboClient.addValueListener(new PropertyChangeListener() {
1079
            @Override
1080
            public void propertyChange(PropertyChangeEvent evt) {
1081
                if (SaisieVenteFactureSQLComponent.this.isFilling())
1082
                    return;
1083
                final SQLRow row = ((SQLRequestComboBox) evt.getSource()).getSelectedRow();
1084
                if (row != null) {
1085
                    if (SaisieVenteFactureSQLComponent.this.client.getTable().contains("ID_TARIF")) {
1086
                        SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
93 ilm 1087
                        if (foreignRow != null && !foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())) {
28 ilm 1088
                            boxTarif.setValue(foreignRow.getID());
1089
                        } else {
80 ilm 1090
                            boxTarif.setValue(foreignRow);
28 ilm 1091
                        }
73 ilm 1092
 
28 ilm 1093
                    }
1094
 
1095
                    int idCpt = row.getInt("ID_COMPTE_PCE");
1096
 
1097
                    if (idCpt <= 1) {
1098
                        // Select Compte client par defaut
1099
                        idCpt = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
1100
                        if (idCpt <= 1) {
1101
                            try {
1102
                                idCpt = ComptePCESQLElement.getIdComptePceDefault("Clients");
1103
                            } catch (Exception e) {
1104
                                e.printStackTrace();
1105
                            }
1106
                        }
1107
                    }
1108
                    if (SaisieVenteFactureSQLComponent.this.compteSel != null) {
1109
                        Integer i = SaisieVenteFactureSQLComponent.this.compteSel.getValue();
1110
                        if (i == null || i.intValue() != idCpt) {
1111
                            SaisieVenteFactureSQLComponent.this.compteSel.setValue(idCpt);
1112
                        }
1113
                    }
1114
                }
1115
 
1116
            }
1117
        });
83 ilm 1118
 
18 ilm 1119
    }
1120
 
94 ilm 1121
    private void calculTimbre() {
1122
        totalTimbre.setValue(0L);
1123
        if (gestionTimbre && this.checkTaux != null && this.checkTaux.isSelected()) {
1124
            if (tauxTimbre.getText().trim().length() != 0) {
1125
                BigDecimal taux = new BigDecimal(tauxTimbre.getText());
1126
                Long ttc = fieldTTC.getValue();
1127
                if (ttc != null) {
1128
                    long timbreValue = taux.multiply(new BigDecimal(ttc)).movePointLeft(2).setScale(0, RoundingMode.HALF_UP).longValue();
1129
                    totalTimbre.setValue(timbreValue);
1130
                }
1131
            }
1132
        }
1133
    }
1134
 
18 ilm 1135
    private JPanel createPanelAvoir() {
1136
        JPanel panelAvoir = new JPanel(new GridBagLayout());
1137
        panelAvoir.setOpaque(false);
1138
        GridBagConstraints cA = new DefaultGridBagConstraints();
1139
        JLabel labelAvoir = new JLabel(getLabelFor("ID_AVOIR_CLIENT"));
1140
        labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
1141
        cA.weightx = 1;
1142
        labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
1143
        panelAvoir.add(labelAvoir, cA);
1144
        cA.weightx = 0;
1145
        cA.gridx++;
1146
        this.selAvoir = new ElementComboBox();
1147
        this.selAvoir.setAddIconVisible(false);
1148
        panelAvoir.add(this.selAvoir, cA);
1149
        final JLabel labelTotalAvoir = new JLabel("Total à régler");
94 ilm 1150
        this.textNetAPayer = new DeviseField();
1151
        this.textNetAPayer.setEditable(false);
18 ilm 1152
        cA.gridx++;
1153
        cA.weightx = 0;
1154
        panelAvoir.add(labelTotalAvoir, cA);
1155
        cA.gridx++;
1156
        cA.weightx = 0;
94 ilm 1157
        panelAvoir.add(this.textNetAPayer, cA);
1158
        addView(textNetAPayer, "NET_A_PAYER");
1159
        this.textNetAPayer.setHorizontalAlignment(SwingConstants.RIGHT);
18 ilm 1160
 
1161
        return panelAvoir;
1162
    }
1163
 
94 ilm 1164
    private JCheckBox checkTaux;
1165
 
1166
    private JPanel createTimbrePanel() {
1167
        JPanel panelTimbre = new JPanel(new GridBagLayout());
1168
        panelTimbre.setOpaque(false);
1169
        GridBagConstraints cA = new DefaultGridBagConstraints();
1170
        this.checkTaux = new JCheckBox(getLabelFor("SOUMIS_TIMBRE_FISCAL") + " " + getLabelFor("TAUX_TIMBRE_FISCAL"));
1171
        checkTaux.setHorizontalAlignment(SwingConstants.RIGHT);
1172
        cA.weightx = 1;
1173
        checkTaux.setHorizontalAlignment(SwingConstants.RIGHT);
1174
        panelTimbre.add(checkTaux, cA);
1175
        cA.weightx = 0;
1176
        cA.gridx++;
1177
        this.tauxTimbre = new JTextField(8);
1178
        panelTimbre.add(this.tauxTimbre, cA);
1179
        final JLabel labelTotalTimbre = new JLabel(getLabelFor("TOTAL_TIMBRE_FISCAL"));
1180
        this.totalTimbre = new DeviseField();
1181
        this.totalTimbre.setEditable(false);
1182
        cA.gridx++;
1183
        cA.weightx = 0;
1184
        panelTimbre.add(labelTotalTimbre, cA);
1185
        cA.gridx++;
1186
        cA.weightx = 0;
1187
        panelTimbre.add(this.totalTimbre, cA);
1188
        this.totalTimbre.setHorizontalAlignment(SwingConstants.RIGHT);
1189
 
1190
        this.addView(checkTaux, "SOUMIS_TIMBRE_FISCAL");
1191
        this.addView(tauxTimbre, "TAUX_TIMBRE_FISCAL");
1192
        this.addView(totalTimbre, "TOTAL_TIMBRE_FISCAL");
1193
        return panelTimbre;
1194
    }
1195
 
18 ilm 1196
    private void setCompteServiceVisible(boolean b) {
1197
        this.compteSelService.setVisible(b);
1198
        this.labelCompteServ.setVisible(b);
1199
    }
1200
 
1201
    private void refreshText() {
73 ilm 1202
        Number n = this.fieldTTC.getValue();
94 ilm 1203
        long totalAvoirTTC = 0;
1204
        long netAPayer = 0;
1205
        long ttc = 0;
1206
        if (n != null) {
1207
            netAPayer = n.longValue();
1208
            ttc = n.longValue();
1209
        }
1210
 
18 ilm 1211
        if (this.selAvoir.getSelectedId() > 1) {
1212
            SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
1213
            if (n != null) {
1214
                SQLRow rowAvoir = tableAvoir.getRow(this.selAvoir.getSelectedId());
1215
                long totalAvoir = ((Number) rowAvoir.getObject("MONTANT_TTC")).longValue();
1216
                totalAvoir -= ((Number) rowAvoir.getObject("MONTANT_SOLDE")).longValue();
1217
                if (getSelectedID() > 1) {
1218
                    SQLRow row = getTable().getRow(getSelectedID());
1219
                    int idAvoirOld = row.getInt("ID_AVOIR_CLIENT");
1220
                    if (idAvoirOld == rowAvoir.getID()) {
1221
                        totalAvoir += Long.valueOf(row.getObject("T_AVOIR_TTC").toString());
1222
                    }
1223
                }
1224
 
1225
                long l = ttc - totalAvoir;
1226
                if (l < 0) {
1227
                    l = 0;
94 ilm 1228
                    totalAvoirTTC = ttc;
18 ilm 1229
                } else {
94 ilm 1230
                    totalAvoirTTC = totalAvoir;
18 ilm 1231
                }
94 ilm 1232
                netAPayer = l;
18 ilm 1233
            }
94 ilm 1234
        }
1235
        if (this.gestionTimbre) {
1236
            Long timbre = this.totalTimbre.getValue();
1237
            if (timbre != null) {
1238
                netAPayer += timbre;
18 ilm 1239
            }
1240
        }
149 ilm 1241
        Long acompte = this.textAcompte.getValue();
1242
        if (acompte != null) {
1243
            netAPayer -= acompte;
1244
        }
94 ilm 1245
        this.textNetAPayer.setValue(netAPayer);
1246
        this.textAvoirTTC.setValue(totalAvoirTTC);
18 ilm 1247
    }
1248
 
1249
    public int insert(SQLRow order) {
1250
        return commit(order);
1251
    }
1252
 
80 ilm 1253
    private void createCompteServiceAuto(int id) throws SQLException {
156 ilm 1254
        SQLRow rowPole = this.comboPoleProduit.getSelectedRow();
18 ilm 1255
        SQLRow rowVerif = this.comboVerificateur.getSelectedRow();
1256
        String verifInitiale = getInitialesFromVerif(rowVerif);
1257
        int idCpt = ComptePCESQLElement.getId("706" + rowPole.getString("CODE") + verifInitiale, "Service " + rowPole.getString("NOM") + " " + rowVerif.getString("NOM"));
1258
        SQLRowValues rowVals = this.getTable().getRow(id).createEmptyUpdateRow();
1259
        rowVals.put("ID_COMPTE_PCE_SERVICE", idCpt);
80 ilm 1260
        rowVals.update();
18 ilm 1261
    }
1262
 
1263
    @Override
1264
    public void select(SQLRowAccessor r) {
80 ilm 1265
 
90 ilm 1266
        this.panelOO.getCheckAbo().setSelected(false);
1267
 
80 ilm 1268
        boolean isPartial = false;
1269
        if (r != null && r.getBoolean("PARTIAL") != null) {
1270
            isPartial = r.getBoolean("PARTIAL").booleanValue();
1271
        }
1272
 
1273
        boolean isSolde = false;
1274
        if (r != null && r.getBoolean("SOLDE") != null) {
1275
            isSolde = r.getBoolean("SOLDE").booleanValue();
1276
        }
1277
 
144 ilm 1278
        if (getMode() == Mode.MODIFICATION && r != null && !r.isUndefined() && (isPartial || isSolde)) {
80 ilm 1279
            throw new IllegalArgumentException("Impossible de modifier une facturation intermédiaire");
1280
        }
1281
 
18 ilm 1282
        if (compteSel != null) {
1283
            this.compteSel.rmValueListener(this.changeCompteListener);
1284
        }
90 ilm 1285
 
18 ilm 1286
        this.rowSelected = r;
1287
        if (r != null) {
83 ilm 1288
            // FIXME Mettre un droit pour autoriser la modification d'une facture lettrée ou pointée
80 ilm 1289
            if (!r.isUndefined() && r.getObject("ID_MOUVEMENT") != null && !r.isForeignEmpty("ID_MOUVEMENT")) {
1290
                SQLTable tableEcr = getTable().getTable("ECRITURE");
1291
                SQLTable tableMvt = getTable().getTable("MOUVEMENT");
1292
                SQLTable tablePiece = getTable().getTable("PIECE");
83 ilm 1293
                {
1294
                    SQLSelect sel = new SQLSelect();
1295
                    sel.addSelect(tableEcr.getKey(), "COUNT");
1296
                    int idPiece = r.getForeign("ID_MOUVEMENT").getInt("ID_PIECE");
1297
                    Where w = new Where(tableMvt.getKey(), "=", tableEcr.getField("ID_MOUVEMENT"));
1298
                    w = w.and(new Where(tablePiece.getKey(), "=", tableMvt.getField("ID_PIECE")));
1299
                    w = w.and(new Where(tablePiece.getKey(), "=", idPiece));
1300
                    w = w.and(new Where(tableEcr.getField("POINTEE"), "!=", "").or(new Where(tableEcr.getField("LETTRAGE"), "!=", "")));
1301
                    sel.setWhere(w);
1302
                    Object o = Configuration.getInstance().getRoot().getBase().getDataSource().executeScalar(sel.asString());
1303
                    if (o != null && ((Number) o).longValue() > 0) {
1304
                        SwingUtilities.invokeLater(new Runnable() {
18 ilm 1305
 
83 ilm 1306
                            @Override
1307
                            public void run() {
1308
                                JOptionPane.showMessageDialog(null, "Attention cette facture est pointée ou lettrée en comptabilité. \nToute modification écrasera ces informations comptables.");
1309
                            }
1310
                        });
1311
                    }
80 ilm 1312
                }
83 ilm 1313
                {
1314
                    SQLSelect sel = new SQLSelect();
1315
                    SQLTable tableAssoc = getTable().getTable("ASSOCIATION_ANALYTIQUE");
1316
                    sel.addSelect(tableAssoc.getKey(), "COUNT");
1317
                    int idPiece = r.getForeign("ID_MOUVEMENT").getInt("ID_PIECE");
1318
                    Where w = new Where(tableMvt.getKey(), "=", tableEcr.getField("ID_MOUVEMENT"));
1319
                    w = w.and(new Where(tableAssoc.getField("ID_ECRITURE"), "=", tableEcr.getKey()));
1320
                    w = w.and(new Where(tablePiece.getKey(), "=", tableMvt.getField("ID_PIECE")));
1321
                    w = w.and(new Where(tablePiece.getKey(), "=", idPiece));
1322
                    w = w.and(new Where(tableAssoc.getField("GESTION_AUTO"), "=", Boolean.FALSE));
1323
                    sel.setWhere(w);
1324
                    System.err.println(sel.asString());
1325
                    Object o = Configuration.getInstance().getRoot().getBase().getDataSource().executeScalar(sel.asString());
1326
                    if (o != null && ((Number) o).longValue() > 0) {
1327
                        SwingUtilities.invokeLater(new Runnable() {
80 ilm 1328
 
83 ilm 1329
                            @Override
1330
                            public void run() {
1331
                                JOptionPane.showMessageDialog(null,
1332
                                        "Attention la répartition analytique a été modifié manuellement sur cette facture. \nToute modification écrasera ces informations comptables.");
1333
                            }
1334
                        });
1335
                    }
1336
                }
80 ilm 1337
            }
18 ilm 1338
        }
1339
            super.select(r);
1340
 
142 ilm 1341
        if (r != null)
1342
 
1343
        {
73 ilm 1344
            // this.tableFacture.getModel().clearRows();
1345
            // this.tableFacture.insertFrom("ID_SAISIE_VENTE_FACTURE", r.getID());
18 ilm 1346
            Boolean b = (Boolean) r.getObject("ACOMPTE");
1347
            if (b != null) {
1348
                setAcompte(b);
1349
            } else {
1350
                setAcompte(false);
1351
            }
1352
        }
90 ilm 1353
 
61 ilm 1354
        if (this.comboClient != null) {
93 ilm 1355
 
61 ilm 1356
            this.comboClient.addValueListener(this.changeClientListener);
1357
        }
18 ilm 1358
        if (this.compteSel != null) {
1359
            this.compteSel.addValueListener(this.changeCompteListener);
1360
        } // nomClient.addValueListener(changeClientListener);
1361
    }
1362
 
1363
    private String getInitialesFromVerif(SQLRow row) {
1364
        String s = "";
1365
 
1366
        if (row != null) {
1367
            String prenom = row.getString("PRENOM");
1368
            if (prenom != null && prenom.length() > 0) {
1369
                s += prenom.toUpperCase().charAt(0);
1370
            }
1371
            String nom = row.getString("NOM");
1372
            if (nom != null && nom.length() > 0) {
1373
                s += nom.toUpperCase().charAt(0);
1374
            }
1375
        }
1376
 
1377
        return s;
1378
    }
1379
 
1380
    public int commit(SQLRow order) {
1381
 
1382
        int idSaisieVF = -1;
1383
        long lFactureOld = 0;
1384
        SQLRow rowFactureOld = null;
1385
        SQLRow rowFacture = null;
142 ilm 1386
        int attempt = 0;
144 ilm 1387
        // on vérifie qu'une facture de même numero n'a pas été insérée entre temps
1388
        boolean validated = this.textNumeroUnique.checkValidation(false);
1389
        while (!validated && attempt < JUniqueTextField.RETRY_COUNT) {
1390
            try {
1391
                Thread.sleep(JUniqueTextField.SLEEP_WAIT_MS);
1392
            } catch (InterruptedException e) {
1393
                e.printStackTrace();
142 ilm 1394
            }
149 ilm 1395
            String num = NumerotationAutoSQLElement.getNextNumero(getElement().getClass(), dateSaisie.getDate(), defaultNum);
144 ilm 1396
            this.textNumeroUnique.setText(num);
1397
            validated = this.textNumeroUnique.checkValidation(false);
1398
            System.err.println("ATTEMPT " + attempt + " WITH NUMERO " + num + " validated : " + validated);
1399
            attempt++;
142 ilm 1400
        }
1401
        final String num = this.textNumeroUnique.getText();
144 ilm 1402
        if (!validated) {
142 ilm 1403
            idSaisieVF = getSelectedID();
1404
            ExceptionHandler.handle("Impossible d'ajouter, numéro de facture existant.");
1405
            final Object root = SwingUtilities.getRoot(this);
1406
            if (root instanceof EditFrame) {
1407
                final EditFrame frame = (EditFrame) root;
1408
                frame.getPanel().setAlwaysVisible(true);
1409
            }
1410
        } else {
73 ilm 1411
            try {
1412
                if (getMode() == Mode.INSERTION) {
1413
                    idSaisieVF = super.insert(order);
1414
                    rowFacture = getTable().getRow(idSaisieVF);
1415
                    // incrémentation du numéro auto
93 ilm 1416
                    final SQLRow rowNum = comboNumAuto == null ? this.tableNum.getRow(2) : comboNumAuto.getSelectedRow();
132 ilm 1417
                    if (NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, rowFacture.getDate("DATE").getTime(), rowNum)
1418
                            .equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
93 ilm 1419
                        SQLRowValues rowVals = rowNum.createEmptyUpdateRow();
18 ilm 1420
 
73 ilm 1421
                        String labelNumberFor = NumerotationAutoSQLElement.getLabelNumberFor(SaisieVenteFactureSQLElement.class);
93 ilm 1422
                        int val = rowNum.getInt(labelNumberFor);
73 ilm 1423
                        val++;
1424
                        rowVals.put(labelNumberFor, Integer.valueOf(val));
93 ilm 1425
                        rowVals.update();
18 ilm 1426
                    }
73 ilm 1427
                } else {
1428
                    if (JOptionPane.showConfirmDialog(this, "Attention en modifiant cette facture, vous supprimerez les chéques et les échéances associés. Continuer?", "Modification de facture",
1429
                            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
1430
                        // On recupere l'ancien total HT
1431
                        rowFactureOld = this.getTable().getRow(getSelectedID());
1432
                        lFactureOld = ((Number) rowFactureOld.getObject("T_HT")).longValue();
18 ilm 1433
 
73 ilm 1434
                        super.update();
18 ilm 1435
 
73 ilm 1436
                        idSaisieVF = getSelectedID();
1437
                    } else {
1438
                        // Annulation par l'utilisateur
1439
                        return idSaisieVF;
1440
                    }
18 ilm 1441
                }
1442
 
73 ilm 1443
                rowFacture = getTable().getRow(idSaisieVF);
1444
                final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
18 ilm 1445
 
73 ilm 1446
                // Mise à jour des tables liées
1447
                this.tableFacture.updateField("ID_SAISIE_VENTE_FACTURE", idSaisieVF);
18 ilm 1448
 
90 ilm 1449
                this.tableFacture.createArticle(idSaisieVF, this.getElement());
18 ilm 1450
 
90 ilm 1451
 
73 ilm 1452
                int idMvt = -1;
83 ilm 1453
                if (!this.checkPrevisionnelle.isSelected()) {
1454
                    if (getMode() == Mode.MODIFICATION) {
1455
                        idMvt = rowFacture.getInt("ID_MOUVEMENT");
1456
                        // on supprime tout ce qui est lié à la facture
1457
                        System.err.println("Archivage des fils");
1458
                        EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
1459
                        eltEcr.archiveMouvementProfondeur(idMvt, false);
1460
                    }
18 ilm 1461
 
73 ilm 1462
                    System.err.println("Regeneration des ecritures");
1463
                    if (idMvt > 1) {
1464
                        new GenerationMvtSaisieVenteFacture(idSaisieVF, idMvt);
1465
                    } else {
1466
                        new GenerationMvtSaisieVenteFacture(idSaisieVF);
1467
                    }
1468
                    System.err.println("Fin regeneration");
61 ilm 1469
 
73 ilm 1470
                    // Mise à jour des stocks
18 ilm 1471
 
73 ilm 1472
                    updateStock(idSaisieVF);
18 ilm 1473
 
73 ilm 1474
                    // On retire l'avoir
1475
                    if (rowFactureOld != null && rowFactureOld.getInt("ID_AVOIR_CLIENT") > 1) {
18 ilm 1476
 
73 ilm 1477
                        SQLRow rowAvoir = rowFactureOld.getForeignRow("ID_AVOIR_CLIENT");
18 ilm 1478
 
73 ilm 1479
                        Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
1480
                        Long avoirTTC = (Long) rowFactureOld.getObject("T_AVOIR_TTC");
18 ilm 1481
 
73 ilm 1482
                        long montant = montantSolde - avoirTTC;
1483
                        if (montant < 0) {
1484
                            montant = 0;
1485
                        }
18 ilm 1486
 
73 ilm 1487
                        SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
1488
 
1489
                        // Soldé
1490
                        rowVals.put("SOLDE", Boolean.FALSE);
1491
                        rowVals.put("MONTANT_SOLDE", montant);
1492
                        Long restant = (Long) rowAvoir.getObject("MONTANT_TTC") - montantSolde;
1493
                        rowVals.put("MONTANT_RESTANT", restant);
1494
 
18 ilm 1495
                        rowVals.update();
73 ilm 1496
 
18 ilm 1497
                    }
1498
 
73 ilm 1499
                    final int idAvoir = rowFacture.getInt("ID_AVOIR_CLIENT");
1500
                    // on solde l'avoir
1501
                    if (idAvoir > 1) {
18 ilm 1502
 
73 ilm 1503
                        SQLRow rowAvoir = rowFacture.getForeignRow("ID_AVOIR_CLIENT");
18 ilm 1504
 
73 ilm 1505
                        Long montantTTC = (Long) rowAvoir.getObject("MONTANT_TTC");
1506
                        Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
1507
                        Long factTTC = (Long) rowFacture.getObject("T_TTC");
18 ilm 1508
 
73 ilm 1509
                        long restant = montantTTC - montantSolde;
18 ilm 1510
 
73 ilm 1511
                        SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
1512
                        final long l2 = factTTC - restant;
1513
                        // Soldé
1514
                        if (l2 >= 0) {
1515
                            rowVals.put("SOLDE", Boolean.TRUE);
1516
                            rowVals.put("MONTANT_SOLDE", montantTTC);
1517
                            rowVals.put("MONTANT_RESTANT", 0);
1518
                        } else {
1519
                            // Il reste encore de l'argent pour l'avoir
1520
                            final long m = montantSolde + factTTC;
1521
                            rowVals.put("MONTANT_SOLDE", m);
1522
                            rowVals.put("MONTANT_RESTANT", montantTTC - m);
1523
                        }
1524
 
18 ilm 1525
                        rowVals.update();
73 ilm 1526
 
18 ilm 1527
                    }
1528
 
1529
 
90 ilm 1530
                    if (getTable().getDBRoot().contains("ABONNEMENT") && panelOO.isCheckAboSelected()) {
1531
                        DoWithRow doWithRow = ((SaisieVenteFactureSQLElement) getElement()).getSpecialAction("subscription.autocreate");
1532
                        if (doWithRow != null) {
1533
                            doWithRow.process(rowFacture);
1534
                        }
1535
                    }
94 ilm 1536
                    createDocument(rowFacture);
90 ilm 1537
 
73 ilm 1538
                }
142 ilm 1539
                if (attempt > 0) {
1540
                    SwingUtilities.invokeLater(new Runnable() {
1541
                        public void run() {
1542
                            JOptionPane.showMessageDialog(null, "Le numéro a été actualisé en " + num);
1543
                        }
1544
                    });
1545
                }
73 ilm 1546
            } catch (Exception e) {
1547
                ExceptionHandler.handle("", e);
18 ilm 1548
            }
1549
        }
1550
        return idSaisieVF;
1551
    }
1552
 
63 ilm 1553
    public void createDocument(SQLRow row) {
1554
        // generation du document
1555
        final VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(row);
1556
 
1557
        try {
1558
            sheet.createDocumentAsynchronous();
1559
            sheet.showPrintAndExportAsynchronous(panelOO.isVisualisationSelected(), panelOO.isImpressionSelected(), true);
1560
        } catch (Exception e) {
1561
            ExceptionHandler.handle("Impossible de générer la facture", e);
1562
        }
1563
    }
1564
 
18 ilm 1565
    @Override
1566
    public void update() {
1567
        commit(null);
1568
    }
1569
 
1570
    /**
1571
     * Création d'une facture à partir d'un devis
1572
     *
1573
     * @param idDevis
1574
     *
1575
     */
1576
    public void loadDevis(int idDevis) {
1577
 
1578
        SQLElement devis = Configuration.getInstance().getDirectory().getElement("DEVIS");
1579
        SQLElement devisElt = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT");
1580
 
1581
        if (idDevis > 1) {
1582
            SQLInjector injector = SQLInjector.getInjector(devis.getTable(), this.getTable());
19 ilm 1583
            SQLRow rowDevis = devis.getTable().getRow(idDevis);
1584
            SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(idDevis);
1585
            String string = rowDevis.getString("OBJET");
1586
            createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ",") + rowDevis.getString("NUMERO"));
1587
            this.select(createRowValuesFrom);
18 ilm 1588
        }
1589
 
1590
            loadItem(this.tableFacture, devis, idDevis, devisElt);
1591
    }
1592
 
1593
    /**
1594
     * Création d'une facture à partir d'une facture existante
1595
     *
1596
     * @param idFacture
1597
     *
1598
     */
1599
    public void loadFactureExistante(int idFacture) {
1600
 
1601
        SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
1602
        SQLElement factElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1603
 
1604
        // On duplique la facture
1605
        if (idFacture > 1) {
1606
            SQLRow row = fact.getTable().getRow(idFacture);
1607
            SQLRowValues rowVals = new SQLRowValues(fact.getTable());
1608
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
93 ilm 1609
            if (getTable().contains("ID_NUMEROTATION_AUTO")) {
1610
                rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date(), row.getForeign("ID_NUMEROTATION_AUTO")));
1611
            } else {
1612
                rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date()));
1613
            }
65 ilm 1614
            rowVals.put("NOM", row.getObject("NOM"));
18 ilm 1615
            this.select(rowVals);
1616
        }
1617
 
1618
        // On duplique les elements de facture
1619
        List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
1620
 
1621
        if (myListItem.size() != 0) {
1622
            this.tableFacture.getModel().clearRows();
1623
 
1624
            for (SQLRow rowElt : myListItem) {
1625
 
1626
                SQLRowValues rowVals = rowElt.createUpdateRow();
1627
                rowVals.clearPrimaryKeys();
1628
                this.tableFacture.getModel().addRow(rowVals);
1629
                int rowIndex = this.tableFacture.getModel().getRowCount() - 1;
1630
                this.tableFacture.getModel().fireTableModelModified(rowIndex);
1631
            }
1632
        } else {
1633
            this.tableFacture.getModel().clearRows();
1634
        }
1635
        this.tableFacture.getModel().fireTableDataChanged();
1636
        this.tableFacture.repaint();
1637
    }
1638
 
19 ilm 1639
    public List<SQLRowValues> createFactureAcompte(int idFacture, long acompte) {
1640
 
1641
        SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
1642
        SQLElement factElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1643
 
1644
        // On duplique la facture
1645
        if (idFacture > 1) {
1646
            SQLRow row = fact.getTable().getRow(idFacture);
1647
            SQLRowValues rowVals = new SQLRowValues(fact.getTable());
1648
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
1649
            rowVals.put("ID_AFFAIRE", row.getInt("ID_AFFAIRE"));
28 ilm 1650
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date()));
19 ilm 1651
            rowVals.put("NOM", "Acompte de " + GestionDevise.currencyToString(acompte) + "€");
1652
            this.select(rowVals);
1653
        }
1654
 
1655
        // On duplique les elements de facture
1656
        List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
1657
        List<SQLRowValues> result = new ArrayList<SQLRowValues>(myListItem.size());
1658
        if (myListItem.size() != 0) {
1659
            this.tableFacture.getModel().clearRows();
1660
 
1661
            double acc = ((double) acompte / (double) myListItem.size());
1662
            long toAdd = 0;
1663
            SQLTable tablePourcentCCIP = Configuration.getInstance().getRoot().findTable("POURCENT_CCIP");
1664
            for (SQLRow rowElt : myListItem) {
1665
 
1666
                SQLRowValues rowValsUp = rowElt.createUpdateRow();
1667
                SQLRowValues rowVals = rowElt.createUpdateRow();
1668
                rowVals.clearPrimaryKeys();
1669
 
1670
                long val = rowVals.getLong("T_PV_HT");
1671
                double value = (acc + toAdd) / val * 100.0;
1672
                // Si l'acompte est supérieur au montant
1673
                if (value > 100) {
1674
                    value = 100;
1675
                    toAdd += (acc - val);
1676
                } else {
1677
                    toAdd = 0;
1678
                }
1679
                BigDecimal pourcentAcompte = new BigDecimal(rowValsUp.getLong("POURCENT_ACOMPTE") - value);
1680
                rowValsUp.put("POURCENT_ACOMPTE", pourcentAcompte);
1681
                BigDecimal pourcentCurrentAcompte = new BigDecimal(value);
1682
                rowVals.put("POURCENT_ACOMPTE", pourcentCurrentAcompte);
1683
                List<SQLRow> rowsCCIP = rowElt.getReferentRows(tablePourcentCCIP);
1684
                if (rowsCCIP.size() > 0) {
1685
                    SQLRowValues rowValsCCIP = rowsCCIP.get(0).createUpdateRow();
1686
                    rowValsCCIP.clearPrimaryKeys();
1687
                    rowValsCCIP.put("ID_SAISIE_VENTE_FACTURE_ELEMENT", rowVals);
1688
                    rowValsCCIP.put("NOM", "Acompte");
1689
                    rowValsCCIP.put("POURCENT", pourcentCurrentAcompte);
1690
                }
1691
                System.err.println(value);
1692
                this.tableFacture.getModel().addRow(rowVals);
1693
                int rowIndex = this.tableFacture.getModel().getRowCount() - 1;
1694
                this.tableFacture.getModel().fireTableModelModified(rowIndex);
1695
            }
1696
            if (toAdd > 0) {
1697
                for (int i = 0; i < this.tableFacture.getModel().getRowCount() && toAdd > 0; i++) {
1698
                    SQLRowValues rowVals = this.tableFacture.getModel().getRowValuesAt(i);
1699
                    if (rowVals.getFloat("POURCENT_ACOMPTE") < 100) {
1700
                        long val = rowVals.getLong("T_PV_HT");
1701
                        double value = (acc + toAdd) / val * 100.0;
1702
                        // Si l'acompte est supérieur au montant
1703
                        if (value > 100) {
1704
                            value = 100;
1705
                            toAdd += (acc - val);
1706
                        } else {
1707
                            toAdd = 0;
1708
                        }
1709
                        rowVals.put("POURCENT_ACOMPTE", new BigDecimal(value));
1710
                        this.tableFacture.getModel().fireTableModelModified(i);
1711
                    }
1712
                }
1713
            }
1714
 
1715
            // FIXME Check total if pb with round
1716
        } else {
1717
            this.tableFacture.getModel().clearRows();
1718
        }
1719
        this.tableFacture.getModel().fireTableDataChanged();
1720
        this.tableFacture.repaint();
1721
        return result;
1722
    }
1723
 
18 ilm 1724
    /**
1725
     * Création d'une facture à partir d'une commande
1726
     *
1727
     * @param idCmd
1728
     *
1729
     */
1730
    public void loadCommande(int idCmd) {
1731
 
1732
        SQLElement cmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
1733
        SQLElement cmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
1734
 
1735
        if (idCmd > 1) {
1736
            SQLInjector injector = SQLInjector.getInjector(cmd.getTable(), this.getTable());
19 ilm 1737
            SQLRow rowCmd = cmd.getTable().getRow(idCmd);
1738
            SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(idCmd);
1739
            String string = rowCmd.getString("NOM");
1740
            createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ",") + rowCmd.getString("NUMERO"));
1741
            this.select(createRowValuesFrom);
18 ilm 1742
            this.listenerModeReglDefaut.propertyChange(null);
1743
        }
1744
        loadItem(this.tableFacture, cmd, idCmd, cmdElt);
1745
    }
1746
 
1747
    /**
1748
     * Création d'une facture à partir d'un bon de livraison
1749
     *
1750
     * @param idBl
1751
     *
1752
     */
67 ilm 1753
    public void loadBonItems(SQLRowAccessor rowBL, boolean clear) {
18 ilm 1754
 
1755
        SQLElement bon = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
1756
        SQLElement bonElt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON_ELEMENT");
67 ilm 1757
 
1758
        loadItem(this.tableFacture, bon, rowBL.getID(), bonElt, clear);
18 ilm 1759
    }
1760
 
1761
    public void addRowItem(SQLRowValues row) {
1762
        this.tableFacture.getModel().addRow(row);
1763
    }
1764
 
1765
    private static final SQLElement eltModeReglement = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
1766
 
1767
    @Override
1768
    protected SQLRowValues createDefaults() {
1769
        SQLRowValues vals = new SQLRowValues(this.getTable());
1770
        SQLRow r;
1771
 
1772
        try {
1773
            r = ModeReglementDefautPrefPanel.getDefaultRow(true);
1774
            if (r.getID() > 1) {
1775
                SQLRowValues rowVals = eltModeReglement.createCopy(r, null);
1776
                System.err.println(rowVals.getInt("ID_TYPE_REGLEMENT"));
1777
                vals.put("ID_MODE_REGLEMENT", rowVals);
1778
            }
1779
        } catch (SQLException e) {
1780
            System.err.println("Impossible de sélectionner le mode de règlement par défaut du client.");
1781
            e.printStackTrace();
1782
        }
1783
        this.tableFacture.getModel().clearRows();
1784
 
1785
        // User
1786
        // SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
1787
        SQLElement eltComm = Configuration.getInstance().getDirectory().getElement("COMMERCIAL");
1788
        int idUser = UserManager.getInstance().getCurrentUser().getId();
1789
 
1790
        // sel.addSelect(eltComm.getTable().getKey());
1791
        // sel.setWhere(new Where(eltComm.getTable().getField("ID_USER_COMMON"), "=", idUser));
1792
        // List<SQLRow> rowsComm = (List<SQLRow>)
1793
        // Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), new
1794
        // SQLRowListRSH(eltComm.getTable()));
1795
 
1796
        SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
1797
 
1798
        if (rowsComm != null) {
1799
            vals.put("ID_COMMERCIAL", rowsComm.getID());
1800
        }
1801
 
94 ilm 1802
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
1803
        Double d = prefs.getDouble(GestionCommercialeGlobalPreferencePanel.TAUX_TIMBRE_FISCAL, Double.valueOf(1));
1804
        vals.put("TAUX_TIMBRE_FISCAL", new BigDecimal(d));
1805
        vals.put("TOTAL_TIMBRE_FISCAL", 0L);
18 ilm 1806
        // User
1807
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
93 ilm 1808
        if (getTable().contains("ID_NUMEROTATION_AUTO")) {
1809
            vals.put("ID_NUMEROTATION_AUTO", this.defaultNum.getID());
1810
            vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date(), vals.getForeign("ID_NUMEROTATION_AUTO")));
1811
        } else {
1812
            vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date()));
1813
        }
18 ilm 1814
        int idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
1815
        if (idCompteVenteProduit <= 1) {
1816
            try {
1817
                idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
1818
            } catch (Exception e) {
1819
                e.printStackTrace();
1820
            }
1821
        }
1822
 
1823
        vals.put("ID_COMPTE_PCE_VENTE", idCompteVenteProduit);
1824
        if (this.checkCT != null) {
1825
            vals.put("CONTROLE_TECHNIQUE", this.checkCT.isSelected());
1826
        }
93 ilm 1827
        if (getTable().contains("CREATE_VIRTUAL_STOCK")) {
1828
            vals.put("CREATE_VIRTUAL_STOCK", Boolean.TRUE);
1829
        }
19 ilm 1830
        int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
1831
        if (idCompteVenteService <= 1) {
1832
            try {
1833
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
1834
            } catch (Exception e) {
1835
                e.printStackTrace();
1836
            }
1837
        }
65 ilm 1838
        if (getTable().contains("ID_TAXE_PORT")) {
80 ilm 1839
            SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
1840
            vals.put("ID_TAXE_PORT", taxeDefault.getID());
65 ilm 1841
        }
156 ilm 1842
        if (getTable().contains("ID_TAXE_FRAIS_DOCUMENT")) {
1843
            SQLRow taxeDefault = TaxeCache.getCache().getFirstTaxe();
1844
            vals.put("ID_TAXE_FRAIS_DOCUMENT", taxeDefault.getID());
1845
        }
19 ilm 1846
        vals.put("ID_COMPTE_PCE_SERVICE", idCompteVenteService);
18 ilm 1847
        System.err.println("Defaults " + vals);
1848
        return vals;
1849
    }
1850
 
1851
    public void setDefaults() {
1852
        this.resetValue();
21 ilm 1853
 
93 ilm 1854
        this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new java.util.Date(), defaultNum));
18 ilm 1855
        this.tableFacture.getModel().clearRows();
1856
    }
1857
 
1858
    public RowValuesTableModel getRowValuesTableModel() {
1859
        return this.tableFacture.getModel();
1860
    }
1861
 
1862
    /**
1863
     * Définir la facture comme prévisionnelle. Pas de génération comptable, ni de mode de règlement
1864
     *
19 ilm 1865
     * @deprecated mettre les valeurs dans une RowValues
18 ilm 1866
     * @param b
1867
     */
19 ilm 1868
    @Deprecated
18 ilm 1869
    public void setPrevisonnelle(boolean b) {
1870
        this.checkPrevisionnelle.setSelected(b);
1871
        if (!b) {
28 ilm 1872
            this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class, new Date()));
18 ilm 1873
        }
1874
    }
1875
 
1876
    /**
1877
     * Définir la facture comme complémentaire. Règlement supérieur au montant de la facture
1878
     * initiale
1879
     *
1880
     * @param b
1881
     */
1882
    public void setComplement(boolean b) {
1883
        this.checkComplement.setSelected(b);
1884
    }
1885
 
1886
    /**
1887
     * Définir la facture comme acompte.
1888
     *
1889
     * @param b
1890
     */
1891
    public void setAcompte(boolean b) {
1892
        this.checkAcompte.setSelected(b);
1893
        this.checkAcompte.firePropertyChange("ValueChanged", !b, b);
1894
    }
1895
 
1896
    public void setTypeInterventionText(String text) {
1897
        this.textTypeMission.setValue(text);
1898
    }
1899
 
1900
    public void setReferenceClientText(String text) {
1901
        this.refClient.setText(text);
1902
    }
1903
 
83 ilm 1904
    protected String getLibelleStock(SQLRowAccessor row, SQLRowAccessor rowElt) {
61 ilm 1905
        return "Saisie vente facture N°" + row.getString("NUMERO");
1906
    }
1907
 
18 ilm 1908
    /**
1909
     * Mise à jour des stocks pour chaque article composant la facture
73 ilm 1910
     *
1911
     * @throws SQLException
18 ilm 1912
     */
73 ilm 1913
    private void updateStock(int id) throws SQLException {
18 ilm 1914
 
67 ilm 1915
        SQLPreferences prefs = SQLPreferences.getMemCached(getTable().getDBRoot());
61 ilm 1916
        if (prefs.getBoolean(GestionArticleGlobalPreferencePanel.STOCK_FACT, true)) {
83 ilm 1917
            SQLRow row = getTable().getRow(id);
1918
            StockItemsUpdater stockUpdater = new StockItemsUpdater(new StockLabel() {
18 ilm 1919
 
61 ilm 1920
                @Override
83 ilm 1921
                public String getLabel(SQLRowAccessor rowOrigin, SQLRowAccessor rowElt) {
61 ilm 1922
                    return getLibelleStock(rowOrigin, rowElt);
18 ilm 1923
                }
93 ilm 1924
            }, row, row.getReferentRows(getTable().getTable("SAISIE_VENTE_FACTURE_ELEMENT")),
1925
                    getTable().contains("CREATE_VIRTUAL_STOCK") && row.getBoolean("CREATE_VIRTUAL_STOCK") ? TypeStockUpdate.REAL_VIRTUAL_DELIVER : TypeStockUpdate.REAL_DELIVER);
18 ilm 1926
 
83 ilm 1927
            stockUpdater.update();
1928
 
18 ilm 1929
        }
1930
    }
73 ilm 1931
 
1932
    @Override
1933
    protected RowValuesTable getRowValuesTable() {
1934
        return this.tableFacture.getRowValuesTable();
1935
    }
1936
 
93 ilm 1937
    @Override
1938
    protected void refreshAfterSelect(SQLRowAccessor r) {
1939
        this.tableFacture.setDateDevise(this.dateSaisie.getValue());
1940
    }
1941
 
174 ilm 1942
    @Override
1943
    protected void initDone() {
1944
 
1945
        super.initDone();
1946
 
1947
        // FIXME listener pour le module project à déplacer dans le module quand l'interface passera
1948
        // en group
1949
        if (getTable().contains("ID_AFFAIRE")) {
1950
            final SQLRequestComboBox viewClient = (SQLRequestComboBox) getView("ID_CLIENT").getComp();
1951
            final SQLRequestComboBox viewAffaire = (SQLRequestComboBox) getView("ID_AFFAIRE").getComp();
1952
            final SQLRequestComboBox viewComm = (SQLRequestComboBox) getView("ID_COMMERCIAL").getComp();
1953
            final SQLRequestComboBox viewAgence;
1954
            if (getTable().contains("ID_POLE_PRODUIT")) {
1955
                viewAgence = (SQLRequestComboBox) getView("ID_POLE_PRODUIT").getComp();
1956
            } else {
1957
                viewAgence = null;
1958
            }
1959
 
1960
            viewAffaire.addModelListener("wantedID", new PropertyChangeListener() {
1961
 
1962
                @Override
1963
                public void propertyChange(PropertyChangeEvent evt) {
1964
                    if (!isFilling()) {
1965
                        SQLRowAccessor selAffaire = viewAffaire.getSelectedRow();
1966
                        if (selAffaire != null && !selAffaire.isUndefined()) {
1967
                            viewClient.setValue(selAffaire.getForeignID("ID_CLIENT"));
1968
                            if (selAffaire.getTable().contains("ID_COMMERCIAL")) {
1969
                                viewComm.setValue(selAffaire.getForeignID("ID_COMMERCIAL"));
1970
                            }
1971
                        }
1972
                    }
1973
                }
1974
            });
1975
 
1976
            if (viewAgence != null) {
1977
 
1978
                viewComm.addModelListener("wantedID", new PropertyChangeListener() {
1979
 
1980
                    @Override
1981
                    public void propertyChange(PropertyChangeEvent evt) {
1982
                        if (!isFilling()) {
1983
                            SQLRowAccessor selComm = viewComm.getSelectedRow();
1984
                            if (selComm != null && !selComm.isUndefined() && selComm.getTable().contains("ID_POLE_PRODUIT")) {
1985
                                viewAgence.setValue(selComm.getForeignID("ID_POLE_PRODUIT"));
1986
                            }
1987
                        }
1988
                    }
1989
                });
1990
            }
1991
        }
1992
 
1993
    }
1994
 
18 ilm 1995
}