OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

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