OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
18 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.erp.core.sales.invoice.component;
15
 
16
import static org.openconcerto.utils.CollectionUtils.createSet;
17
import org.openconcerto.erp.config.ComptaPropsConfiguration;
18
import org.openconcerto.erp.core.common.component.TransfertBaseSQLComponent;
19
import org.openconcerto.erp.core.common.element.NumerotationAutoSQLElement;
20
import org.openconcerto.erp.core.common.ui.AbstractArticleItemTable;
21
import org.openconcerto.erp.core.common.ui.DeviseField;
22
import org.openconcerto.erp.core.common.ui.TotalPanel;
23
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
24
import org.openconcerto.erp.core.finance.accounting.element.EcritureSQLElement;
25
import org.openconcerto.erp.core.finance.payment.component.ModeDeReglementSQLComponent;
26
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
27
import org.openconcerto.erp.core.sales.invoice.report.VenteFactureXmlSheet;
28
import org.openconcerto.erp.core.sales.invoice.ui.SaisieVenteFactureItemTable;
29
import org.openconcerto.erp.core.sales.product.element.ReferenceArticleSQLElement;
30
import org.openconcerto.erp.core.supplychain.stock.element.MouvementStockSQLElement;
31
import org.openconcerto.erp.generationEcritures.GenerationMvtSaisieVenteFacture;
32
import org.openconcerto.erp.model.BanqueModifiedListener;
33
import org.openconcerto.erp.model.ISQLCompteSelector;
21 ilm 34
import org.openconcerto.erp.panel.PanelOOSQLComponent;
18 ilm 35
import org.openconcerto.erp.preferences.DefaultNXProps;
36
import org.openconcerto.erp.preferences.ModeReglementDefautPrefPanel;
37
import org.openconcerto.sql.Configuration;
38
import org.openconcerto.sql.element.ElementSQLObject;
39
import org.openconcerto.sql.element.SQLElement;
40
import org.openconcerto.sql.model.SQLBackgroundTableCache;
41
import org.openconcerto.sql.model.SQLBase;
42
import org.openconcerto.sql.model.SQLField;
43
import org.openconcerto.sql.model.SQLInjector;
44
import org.openconcerto.sql.model.SQLRow;
45
import org.openconcerto.sql.model.SQLRowAccessor;
46
import org.openconcerto.sql.model.SQLRowValues;
47
import org.openconcerto.sql.model.SQLSelect;
48
import org.openconcerto.sql.model.SQLTable;
49
import org.openconcerto.sql.model.UndefinedRowValuesCache;
50
import org.openconcerto.sql.model.Where;
51
import org.openconcerto.sql.sqlobject.ElementComboBox;
52
import org.openconcerto.sql.sqlobject.ISQLElementWithCodeSelector;
53
import org.openconcerto.sql.sqlobject.JUniqueTextField;
54
import org.openconcerto.sql.sqlobject.SQLTextCombo;
55
import org.openconcerto.sql.users.UserManager;
56
import org.openconcerto.sql.view.EditFrame;
57
import org.openconcerto.sql.view.list.RowValuesTableModel;
58
import org.openconcerto.ui.DefaultGridBagConstraints;
25 ilm 59
import org.openconcerto.ui.FormLayouter;
18 ilm 60
import org.openconcerto.ui.JDate;
61
import org.openconcerto.ui.TitledSeparator;
62
import org.openconcerto.ui.component.ITextArea;
19 ilm 63
import org.openconcerto.utils.CollectionMap;
18 ilm 64
import org.openconcerto.utils.ExceptionHandler;
65
import org.openconcerto.utils.GestionDevise;
66
import org.openconcerto.utils.text.SimpleDocumentListener;
67
 
68
import java.awt.GridBagConstraints;
69
import java.awt.GridBagLayout;
70
import java.awt.event.ActionEvent;
71
import java.awt.event.ActionListener;
72
import java.beans.PropertyChangeEvent;
73
import java.beans.PropertyChangeListener;
19 ilm 74
import java.math.BigDecimal;
21 ilm 75
import java.sql.Date;
18 ilm 76
import java.sql.SQLException;
19 ilm 77
import java.util.ArrayList;
18 ilm 78
import java.util.List;
79
import java.util.Map;
80
 
81
import javax.swing.JCheckBox;
82
import javax.swing.JLabel;
83
import javax.swing.JOptionPane;
84
import javax.swing.JPanel;
85
import javax.swing.JScrollPane;
86
import javax.swing.JTextField;
87
import javax.swing.SwingConstants;
88
import javax.swing.SwingUtilities;
89
import javax.swing.event.DocumentEvent;
90
 
91
import org.apache.commons.dbutils.handlers.ArrayListHandler;
92
 
93
public class SaisieVenteFactureSQLComponent extends TransfertBaseSQLComponent {
94
    private AbstractArticleItemTable tableFacture;
95
    private JLabel labelAffaire = new JLabel("Affaire");
96
    private DeviseField textPortHT, textAvoirTTC, textRemiseHT, fieldTTC, textTotalAvoir;
97
    private SQLElement factureElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
98
    private SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
99
    public static final SQLTable TABLE_ADRESSE = Configuration.getInstance().getDirectory().getElement("ADRESSE").getTable();
100
    private SQLTable tableClient = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("CLIENT");
101
    private final SQLElement client = Configuration.getInstance().getDirectory().getElement(this.tableClient);
102
    private JUniqueTextField textNumeroUnique;
103
    private JTextField textSource, textIdSource;
104
    private ElementComboBox comboClient, comboAdresse;
105
    private ISQLCompteSelector compteSel;
106
    private final SQLTable tableNum = this.factureElt.getTable().getBase().getTable("NUMEROTATION_AUTO");
21 ilm 107
    private JCheckBox checkCompteServiceAuto, checkPrevisionnelle, checkComplement, checkAcompte, checkCT;
108
    private PanelOOSQLComponent panelOO;
18 ilm 109
    private ElementComboBox selAvoir, selAffaire;
110
    private ElementSQLObject eltModeRegl;
111
    private static final SQLBase base = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete();
112
    private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
113
    private static final SQLRow rowPrefsCompte = SQLBackgroundTableCache.getInstance().getCacheForTable(tablePrefCompte).getRowFromId(2);
114
    private ISQLElementWithCodeSelector contact;
115
    private SQLRowAccessor rowSelected;
116
    private SQLElement eltContact = Configuration.getInstance().getDirectory().getElement("CONTACT");
117
    private JTextField refClient = new JTextField();
118
    private SQLRowValues defaultContactRowValues = new SQLRowValues(this.eltContact.getTable());
119
    protected TotalPanel totalTTC;
120
    // Type intervention
121
    private SQLTextCombo textTypeMission = new SQLTextCombo();
122
 
123
    private PropertyChangeListener listenerModeReglDefaut = new PropertyChangeListener() {
124
        public void propertyChange(PropertyChangeEvent arg0) {
125
 
126
            int idCli = SaisieVenteFactureSQLComponent.this.comboClient.getSelectedId();
127
            if (idCli > 1) {
128
                SQLRow rowCli = SaisieVenteFactureSQLComponent.this.client.getTable().getRow(idCli);
129
 
130
                if (SaisieVenteFactureSQLComponent.this.rowSelected == null || SaisieVenteFactureSQLComponent.this.rowSelected.getID() <= 1
131
                        || SaisieVenteFactureSQLComponent.this.rowSelected.getInt("ID_CLIENT") != idCli) {
132
                    SQLElement sqleltModeRegl = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
133
                    int idModeRegl = rowCli.getInt("ID_MODE_REGLEMENT");
134
                    if (idModeRegl > 1) {
135
                        SQLRow rowModeRegl = sqleltModeRegl.getTable().getRow(idModeRegl);
136
                        SQLRowValues rowValsModeRegl = rowModeRegl.createUpdateRow();
137
                        rowValsModeRegl.clearPrimaryKeys();
138
                        SaisieVenteFactureSQLComponent.this.eltModeRegl.setValue(rowValsModeRegl);
139
                    }
140
                }
141
            }
142
            Where w = new Where(SaisieVenteFactureSQLComponent.this.tableAvoir.getField("SOLDE"), "=", Boolean.FALSE);
143
            if (SaisieVenteFactureSQLComponent.this.comboClient.isEmpty()) {
144
                w = w.and(new Where(getTable().getBase().getTable("AVOIR_CLIENT").getField("ID_CLIENT"), "=", -1));
145
            } else {
146
                w = w.and(new Where(getTable().getBase().getTable("AVOIR_CLIENT").getField("ID_CLIENT"), "=", SaisieVenteFactureSQLComponent.this.comboClient.getSelectedId()));
147
            }
148
            if (getSelectedID() > 1) {
149
                SQLRow row = getTable().getRow(getSelectedID());
150
                w = w.or(new Where(SaisieVenteFactureSQLComponent.this.tableAvoir.getKey(), "=", row.getInt("ID_AVOIR_CLIENT")));
151
            }
152
 
153
            SaisieVenteFactureSQLComponent.this.selAvoir.getRequest().setWhere(w);
154
            SaisieVenteFactureSQLComponent.this.selAvoir.fillCombo();
155
        }
156
    };
157
 
158
    private PropertyChangeListener changeCompteListener;
159
    private PropertyChangeListener changeClientListener;
160
    private ISQLCompteSelector compteSelService;
161
    private JLabel labelCompteServ;
162
    private ElementComboBox comboCommercial;
163
    private ElementComboBox comboVerificateur = new ElementComboBox();;
164
 
165
 
166
    public SaisieVenteFactureSQLComponent() {
167
        super(Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE"));
168
    }
169
 
170
 
171
    private int previousClient = -1;
172
 
173
    public void addViews() {
174
        this.setLayout(new GridBagLayout());
175
        final GridBagConstraints c = new DefaultGridBagConstraints();
176
 
177
        this.checkPrevisionnelle = new JCheckBox();
178
        this.checkComplement = new JCheckBox();
179
        this.fieldTTC = new DeviseField();
180
 
181
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
182
 
183
        this.textSource = new JTextField();
184
        this.textIdSource = new JTextField();
185
        this.textAvoirTTC = new DeviseField();
186
 
25 ilm 187
        // Champ Module
188
        c.gridx = 0;
189
        c.gridy++;
190
        c.gridwidth = GridBagConstraints.REMAINDER;
191
        final JPanel addP = new JPanel();
192
        this.setAdditionalFieldsPanel(new FormLayouter(addP, 1));
193
        this.add(addP, c);
194
 
195
        c.gridy++;
196
        c.gridwidth = 1;
197
 
18 ilm 198
        /*******************************************************************************************
199
         * * RENSEIGNEMENTS
200
         ******************************************************************************************/
201
        // Ligne 1 : Numero de facture
202
        JLabel labelNum = new JLabel(getLabelFor("NUMERO"));
203
        labelNum.setHorizontalAlignment(SwingConstants.RIGHT);
204
        c.gridx = 0;
205
        c.gridy++;
206
        c.weightx = 0;
207
        this.add(labelNum, c);
208
 
209
        this.textNumeroUnique = new JUniqueTextField(16);
210
        c.gridx++;
211
        c.weightx = 0;
212
        c.fill = GridBagConstraints.NONE;
213
        DefaultGridBagConstraints.lockMinimumSize(this.textNumeroUnique);
214
            this.add(textNumeroUnique, c);
215
 
216
        // Date
217
        c.gridx++;
218
        c.weightx = 0;
219
        c.fill = GridBagConstraints.HORIZONTAL;
220
        this.add(new JLabel(getLabelFor("DATE"), SwingConstants.RIGHT), c);
221
 
222
        c.gridx++;
223
        c.weightx = 1;
224
        c.fill = GridBagConstraints.NONE;
225
        final JDate dateSaisie = new JDate(true);
226
 
227
        this.add(dateSaisie, c);
228
 
229
 
230
        // Ligne 2 : reference
231
        c.gridx = 0;
232
        c.gridwidth = 1;
233
        c.gridy++;
234
        c.weightx = 0;
235
        c.fill = GridBagConstraints.HORIZONTAL;
236
        JLabel labelLibelle = new JLabel(getLabelFor("NOM"));
237
        labelLibelle.setHorizontalAlignment(SwingConstants.RIGHT);
238
        this.add(labelLibelle, c);
239
 
240
        SQLTextCombo textLibelle = new SQLTextCombo();
241
        c.gridx++;
242
        c.weightx = 1;
243
        c.fill = GridBagConstraints.BOTH;
244
        this.add(textLibelle, c);
245
 
246
        this.addSQLObject(textLibelle, "NOM");
247
        c.fill = GridBagConstraints.HORIZONTAL;
248
        this.comboCommercial = new ElementComboBox(false);
249
            // Commercial
250
            String field;
251
                field = "ID_COMMERCIAL";
252
            c.gridx++;
253
            c.weightx = 0;
254
            c.fill = GridBagConstraints.HORIZONTAL;
255
            this.add(new JLabel(getLabelFor(field), SwingConstants.RIGHT), c);
256
 
257
            c.gridx++;
258
            c.weightx = 1;
259
            c.fill = GridBagConstraints.NONE;
260
 
261
            this.add(this.comboCommercial, c);
262
            this.addRequiredSQLObject(this.comboCommercial, field);
263
        // Client
264
        c.gridx = 0;
265
        c.gridy++;
266
        c.weightx = 0;
267
        c.fill = GridBagConstraints.HORIZONTAL;
268
        this.add(new JLabel(getLabelFor("ID_CLIENT"), SwingConstants.RIGHT), c);
269
 
270
        c.gridx++;
271
        c.weightx = 1;
272
        c.fill = GridBagConstraints.NONE;
273
        this.comboClient = new ElementComboBox();
274
 
275
        this.add(this.comboClient, c);
276
 
277
        this.comboClient.addValueListener(this.changeClientListener);
278
 
279
        this.comboAdresse = new ElementComboBox();
280
        this.comboAdresse.setAddIconVisible(false);
281
        this.comboAdresse.setListIconVisible(false);
282
            JLabel labelAdresse = new JLabel(getLabelFor("ID_ADRESSE"));
283
            c.gridy++;
284
            c.gridx = 0;
285
            c.gridwidth = 1;
286
            c.weightx = 0;
287
            labelAdresse.setHorizontalAlignment(SwingConstants.RIGHT);
288
            this.add(labelAdresse, c);
289
 
290
            c.gridx++;
291
            c.gridwidth = GridBagConstraints.REMAINDER;
292
            c.weightx = 1;
293
            this.add(this.comboAdresse, c);
294
 
295
        Boolean bCompteCli = Boolean.valueOf(DefaultNXProps.getInstance().getStringProperty("HideCompteFacture"));
296
        if (!bCompteCli) {
297
            // Ligne 5: Compte Client
298
            c.gridy++;
299
            c.gridx = 0;
300
            c.fill = GridBagConstraints.HORIZONTAL;
301
            c.gridwidth = 1;
302
            c.weightx = 0;
303
            this.add(new JLabel("Compte", SwingConstants.RIGHT), c);
304
 
305
            c.gridx++;
306
            c.weightx = 1;
307
            this.compteSel = new ISQLCompteSelector();
308
            this.compteSel.init();
309
            c.gridwidth = 3;
310
            this.add(this.compteSel, c);
311
            this.compteSel.addValueListener(this.changeCompteListener);
312
 
313
        }
314
 
315
 
316
        // Compte Service
317
        this.checkCompteServiceAuto = new JCheckBox(getLabelFor("COMPTE_SERVICE_AUTO"));
318
        this.addSQLObject(this.checkCompteServiceAuto, "COMPTE_SERVICE_AUTO");
319
        this.compteSelService = new ISQLCompteSelector();
320
 
321
        this.labelCompteServ = new JLabel("Compte Service");
322
        c.gridy++;
323
        c.gridx = 0;
324
        c.gridwidth = 1;
325
        c.weightx = 0;
326
        this.labelCompteServ.setHorizontalAlignment(SwingConstants.RIGHT);
327
        this.add(this.labelCompteServ, c);
328
 
329
        c.gridx++;
330
        c.gridwidth = GridBagConstraints.REMAINDER;
331
        c.weightx = 1;
332
        this.add(this.compteSelService, c);
333
 
334
        String valServ = DefaultNXProps.getInstance().getStringProperty("ArticleService");
335
        Boolean bServ = Boolean.valueOf(valServ);
336
 
337
        this.checkCompteServiceAuto.addActionListener(new ActionListener() {
338
            @Override
339
            public void actionPerformed(ActionEvent e) {
340
                setCompteServiceVisible(!SaisieVenteFactureSQLComponent.this.checkCompteServiceAuto.isSelected());
341
            }
342
        });
343
 
344
        setCompteServiceVisible(!(bServ != null && !bServ.booleanValue()));
345
 
346
 
347
        // Acompte
348
        this.checkAcompte = new JCheckBox(getLabelFor("ACOMPTE"));
349
        this.addView(this.checkAcompte, "ACOMPTE");
350
 
351
        final JPanel pAcompte = new JPanel();
352
        final DeviseField textAcompteHT = new DeviseField();
353
        pAcompte.add(new JLabel("Acompte HT"));
354
        pAcompte.add(textAcompteHT);
355
 
356
        pAcompte.add(new JLabel("soit"));
357
        final JTextField textAcompte = new JTextField(5);
358
        pAcompte.add(textAcompte);
359
        pAcompte.add(new JLabel("%"));
360
        c.gridx = 0;
361
        c.gridy++;
362
        c.anchor = GridBagConstraints.EAST;
363
        c.fill = GridBagConstraints.NONE;
364
        this.add(pAcompte, c);
365
        c.anchor = GridBagConstraints.WEST;
366
        this.addView(textAcompte, "POURCENT_ACOMPTE");
367
 
368
        pAcompte.setVisible(false);
369
 
370
        /*******************************************************************************************
371
         * * DETAILS
372
         ******************************************************************************************/
373
            this.tableFacture = new SaisieVenteFactureItemTable();
19 ilm 374
 
375
        final ElementComboBox boxTarif = new ElementComboBox();
376
        if (this.getTable().getFieldsName().contains("ID_TARIF")) {
377
            // TARIF
378
            c.gridy++;
379
            c.gridx = 0;
380
            c.weightx = 0;
381
            c.weighty = 0;
382
            c.gridwidth = 1;
383
            this.add(new JLabel("Tarif à appliquer"), c);
384
            c.gridx++;
385
            c.gridwidth = GridBagConstraints.REMAINDER;
386
 
387
            c.weightx = 1;
388
            this.add(boxTarif, c);
389
            this.addView(boxTarif, "ID_TARIF");
390
            boxTarif.addValueListener(new PropertyChangeListener() {
391
 
392
                @Override
393
                public void propertyChange(PropertyChangeEvent evt) {
394
                    tableFacture.setTarif(boxTarif.getSelectedRow(), false);
395
                }
396
            });
397
        }
18 ilm 398
        c.gridy++;
399
        c.gridx = 0;
400
        c.weightx = 1;
401
        c.weighty = 1;
402
        c.gridwidth = GridBagConstraints.REMAINDER;
403
 
404
        c.fill = GridBagConstraints.BOTH;
405
        this.add(this.tableFacture, c);
406
 
407
        // FIXME
408
        this.addView(this.tableFacture.getRowValuesTable(), "");
409
 
410
 
411
        /*******************************************************************************************
412
         * * MODE DE REGLEMENT
413
         ******************************************************************************************/
414
        JPanel panelBottom = new JPanel(new GridBagLayout());
415
        GridBagConstraints cBottom = new DefaultGridBagConstraints();
416
        cBottom.weightx = 1;
417
        cBottom.anchor = GridBagConstraints.NORTHWEST;
418
        // Mode de règlement
419
        this.addView("ID_MODE_REGLEMENT", REQ + ";" + DEC + ";" + SEP);
420
        this.eltModeRegl = (ElementSQLObject) this.getView("ID_MODE_REGLEMENT");
421
        panelBottom.add(this.eltModeRegl, cBottom);
422
 
423
        /*******************************************************************************************
424
         * * FRAIS DE PORT ET REMISE
425
         ******************************************************************************************/
426
        JPanel panelFrais = new JPanel();
427
        panelFrais.setLayout(new GridBagLayout());
428
 
429
        final GridBagConstraints cFrais = new DefaultGridBagConstraints();
430
 
431
        this.textPortHT = new DeviseField(5);
432
        DefaultGridBagConstraints.lockMinimumSize(textPortHT);
433
        addSQLObject(this.textPortHT, "PORT_HT");
434
        this.textRemiseHT = new DeviseField(5);
435
        DefaultGridBagConstraints.lockMinimumSize(textRemiseHT);
436
        addSQLObject(this.textRemiseHT, "REMISE_HT");
437
 
438
        // Frais de port
439
        cFrais.gridheight = 1;
440
        cFrais.gridx = 1;
441
 
442
        JLabel labelPortHT = new JLabel(getLabelFor("PORT_HT"));
443
        labelPortHT.setHorizontalAlignment(SwingConstants.RIGHT);
444
        cFrais.gridy++;
445
        panelFrais.add(labelPortHT, cFrais);
446
        cFrais.gridx++;
447
        panelFrais.add(this.textPortHT, cFrais);
448
 
449
        // Remise
450
        JLabel labelRemiseHT = new JLabel(getLabelFor("REMISE_HT"));
451
        labelRemiseHT.setHorizontalAlignment(SwingConstants.RIGHT);
452
        cFrais.gridy++;
453
        cFrais.gridx = 1;
454
        panelFrais.add(labelRemiseHT, cFrais);
455
        cFrais.gridx++;
456
        panelFrais.add(this.textRemiseHT, cFrais);
457
        cFrais.gridy++;
458
 
459
        cBottom.gridx++;
460
        cBottom.weightx = 1;
461
        cBottom.anchor = GridBagConstraints.NORTHEAST;
462
        cBottom.fill = GridBagConstraints.NONE;
463
        panelBottom.add(panelFrais, cBottom);
464
 
465
        /*******************************************************************************************
466
         * * CALCUL DES TOTAUX
467
         ******************************************************************************************/
468
        DeviseField fieldHT = new DeviseField();
469
        final DeviseField fieldTVA = new DeviseField();
470
        DeviseField fieldService = new DeviseField();
471
        DeviseField fieldTHA = new DeviseField();
19 ilm 472
 
473
        DeviseField fieldDevise = null;
474
        if (getTable().getFieldsName().contains("T_DEVISE")) {
475
            fieldDevise = new DeviseField();
476
            addSQLObject(fieldDevise, "T_DEVISE");
477
        }
18 ilm 478
        // FIXME was required but not displayed for KD
479
        addSQLObject(fieldTHA, "T_HA");
480
        addRequiredSQLObject(fieldHT, "T_HT");
481
        addRequiredSQLObject(fieldTVA, "T_TVA");
482
        addRequiredSQLObject(this.fieldTTC, "T_TTC");
483
        addRequiredSQLObject(fieldService, "T_SERVICE");
19 ilm 484
        JTextField poids = new JTextField();
485
        addSQLObject(poids, "T_POIDS");
18 ilm 486
        totalTTC = new TotalPanel(this.tableFacture.getRowValuesTable(), this.tableFacture.getPrixTotalHTElement(), this.tableFacture.getPrixTotalTTCElement(), this.tableFacture.getHaElement(),
19 ilm 487
                this.tableFacture.getQteElement(), fieldHT, fieldTVA, this.fieldTTC, this.textPortHT, this.textRemiseHT, fieldService, this.tableFacture.getPrixServiceElement(), null, fieldTHA,
488
                fieldDevise, this.tableFacture.getTableElementTotalDevise(), poids, this.tableFacture.getPoidsTotalElement());
18 ilm 489
        DefaultGridBagConstraints.lockMinimumSize(totalTTC);
490
        cBottom.gridx++;
491
        cBottom.weightx = 1;
492
        cBottom.anchor = GridBagConstraints.EAST;
493
        cBottom.fill = GridBagConstraints.HORIZONTAL;
494
        panelBottom.add(totalTTC, cBottom);
495
 
496
        c.anchor = GridBagConstraints.WEST;
497
        c.gridwidth = GridBagConstraints.REMAINDER;
498
        c.fill = GridBagConstraints.HORIZONTAL;
499
        c.gridx = 0;
500
        c.gridy++;
501
        c.weighty = 0;
502
        this.add(panelBottom, c);
503
 
504
        // Ligne : Avoir
505
        c.gridy++;
506
        c.gridx = 0;
507
        c.weightx = 1;
508
        c.weighty = 0;
509
        c.gridwidth = GridBagConstraints.REMAINDER;
510
        c.anchor = GridBagConstraints.EAST;
511
        c.fill = GridBagConstraints.HORIZONTAL;
512
        this.add(createPanelAvoir(), c);
513
 
514
        // Infos
515
        c.gridy++;
516
        c.gridx = 0;
517
        c.gridwidth = 4;
518
        c.fill = GridBagConstraints.BOTH;
519
        this.add(new TitledSeparator(getLabelFor("INFOS")), c);
520
 
521
        ITextArea infos = new ITextArea(4, 4);
522
        c.gridy++;
523
 
524
        final JScrollPane comp = new JScrollPane(infos);
525
        infos.setBorder(null);
526
        DefaultGridBagConstraints.lockMinimumSize(comp);
527
        this.add(comp, c);
528
 
21 ilm 529
        this.panelOO = new PanelOOSQLComponent(this);
18 ilm 530
        c.gridy++;
531
        c.gridx = 0;
532
        c.weightx = 1;
533
        c.fill = GridBagConstraints.NONE;
534
        c.anchor = GridBagConstraints.NORTHEAST;
21 ilm 535
        this.add(this.panelOO, c);
18 ilm 536
 
537
        this.addSQLObject(this.textSource, "SOURCE");
538
        this.addSQLObject(this.textAvoirTTC, "T_AVOIR_TTC");
539
        this.addSQLObject(this.textIdSource, "IDSOURCE");
540
 
541
        this.addRequiredSQLObject(dateSaisie, "DATE");
542
        this.addRequiredSQLObject(this.comboClient, "ID_CLIENT");
543
            this.addSQLObject(this.comboAdresse, "ID_ADRESSE");
544
        this.addRequiredSQLObject(this.textNumeroUnique, "NUMERO");
545
        this.addSQLObject(infos, "INFOS");
546
        this.addSQLObject(this.checkPrevisionnelle, "PREVISIONNELLE");
547
        this.addSQLObject(this.checkComplement, "COMPLEMENT");
548
        this.addSQLObject(this.selAvoir, "ID_AVOIR_CLIENT");
549
        this.addSQLObject(this.compteSelService, "ID_COMPTE_PCE_SERVICE");
19 ilm 550
        final SQLTable tableBanque;
551
        ModeDeReglementSQLComponent modeReglComp;
552
        modeReglComp = (ModeDeReglementSQLComponent) this.eltModeRegl.getSQLChild();
18 ilm 553
        this.selAvoir.getRequest().setWhere(new Where(this.tableAvoir.getField("SOLDE"), "=", Boolean.FALSE));
554
        this.selAvoir.fillCombo();
555
 
556
        // Selection du compte de service
557
        int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
558
        if (idCompteVenteService <= 1) {
559
            try {
560
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
561
            } catch (Exception e) {
562
                e.printStackTrace();
563
            }
564
        }
565
        this.compteSelService.setValue(idCompteVenteService);
566
 
567
        // Lock
568
 
569
        DefaultGridBagConstraints.lockMinimumSize(this.comboClient);
570
        DefaultGridBagConstraints.lockMinimumSize(this.comboCommercial);
571
        DefaultGridBagConstraints.lockMinimumSize(this.comboAdresse);
572
 
573
        // Listeners
574
 
575
        this.comboClient.addValueListener(this.listenerModeReglDefaut);
576
        this.fieldTTC.getDocument().addDocumentListener(new SimpleDocumentListener() {
577
            @Override
578
            public void update(DocumentEvent e) {
579
                refreshText();
580
            }
581
 
582
        });
583
 
584
        this.selAvoir.addValueListener(new PropertyChangeListener() {
585
 
586
            public void propertyChange(PropertyChangeEvent evt) {
587
                refreshText();
588
            }
589
 
590
        });
591
 
592
        this.checkAcompte.addPropertyChangeListener(new PropertyChangeListener() {
593
 
594
            public void propertyChange(PropertyChangeEvent evt) {
595
 
596
                pAcompte.setVisible(SaisieVenteFactureSQLComponent.this.checkAcompte.isSelected());
597
            }
598
        });
599
 
600
        this.changeClientListener = new PropertyChangeListener() {
601
 
602
            public void propertyChange(PropertyChangeEvent evt) {
603
                // compteSel.removeValueListener(changeCompteListener);
604
 
605
                if (SaisieVenteFactureSQLComponent.this.comboClient.getValue() != null) {
606
                    Integer id = SaisieVenteFactureSQLComponent.this.comboClient.getValue();
607
 
608
                    SaisieVenteFactureSQLComponent.this.defaultContactRowValues.put("ID_CLIENT", id);
609
                    if (id > 1) {
610
 
611
                        SQLRow row = SaisieVenteFactureSQLComponent.this.client.getTable().getRow(id);
19 ilm 612
                        if (SaisieVenteFactureSQLComponent.this.client.getTable().getFieldsName().contains("ID_TARIF")) {
613
 
614
                            SQLRowAccessor foreignRow = row.getForeignRow("ID_TARIF");
615
                            if (!foreignRow.isUndefined() && (boxTarif.getSelectedRow() == null || boxTarif.getSelectedId() != foreignRow.getID())
616
                                    && JOptionPane.showConfirmDialog(null, "Appliquer les tarifs associés au client?") == JOptionPane.YES_OPTION) {
617
                                boxTarif.setValue(foreignRow.getID());
618
                                // SaisieVenteFactureSQLComponent.this.tableFacture.setTarif(foreignRow,
619
                                // true);
620
                            } else {
621
                                boxTarif.setValue(foreignRow.getID());
622
                            }
623
                            // if (foreignRow.isUndefined() &&
624
                            // !row.getForeignRow("ID_DEVISE").isUndefined()) {
625
                            // SQLRowValues rowValsD = new SQLRowValues(foreignRow.getTable());
626
                            // rowValsD.put("ID_DEVISE", row.getObject("ID_DEVISE"));
627
                            // foreignRow = rowValsD;
628
                            //
629
                            // }
630
                        }
18 ilm 631
                        int idCpt = row.getInt("ID_COMPTE_PCE");
632
 
633
                        if (idCpt <= 1) {
634
                            // Select Compte client par defaut
635
                            idCpt = rowPrefsCompte.getInt("ID_COMPTE_PCE_CLIENT");
636
                            if (idCpt <= 1) {
637
                                try {
638
                                    idCpt = ComptePCESQLElement.getIdComptePceDefault("Clients");
639
                                } catch (Exception e) {
640
                                    e.printStackTrace();
641
                                }
642
                            }
643
                        }
644
                        if (SaisieVenteFactureSQLComponent.this.compteSel != null) {
645
                            Integer i = SaisieVenteFactureSQLComponent.this.compteSel.getValue();
646
                            if (i == null || i.intValue() != idCpt) {
647
                                SaisieVenteFactureSQLComponent.this.compteSel.setValue(idCpt);
648
                            }
649
                        }
650
                        if (SaisieVenteFactureSQLComponent.this.contact != null) {
651
                            Where w = new Where(SaisieVenteFactureSQLComponent.this.eltContact.getTable().getField("ID_CLIENT"), "=", SQLRow.NONEXISTANT_ID);
652
                                w = w.or(new Where(SaisieVenteFactureSQLComponent.this.eltContact.getTable().getField("ID_CLIENT"), "=", id));
653
                            SaisieVenteFactureSQLComponent.this.contact.setWhereOnRequest(w);
654
                        }
655
                            if (SaisieVenteFactureSQLComponent.this.comboAdresse != null) {
656
 
657
                                Where w = new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row.getInt("ID_ADRESSE"));
658
 
659
                                w = w.or(new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row.getInt("ID_ADRESSE_L")));
660
                                w = w.or(new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getKey(), "=", row.getInt("ID_ADRESSE_F")));
661
 
662
                                SQLRow rowCli = row;
663
 
664
                                w = w.or(new Where(SaisieVenteFactureSQLComponent.TABLE_ADRESSE.getField("ID_CLIENT"), "=", rowCli.getID()));
665
 
666
                                SaisieVenteFactureSQLComponent.this.comboAdresse.getRequest().setWhere(w);
667
                            }
668
                    } else {
669
                            if (SaisieVenteFactureSQLComponent.this.comboAdresse != null) {
670
                                SaisieVenteFactureSQLComponent.this.comboAdresse.getRequest().setWhere(null);
671
                            }
672
                    }
673
                    SaisieVenteFactureSQLComponent.this.previousClient = id;
674
                }
675
                // compteSel.addValueListener(changeCompteListener);
676
            }
677
        };
678
 
679
        this.changeCompteListener = new PropertyChangeListener() {
680
            public void propertyChange(PropertyChangeEvent evt) {
681
                SQLSelect sel = new SQLSelect(getTable().getBase());
682
                sel.addSelect(SaisieVenteFactureSQLComponent.this.client.getTable().getKey());
683
                Where where = new Where(SaisieVenteFactureSQLComponent.this.client.getTable().getField("ID_COMPTE_PCE"), "=", SaisieVenteFactureSQLComponent.this.compteSel.getValue());
684
                sel.setWhere(where);
685
 
686
                String req = sel.asString();
687
                List l = getTable().getBase().getDataSource().execute(req);
688
                if (l != null) {
689
                    if (l.size() == 1) {
690
                        Map<String, Object> m = (Map<String, Object>) l.get(0);
691
                        Object o = m.get(SaisieVenteFactureSQLComponent.this.client.getTable().getKey().getName());
692
                        System.err.println("Only one value match :: " + o);
693
                        if (o != null) {
694
                            SaisieVenteFactureSQLComponent.this.comboClient.setValue(Integer.valueOf(((Number) o).intValue()));
695
                        }
696
                    }
697
                }
698
            }
699
        };
700
        this.textPortHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
701
            @Override
702
            public void update(DocumentEvent e) {
703
                totalTTC.updateTotal();
704
            }
705
        });
706
 
707
        this.textRemiseHT.getDocument().addDocumentListener(new SimpleDocumentListener() {
708
            @Override
709
            public void update(DocumentEvent e) {
710
                totalTTC.updateTotal();
711
            }
712
        });
713
    }
714
 
715
    private JPanel createPanelAvoir() {
716
        JPanel panelAvoir = new JPanel(new GridBagLayout());
717
        panelAvoir.setOpaque(false);
718
        GridBagConstraints cA = new DefaultGridBagConstraints();
719
        JLabel labelAvoir = new JLabel(getLabelFor("ID_AVOIR_CLIENT"));
720
        labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
721
        cA.weightx = 1;
722
        labelAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
723
        panelAvoir.add(labelAvoir, cA);
724
        cA.weightx = 0;
725
        cA.gridx++;
726
        this.selAvoir = new ElementComboBox();
727
        this.selAvoir.setAddIconVisible(false);
728
        panelAvoir.add(this.selAvoir, cA);
729
        final JLabel labelTotalAvoir = new JLabel("Total à régler");
730
        this.textTotalAvoir = new DeviseField();
731
        this.textTotalAvoir.setEditable(false);
732
        cA.gridx++;
733
        cA.weightx = 0;
734
        panelAvoir.add(labelTotalAvoir, cA);
735
        cA.gridx++;
736
        cA.weightx = 0;
737
        panelAvoir.add(this.textTotalAvoir, cA);
738
        this.textTotalAvoir.setHorizontalAlignment(SwingConstants.RIGHT);
739
 
740
        return panelAvoir;
741
    }
742
 
743
    private void setCompteServiceVisible(boolean b) {
744
        this.compteSelService.setVisible(b);
745
        this.labelCompteServ.setVisible(b);
746
    }
747
 
748
    private void refreshText() {
749
        Number n = (Number) this.fieldTTC.getUncheckedValue();
750
        if (this.selAvoir.getSelectedId() > 1) {
751
            SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable();
752
            if (n != null) {
753
                long ttc = n.longValue();
754
                SQLRow rowAvoir = tableAvoir.getRow(this.selAvoir.getSelectedId());
755
                long totalAvoir = ((Number) rowAvoir.getObject("MONTANT_TTC")).longValue();
756
                totalAvoir -= ((Number) rowAvoir.getObject("MONTANT_SOLDE")).longValue();
757
                if (getSelectedID() > 1) {
758
                    SQLRow row = getTable().getRow(getSelectedID());
759
                    int idAvoirOld = row.getInt("ID_AVOIR_CLIENT");
760
                    if (idAvoirOld == rowAvoir.getID()) {
761
                        totalAvoir += Long.valueOf(row.getObject("T_AVOIR_TTC").toString());
762
                    }
763
                }
764
 
765
                long l = ttc - totalAvoir;
766
                if (l < 0) {
767
                    l = 0;
768
                    this.textAvoirTTC.setValue(GestionDevise.currencyToString(ttc));
769
                } else {
770
                    this.textAvoirTTC.setValue(GestionDevise.currencyToString(totalAvoir));
771
                }
772
                this.textTotalAvoir.setValue(GestionDevise.currencyToString(l));
773
 
774
            } else {
775
                this.textTotalAvoir.setValue(GestionDevise.currencyToString(0));
776
            }
777
        } else {
778
            if (n != null) {
779
                this.textTotalAvoir.setValue(GestionDevise.currencyToString(n.longValue()));
780
            } else {
781
                this.textTotalAvoir.setValue(GestionDevise.currencyToString(0));
782
            }
783
            this.textAvoirTTC.setValue(GestionDevise.currencyToString(0));
784
        }
785
    }
786
 
21 ilm 787
    // @Override
788
    // public synchronized boolean isValidated() {
789
    // // TODO Auto-generated method stub
790
    // boolean b = true;
791
    // if (fieldTTC != null && fieldTTC.getUncheckedValue() != null) {
792
    //
793
    // long l = ((Long) fieldTTC.getUncheckedValue());
794
    //
795
    // if (this.selAvoir != null && !this.selAvoir.isEmpty() && this.selAvoir.getSelectedId() >
796
    // 1) {
797
    // SQLElement eltAvoir =
798
    // Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT");
799
    // SQLRow rowAvoir = eltAvoir.getTable().getRow(this.selAvoir.getSelectedId());
800
    // l -= ((Number) rowAvoir.getObject("MONTANT_TTC")).longValue();
801
    // }
802
    // b = l >= 0;
803
    // }
804
    // return super.isValidated() && b;
805
    // }
18 ilm 806
 
807
    public int insert(SQLRow order) {
808
 
809
        return commit(order);
810
    }
811
 
812
    private void createCompteServiceAuto(int id) {
813
        SQLRow rowPole = this.comboCommercial.getSelectedRow();
814
        SQLRow rowVerif = this.comboVerificateur.getSelectedRow();
815
        String verifInitiale = getInitialesFromVerif(rowVerif);
816
        int idCpt = ComptePCESQLElement.getId("706" + rowPole.getString("CODE") + verifInitiale, "Service " + rowPole.getString("NOM") + " " + rowVerif.getString("NOM"));
817
        SQLRowValues rowVals = this.getTable().getRow(id).createEmptyUpdateRow();
818
        rowVals.put("ID_COMPTE_PCE_SERVICE", idCpt);
819
        try {
820
            rowVals.update();
821
        } catch (SQLException e) {
822
            e.printStackTrace();
823
        }
824
    }
825
 
826
    @Override
827
    public void select(SQLRowAccessor r) {
828
        if (compteSel != null) {
829
            this.compteSel.rmValueListener(this.changeCompteListener);
830
        }
831
        this.comboClient.rmValueListener(this.listenerModeReglDefaut);
832
        this.rowSelected = r;
833
        if (r != null) {
834
            this.textNumeroUnique.setIdSelected(r.getID());
835
 
836
        }
837
            super.select(r);
838
 
839
        if (r != null) {
840
            this.tableFacture.getModel().clearRows();
841
            this.tableFacture.insertFrom("ID_SAISIE_VENTE_FACTURE", r.getID());
842
            Boolean b = (Boolean) r.getObject("ACOMPTE");
843
            if (b != null) {
844
                setAcompte(b);
845
            } else {
846
                setAcompte(false);
847
            }
848
        }
849
        this.comboClient.addValueListener(this.listenerModeReglDefaut);
850
        this.comboClient.addValueListener(this.changeClientListener);
851
        if (this.compteSel != null) {
852
            this.compteSel.addValueListener(this.changeCompteListener);
853
        } // nomClient.addValueListener(changeClientListener);
854
    }
855
 
856
    private String getInitialesFromVerif(SQLRow row) {
857
        String s = "";
858
 
859
        if (row != null) {
860
            String prenom = row.getString("PRENOM");
861
            if (prenom != null && prenom.length() > 0) {
862
                s += prenom.toUpperCase().charAt(0);
863
            }
864
            String nom = row.getString("NOM");
865
            if (nom != null && nom.length() > 0) {
866
                s += nom.toUpperCase().charAt(0);
867
            }
868
        }
869
 
870
        return s;
871
    }
872
 
873
    public int commit(SQLRow order) {
874
 
875
        int idSaisieVF = -1;
876
        long lFactureOld = 0;
877
        SQLRow rowFactureOld = null;
878
        SQLRow rowFacture = null;
879
        SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
880
        if (this.textNumeroUnique.checkValidation()) {
881
 
882
            if (getMode() == Mode.INSERTION) {
883
                idSaisieVF = super.insert(order);
884
 
885
                // incrémentation du numéro auto
886
                if (NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class).equalsIgnoreCase(this.textNumeroUnique.getText().trim())) {
887
                    SQLRowValues rowVals = new SQLRowValues(this.tableNum);
888
                    int val = this.tableNum.getRow(2).getInt("FACT_START");
889
                    val++;
890
                    rowVals.put("FACT_START", Integer.valueOf(val));
891
 
892
                    try {
893
                        rowVals.update(2);
894
                    } catch (SQLException e) {
895
                        e.printStackTrace();
896
                    }
897
                }
898
            } else {
899
                if (JOptionPane.showConfirmDialog(this, "Attention en modifiant cette facture, vous supprimerez les chéques et les échéances associés. Continuer?", "Modification de facture",
900
                        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
901
 
902
                    // On efface les anciens mouvements de stocks
903
                    SQLSelect sel = new SQLSelect(eltMvtStock.getTable().getBase());
904
                    sel.addSelect(eltMvtStock.getTable().getField("ID"));
905
                    Where w = new Where(eltMvtStock.getTable().getField("IDSOURCE"), "=", getSelectedID());
906
                    Where w2 = new Where(eltMvtStock.getTable().getField("SOURCE"), "=", getTable().getName());
907
                    sel.setWhere(w.and(w2));
908
 
909
                    List l = (List) eltMvtStock.getTable().getBase().getDataSource().execute(sel.asString(), new ArrayListHandler());
910
                    if (l != null) {
911
                        for (int i = 0; i < l.size(); i++) {
912
                            Object[] tmp = (Object[]) l.get(i);
913
                            try {
914
                                eltMvtStock.archive(((Number) tmp[0]).intValue());
915
                            } catch (SQLException e) {
916
                                e.printStackTrace();
917
                            }
918
                        }
919
                    }
920
 
921
                    // On recupere l'ancien total HT
922
                    rowFactureOld = this.getTable().getRow(getSelectedID());
923
                    lFactureOld = ((Number) rowFactureOld.getObject("T_HT")).longValue();
924
 
925
                    super.update();
926
 
927
                    idSaisieVF = getSelectedID();
928
                } else {
929
                    // Annulation par l'utilisateur
930
                    return idSaisieVF;
931
                }
932
            }
933
 
934
            rowFacture = getTable().getRow(idSaisieVF);
19 ilm 935
            final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
18 ilm 936
 
937
            // Mise à jour des tables liées
938
            this.tableFacture.updateField("ID_SAISIE_VENTE_FACTURE", idSaisieVF);
939
 
940
 
941
            // generation du document
25 ilm 942
            final VenteFactureXmlSheet sheet = new VenteFactureXmlSheet(rowFacture);
18 ilm 943
 
25 ilm 944
            try {
945
                sheet.createDocumentAsynchronous();
946
                sheet.showPrintAndExportAsynchronous(panelOO.isVisualisationSelected(), panelOO.isImpressionSelected(), true);
947
            } catch (Exception e) {
948
                ExceptionHandler.handle("Impossible de générer la facture", e);
949
            }
950
 
18 ilm 951
            int idMvt = -1;
952
            if (getMode() == Mode.MODIFICATION) {
953
 
954
                idMvt = rowFacture.getInt("ID_MOUVEMENT");
955
 
956
                // on supprime tout ce qui est lié à la facture
957
                System.err.println("Archivage des fils");
958
                EcritureSQLElement eltEcr = (EcritureSQLElement) Configuration.getInstance().getDirectory().getElement("ECRITURE");
959
                eltEcr.archiveMouvementProfondeur(idMvt, false);
960
            }
961
 
962
            if (!this.checkPrevisionnelle.isSelected()) {
963
                System.err.println("Regeneration des ecritures");
964
                if (idMvt > 1) {
965
                    new GenerationMvtSaisieVenteFacture(idSaisieVF, idMvt);
966
                } else {
967
                    new GenerationMvtSaisieVenteFacture(idSaisieVF);
968
                }
969
                System.err.println("Fin regeneration");
970
 
971
                // Mise à jour des stocks
972
                updateStock(idSaisieVF);
973
 
974
                // On retire l'avoir
975
                if (rowFactureOld != null && rowFactureOld.getInt("ID_AVOIR_CLIENT") > 1) {
976
 
977
                    SQLRow rowAvoir = rowFactureOld.getForeignRow("ID_AVOIR_CLIENT");
978
 
979
                    Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
980
                    Long avoirTTC = (Long) rowFactureOld.getObject("T_AVOIR_TTC");
981
 
982
                    long montant = montantSolde - avoirTTC;
983
                    if (montant < 0) {
984
                        montant = 0;
985
                    }
986
 
987
                    SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
988
 
989
                    // Soldé
990
                    rowVals.put("SOLDE", Boolean.FALSE);
991
                    rowVals.put("MONTANT_SOLDE", montant);
992
                    Long restant = (Long) rowAvoir.getObject("MONTANT_TTC") - montantSolde;
993
                    rowVals.put("MONTANT_RESTANT", restant);
994
                    try {
995
                        rowVals.update();
996
                    } catch (SQLException e) {
997
                        e.printStackTrace();
998
                    }
999
                }
1000
 
1001
                final int idAvoir = rowFacture.getInt("ID_AVOIR_CLIENT");
1002
                // on solde l'avoir
1003
                if (idAvoir > 1) {
1004
 
1005
                    SQLRow rowAvoir = rowFacture.getForeignRow("ID_AVOIR_CLIENT");
1006
 
1007
                    Long montantTTC = (Long) rowAvoir.getObject("MONTANT_TTC");
1008
                    Long montantSolde = (Long) rowAvoir.getObject("MONTANT_SOLDE");
1009
                    Long factTTC = (Long) rowFacture.getObject("T_TTC");
1010
 
1011
                    long restant = montantTTC - montantSolde;
1012
 
1013
                    SQLRowValues rowVals = rowAvoir.createEmptyUpdateRow();
1014
                    final long l2 = factTTC - restant;
1015
                    // Soldé
1016
                    if (l2 >= 0) {
1017
                        rowVals.put("SOLDE", Boolean.TRUE);
1018
                        rowVals.put("MONTANT_SOLDE", montantTTC);
1019
                        rowVals.put("MONTANT_RESTANT", 0);
1020
                    } else {
1021
                        // Il reste encore de l'argent pour l'avoir
1022
                        final long m = montantSolde + factTTC;
1023
                        rowVals.put("MONTANT_SOLDE", m);
1024
                        rowVals.put("MONTANT_RESTANT", montantTTC - m);
1025
                    }
1026
                    try {
1027
                        rowVals.update();
1028
                    } catch (SQLException e) {
1029
                        e.printStackTrace();
1030
                    }
1031
                }
1032
 
1033
 
1034
            }
1035
        } else {
1036
            ExceptionHandler.handle("Impossible d'ajouter, numéro de facture existant.");
1037
            Object root = SwingUtilities.getRoot(this);
1038
            if (root instanceof EditFrame) {
1039
                EditFrame frame = (EditFrame) root;
1040
                frame.getPanel().setAlwaysVisible(true);
1041
            }
1042
        }
1043
        return idSaisieVF;
1044
    }
1045
 
1046
    @Override
1047
    public void update() {
1048
        commit(null);
1049
    }
1050
 
1051
    /**
1052
     * Création d'une facture à partir d'un devis
1053
     *
1054
     * @param idDevis
1055
     *
1056
     */
1057
    public void loadDevis(int idDevis) {
1058
 
1059
        SQLElement devis = Configuration.getInstance().getDirectory().getElement("DEVIS");
1060
        SQLElement devisElt = Configuration.getInstance().getDirectory().getElement("DEVIS_ELEMENT");
1061
 
1062
        if (idDevis > 1) {
1063
            SQLInjector injector = SQLInjector.getInjector(devis.getTable(), this.getTable());
19 ilm 1064
            SQLRow rowDevis = devis.getTable().getRow(idDevis);
1065
            SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(idDevis);
1066
            String string = rowDevis.getString("OBJET");
1067
            createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ",") + rowDevis.getString("NUMERO"));
1068
            this.select(createRowValuesFrom);
18 ilm 1069
        }
1070
 
1071
            loadItem(this.tableFacture, devis, idDevis, devisElt);
1072
    }
1073
 
1074
    /**
1075
     * Création d'une facture à partir d'une facture existante
1076
     *
1077
     * @param idFacture
1078
     *
1079
     */
1080
    public void loadFactureExistante(int idFacture) {
1081
 
1082
        SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
1083
        SQLElement factElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1084
 
1085
        // On duplique la facture
1086
        if (idFacture > 1) {
1087
            SQLRow row = fact.getTable().getRow(idFacture);
1088
            SQLRowValues rowVals = new SQLRowValues(fact.getTable());
1089
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
1090
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class));
1091
            this.select(rowVals);
1092
        }
1093
 
1094
        // On duplique les elements de facture
1095
        List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
1096
 
1097
        if (myListItem.size() != 0) {
1098
            this.tableFacture.getModel().clearRows();
1099
 
1100
            for (SQLRow rowElt : myListItem) {
1101
 
1102
                SQLRowValues rowVals = rowElt.createUpdateRow();
1103
                rowVals.clearPrimaryKeys();
1104
                this.tableFacture.getModel().addRow(rowVals);
1105
                int rowIndex = this.tableFacture.getModel().getRowCount() - 1;
1106
                this.tableFacture.getModel().fireTableModelModified(rowIndex);
1107
            }
1108
        } else {
1109
            this.tableFacture.getModel().clearRows();
1110
        }
1111
        this.tableFacture.getModel().fireTableDataChanged();
1112
        this.tableFacture.repaint();
1113
    }
1114
 
19 ilm 1115
    public List<SQLRowValues> createFactureAcompte(int idFacture, long acompte) {
1116
 
1117
        SQLElement fact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE");
1118
        SQLElement factElt = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1119
 
1120
        // On duplique la facture
1121
        if (idFacture > 1) {
1122
            SQLRow row = fact.getTable().getRow(idFacture);
1123
            SQLRowValues rowVals = new SQLRowValues(fact.getTable());
1124
            rowVals.put("ID_CLIENT", row.getInt("ID_CLIENT"));
1125
            rowVals.put("ID_AFFAIRE", row.getInt("ID_AFFAIRE"));
1126
            rowVals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class));
1127
            rowVals.put("NOM", "Acompte de " + GestionDevise.currencyToString(acompte) + "€");
1128
            this.select(rowVals);
1129
        }
1130
 
1131
        // On duplique les elements de facture
1132
        List<SQLRow> myListItem = fact.getTable().getRow(idFacture).getReferentRows(factElt.getTable());
1133
        List<SQLRowValues> result = new ArrayList<SQLRowValues>(myListItem.size());
1134
        if (myListItem.size() != 0) {
1135
            this.tableFacture.getModel().clearRows();
1136
 
1137
            double acc = ((double) acompte / (double) myListItem.size());
1138
            long toAdd = 0;
1139
            SQLTable tablePourcentCCIP = Configuration.getInstance().getRoot().findTable("POURCENT_CCIP");
1140
            for (SQLRow rowElt : myListItem) {
1141
 
1142
                SQLRowValues rowValsUp = rowElt.createUpdateRow();
1143
                SQLRowValues rowVals = rowElt.createUpdateRow();
1144
                rowVals.clearPrimaryKeys();
1145
 
1146
                long val = rowVals.getLong("T_PV_HT");
1147
                double value = (acc + toAdd) / val * 100.0;
1148
                // Si l'acompte est supérieur au montant
1149
                if (value > 100) {
1150
                    value = 100;
1151
                    toAdd += (acc - val);
1152
                } else {
1153
                    toAdd = 0;
1154
                }
1155
                BigDecimal pourcentAcompte = new BigDecimal(rowValsUp.getLong("POURCENT_ACOMPTE") - value);
1156
                rowValsUp.put("POURCENT_ACOMPTE", pourcentAcompte);
1157
                BigDecimal pourcentCurrentAcompte = new BigDecimal(value);
1158
                rowVals.put("POURCENT_ACOMPTE", pourcentCurrentAcompte);
1159
                List<SQLRow> rowsCCIP = rowElt.getReferentRows(tablePourcentCCIP);
1160
                if (rowsCCIP.size() > 0) {
1161
                    SQLRowValues rowValsCCIP = rowsCCIP.get(0).createUpdateRow();
1162
                    rowValsCCIP.clearPrimaryKeys();
1163
                    rowValsCCIP.put("ID_SAISIE_VENTE_FACTURE_ELEMENT", rowVals);
1164
                    rowValsCCIP.put("NOM", "Acompte");
1165
                    rowValsCCIP.put("POURCENT", pourcentCurrentAcompte);
1166
                }
1167
                System.err.println(value);
1168
                this.tableFacture.getModel().addRow(rowVals);
1169
                int rowIndex = this.tableFacture.getModel().getRowCount() - 1;
1170
                this.tableFacture.getModel().fireTableModelModified(rowIndex);
1171
            }
1172
            if (toAdd > 0) {
1173
                for (int i = 0; i < this.tableFacture.getModel().getRowCount() && toAdd > 0; i++) {
1174
                    SQLRowValues rowVals = this.tableFacture.getModel().getRowValuesAt(i);
1175
                    if (rowVals.getFloat("POURCENT_ACOMPTE") < 100) {
1176
                        long val = rowVals.getLong("T_PV_HT");
1177
                        double value = (acc + toAdd) / val * 100.0;
1178
                        // Si l'acompte est supérieur au montant
1179
                        if (value > 100) {
1180
                            value = 100;
1181
                            toAdd += (acc - val);
1182
                        } else {
1183
                            toAdd = 0;
1184
                        }
1185
                        rowVals.put("POURCENT_ACOMPTE", new BigDecimal(value));
1186
                        this.tableFacture.getModel().fireTableModelModified(i);
1187
                    }
1188
                }
1189
            }
1190
 
1191
            // FIXME Check total if pb with round
1192
        } else {
1193
            this.tableFacture.getModel().clearRows();
1194
        }
1195
        this.tableFacture.getModel().fireTableDataChanged();
1196
        this.tableFacture.repaint();
1197
        return result;
1198
    }
1199
 
18 ilm 1200
    /**
1201
     * Création d'une facture à partir d'une commande
1202
     *
1203
     * @param idCmd
1204
     *
1205
     */
1206
    public void loadCommande(int idCmd) {
1207
 
1208
        SQLElement cmd = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT");
1209
        SQLElement cmdElt = Configuration.getInstance().getDirectory().getElement("COMMANDE_CLIENT_ELEMENT");
1210
 
1211
        if (idCmd > 1) {
1212
            SQLInjector injector = SQLInjector.getInjector(cmd.getTable(), this.getTable());
19 ilm 1213
            SQLRow rowCmd = cmd.getTable().getRow(idCmd);
1214
            SQLRowValues createRowValuesFrom = injector.createRowValuesFrom(idCmd);
1215
            String string = rowCmd.getString("NOM");
1216
            createRowValuesFrom.put("NOM", string + (string.trim().length() == 0 ? "" : ",") + rowCmd.getString("NUMERO"));
1217
            this.select(createRowValuesFrom);
18 ilm 1218
            this.listenerModeReglDefaut.propertyChange(null);
1219
        }
1220
        loadItem(this.tableFacture, cmd, idCmd, cmdElt);
1221
    }
1222
 
1223
    /**
1224
     * Création d'une facture à partir d'un bon de livraison
1225
     *
1226
     * @param idBl
1227
     *
1228
     */
1229
    public void loadBonItems(int idBl) {
1230
 
1231
        SQLElement bon = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON");
1232
        SQLElement bonElt = Configuration.getInstance().getDirectory().getElement("BON_DE_LIVRAISON_ELEMENT");
1233
        if (idBl > 1) {
1234
            SQLInjector injector = SQLInjector.getInjector(bon.getTable(), this.getTable());
1235
            this.select(injector.createRowValuesFrom(idBl));
1236
            this.listenerModeReglDefaut.propertyChange(null);
1237
        }
1238
        loadItem(this.tableFacture, bon, idBl, bonElt);
1239
    }
1240
 
1241
    public void addRowItem(SQLRowValues row) {
1242
        this.tableFacture.getModel().addRow(row);
1243
    }
1244
 
1245
    private static final SQLElement eltModeReglement = Configuration.getInstance().getDirectory().getElement("MODE_REGLEMENT");
1246
 
1247
    @Override
1248
    protected SQLRowValues createDefaults() {
1249
        SQLRowValues vals = new SQLRowValues(this.getTable());
1250
        SQLRow r;
1251
 
1252
        try {
1253
            r = ModeReglementDefautPrefPanel.getDefaultRow(true);
1254
            if (r.getID() > 1) {
1255
                SQLRowValues rowVals = eltModeReglement.createCopy(r, null);
1256
                System.err.println(rowVals.getInt("ID_TYPE_REGLEMENT"));
1257
                vals.put("ID_MODE_REGLEMENT", rowVals);
1258
            }
1259
        } catch (SQLException e) {
1260
            System.err.println("Impossible de sélectionner le mode de règlement par défaut du client.");
1261
            e.printStackTrace();
1262
        }
1263
        this.tableFacture.getModel().clearRows();
1264
        this.tableFacture.getModel().addNewRow();
1265
 
1266
        // User
1267
        // SQLSelect sel = new SQLSelect(Configuration.getInstance().getBase());
1268
        SQLElement eltComm = Configuration.getInstance().getDirectory().getElement("COMMERCIAL");
1269
        int idUser = UserManager.getInstance().getCurrentUser().getId();
1270
 
1271
        // sel.addSelect(eltComm.getTable().getKey());
1272
        // sel.setWhere(new Where(eltComm.getTable().getField("ID_USER_COMMON"), "=", idUser));
1273
        // List<SQLRow> rowsComm = (List<SQLRow>)
1274
        // Configuration.getInstance().getBase().getDataSource().execute(sel.asString(), new
1275
        // SQLRowListRSH(eltComm.getTable()));
1276
 
1277
        SQLRow rowsComm = SQLBackgroundTableCache.getInstance().getCacheForTable(eltComm.getTable()).getFirstRowContains(idUser, eltComm.getTable().getField("ID_USER_COMMON"));
1278
 
1279
        if (rowsComm != null) {
1280
            vals.put("ID_COMMERCIAL", rowsComm.getID());
1281
        }
1282
 
1283
        // User
1284
        final ComptaPropsConfiguration comptaPropsConfiguration = ((ComptaPropsConfiguration) Configuration.getInstance());
1285
        vals.put("NUMERO", NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class));
1286
        int idCompteVenteProduit = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_PRODUIT");
1287
        if (idCompteVenteProduit <= 1) {
1288
            try {
1289
                idCompteVenteProduit = ComptePCESQLElement.getIdComptePceDefault("VentesProduits");
1290
            } catch (Exception e) {
1291
                e.printStackTrace();
1292
            }
1293
        }
1294
 
1295
        vals.put("ID_COMPTE_PCE_VENTE", idCompteVenteProduit);
1296
        if (this.checkCT != null) {
1297
            vals.put("CONTROLE_TECHNIQUE", this.checkCT.isSelected());
1298
        }
19 ilm 1299
 
1300
        int idCompteVenteService = rowPrefsCompte.getInt("ID_COMPTE_PCE_VENTE_SERVICE");
1301
        if (idCompteVenteService <= 1) {
1302
            try {
1303
                idCompteVenteService = ComptePCESQLElement.getIdComptePceDefault("VentesServices");
1304
            } catch (Exception e) {
1305
                e.printStackTrace();
1306
            }
1307
        }
1308
 
1309
        vals.put("ID_COMPTE_PCE_SERVICE", idCompteVenteService);
18 ilm 1310
        System.err.println("Defaults " + vals);
1311
        return vals;
1312
    }
1313
 
1314
    public void setDefaults() {
1315
        this.resetValue();
21 ilm 1316
 
18 ilm 1317
        this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class));
1318
        this.tableFacture.getModel().clearRows();
1319
    }
1320
 
1321
    public RowValuesTableModel getRowValuesTableModel() {
1322
        return this.tableFacture.getModel();
1323
    }
1324
 
1325
    /**
1326
     * Définir la facture comme prévisionnelle. Pas de génération comptable, ni de mode de règlement
1327
     *
19 ilm 1328
     * @deprecated mettre les valeurs dans une RowValues
18 ilm 1329
     * @param b
1330
     */
19 ilm 1331
    @Deprecated
18 ilm 1332
    public void setPrevisonnelle(boolean b) {
1333
        this.checkPrevisionnelle.setSelected(b);
1334
        if (!b) {
1335
            this.textNumeroUnique.setText(NumerotationAutoSQLElement.getNextNumero(SaisieVenteFactureSQLElement.class));
1336
        }
1337
    }
1338
 
1339
    /**
1340
     * Définir la facture comme complémentaire. Règlement supérieur au montant de la facture
1341
     * initiale
1342
     *
1343
     * @param b
1344
     */
1345
    public void setComplement(boolean b) {
1346
        this.checkComplement.setSelected(b);
1347
    }
1348
 
1349
    /**
1350
     * Définir la facture comme acompte.
1351
     *
1352
     * @param b
1353
     */
1354
    public void setAcompte(boolean b) {
1355
 
1356
        // boolean bOld = this.checkAcompte.isSelected();
1357
        // System.err.println("---> Set acompte " + b + " Old Value " + bOld);
1358
        this.checkAcompte.setSelected(b);
1359
        this.checkAcompte.firePropertyChange("ValueChanged", !b, b);
1360
    }
1361
 
1362
    public void setTypeInterventionText(String text) {
1363
        this.textTypeMission.setValue(text);
1364
    }
1365
 
1366
    public void setReferenceClientText(String text) {
1367
        this.refClient.setText(text);
1368
    }
1369
 
1370
    /**
1371
     * Mise à jour des stocks pour chaque article composant la facture
1372
     */
1373
    private void updateStock(int id) {
1374
 
1375
        SQLElement eltArticleFact = Configuration.getInstance().getDirectory().getElement("SAISIE_VENTE_FACTURE_ELEMENT");
1376
        SQLTable sqlTableArticle = ((ComptaPropsConfiguration) Configuration.getInstance()).getRootSociete().getTable("ARTICLE");
1377
        SQLElement eltArticle = Configuration.getInstance().getDirectory().getElement(sqlTableArticle);
1378
        SQLRow rowFacture = getTable().getRow(id);
1379
 
1380
        // FIXME Si la facture vient d'un bon de livraison le stock a deja été mis à jour
1381
        // if (rowFacture.getString("SOURCE").equalsIgnoreCase("BON_DE_LIVRAISON")) {
1382
        // return;
1383
        // }
1384
 
1385
        // On récupére les articles qui composent la facture
1386
        SQLSelect selEltfact = new SQLSelect(eltArticleFact.getTable().getBase());
1387
        selEltfact.addSelect(eltArticleFact.getTable().getField("ID"));
1388
        selEltfact.setWhere(new Where(eltArticleFact.getTable().getField("ID_SAISIE_VENTE_FACTURE"), "=", id));
1389
 
1390
        List lEltFact = (List) eltArticleFact.getTable().getBase().getDataSource().execute(selEltfact.asString(), new ArrayListHandler());
1391
 
1392
        if (lEltFact != null) {
19 ilm 1393
            List<Integer> l = new ArrayList<Integer>();
18 ilm 1394
            for (int i = 0; i < lEltFact.size(); i++) {
1395
 
1396
                // Elt qui compose facture
1397
                Object[] tmp = (Object[]) lEltFact.get(i);
1398
                int idEltFact = ((Number) tmp[0]).intValue();
1399
                SQLRow rowEltFact = eltArticleFact.getTable().getRow(idEltFact);
1400
 
1401
                // on récupére l'article qui lui correspond
1402
                SQLRowValues rowArticle = new SQLRowValues(eltArticle.getTable());
1403
                for (SQLField field : eltArticle.getTable().getFields()) {
1404
                    if (rowEltFact.getTable().getFieldsName().contains(field.getName())) {
1405
                        rowArticle.put(field.getName(), rowEltFact.getObject(field.getName()));
1406
                    }
1407
                }
1408
                // rowArticle.loadAllSafe(rowEltFact);
1409
                int idArticle = ReferenceArticleSQLElement.getIdForCNM(rowArticle, true);
1410
 
1411
                // on crée un mouvement de stock pour chacun des articles
1412
                SQLElement eltMvtStock = Configuration.getInstance().getDirectory().getElement("MOUVEMENT_STOCK");
1413
                SQLRowValues rowVals = new SQLRowValues(eltMvtStock.getTable());
1414
                rowVals.put("QTE", -(rowEltFact.getInt("QTE")));
1415
                rowVals.put("NOM", "Saisie vente facture N°" + rowFacture.getString("NUMERO"));
1416
                rowVals.put("IDSOURCE", id);
1417
                rowVals.put("SOURCE", getTable().getName());
1418
                rowVals.put("ID_ARTICLE", idArticle);
1419
                rowVals.put("DATE", rowFacture.getObject("DATE"));
1420
                try {
1421
                    SQLRow row = rowVals.insert();
19 ilm 1422
                    l.add(row.getID());
18 ilm 1423
                } catch (SQLException e) {
1424
                    e.printStackTrace();
1425
                }
1426
                // }
1427
            }
19 ilm 1428
            CollectionMap<SQLRow, List<SQLRowValues>> map = MouvementStockSQLElement.updateStock(l);
1429
            if (map.keySet().size() > 0) {
1430
                if (JOptionPane.showConfirmDialog(null, "Certains articles sont en dessous du stock minimum.\n Voulez créer une commande?") == JOptionPane.YES_OPTION) {
1431
                    MouvementStockSQLElement.createCommandeF(map, rowFacture.getForeignRow("ID_TARIF").getForeignRow("ID_DEVISE"));
1432
                }
1433
            }
18 ilm 1434
        }
1435
    }
1436
}